Skip to content

Commit

Permalink
sharpe for constant series (#428)
Browse files Browse the repository at this point in the history
* sharpe for constant series

* fmt

* address log warnings (#429)
  • Loading branch information
tschm authored Nov 9, 2024
1 parent e22ad7a commit 7f72596
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 7 deletions.
4 changes: 2 additions & 2 deletions cvx/simulator/portfolio.py
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,7 @@ def snapshot(
table.loc[label_strategy, "end"] = self.nav.index[-1].strftime("%Y-%m-%d")
table.loc[label_strategy, "# assets"] = len(self.assets)

s = sharpe(self.nav.pct_change().dropna())
s = sharpe(self.nav.ffill().pct_change(fill_method=None).dropna())
table.loc[label_strategy, "Sharpe ratio"] = f"{s:.2f}"

if benchmark is not None:
Expand All @@ -372,7 +372,7 @@ def snapshot(
table_bench.loc[label_benchmark, "# assets"] = ""
table_bench.loc[
label_benchmark, "Sharpe ratio"
] = f"{sharpe(benchmark.pct_change().dropna()):.2f}"
] = f"{sharpe(benchmark.ffill().pct_change(fill_method=None).dropna()):.2f}"

table = pd.concat([table, table_bench], axis=0)

Expand Down
13 changes: 8 additions & 5 deletions cvx/simulator/utils/metric.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from math import sqrt

import numpy as np
import pandas as pd


Expand All @@ -8,12 +7,16 @@ def _periods(ts):
compute the number of periods in a time series
"""
series = pd.Series(data=ts.index)
return 365 * 24 * 60 * 60 / (series.diff().mean().total_seconds())
return 365 * 24 * 60 * 60 / (series.diff().dropna().mean().total_seconds())


def sharpe(ts, n=None):
"""
compute the sharpe ratio of a time series
"""
n = n or _periods(ts)
return ts.mean() / ts.std() * sqrt(n)
std = ts.std()
if std > 0:
n = n or _periods(ts)
return (ts.mean() / std) * np.sqrt(n)
else:
return np.inf

0 comments on commit 7f72596

Please sign in to comment.