-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperformance.py
More file actions
115 lines (86 loc) · 3.14 KB
/
Copy pathperformance.py
File metadata and controls
115 lines (86 loc) · 3.14 KB
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
from __future__ import annotations
"""
Performance Analytics Module
Reads backtest results CSV and computes:
• CAGR
• Sharpe Ratio
• Max Drawdown
• Profit Factor
• Number of Trades
• Average Holding Period
Assumptions:
------------
- Trades are sequential (no overlapping positions)
- Capital fully allocated per trade
- No compounding during trade
- Equity updated at trade exit
- Initial capital = 1.0 (normalized)
"""
from dataclasses import dataclass
from pathlib import Path
from typing import Dict
import numpy as np
import pandas as pd
@dataclass
class PerformanceReport:
log_path: str | Path
risk_free_rate: float = 0.0 # annual risk-free
def generate(self) -> Dict[str, float]:
df = pd.read_csv(self.log_path)
if df.empty:
raise ValueError("Log file is empty")
df["entry_time"] = pd.to_datetime(df["entry_time"])
df["exit_time"] = pd.to_datetime(df["exit_time"])
df = df.sort_values("exit_time")
# ================================
# Basic Trade Metrics
# ================================
number_of_trades = len(df)
gross_profit = df.loc[df["pnl"] > 0, "pnl"].sum()
gross_loss = -df.loc[df["pnl"] < 0, "pnl"].sum()
profit_factor = gross_profit / gross_loss if gross_loss != 0 else np.inf
holding_periods = (df["exit_time"] - df["entry_time"]).dt.total_seconds() / 3600
avg_holding_hours = holding_periods.mean()
# ================================
# Equity Curve Construction
# ================================
equity = 1.0
equity_curve = []
for pnl in df["pnl"]:
equity += pnl
equity_curve.append(equity)
equity_curve = np.array(equity_curve)
# ================================
# CAGR
# ================================
start_date = df["entry_time"].min()
end_date = df["exit_time"].max()
total_years = (end_date - start_date).days / 365.25
final_equity = equity_curve[-1]
cagr = (final_equity / 1.0) ** (1 / total_years) - 1 if total_years > 0 else 0
# ================================
# Sharpe Ratio
# ================================
returns = np.diff(equity_curve, prepend=1.0)
returns_pct = returns / equity_curve[:-1].mean() if len(returns) > 1 else np.array([0])
if returns_pct.std() != 0:
sharpe = (
(returns_pct.mean() - self.risk_free_rate / 252)
/ returns_pct.std()
) * np.sqrt(252)
else:
sharpe = 0.0
# ================================
# Max Drawdown
# ================================
running_max = np.maximum.accumulate(equity_curve)
drawdowns = (equity_curve - running_max) / running_max
max_drawdown = drawdowns.min()
return {
"CAGR": cagr,
"Sharpe": sharpe,
"Max Drawdown": max_drawdown,
"Profit Factor": profit_factor,
"Number of Trades": number_of_trades,
"Average Holding Period (hours)": avg_holding_hours,
}