-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegression.py
More file actions
133 lines (106 loc) · 4.56 KB
/
Copy pathRegression.py
File metadata and controls
133 lines (106 loc) · 4.56 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
import numpy as np
import pandas as pd
def align_ff5_clock(ff5_df: pd.DataFrame, shift_months: int = 1) -> pd.DataFrame:
ff5 = ff5_df.copy()
ff5.columns = [column.strip() for column in ff5.columns]
required = ["Mkt-RF", "SMB", "HML", "RMW", "CMA", "RF"]
if ff5[required].abs().max().max() > 1:
ff5[required] = ff5[required] / 100.0
ff5.index = pd.to_datetime(ff5.index) + pd.DateOffset(months=shift_months)
return ff5
class FF5Regression:
def __init__(self, price_df: pd.DataFrame, ff5_df: pd.DataFrame):
self.price_df = price_df.copy()
self.ff5_df = ff5_df.copy()
self.returns = None
self.ff5_clean = None
def compute_returns(self) -> pd.DataFrame:
df = self.price_df.copy()
if "Date" in df.columns:
df["Date"] = pd.to_datetime(df["Date"])
df = df.set_index("Date")
df = df.select_dtypes(include=[np.number])
returns = df.pct_change().iloc[1:]
returns = returns.loc[:, returns.isna().mean() < 0.2]
self.returns = returns
return returns
def prepare_ff5(self, shift_months: int = 1) -> pd.DataFrame:
# Price data are stamped at the first day of each month, so the return
# indexed by 2024-04-01 represents the realized move over March. Shift
# FF5 monthly factors forward so they align with the month-start return
# labels used throughout the backtest.
ff5 = align_ff5_clock(self.ff5_df, shift_months=shift_months)
self.ff5_clean = ff5
return ff5
def run_single_regression(self, ticker: str, ridge_alpha: float = 0.0) -> dict:
if self.returns is None:
self.compute_returns()
if self.ff5_clean is None:
self.prepare_ff5()
common_idx = self.returns.index.intersection(self.ff5_clean.index)
y_stock = self.returns.loc[common_idx, ticker]
risk_free = self.ff5_clean.loc[common_idx, "RF"]
y = (y_stock - risk_free).values
factor_values = self.ff5_clean.loc[
common_idx, ["Mkt-RF", "SMB", "HML", "RMW", "CMA"]
].values
x_mat = np.column_stack((np.ones(len(factor_values)), factor_values))
valid_mask = ~np.isnan(y)
if valid_mask.sum() < 6:
raise ValueError(f"[WARNING] {ticker} does not have enough valid observations.")
x_valid = x_mat[valid_mask]
y_valid = y[valid_mask]
if ridge_alpha > 0:
penalty = np.eye(x_valid.shape[1]) * ridge_alpha
penalty[0, 0] = 0.0
betas = np.linalg.solve(x_valid.T @ x_valid + penalty, x_valid.T @ y_valid)
else:
betas, _, _, _ = np.linalg.lstsq(x_valid, y_valid, rcond=None)
return {
"ticker": ticker,
"alpha": betas[0],
"beta_mkt": betas[1],
"beta_smb": betas[2],
"beta_hml": betas[3],
"beta_rmw": betas[4],
"beta_cma": betas[5],
}
def run_all_regression(self, ridge_alpha: float = 0.0) -> pd.DataFrame:
if self.returns is None:
self.compute_returns()
if self.ff5_clean is None:
self.prepare_ff5()
common_idx = self.returns.index.intersection(self.ff5_clean.index)
all_returns = self.returns.loc[common_idx]
factor_values = self.ff5_clean.loc[
common_idx, ["Mkt-RF", "SMB", "HML", "RMW", "CMA"]
]
risk_free = self.ff5_clean.loc[common_idx, "RF"]
excess_returns = all_returns.sub(risk_free, axis=0)
x_mat = np.column_stack((np.ones(len(factor_values)), factor_values.values))
penalty = np.eye(x_mat.shape[1]) * ridge_alpha
penalty[0, 0] = 0.0
results = []
for ticker in excess_returns.columns:
y = excess_returns[ticker].values
valid_mask = ~np.isnan(y)
if valid_mask.sum() < 6:
continue
x_valid = x_mat[valid_mask]
y_valid = y[valid_mask]
if ridge_alpha > 0:
betas = np.linalg.solve(x_valid.T @ x_valid + penalty, x_valid.T @ y_valid)
else:
betas, _, _, _ = np.linalg.lstsq(x_valid, y_valid, rcond=None)
results.append(
{
"ticker": ticker,
"alpha": betas[0],
"beta_mkt": betas[1],
"beta_smb": betas[2],
"beta_hml": betas[3],
"beta_rmw": betas[4],
"beta_cma": betas[5],
}
)
return pd.DataFrame(results)