File size: 4,425 Bytes
cbdae8d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
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}<extra>Realized P&L</extra>",
        )
    )

    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}<extra>-VaR</extra>",
        )
    )

    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}<extra>-ES</extra>",
        )
    )

    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}<extra>Exceedance</extra>",
        )
    )

    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}<extra>Expected</extra>",
        )
    )

    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}<extra>Observed</extra>",
        )
    )

    fig.update_layout(
        title=f"Cumulative exceedances ({confidence:.1%})",
        xaxis_title="Date",
        yaxis_title="Exceedances",
        template="plotly_white",
        hovermode="x unified",
    )

    return fig