Download code/experiments/analysis.py from DeepAuto-AI/MacroLens: direct link, hf CLI and curl.
- Browser
- Download file 14.6 kB
-
https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/experiments/analysis.py
- Command line
-
hf download hf://datasets/DeepAuto-AI/MacroLens/code/experiments/analysis.py
-
curl -L -o analysis.py https://huggingface.co/datasets/DeepAuto-AI/MacroLens/resolve/main/code/experiments/analysis.py
14.6 kB
| """Post-hoc analysis scripts for MacroLens paper §4.4. | |
| Generates: | |
| 1. Per-category ScenRet breakdown (Table in appendix) | |
| 2. Cross-sectional heterogeneity (by sector, market-cap quartile, filing density) | |
| 3. Cross-frequency robustness summary | |
| """ | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| from pathlib import Path | |
| from typing import Any | |
| import numpy as np | |
| import pandas as pd | |
| from .. import config | |
| logger = logging.getLogger(__name__) | |
| # ── Per-Category ScenRet Breakdown ────────────────────────────────────── | |
| def scenret_per_category( | |
| granularity: str = "daily", | |
| ) -> dict[str, Any]: | |
| """Stratify ScenRet ground truth by scenario category. | |
| Computes per-category statistics: mean return, std, count, | |
| and the baseline (cross-ticker mean) MAE per category. | |
| """ | |
| bench_dir = config.get_benchmark_dir(granularity) | |
| gt_path = bench_dir / "scenario_forecast_ground_truth.parquet" | |
| if not gt_path.exists(): | |
| return {"error": "scenario_forecast_ground_truth.parquet not found"} | |
| gt = pd.read_parquet(gt_path) | |
| gt = gt.dropna(subset=["actual_return_pct"]) | |
| if "event_type" not in gt.columns: | |
| return {"error": "No event_type column"} | |
| # Map event_type to category | |
| category_map = _build_category_map() | |
| gt["category"] = gt["event_type"].map( | |
| lambda et: category_map.get(et, "other") | |
| ) | |
| # Per-category stats | |
| categories = {} | |
| for cat, group in gt.groupby("category"): | |
| returns = group["actual_return_pct"] | |
| # Cross-ticker mean baseline MAE | |
| scenario_means = group.groupby("scenario_id")["actual_return_pct"].transform("mean") | |
| baseline_mae = float(np.mean(np.abs(returns - scenario_means))) | |
| categories[cat] = { | |
| "n_instances": len(group), | |
| "n_scenarios": group["scenario_id"].nunique(), | |
| "mean_return_pct": round(float(returns.mean()), 3), | |
| "std_return_pct": round(float(returns.std()), 3), | |
| "median_return_pct": round(float(returns.median()), 3), | |
| "baseline_mae_pct": round(baseline_mae, 3), | |
| "pct_positive": round(float((returns > 0).mean()), 3), | |
| } | |
| # Overall | |
| overall_returns = gt["actual_return_pct"] | |
| scenario_means_all = gt.groupby("scenario_id")["actual_return_pct"].transform("mean") | |
| overall_baseline_mae = float(np.mean(np.abs(overall_returns - scenario_means_all))) | |
| result = { | |
| "granularity": granularity, | |
| "total_instances": len(gt), | |
| "total_scenarios": gt["scenario_id"].nunique(), | |
| "overall_baseline_mae_pct": round(overall_baseline_mae, 3), | |
| "per_category": categories, | |
| } | |
| logger.info("ScenRet per-category: %d categories, %d total instances", | |
| len(categories), len(gt)) | |
| return result | |
| def _build_category_map() -> dict[str, str]: | |
| """Map event_type -> high-level category. | |
| Event-type strings come from `generate_scenarios.py`'s detector functions. | |
| Whenever a detector is added or renamed there, update this map and the | |
| `tests/test_scenario_categories.py` coverage assertion. | |
| """ | |
| mapping = {} | |
| rates = [ | |
| "fed_rate_change", "sofr_shock", "treasury_move", | |
| "treasury_acute_shock", # short-window 10Y move | |
| "long_bond_shock", # DGS30 | |
| "yield_curve_event", # 10Y-2Y inversion | |
| "yield_curve_3m10y_inversion", | |
| "yield_curve_3m10y_uninversion", | |
| "mortgage_rate_shock", | |
| "real_yield_shift", "term_premium_change", | |
| ] | |
| equity = [ | |
| "sp500_drawdown", "sp500_acute_shock", # short-window crash | |
| "nasdaq_move", "nasdaq_acute_shock", | |
| "djia_move", | |
| "vix_spike", "volatility_regime", | |
| "sector_rotation", # SP500 vs NASDAQ divergence | |
| "market_drawdown", | |
| ] | |
| commodities = [ | |
| "oil_shock", "oil_acute_shock", | |
| "wti_oil_shock", "henry_hub_shock", | |
| "natgas_shock", | |
| ] | |
| fx = ["fx_shock", "usd_shock"] | |
| inflation = [ | |
| "inflation_shock", "ppi_shock", "pce_inflation_shock", | |
| "breakeven_inflation_shock", | |
| ] | |
| labor = [ | |
| "unemployment_shock", "payroll_shock", "jolts_shock", | |
| "earnings_shock", | |
| ] | |
| credit = [ | |
| "hy_spread_event", "ig_spread_event", "credit_compression", | |
| "ted_spread_spike", | |
| ] | |
| housing = [ | |
| "housing_starts_shock", "home_price_event", | |
| "building_permit_shock", "existing_home_sales_shock", | |
| ] | |
| money = [ | |
| "m2_contraction", "m2_surge", # split from m2_shock | |
| "monetary_base_shock", "fed_balance_sheet", | |
| "business_loans_shock", | |
| "nfci_event", # Chicago Fed NFCI | |
| ] | |
| for et in rates: mapping[et] = "rates" | |
| for et in equity: mapping[et] = "equity" | |
| for et in commodities: mapping[et] = "commodities" | |
| for et in fx: mapping[et] = "fx" | |
| for et in inflation: mapping[et] = "inflation" | |
| for et in labor: mapping[et] = "labor" | |
| for et in credit: mapping[et] = "credit" | |
| for et in housing: mapping[et] = "housing" | |
| for et in money: mapping[et] = "money_supply" | |
| return mapping | |
| # ── Cross-Sectional Heterogeneity ─────────────────────────────────────── | |
| def cross_sectional_analysis( | |
| granularity: str = "daily", | |
| ) -> dict[str, Any]: | |
| """Stratify TSF and ScenRet by sector, market-cap quartile, filing density.""" | |
| bench_dir = config.get_benchmark_dir(granularity) | |
| test_path = bench_dir / "panel_test.parquet" | |
| gt_path = bench_dir / "scenario_forecast_ground_truth.parquet" | |
| if not test_path.exists(): | |
| return {"error": "panel_test.parquet not found"} | |
| panel = pd.read_parquet(test_path) | |
| result: dict[str, Any] = {"granularity": granularity} | |
| # ── By Sector ── | |
| if "sector" in panel.columns and "close" in panel.columns: | |
| # Compute per-ticker daily returns first, THEN aggregate by sector, | |
| # so we don't take pct_change across ticker boundaries (which would | |
| # produce a spurious return at every (ticker_a, ticker_b) seam). | |
| panel_sorted = panel.sort_values(["ticker", "date"]) | |
| per_ticker_ret = panel_sorted.groupby("ticker", sort=False)["close"].pct_change() | |
| panel_sorted["_ret"] = per_ticker_ret | |
| sector_stats = {} | |
| for sector, grp in panel_sorted.groupby("sector"): | |
| close = grp["close"].dropna() | |
| if len(close) < 10: | |
| continue | |
| returns = grp["_ret"].dropna() | |
| sector_stats[sector] = { | |
| "n_rows": len(grp), | |
| "n_tickers": grp["ticker"].nunique(), | |
| "mean_close": round(float(close.mean()), 2), | |
| "volatility": round(float(returns.std()), 4), | |
| "mean_return": round(float(returns.mean()), 6), | |
| } | |
| result["by_sector"] = sector_stats | |
| # ── By Market-Cap Quartile ── | |
| if "derived_market_cap" in panel.columns: | |
| latest = panel.sort_values("date").groupby("ticker").last() | |
| # `duplicates="drop"` keeps qcut robust to small / degenerate | |
| # market-cap distributions (e.g., synthetic fixtures or tiny | |
| # universes where many tickers share the same derived_market_cap | |
| # round number). On the real R2K + S&P 600 universe it has no | |
| # effect because the bin edges are dense. | |
| try: | |
| latest["mcap_quartile"] = pd.qcut( | |
| latest["derived_market_cap"].clip(lower=1), | |
| 4, labels=["Q1_small", "Q2", "Q3", "Q4_large"], | |
| duplicates="drop", | |
| ) | |
| except ValueError as e: | |
| logger.warning("mcap qcut failed (%s); skipping by_mcap_quartile", e) | |
| latest["mcap_quartile"] = pd.NA | |
| ticker_quartile = latest["mcap_quartile"].to_dict() | |
| # Compute returns per-ticker BEFORE assigning quartile labels, otherwise | |
| # pct_change() taken inside `groupby(mcap_quartile)` would compute a | |
| # return at every cross-ticker seam. | |
| panel_sorted = panel.sort_values(["ticker", "date"]).copy() | |
| panel_sorted["_ret"] = panel_sorted.groupby("ticker", sort=False)["close"].pct_change() | |
| panel_sorted["mcap_quartile"] = panel_sorted["ticker"].map(ticker_quartile) | |
| mcap_stats = {} | |
| for q, grp in panel_sorted.groupby("mcap_quartile"): | |
| returns = grp["_ret"].dropna() | |
| mcap_stats[str(q)] = { | |
| "n_tickers": grp["ticker"].nunique(), | |
| "mean_mcap": round(float(grp["derived_market_cap"].mean()), 0), | |
| "volatility": round(float(returns.std()), 4), | |
| } | |
| result["by_mcap_quartile"] = mcap_stats | |
| # ── By Filing Density ── | |
| corpus_path = bench_dir / "filing_corpus.parquet" | |
| if corpus_path.exists(): | |
| corpus = pd.read_parquet(corpus_path) | |
| filings_per_ticker = corpus.groupby("ticker").size() | |
| ticker_filing_density = filings_per_ticker.to_dict() | |
| # Split into terciles | |
| all_tickers = panel["ticker"].unique() | |
| densities = pd.Series({ | |
| t: ticker_filing_density.get(t, 0) for t in all_tickers | |
| }) | |
| terciles = pd.qcut(densities.clip(lower=0), 3, | |
| labels=["low_filing", "mid_filing", "high_filing"], | |
| duplicates="drop") | |
| # As above: take pct_change PER ticker first, then aggregate by tercile, | |
| # so we don't mix returns across ticker boundaries. | |
| panel_sorted_fd = panel.sort_values(["ticker", "date"]).copy() | |
| panel_sorted_fd["_ret"] = panel_sorted_fd.groupby("ticker", sort=False)["close"].pct_change() | |
| filing_stats = {} | |
| for t_label in terciles.unique(): | |
| tickers_in = set(terciles[terciles == t_label].index) | |
| grp = panel_sorted_fd[panel_sorted_fd["ticker"].isin(tickers_in)] | |
| returns = grp["_ret"].dropna() | |
| filing_stats[str(t_label)] = { | |
| "n_tickers": len(tickers_in), | |
| "mean_filings": round(float(densities[terciles == t_label].mean()), 1), | |
| "volatility": round(float(returns.std()), 4), | |
| } | |
| result["by_filing_density"] = filing_stats | |
| # ── ScenRet by sector ── | |
| if gt_path.exists(): | |
| gt = pd.read_parquet(gt_path).dropna(subset=["actual_return_pct"]) | |
| # Get ticker→sector from panel | |
| ticker_sector = panel.drop_duplicates("ticker").set_index("ticker")["sector"].to_dict() | |
| gt["sector"] = gt["ticker"].map(ticker_sector) | |
| scenret_by_sector = {} | |
| for sector, grp in gt.groupby("sector"): | |
| if pd.isna(sector): | |
| continue | |
| returns = grp["actual_return_pct"] | |
| scenret_by_sector[sector] = { | |
| "n_instances": len(grp), | |
| "mean_return_pct": round(float(returns.mean()), 3), | |
| "std_return_pct": round(float(returns.std()), 3), | |
| } | |
| result["scenret_by_sector"] = scenret_by_sector | |
| return result | |
| # ── Cross-Frequency Summary ───────────────────────────────────────────── | |
| def cross_frequency_summary() -> dict[str, Any]: | |
| """Collect best baseline results across daily/weekly/monthly.""" | |
| result: dict[str, Any] = {} | |
| legacy_dir = Path(__file__).resolve().parent / "results" / "legacy_per_family" | |
| for gran in ["daily", "weekly", "monthly"]: | |
| # ``all_results.json`` is the legacy per-family aggregate. It used | |
| # to live under ``data_small_caps/benchmark/<g>/`` but moved to | |
| # ``experiments/results/legacy_per_family/`` once experiment | |
| # outputs were separated from the benchmark tree. The new | |
| # canonical aggregate is ``experiments/paper_artifacts/aggregate.parquet``. | |
| full_path = legacy_dir / "all_results.json" | |
| quick_path = legacy_dir / "all_results_quick.json" | |
| path = full_path if full_path.exists() else quick_path | |
| if not path.exists(): | |
| result[gran] = {"status": "no_results"} | |
| continue | |
| data = json.loads(path.read_text()) | |
| summary: dict[str, Any] = {"status": "available"} | |
| # Extract best TSF MAE across models | |
| best_tsf_mae = {} | |
| for key, val in data.items(): | |
| if isinstance(val, dict): | |
| for sub_key, sub_val in val.items(): | |
| if isinstance(sub_val, dict) and "overall" in sub_val: | |
| overall = sub_val["overall"] | |
| if "mae" in overall: | |
| h = sub_val.get("horizon", sub_key) | |
| if h not in best_tsf_mae or overall["mae"] < best_tsf_mae[h]["mae"]: | |
| best_tsf_mae[h] = { | |
| "model": sub_key, | |
| "mae": overall["mae"], | |
| "da": overall.get("directional_accuracy", 0), | |
| } | |
| summary["best_tsf"] = best_tsf_mae | |
| result[gran] = summary | |
| return result | |
| # ── Main ──────────────────────────────────────────────────────────────── | |
| def run_all_analyses(granularity: str = "daily") -> dict[str, Any]: | |
| """Run all §4.4 analyses and save results.""" | |
| results: dict[str, Any] = {} | |
| logger.info("Running per-category ScenRet analysis...") | |
| results["scenret_per_category"] = scenret_per_category(granularity) | |
| logger.info("Running cross-sectional analysis...") | |
| results["cross_sectional"] = cross_sectional_analysis(granularity) | |
| logger.info("Running cross-frequency summary...") | |
| results["cross_frequency"] = cross_frequency_summary() | |
| # Save | |
| out_dir = config.get_benchmark_dir(granularity) | |
| out_path = out_dir / "analysis_results.json" | |
| out_path.write_text(json.dumps(results, indent=2, default=str)) | |
| logger.info("Analysis saved to %s", out_path) | |
| return results | |
| if __name__ == "__main__": | |
| logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s") | |
| run_all_analyses() | |