Spaces:
Sleeping
Sleeping
Download scripts/analyze_correlation_drift.py from ymo2017/jumper-dashboard: direct link, hf CLI and curl.
- Browser
- Download file 1.93 kB
-
https://huggingface.co/spaces/ymo2017/jumper-dashboard/resolve/main/scripts/analyze_correlation_drift.py
- Command line
-
hf download hf://spaces/ymo2017/jumper-dashboard/scripts/analyze_correlation_drift.py
-
curl -L -o analyze_correlation_drift.py https://huggingface.co/spaces/ymo2017/jumper-dashboard/resolve/main/scripts/analyze_correlation_drift.py
1.93 kB
| import pandas as pd | |
| import numpy as np | |
| import os | |
| import sys | |
| sys.path.append(os.getcwd()) | |
| from lib.backtest_utils import load_data, DEFAULT_TICKERS | |
| def analyze_correlation_drift(target_ticker="ZROZ", split_date="2021-01-01"): | |
| """ | |
| Analyzes how the correlation of a target asset with the rest of the portfolio | |
| has shifted over time, specifically comparing a pre-period and a post-period. | |
| Useful for identifying regime shifts that break global machine learning models. | |
| """ | |
| df = load_data('data', DEFAULT_TICKERS) | |
| # Define a default universe if you just want a quick look | |
| tickers = ["SMH", "XLE", "XLP", "MCHI", "XLU", target_ticker] | |
| # Filter to tickers that actually exist in the data | |
| valid_tickers = [t for t in tickers if t in df.columns] | |
| if target_ticker not in valid_tickers: | |
| print(f"Error: {target_ticker} data not found.") | |
| return | |
| rets = df[valid_tickers].pct_change().dropna() | |
| print(f"=== Correlation Drift Analysis for {target_ticker} ===") | |
| print(f"Split Date: {split_date}\n") | |
| # Train period (pre-split) | |
| train_rets = rets.loc[:split_date] | |
| train_corr = train_rets.corr()[target_ticker].drop(target_ticker) | |
| # Test period (post-split) | |
| test_rets = rets.loc[split_date:] | |
| test_corr = test_rets.corr()[target_ticker].drop(target_ticker) | |
| comparison = pd.DataFrame({ | |
| f'Pre-{split_date[:4]} Corr': train_corr, | |
| f'Post-{split_date[:4]} Corr': test_corr, | |
| 'Drift (Absolute Change)': test_corr - train_corr | |
| }) | |
| print(comparison.sort_values('Drift (Absolute Change)', ascending=False)) | |
| if __name__ == "__main__": | |
| # You can pass a different ticker as an argument if needed | |
| ticker = sys.argv[1] if len(sys.argv) > 1 else "ZROZ" | |
| split = sys.argv[2] if len(sys.argv) > 2 else "2021-01-01" | |
| analyze_correlation_drift(target_ticker=ticker, split_date=split) | |