-
Notifications
You must be signed in to change notification settings - Fork 35
/
Copy pathtest_portfolio.py
361 lines (249 loc) · 14 KB
/
test_portfolio.py
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import numpy as np
import pandas as pd
import pytest
from pytest import approx
from pytest import mark
from numpy.testing import assert_array_equal, assert_allclose
from pandas.testing import assert_series_equal, assert_frame_equal
import okama as ok
from tests import conftest
def test_initialization_failing():
with pytest.raises(
ValueError,
match=r"Number of tickers \(2\) should be equal to the weights number \(3\)",
):
ok.Portfolio(assets=["MCFTR.INDX", "MCFTR.INDX", "RUB.FX"], weights=[0.3, 0.3, 0.4])
def test_repr(portfolio_rebalanced_year):
value = pd.Series(
dict(
symbol="pf1.PF",
assets="[RGBITR.INDX, MCFTR.INDX]",
weights="[0.5, 0.5]",
rebalancing_period="year",
currency="RUB",
inflation="RUB.INFL",
first_date="2015-01",
last_date="2020-01",
period_length="5 years, 1 months",
)
)
assert repr(portfolio_rebalanced_year) == repr(value)
def test_symbol_failing(portfolio_rebalanced_year):
with pytest.raises(
ValueError,
match='portfolio symbol must be a string ending with ".PF" namespace.',
):
portfolio_rebalanced_year.symbol = 1
with pytest.raises(ValueError, match='portfolio symbol must be a string ending with ".PF" namespace.'):
portfolio_rebalanced_year.symbol = "Not_a_good_symbol_for_portfolio.US"
with pytest.raises(ValueError, match="portfolio text symbol should not have whitespace characters."):
portfolio_rebalanced_year.symbol = "Not a good symbol for portfolio.PF"
def test_symbol_setter(portfolio_rebalanced_year):
portfolio_rebalanced_year.symbol = "portfolio_1.PF"
assert portfolio_rebalanced_year.symbol == "portfolio_1.PF"
def test_ror_rebalance(portfolio_rebalanced_year, portfolio_not_rebalanced):
assert portfolio_rebalanced_year.ror[-2] == approx(0.03052, rel=1e-1)
assert portfolio_not_rebalanced.ror[-1] == approx(0.01167, rel=1e-1)
def test_ror(portfolio_rebalanced_month):
portfolio_sample = pd.read_pickle(conftest.data_folder / "portfolio.pkl")
actual = portfolio_rebalanced_month.ror
assert_series_equal(actual, portfolio_sample, atol=1e-01)
def test_wealth_index(portfolio_rebalanced_year):
assert portfolio_rebalanced_year.wealth_index.iloc[-1, 1] == approx(1315.848, rel=1e-2)
def test_wealth_index_with_assets(portfolio_rebalanced_year, portfolio_no_inflation):
result = portfolio_rebalanced_year.wealth_index_with_assets.iloc[-1, :].values
assert_allclose(np.array(result), np.array([2490.845572, 2079.757278, 2924.031272, 1315.848632]), rtol=1e-02)
def test_weights(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.weights == [0.5, 0.5]
def test_weights_ts_rebalanced_month(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.weights_ts["RGBITR.INDX"].iloc[-1] == approx(0.5, rel=1e-2)
def test_weights_ts_rebalanced_year(portfolio_rebalanced_year, portfolio_not_rebalanced):
assert portfolio_rebalanced_year.weights_ts["RGBITR.INDX"].iloc[-2] == approx(0.4645, rel=1e-2)
def test_weights_ts_not_rebalanced(portfolio_not_rebalanced):
assert portfolio_not_rebalanced.weights_ts["RGBITR.INDX"].iloc[-1] == approx(0.4156, rel=1e-2)
def test_mean_return(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.mean_return_monthly == approx(0.01536, rel=1e-2)
assert portfolio_rebalanced_month.mean_return_annual == approx(0.20080, rel=1e-2)
def test_real_mean_return(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.real_mean_return == approx(0.13746, rel=1e-2)
@mark.parametrize(
"window, real, expected",
[(1, True, 0.01100), (12, False, 0.24604), (12, True, 0.2165)],
)
def test_get_rolling_cumulative_return(portfolio_rebalanced_month, window, real, expected):
assert portfolio_rebalanced_month.get_rolling_cumulative_return(window=window, real=real).iloc[-1, 0] == approx(
expected, abs=1e-1
)
def test_assets_close_monthly(portfolio_not_rebalanced):
assert portfolio_not_rebalanced.assets_close_monthly.iloc[-1, 0] == approx(578.19, rel=1e-2) # RGBITR.INDX
assert portfolio_not_rebalanced.assets_close_monthly.iloc[-1, 1] == 5245.6 # MCFTR.INDX
def test_close_monthly(portfolio_not_rebalanced):
assert portfolio_not_rebalanced.close_monthly.iloc[-1] == approx(2501.89, rel=1e-2)
def test_get_assets_dividends(portfolio_dividends):
assert portfolio_dividends._get_assets_dividends().iloc[-1, 0] == approx(0, abs=1e-2)
# T.US 2020-01=$0.3927 , RUBUSD=63.03 ( http://joxi.ru/823dnYWizBvEOA )
# T.US 2020-01=$0.5200 , RUBUSD=63.03 ( http://joxi.ru/Grqjdaliz5Ow9m ) 04.09.2022
# T.US 2020-01-09, 0.5200 from EOD
assert portfolio_dividends._get_assets_dividends().iloc[-1, 1] == approx(32.77, rel=1e-2)
assert portfolio_dividends._get_assets_dividends().iloc[-1, 2] == approx(0, rel=1e-2)
def test_number_of_securities(portfolio_not_rebalanced, portfolio_dividends):
assert portfolio_not_rebalanced.number_of_securities.iloc[-1, 0] == approx(1.798, rel=1e-2) # RGBITR.INDX
assert portfolio_not_rebalanced.number_of_securities.iloc[-1, 1] == approx(0.2787, abs=1e-2) # MCFTR.INDX
# with dividends
assert portfolio_dividends.number_of_securities.iloc[-1, 0] == approx(3.97, rel=1e-2) # SBER.MOEX
assert portfolio_dividends.number_of_securities.iloc[-1, 1] == approx(0.425, abs=1e-2) # T.US
assert portfolio_dividends.number_of_securities.iloc[-1, 2] == approx(0.392, abs=1e-2) # GNS.LSE
def test_dividends(portfolio_dividends):
assert portfolio_dividends.dividends.iloc[-1] == approx(13.96, rel=1e-2)
def test_dividend_yield(portfolio_dividends):
assert portfolio_dividends.dividend_yield.iloc[-1] == approx(0.0396, abs=1e-2)
def test_risk(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.risk_monthly == approx(0.02233, rel=1e-1)
assert portfolio_rebalanced_month.risk_annual == approx(0.091634, rel=1e-1)
def test_semideviation(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.semideviation_monthly == approx(0.02080, abs=1e-2)
assert portfolio_rebalanced_month.semideviation_annual == approx(0.04534, abs=1e-2)
def test_get_var_historic(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.get_var_historic(time_frame=1, level=5) == approx(0.01500, abs=1e-2)
assert portfolio_rebalanced_month.get_var_historic(time_frame=5, level=1) == approx(0.0491, abs=1e-2)
def test_get_cvar_historic(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.get_cvar_historic(time_frame=1, level=5) == approx(0.02577, abs=1e-2)
assert portfolio_rebalanced_month.get_cvar_historic(time_frame=5, level=1) == approx(0.04918, abs=1e-2)
def test_drawdowns(portfolio_not_rebalanced):
assert portfolio_not_rebalanced.drawdowns.min() == approx(-0.0560, rel=1e-2)
def test_recovery_period(portfolio_not_rebalanced):
assert portfolio_not_rebalanced.recovery_period == 6
def test_get_cagr(portfolio_rebalanced_month, portfolio_no_inflation):
values1 = pd.Series({"pf1.PF": 0.1974, "RUB.INFL": 0.055480})
actual1 = portfolio_rebalanced_month.get_cagr()
assert_series_equal(actual1, values1, atol=1e-2)
# no inflation
values2 = pd.Series({"pf1.PF": 0.1974})
actual2 = portfolio_no_inflation.get_cagr()
assert_series_equal(actual2, values2, atol=1e-2)
# failing if wrong period
with pytest.raises(TypeError):
portfolio_rebalanced_month.get_cagr(period="one year")
cagr_testdata1 = [
(1, 0.21655),
(None, 0.13446),
]
@mark.parametrize(
"input_data, expected",
cagr_testdata1,
ids=["1 year", "full period"],
)
def test_get_cagr_real(portfolio_rebalanced_month, input_data, expected):
assert portfolio_rebalanced_month.get_cagr(period=input_data, real=True).values[0] == approx(expected, abs=1e-2)
def test_get_cagr_real_no_inflation_exception(portfolio_no_inflation):
with pytest.raises(ValueError):
portfolio_no_inflation.get_cagr(period=1, real=True)
@mark.parametrize(
"period, real, expected",
[("YTD", False, 0.01505), (1, False, 0.24604), (2, True, 0.2742)],
ids=["YTD - nominal", "1 year - nominal", "2 years - real"],
)
def test_cumulative_return(portfolio_rebalanced_month, period, real, expected):
assert portfolio_rebalanced_month.get_cumulative_return(period=period, real=real).iloc[0] == approx(
expected, abs=1e-2
)
cumulative_return_fail = [
(1.5, False, TypeError),
(-1, False, ValueError),
(1, True, ValueError),
]
@mark.parametrize("period, real, exception", cumulative_return_fail)
def test_cumulative_return_error(portfolio_no_inflation, period, real, exception):
with pytest.raises(exception):
portfolio_no_inflation.get_cumulative_return(period=period, real=real)
def test_describe_inflation(portfolio_rebalanced_month):
description = portfolio_rebalanced_month.describe()
description_sample = pd.read_pickle(conftest.data_folder / "portfolio_description.pkl")
assert_frame_equal(description, description_sample, check_dtype=False, check_column_type=False, atol=1e-2)
def test_describe_no_inflation(portfolio_no_inflation):
description = portfolio_no_inflation.describe()
description_sample = pd.read_pickle(conftest.data_folder / "portfolio_description_no_inflation.pkl")
assert_frame_equal(description, description_sample, check_dtype=False, check_column_type=False, atol=1e-2)
def test_percentile_from_history(portfolio_rebalanced_month, portfolio_no_inflation, portfolio_short_history):
assert portfolio_rebalanced_month.percentile_history_cagr(years=1).iloc[0, 1] == approx(0.173181, abs=1e-2)
assert portfolio_no_inflation.percentile_history_cagr(years=1).iloc[0, 1] == approx(0.17318, abs=1e-2)
with pytest.raises(
ValueError,
match="Time series does not have enough history to forecast. "
"Period length is 0.90 years. At least 2 years are required.",
):
portfolio_short_history.percentile_history_cagr(years=1)
@mark.parametrize(
"distribution, expected",
[("hist", 0), ("norm", 0.9), ("lognorm", 0.7)],
)
def test_percentile_inverse_cagr(portfolio_rebalanced_month, distribution, expected):
assert portfolio_rebalanced_month.percentile_inverse_cagr(distr=distribution, years=1, score=0, n=5000) == approx(
expected, abs=1e-0
)
def test_table(portfolio_rebalanced_month):
assert_array_equal(
portfolio_rebalanced_month.table["ticker"].values,
np.array(["RGBITR.INDX", "MCFTR.INDX"]),
)
@mark.parametrize(
"window, real, expected",
[(12, False, 0.1290), (24, True, 0.17067)],
)
def test_get_rolling_cagr(portfolio_rebalanced_month, window, real, expected):
assert portfolio_rebalanced_month.get_rolling_cagr(window=window, real=real).iloc[0, -1] == approx(
expected, abs=1e-2
)
def test_get_rolling_cagr_failing_short_window(portfolio_not_rebalanced):
with pytest.raises(ValueError, match="window size should be at least 1 year"):
portfolio_not_rebalanced.get_rolling_cagr(window=1)
def test_get_rolling_cagr_failing_long_window(portfolio_not_rebalanced):
with pytest.raises(ValueError, match="window size is more than data history depth"):
portfolio_not_rebalanced.get_rolling_cagr(window=100)
def test_get_rolling_cagr_failing_no_inflation(portfolio_no_inflation):
with pytest.raises(
ValueError,
match="Real return is not defined. Set inflation=True when initiating the class.",
):
portfolio_no_inflation.get_rolling_cagr(real=True)
def test_monte_carlo_wealth(portfolio_rebalanced_month):
assert portfolio_rebalanced_month._monte_carlo_wealth(distr="norm", years=1, n=1000).iloc[-1, :].mean() == approx(
3005.763, rel=1e-1
)
@mark.parametrize(
"distribution, expected",
[("hist", 2931.484), ("norm", 3062.036), ("lognorm", 3030.9024)],
)
def test_percentile_wealth(portfolio_rebalanced_month, distribution, expected):
dic = portfolio_rebalanced_month.percentile_wealth(distr=distribution, years=1, n=100, percentiles=[50])
assert dic[50] == approx(expected, rel=1e-1)
def test_forecast_monte_carlo_cagr(portfolio_rebalanced_month):
dic = portfolio_rebalanced_month.percentile_distribution_cagr(years=2, distr="lognorm", n=100, percentiles=[50])
assert dic[50] == approx(0.1905, abs=5e-2)
with pytest.raises(ValueError):
portfolio_rebalanced_month.percentile_distribution_cagr(years=10, distr="lognorm", n=100, percentiles=[50])
def test_skewness(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.skewness.iloc[-1] == approx(0.4980, abs=1e-1)
def test_rolling_skewness(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.skewness_rolling(window=24).iloc[-1] == approx(0.4498, abs=1e-1)
def test_kurtosis(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.kurtosis.iloc[-1] == approx(1.463, rel=1e-2)
def test_kurtosis_rolling(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.kurtosis_rolling(window=24).iloc[-1] == approx(-0.2498, rel=1e-1)
def test_jarque_bera(portfolio_rebalanced_month):
assert portfolio_rebalanced_month.jarque_bera["statistic"] == approx(6.3657, rel=1e-1)
def test_get_sharpe_ratio(portfolio_no_inflation):
assert portfolio_no_inflation.get_sharpe_ratio(rf_return=0.05) == approx(1.6457, abs=1e-1)
def test_get_sortino_ratio(portfolio_no_inflation):
assert portfolio_no_inflation.get_sortino_ratio(t_return=0.05) == approx(2.2766, rel=1e-2)
def test_diversification_ratio(portfolio_no_inflation):
assert portfolio_no_inflation.diversification_ratio == approx(1.2961, rel=1e-2)
# This test should be a last one, as it changes the weights
def test_init_portfolio_failing():
with pytest.raises(
ValueError,
match=r"Number of tickers \(2\) should be equal to the weights number \(3\)",
):
ok.Portfolio(["RGBITR.INDX", "MCFTR.INDX"], weights=[0.1, 0.2, 0.7])
with pytest.raises(ValueError, match="Weights sum is not equal to one."):
ok.Portfolio(["RGBITR.INDX", "MCFTR.INDX"], weights=[0.1, 0.2])