27 lines
924 B
Python
27 lines
924 B
Python
from __future__ import annotations
|
|
import math
|
|
import pandas as pd
|
|
from typing import Dict
|
|
|
|
def portfolio_metrics(equity: pd.Series) -> Dict[str, float]:
|
|
if equity.empty or equity.iloc[0] <= 0:
|
|
return {"max_dd": 0.0, "sharpe": 0.0, "cagr": 0.0}
|
|
|
|
roll_max = equity.cummax()
|
|
dd = (equity/roll_max) - 1.0
|
|
max_dd = float(dd.min())
|
|
|
|
rets = equity.pct_change().dropna()
|
|
if rets.empty or rets.std(ddof=0) == 0:
|
|
sharpe = 0.0
|
|
else:
|
|
periods_per_year = 365*24*60 # dla 1m
|
|
sharpe = float((rets.mean()/rets.std(ddof=0)) * math.sqrt(periods_per_year))
|
|
|
|
t0 = pd.to_datetime(equity.index[0], unit="ms", utc=True)
|
|
t1 = pd.to_datetime(equity.index[-1], unit="ms", utc=True)
|
|
years = max((t1 - t0).total_seconds() / (365.25*24*3600), 1e-9)
|
|
cagr = float((equity.iloc[-1]/equity.iloc[0])**(1/years) - 1.0)
|
|
|
|
return {"max_dd": max_dd, "sharpe": sharpe, "cagr": cagr}
|