added sharpe ratio

This commit is contained in:
Gourav Kumar 2022-04-29 07:43:06 +05:30
parent 0f002f3478
commit 336cf41ca8
3 changed files with 51 additions and 23 deletions

View File

@ -1,3 +1,4 @@
from .core import * from .core import *
from .fincal import * from .fincal import *
from .statistics import *
from .utils import * from .utils import *

22
fincal/statistics.py Normal file
View File

@ -0,0 +1,22 @@
from .fincal import TimeSeries
def sharpe_ratio(
time_series_data: TimeSeries, risk_free_data: TimeSeries = None, risk_free_rate: float = None, **kwargs
):
pass
if risk_free_data is None and risk_free_rate is None:
raise ValueError("At least one of risk_free_data or risk_free rate is required")
returns_ts = time_series_data.calculate_rolling_returns(**kwargs)
if risk_free_data is not None:
risk_free_data = returns_ts.sync(risk_free_data)
else:
risk_free_data = risk_free_rate
excess_returns = returns_ts - risk_free_data
sd = time_series_data.volatility(**kwargs)
sharpe_ratio = excess_returns.mean() / sd
return sharpe_ratio

51
test.py
View File

@ -1,29 +1,34 @@
# from fincal.core import FincalOptions # from fincal.core import FincalOptions
from fincal.fincal import TimeSeries import fincal as fc
data = [ data = [
("2022-01-01", 10), ("2022-01-01", 150),
("2022-01-02", 12), ("2022-01-02", 152),
("2022-01-03", 14), ("2022-01-03", 151),
("2022-01-04", 16), ("2022-01-04", 154),
("2022-01-06", 18), ("2022-01-05", 150),
("2022-01-07", 20), ("2022-01-06", 157),
("2022-01-09", 22), ("2022-01-07", 155),
("2022-01-10", 24), ("2022-01-08", 158),
("2022-01-11", 26), ("2022-01-09", 162),
("2022-01-13", 28), ("2022-01-10", 160),
("2022-01-14", 30), ("2022-01-11", 156),
("2022-01-15", 32), ("2022-01-12", 162),
("2022-01-16", 34), ("2023-01-01", 164),
("2023-01-02", 161),
("2023-01-03", 167),
("2023-01-04", 168),
] ]
ts = TimeSeries(data, frequency="D") ts = fc.TimeSeries(data, frequency="D", date_format="%Y-%d-%m")
print(ts) print(ts)
data = [("2022-01-01", 220), ("2022-01-08", 230), ("2022-01-15", 240)] sharpe = fc.sharpe_ratio(
ts2 = TimeSeries(data, frequency="W") ts,
print(ts2) risk_free_rate=(1 + 0.15) ** (1 / 12) - 1,
from_date="2022-02-01",
synced_ts = ts.sync(ts2) to_date="2023-04-01",
print("---------\n") frequency="M",
for i in synced_ts: return_period_unit="months",
print(i) return_period_value=1,
)
print(f"{sharpe=}")