-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathtest_reports.py
More file actions
280 lines (232 loc) · 10.4 KB
/
Copy pathtest_reports.py
File metadata and controls
280 lines (232 loc) · 10.4 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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
"""
Tests for quantstats.reports module
"""
import pytest
import pandas as pd
import numpy as np
import tempfile
import os
import quantstats as qs
from quantstats import reports
from dateutil.relativedelta import relativedelta
@pytest.fixture
def sample_returns():
"""Generate sample daily returns for testing."""
np.random.seed(42)
dates = pd.date_range("2020-01-01", periods=500, freq="D")
returns = pd.Series(np.random.randn(500) * 0.02, index=dates, name="Strategy")
return returns
@pytest.fixture
def sample_benchmark():
"""Generate sample benchmark returns for testing."""
np.random.seed(123)
dates = pd.date_range("2020-01-01", periods=500, freq="D")
returns = pd.Series(np.random.randn(500) * 0.015, index=dates, name="Benchmark")
return returns
class TestHTMLReport:
"""Test HTML report generation."""
def test_html_generates_file(self, sample_returns, sample_benchmark):
"""Test that HTML report generates a file."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".html", delete=False) as f:
output_path = f.name
try:
reports.html(sample_returns, sample_benchmark, output=output_path)
assert os.path.exists(output_path)
# Check file has content
with open(output_path, "r") as f:
content = f.read()
assert len(content) > 1000 # Should have substantial content
assert "<!DOCTYPE html>" in content
finally:
if os.path.exists(output_path):
os.remove(output_path)
def test_html_contains_title(self, sample_returns):
"""Test that HTML report contains proper title."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".html", delete=False) as f:
output_path = f.name
try:
reports.html(sample_returns, output=output_path, title="My Strategy")
with open(output_path, "r") as f:
content = f.read()
assert "My Strategy" in content
assert "(Compounded)" in content
finally:
if os.path.exists(output_path):
os.remove(output_path)
def test_html_simple_returns_title(self, sample_returns):
"""Test title does NOT show (Compounded) when compounded=False."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".html", delete=False) as f:
output_path = f.name
try:
reports.html(sample_returns, output=output_path, compounded=False)
with open(output_path, "r") as f:
content = f.read()
assert "(Compounded)" not in content
finally:
if os.path.exists(output_path):
os.remove(output_path)
def test_html_contains_benchmark_param(self, sample_returns, sample_benchmark):
"""Test that HTML report shows benchmark in parameters."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".html", delete=False) as f:
output_path = f.name
try:
reports.html(sample_returns, sample_benchmark, output=output_path)
with open(output_path, "r") as f:
content = f.read()
assert "Benchmark:" in content
assert "Periods/Year: 252" in content
assert "RF:" in content
finally:
if os.path.exists(output_path):
os.remove(output_path)
def test_html_matched_dates_indicator(self, sample_returns, sample_benchmark):
"""Test matched dates indicator appears when appropriate."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".html", delete=False) as f:
output_path = f.name
try:
reports.html(
sample_returns, sample_benchmark, output=output_path, match_dates=True
)
with open(output_path, "r") as f:
content = f.read()
assert "(matched dates)" in content
finally:
if os.path.exists(output_path):
os.remove(output_path)
def test_html_no_dark_mode(self, sample_returns):
"""Test that dark mode CSS is not present."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".html", delete=False) as f:
output_path = f.name
try:
reports.html(sample_returns, output=output_path)
with open(output_path, "r") as f:
content = f.read()
assert "prefers-color-scheme:dark" not in content
assert "color-scheme" not in content
finally:
if os.path.exists(output_path):
os.remove(output_path)
def test_html_custom_rf(self, sample_returns):
"""Test custom risk-free rate in parameters."""
with tempfile.NamedTemporaryFile(mode="w", suffix=".html", delete=False) as f:
output_path = f.name
try:
reports.html(sample_returns, output=output_path, rf=0.05)
with open(output_path, "r") as f:
content = f.read()
assert "RF: 5.0%" in content
finally:
if os.path.exists(output_path):
os.remove(output_path)
class TestMetrics:
"""Test metrics function."""
def test_metrics_basic_mode(self, sample_returns):
"""Test metrics in basic mode."""
result = reports.metrics(sample_returns, display=False, mode="basic")
assert isinstance(result, pd.DataFrame)
assert len(result) > 0
def test_metrics_full_mode(self, sample_returns):
"""Test metrics in full mode."""
result = reports.metrics(sample_returns, display=False, mode="full")
assert isinstance(result, pd.DataFrame)
# Full mode should have more metrics than basic
basic_result = reports.metrics(sample_returns, display=False, mode="basic")
assert len(result) >= len(basic_result)
def test_metrics_with_benchmark(self, sample_returns, sample_benchmark):
"""Test metrics with benchmark comparison."""
result = reports.metrics(
sample_returns, benchmark=sample_benchmark, display=False
)
assert isinstance(result, pd.DataFrame)
# Should have at least two columns (strategy + benchmark)
assert result.shape[1] >= 2
def test_metrics_with_rf(self, sample_returns):
"""Test metrics with non-zero risk-free rate."""
result_no_rf = reports.metrics(sample_returns, rf=0, display=False)
result_with_rf = reports.metrics(sample_returns, rf=0.02, display=False)
# Results should be different
assert not result_no_rf.equals(result_with_rf)
def test_metrics_use_full_three_and_five_year_windows(self):
"""Test that multi-year annualized metrics use full labeled windows."""
dates = pd.date_range("2020-01-31", "2026-01-31", freq="ME")
returns = pd.Series(0.0, index=dates, name="Strategy")
returns.loc[pd.Timestamp("2021-01-31")] = 0.25
returns.loc[pd.Timestamp("2023-01-31")] = 0.15
result = reports.metrics(returns, display=False)
expected_3y = qs.stats.cagr(
returns[returns.index >= dates[-1] - relativedelta(years=3)],
rf=0.0,
compounded=True,
).iloc[0]
expected_5y = qs.stats.cagr(
returns[returns.index >= dates[-1] - relativedelta(years=5)],
rf=0.0,
compounded=True,
).iloc[0]
assert result.loc["3Y (ann.)", "Strategy"] == pytest.approx(round(expected_3y, 2))
assert result.loc["5Y (ann.)", "Strategy"] == pytest.approx(round(expected_5y, 2))
class TestMatchDates:
"""Test date matching functionality."""
def test_match_dates_aligns_series(self):
"""Test that _match_dates aligns returns and benchmark."""
# Create returns starting later than benchmark
dates1 = pd.date_range("2020-01-10", periods=100, freq="D")
dates2 = pd.date_range("2020-01-01", periods=110, freq="D")
returns = pd.Series(np.random.randn(100) * 0.01, index=dates1)
benchmark = pd.Series(np.random.randn(110) * 0.01, index=dates2)
# Set first values to non-zero
returns.iloc[0] = 0.01
benchmark.iloc[0] = 0.01
aligned_ret, aligned_bench = reports._match_dates(returns, benchmark)
# Both should now start from the same date
assert aligned_ret.index[0] == aligned_bench.index[0]
class TestParametersTable:
"""Test parameters table printing."""
def test_print_parameters_table_with_benchmark(self, capsys):
"""Test parameters table output with benchmark."""
reports._print_parameters_table(
benchmark_title="SPY",
periods_per_year=252,
rf=0.02,
compounded=True,
match_dates=True,
)
captured = capsys.readouterr()
assert "SPY" in captured.out
assert "252" in captured.out
assert "2.0%" in captured.out
assert "Yes" in captured.out
def test_print_parameters_table_no_benchmark(self, capsys):
"""Test parameters table output without benchmark."""
reports._print_parameters_table(
benchmark_title=None,
periods_per_year=252,
rf=0.0,
compounded=False,
match_dates=True,
)
captured = capsys.readouterr()
assert "Benchmark" not in captured.out
assert "252" in captured.out
assert "No" in captured.out # Compounded = No
class TestEdgeCases:
"""Test edge cases in reports."""
def test_html_with_dataframe(self, sample_returns, sample_benchmark):
"""Test HTML generation with DataFrame input."""
df = pd.DataFrame({"Strategy": sample_returns})
with tempfile.NamedTemporaryFile(mode="w", suffix=".html", delete=False) as f:
output_path = f.name
try:
reports.html(df, sample_benchmark, output=output_path)
assert os.path.exists(output_path)
finally:
if os.path.exists(output_path):
os.remove(output_path)
def test_metrics_empty_benchmark_title(self, sample_returns, sample_benchmark):
"""Test metrics when benchmark has no name."""
benchmark_no_name = sample_benchmark.copy()
benchmark_no_name.name = None
result = reports.metrics(
sample_returns, benchmark=benchmark_no_name, display=False
)
assert isinstance(result, pd.DataFrame)