svgefficient-frontier
Efficient frontier
Which portfolios give the most return for each level of risk, and where does the chosen one sit?
How to read it
- Read x as risk and y as return.
- The curve is the best return at each risk.
- Points below it are beatable; the marker is the chosen portfolio.
- Callout 1: The chosen portfolio.
- Callout 2: A frontier point: more return, more risk.
- Callout 3: An asset below the frontier: beatable.
Watch out
- It's very sensitive to estimated returns, so small estimation errors move the frontier a lot.
Defaults
No settings: the chart draws one way.
Pinned in the code
- Draws the run's numbers as given (computed by the Python/R engine); the chart computes nothing statistical.
- Frontier rows are joined in order of risk; values within ±2 on both axes are shown as percentages.
# Efficient frontier — Codesplash Chart Lab (recipe "efficient-frontier")
# controls: defaults
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else plt.rcParams["axes.prop_cycle"].by_key()["color"]
df = pd.read_csv("efficient-frontier-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["frontier", "asset"])
R = "volatility"
RET = "expected return"
LABEL = "label"
CH = "chosen"
KIND = "kind"
d = df.dropna(subset=[R, RET])
asset = d[KIND].astype(str) == "asset" if KIND else pd.Series(False, index=d.index)
f, a = d[~asset].sort_values(R), d[asset]
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(f[R], f[RET], marker="o", ms=3, color=PALETTE[0], linewidth=2, label="efficient frontier")
ax.scatter(a[R], a[RET], facecolors="none", edgecolors="grey", s=36, label="assets")
if LABEL:
for _, r in a.iterrows():
ax.annotate(str(r[LABEL]), (r[R], r[RET]), xytext=(6, 0), textcoords="offset points", va="center", fontsize=8)
if CH:
ch = d[d[CH].astype(bool)]
ax.scatter(ch[R], ch[RET], color=PALETTE[1], s=80, zorder=3, label="chosen")
ax.set_xlabel(R)
ax.set_ylabel(RET)
ax.legend(fontsize=8)
plt.show()Needs pandas, numpy, matplotlib · reads efficient-frontier-demo.csv · app theme from the optional codesplash helper
# Efficient frontier — Codesplash Chart Lab (recipe "efficient-frontier")
# controls: defaults
import numpy as np
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
try:
import codesplash as cs # optional: the app's chart theme
except ImportError:
cs = None
if cs:
cs.use_codesplash(dark=False)
PALETTE = cs.palette(dark=False)["categorical"] if cs else px.colors.qualitative.Plotly
df = pd.read_csv("efficient-frontier-demo.csv", keep_default_na=False, na_values=[""]) # demo data (only empty cells are missing): Chart Lab → Code → Download demo CSV
df["kind"] = pd.Categorical(df["kind"].astype("string"), categories=["frontier", "asset"])
R = "volatility"
RET = "expected return"
LABEL = "label"
CH = "chosen"
KIND = "kind"
d = df.dropna(subset=[R, RET])
asset = d[KIND].astype(str) == "asset" if KIND else pd.Series(False, index=d.index)
f, a = d[~asset].sort_values(R), d[asset]
fig = go.Figure()
fig.add_scatter(x=f[R], y=f[RET], mode="lines+markers", name="efficient frontier", line=dict(color=PALETTE[0], width=2.5))
fig.add_scatter(x=a[R], y=a[RET], mode="markers+text", text=a[LABEL] if LABEL else None, textposition="middle right", name="assets", marker=dict(color="white", line=dict(color="grey", width=1.5), size=9))
if CH:
ch = d[d[CH].astype(bool)]
fig.add_scatter(x=ch[R], y=ch[RET], mode="markers", name="chosen", marker=dict(color=PALETTE[1], size=14))
fig.update_layout(xaxis_title=R, yaxis_title=RET)
fig.show()Needs pandas, numpy, plotly · reads efficient-frontier-demo.csv · app theme from the optional codesplash helper
# Efficient frontier — Codesplash Chart Lab (recipe "efficient-frontier")
# controls: defaults
library(ggplot2)
has_cs <- isTRUE(requireNamespace("codesplashr", quietly = TRUE)) # optional: the app's chart theme
theme_cs <- if (has_cs) codesplashr::theme_codesplash(dark = FALSE) else theme_minimal()
cs_cat <- if (has_cs) codesplashr::cs_palette(dark = FALSE)$categorical else grDevices::palette.colors(8, "Okabe-Ito")
if (has_cs) update_geom_defaults("text", list(colour = codesplashr::cs_palette(dark = FALSE)$foreground))
df <- read.csv("efficient-frontier-demo.csv", check.names = FALSE, stringsAsFactors = FALSE, na.strings = "") # empty cells are missing; Chart Lab → Code → Download demo CSV
df[["chosen"]] <- as.logical(df[["chosen"]])
df[["label"]] <- factor(df[["label"]])
df[["kind"]] <- factor(df[["kind"]], levels = c("frontier", "asset"))
r_col <- "volatility"
ret_col <- "expected return"
label_col <- "label"
ch_col <- "chosen"
kind_col <- "kind"
d <- data.frame(r = df[[r_col]], ret = df[[ret_col]], label = if (is.null(label_col)) NA else as.character(df[[label_col]]),
chosen = if (is.null(ch_col)) FALSE else as.logical(df[[ch_col]]), asset = if (is.null(kind_col)) FALSE else df[[kind_col]] == "asset")
f <- d[!d$asset, ]; f <- f[order(f$r), ]
p <- ggplot() + geom_line(data = f, aes(r, ret), colour = cs_cat[1], linewidth = 1) + geom_point(data = f, aes(r, ret), colour = cs_cat[1], size = 1) +
geom_point(data = d[d$asset, ], aes(r, ret), shape = 21, fill = "white", colour = "grey45", size = 2.6) +
geom_text(data = d[d$asset, ], aes(r, ret, label = label), hjust = -0.2, size = 3) +
geom_point(data = d[d$chosen %in% TRUE, ], aes(r, ret), colour = cs_cat[2], size = 4) +
labs(x = r_col, y = ret_col) + theme_cs
print(p)Needs ggplot2 · reads efficient-frontier-demo.csv · app theme from the optional codesplashr helper