-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreport.py
More file actions
218 lines (191 loc) · 6.69 KB
/
Copy pathreport.py
File metadata and controls
218 lines (191 loc) · 6.69 KB
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
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
from __future__ import annotations
from typing import TYPE_CHECKING
import plotly.graph_objects as go
from plotly.subplots import make_subplots
if TYPE_CHECKING:
from trade_lab.backtesting.engine import BacktestResult
def generate_report(
result: BacktestResult,
output_path: str = "backtest_report.html",
) -> str:
"""Generate an HTML backtest report with charts and metrics.
Parameters
----------
result : BacktestResult
Output of ``BacktestEngine.run()``.
output_path : str
File path for the HTML report.
Returns
-------
str
The output file path.
"""
fig = make_subplots(
rows=3,
cols=1,
shared_xaxes=True,
subplot_titles=["Equity Curve", "Drawdown", "Price & Trades"],
vertical_spacing=0.06,
row_heights=[0.4, 0.2, 0.4],
)
# ---- Equity curve ----
fig.add_trace(
go.Scatter(
x=result.equity_curve.index.to_numpy(),
y=result.equity_curve.to_numpy(),
mode="lines",
name="Equity",
line=dict(color="#2962FF"),
),
row=1,
col=1,
)
# ---- Drawdown ----
peak = result.equity_curve.cummax()
dd = (result.equity_curve - peak) / peak * 100
fig.add_trace(
go.Scatter(
x=dd.index.to_numpy(),
y=dd.to_numpy(),
mode="lines",
fill="tozeroy",
name="Drawdown %",
line=dict(color="#FF6D00"),
),
row=2,
col=1,
)
# ---- Price + trade markers ----
fig.add_trace(
go.Scatter(
x=result.df.index.to_numpy(),
y=result.df["Close"].to_numpy(),
mode="lines",
name="Close",
line=dict(color="#666"),
),
row=3,
col=1,
)
if len(result.trade_log) > 0:
tl = result.trade_log
longs = tl[tl["direction"] == "long"]
shorts = tl[tl["direction"] == "short"]
if len(longs) > 0:
fig.add_trace(
go.Scatter(
x=longs["entry_date"],
y=longs["entry_price"],
mode="markers",
name="Long Entry",
marker=dict(symbol="triangle-up", size=10, color="green"),
),
row=3,
col=1,
)
if len(shorts) > 0:
fig.add_trace(
go.Scatter(
x=shorts["entry_date"],
y=shorts["entry_price"],
mode="markers",
name="Short Entry",
marker=dict(symbol="triangle-down", size=10, color="red"),
),
row=3,
col=1,
)
fig.add_trace(
go.Scatter(
x=tl["exit_date"],
y=tl["exit_price"],
mode="markers",
name="Exit",
marker=dict(symbol="x", size=8, color="gray"),
),
row=3,
col=1,
)
fig.update_layout(height=900, title_text="Backtest Report", showlegend=True)
# ---- Assemble HTML ----
metrics_table = _format_metrics_tables(result.metrics)
chart_html = fig.to_html(include_plotlyjs="cdn", full_html=False)
html = (
"<!DOCTYPE html>\n<html>\n<head>\n"
'<meta charset="utf-8">\n'
"<title>Backtest Report</title>\n"
"<style>\n"
"body { font-family: Arial, sans-serif; margin: 20px; background: #fafafa; }\n"
"h1 { color: #333; }\n"
".metrics-grid { "
"display: grid; "
"grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); "
"gap: 20px; margin: 20px 0; "
"}\n"
".metrics-card h2 { margin: 0 0 8px 0; color: #333; font-size: 1.05rem; }\n"
"table { border-collapse: collapse; width: 100%; background: white; }\n"
"th, td { border: 1px solid #ddd; padding: 8px 16px; text-align: right; }\n"
"th { background: #f5f5f5; text-align: left; }\n"
".pos { color: #2e7d32; }\n"
".neg { color: #c62828; }\n"
"</style>\n</head>\n<body>\n"
"<h1>Backtest Report</h1>\n"
f"{metrics_table}\n"
f"{chart_html}\n"
"</body>\n</html>"
)
with open(output_path, "w", encoding="utf-8") as f:
f.write(html)
return output_path
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
_METRIC_FORMAT_MAIN = [
("total_return", "Total Return", "{:.2%}", True),
("annualized_return", "Annualized Return", "{:.2%}", True),
("sharpe_ratio", "Sharpe Ratio", "{:.2f}", True),
("sortino_ratio", "Sortino Ratio", "{:.2f}", True),
("max_drawdown", "Max Drawdown", "{:.2%}", True),
("annual_volatility", "Annual Volatility", "{:.2%}", False),
("total_trades", "Total Trades", "{:.0f}", False),
("win_rate", "Win Rate", "{:.1%}", False),
("profit_factor", "Profit Factor", "{:.2f}", False),
("avg_win", "Avg Win", "${:,.2f}", False),
("avg_loss", "Avg Loss", "${:,.2f}", False),
("avg_trade_bars", "Avg Trade Duration", "{:.1f} bars", False),
("total_commission", "Total Commission", "${:,.2f}", False),
("total_financing", "Total Financing", "${:,.2f}", False),
]
_METRIC_FORMAT_DIRECTIONAL = [
("long_win_rate", "Long Win Rate", "{:.1%}", False),
("long_avg_win", "Long Avg Profit", "${:,.2f}", True),
("long_avg_loss", "Long Avg Loss", "${:,.2f}", True),
("short_win_rate", "Short Win Rate", "{:.1%}", False),
("short_avg_win", "Short Avg Profit", "${:,.2f}", True),
("short_avg_loss", "Short Avg Loss", "${:,.2f}", True),
]
def _format_metrics_table(metrics: dict, metric_format: list[tuple]) -> str:
rows: list[str] = []
for key, label, fmt, colorise in metric_format:
val = metrics.get(key, 0)
formatted = fmt.format(val)
css = ""
if colorise:
css = ' class="pos"' if val > 0 else ' class="neg"' if val < 0 else ""
rows.append(f"<tr><th>{label}</th><td{css}>{formatted}</td></tr>")
return f"<table>{''.join(rows)}</table>"
def _format_metrics_tables(metrics: dict) -> str:
main_table = _format_metrics_table(metrics, _METRIC_FORMAT_MAIN)
directional_table = _format_metrics_table(metrics, _METRIC_FORMAT_DIRECTIONAL)
return (
'<div class="metrics-grid">'
'<section class="metrics-card">'
"<h2>Overall Metrics</h2>"
f"{main_table}"
"</section>"
'<section class="metrics-card">'
"<h2>Long / Short Breakdown</h2>"
f"{directional_table}"
"</section>"
"</div>"
)