jumper-dashboard / scripts /analyze_feature_stability.py
ymo2017's picture
Upload folder using huggingface_hub
529299c verified
Raw History Blame Contribute Delete
2.67 kB
import sys
import os
sys.path.append(os.getcwd())
import numpy as np
import pandas as pd
import importlib.util
import argparse
from lib.backtest_utils import load_data, DEFAULT_TICKERS
"""
Script used to identify unstable features in P69 by comparing Ridge coefficients
across three overlapping 10-year training windows.
"""
def analyze(policy_id='P69'):
# Load data
df = load_data('data', DEFAULT_TICKERS)
# Load policy config
param_path = f'policies/params/{policy_id}.py'
if not os.path.exists(param_path):
print(f"Error: Parameter file {param_path} not found.")
return
spec = importlib.util.spec_from_file_location(policy_id, param_path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
total = len(df)
windows = [('W1', 0, int(total*0.45)), ('W2', int(total*0.25), int(total*0.75)), ('W3', int(total*0.55), total)]
all_coefs = {}
for label, start, end in windows:
df_slice = df.iloc[start:end].reset_index(drop=True)
policy = mod.POLICY_CLASS(**mod.PARAMS)
policy.fit(df_slice)
features = policy._feat_order
# Average absolute coef across all ticker models
avg_coef = np.zeros(len(features))
for m in policy.models:
avg_coef += np.abs(m.coef_)
avg_coef /= len(policy.models)
all_coefs[label] = dict(zip(features, avg_coef))
actual_dates = df.iloc[start:end].index
print(f'Trained on {label}: {actual_dates[0].date()} to {actual_dates[-1].date()} ({len(df_slice)} rows)')
# Build comparison table
features = sorted(all_coefs[list(all_coefs.keys())[0]].keys())
rows = []
for f in features:
vals = [all_coefs[w].get(f, 0) for w in all_coefs]
mean_imp = np.mean(vals)
std_imp = np.std(vals)
cv = std_imp / (mean_imp + 1e-10) # coefficient of variation
rows.append((f, vals[0], vals[1], vals[2], mean_imp, std_imp, cv))
# Sort by instability (CV)
rows.sort(key=lambda x: x[6], reverse=True)
print()
print(f"{'Feature':35s} {'W1':>8s} {'W2':>8s} {'W3':>8s} {'Mean':>8s} {'StdDev':>8s} {'CV':>6s} Verdict")
print('-' * 115)
for f, v1, v2, v3, mean, std, cv in rows:
verdict = 'UNSTABLE' if cv > 0.6 else ('moderate' if cv > 0.4 else 'stable')
print(f'{f:35s} {v1:8.5f} {v2:8.5f} {v3:8.5f} {mean:8.5f} {std:8.5f} {cv:6.2f} {verdict}')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--policy", type=str, default="P69", help="Policy ID to analyze (e.g. P44)")
args = parser.parse_args()
analyze(args.policy)