jumper-dashboard / scripts /permutation_importance.py
ymo2017's picture
Upload folder using huggingface_hub
529299c verified
Raw History Blame Contribute Delete
8.55 kB
import sys
import os
sys.path.append(os.getcwd())
import numpy as np
import pandas as pd
import importlib.util
import argparse
import warnings
from copy import deepcopy
from lib.backtest_utils import load_data, DEFAULT_TICKERS
warnings.filterwarnings("ignore", category=UserWarning, module="sklearn")
def get_policy(policy_id):
param_path = f'policies/params/{policy_id}.py'
if not os.path.exists(param_path):
raise ValueError(f"Parameter file {param_path} not found.")
spec = importlib.util.spec_from_file_location(policy_id, param_path)
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod)
if hasattr(mod, "get_policy"):
return mod.get_policy()
elif hasattr(mod, "POLICY_CLASS"):
return mod.POLICY_CLASS(**getattr(mod, "PARAMS", {}))
else:
raise ValueError(f"Policy config for {policy_id} must define POLICY_CLASS or get_policy()")
def evaluate_window(policy, df, start_idx, end_idx, feature_to_shuffle=None):
"""
Evaluates the policy over a specific window of indices.
Returns the sequence of chosen tickers.
If feature_to_shuffle is provided, that feature's values are shuffled within this window.
"""
# 1. We need access to the precomputed features
# Assuming LeanAlphaStable/Pruned or V5/V6 architecture where _precompute is used
if not hasattr(policy, '_batch_metrics') or not policy._batch_metrics:
# Precompute if not done already
if hasattr(policy, '_precompute'):
policy._precompute(df)
else:
raise ValueError("Policy must have a _precompute method to use this tool.")
metrics = policy._batch_metrics
features_list = sorted(list(metrics[-1].keys())) if metrics else []
if feature_to_shuffle and feature_to_shuffle not in features_list:
# Feature doesn't exist, return baseline equivalent
pass
# 2. Extract the features for the window
window_metrics = [deepcopy(metrics[i]) for i in range(start_idx, end_idx)]
if feature_to_shuffle and window_metrics:
# Extract values for the target feature
target_vals = [m.get(feature_to_shuffle, 0.0) for m in window_metrics]
# Shuffle them
np.random.shuffle(target_vals)
# Put them back
for i, m in enumerate(window_metrics):
if feature_to_shuffle in m:
m[feature_to_shuffle] = target_vals[i]
# 3. Simulate decisions
# We must construct the X_all matrix based on these metrics to run through the models
if not hasattr(policy, '_feat_order'):
policy._feat_order = sorted(list(window_metrics[0].keys())) if window_metrics else []
feat_order = policy._feat_order
L = len(window_metrics)
X_all = []
for m in window_metrics:
X_all.append([m.get(k, 0.0) for k in feat_order])
X_all = np.array(X_all)
res_preds = []
for idx, m in enumerate(policy.models):
if not m:
res_preds.append(np.zeros(L))
continue
if hasattr(policy, 'per_model_feats') and policy.per_model_feats[idx] is not None:
mask = [feat_order.index(f) for f in policy.per_model_feats[idx] if f in feat_order]
res_preds.append(m.predict(X_all[:, mask]))
else:
res_preds.append(m.predict(X_all))
choices = []
# For each day in the window
for i in range(L):
# Calculate min_edge / penalties (similar to the call method)
feat = window_metrics[i]
preds = {t: res_preds[idx][i] for idx, t in enumerate(policy.active_tickers)}
min_p = {t: 0.0 for t in policy.active_tickers}
# We assume LeanAlphaStable style vol penalty logic here
vol_thresh = getattr(policy, 'VOL_THRESHOLD', 0.35)
vol_pen = getattr(policy, 'VOL_PENALTY', 0.0)
for t in policy.active_tickers:
if feat.get(f'{t}_Vol', 0) > vol_thresh:
min_p[t] += vol_pen
if getattr(policy, 'banned_tickers', None) and t in policy.banned_tickers:
min_p[t] += 100.0
if getattr(policy, 'per_ticker_selection_penalty', None):
min_p[t] += policy.per_ticker_selection_penalty.get(t, 0.0)
eligible = sorted([(t, preds[t]-min_p[t]) for t in policy.active_tickers if preds[t]-min_p[t] > 0], key=lambda x:x[1], reverse=True)
# Pick top_k or cash
top_k = getattr(policy, 'top_k', 1)
if not eligible:
choices.append((policy.cash_ticker,))
else:
chosen = tuple(eligible[j][0] for j in range(min(top_k, len(eligible))))
choices.append(chosen)
return choices
def run_permutation_importance(policy_id, runs=5):
print(f"Loading data and training {policy_id}...")
df = load_data('data', DEFAULT_TICKERS)
policy = get_policy(policy_id)
N = len(df)
train_end = N - 252 # Train up to 1 year ago
is_start = train_end - 252 # In-sample eval is 1 year before train end
is_end = train_end
oos_start = train_end
oos_end = N
# 1. Train the policy
df_train = df.iloc[:train_end].copy()
if hasattr(policy, 'fit'):
policy.fit(df_train)
# We must precompute the full metrics array for the evaluation step
if hasattr(policy, '_precompute'):
policy._precompute(df) # Precompute on full df so we have features for IS and OOS
print(f"Train : {df.index[0].date()} to {df.index[train_end-1].date()}")
print(f"In-Sample : {df.index[is_start].date()} to {df.index[is_end-1].date()} ({is_end - is_start} days)")
print(f"OOS : {df.index[oos_start].date()} to {df.index[oos_end-1].date()} ({oos_end - oos_start} days)")
# 2. Get Baselines
baseline_is = evaluate_window(policy, df, is_start, is_end)
baseline_oos = evaluate_window(policy, df, oos_start, oos_end)
# Identify all available features
metrics = policy._batch_metrics
features = sorted(list(metrics[-1].keys()))
results = []
print("\nRunning perturbation impact analysis (calculating % changed decisions)...")
for f in features:
is_changes = []
oos_changes = []
for _ in range(runs):
# Perturb IS
pert_is = evaluate_window(policy, df, is_start, is_end, feature_to_shuffle=f)
diff_is = sum(1 for a, b in zip(baseline_is, pert_is) if a != b) / len(baseline_is)
is_changes.append(diff_is)
# Perturb OOS
pert_oos = evaluate_window(policy, df, oos_start, oos_end, feature_to_shuffle=f)
diff_oos = sum(1 for a, b in zip(baseline_oos, pert_oos) if a != b) / len(baseline_oos)
oos_changes.append(diff_oos)
avg_is_impact = np.mean(is_changes)
avg_oos_impact = np.mean(oos_changes)
# Change delta (OOS - IS)
delta = avg_oos_impact - avg_is_impact
# If delta is negative, feature is LESS useful in OOS (potential overfitting)
# We classify severe drops as "DEGRADED"
status = "STABLE"
if delta < -0.05 and avg_is_impact > 0.05:
status = "DEGRADED"
elif delta > 0.05 and avg_is_impact < 0.05:
status = "OVERFITTING_OOS" # OOS impact is surprisingly higher
results.append({
'Feature': f,
'IS_Impact': avg_is_impact * 100,
'OOS_Impact': avg_oos_impact * 100,
'Delta': delta * 100,
'Status': status
})
results.sort(key=lambda x: x['IS_Impact'], reverse=True)
# Format Output Table
print("\n--- Perturbation Feature Importance Analysis ---")
print(f"{'Feature':30s} {'IS Impact (%)':>15s} {'OOS Impact (%)':>15s} {'Delta vs IS':>15s} {'Status':>10s}")
print("-" * 92)
for r in results:
f_name = r['Feature']
print(f"{f_name:30s} {r['IS_Impact']:14.2f}% {r['OOS_Impact']:14.2f}% {r['Delta']:14.2f}% {r['Status']:10s}")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Calculate feature importance via permutation on a specific policy.")
parser.add_argument("--policy", type=str, required=True, help="Policy ID (e.g., P43)")
parser.add_argument("--runs", type=int, default=5, help="Number of random shuffles per feature")
args = parser.parse_args()
run_permutation_importance(args.policy, args.runs)