"""Return prediction and portfolio tests that follow the paper. 1. Each month m, fit a cross sectional ridge regression r[i, t+1] = a_m + b_m' e[i, t] + error, with the penalty chosen by leave one out cross validation over a grid from 1e-10 to 1e10 (paper footnote 6). 2. The forecast in month m uses the average a and b of all earlier months, so every forecast is out of sample (paper equation 2). 3. Each day, buy the stocks with the highest forecasts and short the lowest, equal weighted, held for one day. """ import io import zipfile import numpy as np import pandas as pd import requests from scipy import stats from sklearn.linear_model import RidgeCV ALPHAS = np.logspace(-10, 10, 21) def monthly_fits(df, X, target="ret_next"): """One ridge fit per calendar month: {month: (intercept, coefficients, penalty)}.""" month = df["date"].dt.to_period("M") y = df[target].values fits = {} ok = np.isfinite(y) for m in sorted(month.unique()): idx = np.where((month == m) & ok)[0] r = RidgeCV(alphas=ALPHAS).fit(X[idx], y[idx]) fits[m] = (r.intercept_, r.coef_, r.alpha_) return fits def out_of_sample_forecasts(df, X, burn_in=6, target="ret_next"): """Forecast for month m from the averaged intercepts and slopes of months before m.""" fits = monthly_fits(df, X, target) months = sorted(fits) month = df["date"].dt.to_period("M") pred = pd.Series(np.nan, index=df.index) for k, m in enumerate(months): if k < burn_in: continue a = np.mean([fits[p][0] for p in months[:k]]) b = np.mean([fits[p][1] for p in months[:k]], axis=0) idx = np.where(month == m)[0] pred.iloc[idx] = a + X[idx] @ b penalties = pd.Series({m: f[2] for m, f in fits.items()}, name="ridge_penalty") return pred, penalties def cached_forecasts(df, X, path, burn_in=12, target="ret_next"): """out_of_sample_forecasts, saved to parquet so the notebook can be rerun quickly.""" import os if os.path.exists(path): pred = pd.read_parquet(path)["pred"].reindex(df.index) pen = pd.read_parquet(path.replace(".parquet", "_pen.parquet"))["ridge_penalty"] return pred, pen pred, pen = out_of_sample_forecasts(df, X, burn_in=burn_in, target=target) os.makedirs(os.path.dirname(path), exist_ok=True) pred.to_frame("pred").to_parquet(path) pen.index = pen.index.astype(str) pen.to_frame().to_parquet(path.replace(".parquet", "_pen.parquet")) return pred, pen def placebo_sharpes(df, n_draws=200, n_groups=10, seed=0): """H-L Sharpe ratios when stocks are ranked at random each day (the noise band).""" rng = np.random.default_rng(seed) out = [] for _ in range(n_draws): g = decile_returns(df, pd.Series(rng.random(len(df)), index=df.index), n_groups) out.append(sharpe(g["H-L"])) return np.array(out) def daily_ic(df, pred, target="ret_next"): """Spearman rank correlation between forecast and outcome, one value per day.""" d = df.assign(pred=pred).dropna(subset=["pred", target]) return d.groupby("date")[["pred", target]].apply( lambda g: g["pred"].corr(g[target], method="spearman")).dropna() def decile_returns(df, pred, n_groups=10, min_stocks=50): """Daily equal weighted return of each forecast group (1 = lowest) and of H-L.""" d = df[["date", "ret_next"]].assign(pred=pred).dropna(subset=["pred"]) d = d[d.groupby("date")["pred"].transform("size") >= min_stocks] rank = d.groupby("date")["pred"].rank(method="first") size = d.groupby("date")["pred"].transform("size") d["group"] = np.ceil(rank / size * n_groups).astype(int) out = d.pivot_table(index="date", columns="group", values="ret_next", aggfunc="mean") out["H-L"] = out[n_groups] - out[1] return out def performance_table(groups): """Annualised mean and SD in percent, and Sharpe ratio, for each column (paper Table 3).""" return pd.DataFrame({"mean %": groups.mean() * 252 * 100, "SD %": groups.std() * np.sqrt(252) * 100, "Sharpe": groups.mean() / groups.std() * np.sqrt(252)}) def long_short(df, score, n_groups=10, min_stocks=50): """Daily equal weighted top minus bottom group return.""" d = df.assign(score=score).dropna(subset=["score"]) rows = [] for date, g in d.groupby("date"): if len(g) < min_stocks: continue rank = g["score"].rank(method="first") bucket = np.ceil(rank / len(g) * n_groups).astype(int) long = g.loc[bucket == n_groups] short = g.loc[bucket == 1] rows.append({"date": date, "ret": long["ret_next"].mean() - short["ret_next"].mean(), "long": frozenset(long["ticker"]), "short": frozenset(short["ticker"])}) return pd.DataFrame(rows).set_index("date") def sharpe(r, periods=252): return np.sqrt(periods) * r.mean() / r.std(ddof=1) def turnover(ls): """Average share of each leg that is replaced from one day to the next.""" t = [] for prev, cur in zip(ls.iloc[:-1].itertuples(), ls.iloc[1:].itertuples()): for a, b in ((prev.long, cur.long), (prev.short, cur.short)): if b: t.append(1 - len(a & b) / len(b)) return float(np.mean(t)) def net_of_costs(ls, cost_bps): """Charge cost_bps per unit traded. Both legs trade, so daily cost = 2 x turnover x cost.""" return ls["ret"] - 2 * turnover(ls) * cost_bps / 1e4 def _hac_cov(u, lags): u = u - u.mean(0) T = len(u) S = u.T @ u / T for L in range(1, lags + 1): w = 1 - L / (lags + 1) G = u[L:].T @ u[:-L] / T S += w * (G + G.T) return S def sharpe_diff_test(r1, r2, lags=5): """Ledoit and Wolf (2008) test that two Sharpe ratios are equal (HAC delta method).""" x = pd.concat([r1, r2], axis=1).dropna().values m1, m2 = x.mean(0) g1, g2 = (x ** 2).mean(0) diff = m1 / np.sqrt(g1 - m1 ** 2) - m2 / np.sqrt(g2 - m2 ** 2) u = np.column_stack([x[:, 0], x[:, 1], x[:, 0] ** 2, x[:, 1] ** 2]) psi = _hac_cov(u, lags) grad = np.array([g1 / (g1 - m1 ** 2) ** 1.5, -g2 / (g2 - m2 ** 2) ** 1.5, -0.5 * m1 / (g1 - m1 ** 2) ** 1.5, 0.5 * m2 / (g2 - m2 ** 2) ** 1.5]) se = np.sqrt(grad @ psi @ grad / len(x)) z = diff / se return np.sqrt(252) * diff, 2 * (1 - stats.norm.cdf(abs(z))) FF5 = "https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Research_Data_5_Factors_2x3_daily_CSV.zip" MOM = "https://mba.tuck.dartmouth.edu/pages/faculty/ken.french/ftp/F-F_Momentum_Factor_daily_CSV.zip" def _french(url): raw = requests.get(url, timeout=60).content with zipfile.ZipFile(io.BytesIO(raw)) as z: text = z.read(z.namelist()[0]).decode("latin-1") lines = text.splitlines() start = next(i for i, l in enumerate(lines) if l.strip()[:8].isdigit()) - 1 df = pd.read_csv(io.StringIO("\n".join(lines[start:])), index_col=0) df = df[df.index.astype(str).str.strip().str.fullmatch(r"\d{8}")] df.index = pd.to_datetime(df.index.astype(str).str.strip(), format="%Y%m%d") df.columns = [c.strip() for c in df.columns] return df.astype(float) / 100 def french_factors(): """Daily Fama French five factors plus momentum from Ken French's website.""" return _french(FF5).join(_french(MOM), how="inner") def factor_alpha(r, factors, cols=("Mkt-RF", "SMB", "HML", "RMW", "CMA", "Mom")): """OLS of the long short return on the factors with Newey West errors.""" import statsmodels.api as sm d = pd.concat([r.rename("ls"), factors[list(cols)]], axis=1, join="inner").dropna() fit = sm.OLS(d["ls"], sm.add_constant(d[list(cols)])).fit(cov_type="HAC", cov_kwds={"maxlags": 5}) return fit