import pandas as pd
import plotly.graph_objects as go
from data.schema import Out
# Realised P&L is context, so it stays neutral; the forecast
# lines share one hue; exceedances use the critical status
# color plus an x marker and a legend label.
PNL_COLOR = "#b4b2a9"
VAR_COLOR = "#2a78d6"
ES_COLOR = "#184f95"
EXCEEDANCE_COLOR = "#d03b3b"
EXPECTED_COLOR = "#52514e"
def _select(forecasts, confidence):
selected = forecasts[
forecasts[Out.CONFIDENCE] == confidence
]
if selected.empty:
raise ValueError(
f"No backtest results at confidence {confidence}."
)
return selected.sort_values(Out.DATE)
def _break_at_gaps(df, gap_days):
"""
Insert an empty row after every gap longer than `gap_days`
so lines are not drawn across periods without data.
"""
if not gap_days:
return df
gaps = df[Out.DATE].diff() > pd.Timedelta(days=gap_days)
breaks = pd.DataFrame(
{Out.DATE: df.loc[gaps, Out.DATE] - pd.Timedelta(days=1)}
)
return (
pd.concat([df, breaks])
.sort_values(Out.DATE)
.reset_index(drop=True)
)
def plot_backtest_pnl(
forecasts,
confidence,
gap_days=None,
):
"""
Realised P&L against the forecast -VaR and -ES,
with exceedances marked.
"""
df = _select(forecasts, confidence)
exceeded = df[df[Out.EXCEEDANCE]]
df = _break_at_gaps(df, gap_days)
fig = go.Figure()
fig.add_trace(
go.Bar(
x=df[Out.DATE],
y=df[Out.REALIZED_PNL],
name="Realized P&L",
marker_color=PNL_COLOR,
hovertemplate="%{y:,.0f}Realized P&L",
)
)
fig.add_trace(
go.Scatter(
x=df[Out.DATE],
y=-df[Out.VAR],
mode="lines",
name=f"-VaR {confidence:.1%}",
line=dict(color=VAR_COLOR, width=2),
hovertemplate="%{y:,.0f}-VaR",
)
)
fig.add_trace(
go.Scatter(
x=df[Out.DATE],
y=-df[Out.ES],
mode="lines",
name=f"-ES {confidence:.1%}",
line=dict(color=ES_COLOR, width=2, dash="dot"),
hovertemplate="%{y:,.0f}-ES",
)
)
fig.add_trace(
go.Scatter(
x=exceeded[Out.DATE],
y=exceeded[Out.REALIZED_PNL],
mode="markers",
name=f"Exceedance ({len(exceeded)})",
marker=dict(
color=EXCEEDANCE_COLOR,
symbol="x",
size=11,
line=dict(width=1, color=EXCEEDANCE_COLOR),
),
hovertemplate="%{y:,.0f}Exceedance",
)
)
fig.update_layout(
title=(
f"Out-of-sample backtest: realized P&L vs "
f"forecast VaR ({confidence:.1%})"
),
xaxis_title="Date",
yaxis_title="P&L",
template="plotly_white",
hovermode="x unified",
bargap=0.3,
)
return fig
def plot_cumulative_exceedances(
forecasts,
confidence,
gap_days=None,
):
"""
Observed exceedances over time against the number a
correctly calibrated model would produce.
"""
df = _select(forecasts, confidence).reset_index(drop=True)
df[Out.EXCEEDANCES] = df[Out.EXCEEDANCE].astype(int).cumsum()
df[Out.EXPECTED_EXCEEDANCES] = (1 - confidence) * (df.index + 1)
df = _break_at_gaps(df, gap_days)
observed = df[Out.EXCEEDANCES]
expected = df[Out.EXPECTED_EXCEEDANCES]
fig = go.Figure()
fig.add_trace(
go.Scatter(
x=df[Out.DATE],
y=expected,
mode="lines",
name="Expected",
line=dict(color=EXPECTED_COLOR, width=2, dash="dash"),
hovertemplate="%{y:.2f}Expected",
)
)
fig.add_trace(
go.Scatter(
x=df[Out.DATE],
y=observed,
mode="lines",
name="Observed",
line=dict(color=VAR_COLOR, width=2, shape="hv"),
hovertemplate="%{y}Observed",
)
)
fig.update_layout(
title=f"Cumulative exceedances ({confidence:.1%})",
xaxis_title="Date",
yaxis_title="Exceedances",
template="plotly_white",
hovermode="x unified",
)
return fig