Skip to content

Commit e84d398

Browse files
committed
chore: refactor describe method in AssetList and Portfolio
1 parent 7537dca commit e84d398

File tree

4 files changed

+32
-50
lines changed

4 files changed

+32
-50
lines changed

main.py

Lines changed: 3 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -12,29 +12,7 @@
1212

1313
pd.set_option("display.float_format", lambda x: "%.2f" % x)
1414

15-
ls_m = ["SPY.US", "GLD.US", "PGJ.US", "RGBITR.INDX", "MCFTR.INDX"]
16-
curr_rub = "RUB"
17-
18-
# x = ok.EfficientFrontier(
19-
# assets=ls_m,
20-
# first_date="2005-01",
21-
# last_date="2020-11",
22-
# ccy=curr_rub,
23-
# # rebalancing_strategy=ok.Rebalance(period="year"), # set rebalancing period to one year
24-
# n_points=20,
25-
# verbose=False,
26-
# )
27-
28-
x = ok.EfficientFrontier(
29-
assets=ls_m,
30-
first_date="2005-01",
31-
last_date="2020-11",
32-
ccy=curr_rub,
33-
n_points=40,
34-
# rebalancing_strategy=ok.Rebalance(period="year"), # set rebalancing period to one year
35-
)
36-
37-
x.plot_transition_map(x_axe="risk")
38-
39-
plt.show()
15+
a = ok.Inflation('RUB.INFL' ,first_date="2000-01-01")
16+
17+
print(a)
4018

okama/asset_list.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -744,14 +744,14 @@ def describe(self, years: Tuple[int, ...] = (1, 5, 10), tickers: bool = True) ->
744744
6 Risk 17 years, 10 months 0.037796 0.158301 NaN
745745
7 CVAR 17 years, 10 months 0.023107 0.399398 NaN
746746
"""
747-
description = pd.DataFrame()
747+
rows_list = []
748748
dt0 = self.last_date
749749
df = self._add_inflation()
750750
# YTD return
751751
ytd_return = self.get_cumulative_return(period="YTD")
752752
row = ytd_return.to_dict()
753753
row.update(period="YTD", property="Compound return")
754-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
754+
rows_list.append(row)
755755
# CAGR for a list of periods
756756
if self.pl.years >= 1:
757757
for i in years:
@@ -761,39 +761,39 @@ def describe(self, years: Tuple[int, ...] = (1, 5, 10), tickers: bool = True) ->
761761
else:
762762
row = {x: None for x in df.columns}
763763
row.update(period=f"{i} years", property="CAGR")
764-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
764+
rows_list.append(row)
765765
# CAGR for full period
766766
row = self.get_cagr(period=None).to_dict()
767767
row.update(period=self._pl_txt, property="CAGR")
768-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
768+
rows_list.append(row)
769769
# Mean rate of return (arithmetic mean)
770770
row = self.mean_return.to_dict()
771771
row.update(
772772
period=self._pl_txt,
773773
property="Annualized mean return",
774774
)
775-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
775+
rows_list.append(row)
776776
# Dividend Yield
777777
row = self._assets_dividend_yield.iloc[-1].to_dict()
778778
row.update(period="LTM", property="Dividend yield")
779-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
779+
rows_list.append(row)
780780
# risk for full period
781781
row = self.risk_annual.iloc[-1, :].to_dict()
782782
row.update(period=self._pl_txt, property="Risk")
783-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
783+
rows_list.append(row)
784784
# CVAR
785785
if self.pl.years >= 1:
786786
row = self.get_cvar_historic().to_dict()
787787
row.update(period=self._pl_txt, property="CVAR")
788-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
788+
rows_list.append(row)
789789
# max drawdowns
790790
row = self.drawdowns.min().to_dict()
791791
row.update(period=self._pl_txt, property="Max drawdowns")
792-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
792+
rows_list.append(row)
793793
# max drawdowns dates
794794
row = self.drawdowns.idxmin().to_dict()
795795
row.update(period=self._pl_txt, property="Max drawdowns dates")
796-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
796+
rows_list.append(row)
797797
# inception dates
798798
row = {}
799799
for ti in self.symbols:
@@ -803,7 +803,7 @@ def describe(self, years: Tuple[int, ...] = (1, 5, 10), tickers: bool = True) ->
803803
row.update(period=None, property="Inception date")
804804
if hasattr(self, "inflation"):
805805
row.update({self.inflation: self.inflation_first_date.strftime("%Y-%m")})
806-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
806+
rows_list.append(row)
807807
# last asset date
808808
row = {}
809809
for ti in self.symbols:
@@ -813,11 +813,13 @@ def describe(self, years: Tuple[int, ...] = (1, 5, 10), tickers: bool = True) ->
813813
row.update(period=None, property="Last asset date")
814814
if hasattr(self, "inflation"):
815815
row.update({self.inflation: self.inflation_last_date.strftime("%Y-%m")})
816-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
816+
rows_list.append(row)
817817
# last data date
818818
row = {x: self.last_date.strftime("%Y-%m") for x in df.columns}
819819
row.update(period=None, property="Common last data date")
820-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
820+
rows_list.append(row)
821+
# Create DataFrame from list of rows
822+
description = pd.DataFrame(rows_list)
821823
# rename columns
822824
if hasattr(self, "inflation"):
823825
description.rename(columns={self.inflation: "inflation"}, inplace=True)

okama/common/helpers/helpers.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,9 +225,9 @@ def get_annual_return_ts_from_monthly(
225225
Annual Rate of Returns time series from monthly data.
226226
"""
227227
if return_type.lower() == "cagr":
228-
ts = ror_monthly.resample("A").apply(lambda x: np.prod(x + 1.0) - 1)
228+
ts = ror_monthly.resample("Y").apply(lambda x: np.prod(x + 1.0) - 1)
229229
elif return_type.lower() == "arithmetic_mean":
230-
ts = ror_monthly.resample("A").sum()
230+
ts = ror_monthly.resample("Y").sum()
231231
else:
232232
raise ValueError("Return type must be either cagr or arithmetic_mean.")
233233
if isinstance(ts, pd.Series):

okama/portfolios/core.py

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1291,14 +1291,14 @@ def describe(self, years: Tuple[int] = (1, 5, 10)) -> pd.DataFrame:
12911291
8 Max drawdown 14 years, 3 months -0.266915 NaN
12921292
9 Max drawdown date 14 years, 3 months 2009-02 NaN
12931293
"""
1294-
description = pd.DataFrame()
1294+
rows_list = []
12951295
dt0 = self.last_date
12961296
df = self._add_inflation()
12971297
# YTD return
12981298
ytd_return = self.get_cumulative_return(period="YTD")
12991299
row = ytd_return.to_dict()
13001300
row.update(period="YTD", property="compound return")
1301-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
1301+
rows_list.append(row)
13021302
# CAGR for a list of periods
13031303
if self.pl.years >= 1:
13041304
for i in years:
@@ -1308,56 +1308,58 @@ def describe(self, years: Tuple[int] = (1, 5, 10)) -> pd.DataFrame:
13081308
else:
13091309
row = {x: None for x in df.columns} if hasattr(self, "inflation") else {self.symbol: None}
13101310
row.update(period=f"{i} years", property="CAGR")
1311-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
1311+
rows_list.append(row)
13121312
# CAGR for full period
13131313
row = self.get_cagr(period=None).to_dict()
13141314
row.update(
13151315
period=self._pl_txt,
13161316
property="CAGR",
13171317
)
1318-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
1318+
rows_list.append(row)
13191319
# Mean rate of return (arithmetic mean)
13201320
value = self.mean_return_annual
13211321
row = {self.symbol: value}
13221322
row.update(
13231323
period=self._pl_txt,
13241324
property="Annualized mean return",
13251325
)
1326-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
1326+
rows_list.append(row)
13271327
# Dividend Yield
13281328
value = self.dividend_yield.iloc[-1]
13291329
row = {self.symbol: value}
13301330
row.update(
13311331
period="LTM",
13321332
property="Dividend yield",
13331333
)
1334-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
1334+
rows_list.append(row)
13351335
# risk (standard deviation)
13361336
row = {self.symbol: self.risk_annual.iloc[-1]}
13371337
row.update(period=self._pl_txt, property="Risk")
1338-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
1338+
rows_list.append(row)
13391339
# CVAR
13401340
if self.pl.years >= 1:
13411341
row = {self.symbol: self.get_cvar_historic(level=1)}
13421342
row.update(
13431343
period=self._pl_txt,
13441344
property="CVAR (α=1)",
13451345
)
1346-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
1346+
rows_list.append(row)
13471347
# max drawdowns
13481348
row = {self.symbol: self.drawdowns.min()}
13491349
row.update(
13501350
period=self._pl_txt,
13511351
property="Max drawdown",
13521352
)
1353-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
1353+
rows_list.append(row)
13541354
# max drawdowns dates
13551355
row = {self.symbol: self.drawdowns.idxmin()}
13561356
row.update(
13571357
period=self._pl_txt,
13581358
property="Max drawdown date",
13591359
)
1360-
description = pd.concat([description, pd.DataFrame(row, index=[0])], ignore_index=True)
1360+
rows_list.append(row)
1361+
# Create DataFrame from list of rows
1362+
description = pd.DataFrame(rows_list)
13611363
if hasattr(self, "inflation"):
13621364
description.rename(columns={self.inflation: "inflation"}, inplace=True)
13631365
description = helpers.Frame.change_columns_order(description, ["property", "period", self.symbol])

0 commit comments

Comments
 (0)