- autoresearch: automated research pipeline - MiroFish: financial market simulation with LLM agents - thesis_portfolio_opt: portfolio optimization with ML models - plan.md: 21-week thesis project plan
204 lines
7.6 KiB
Python
204 lines
7.6 KiB
Python
"""
|
|
Research-level integration tests.
|
|
|
|
These tests verify that all pipeline artefacts (data files, experiment
|
|
results, deliverables) were generated correctly and satisfy quality
|
|
constraints. They read only from the on-disk outputs so they can run
|
|
without re-executing the full pipeline.
|
|
"""
|
|
|
|
import pytest
|
|
import numpy as np
|
|
import pandas as pd
|
|
from pathlib import Path
|
|
|
|
from src.config import RAW_DIR, PROCESSED_DIR, RESULTS_DIR
|
|
|
|
PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
|
DELIVERABLES_DIR = PROJECT_ROOT / "deliverables"
|
|
|
|
|
|
# ============================================================================
|
|
# DATA FILE EXISTENCE & SHAPE
|
|
# ============================================================================
|
|
|
|
class TestDataFiles:
|
|
"""Verify that core data artefacts exist and have expected dimensions."""
|
|
|
|
def test_features_csv_exists(self):
|
|
"""features.csv should have been generated by the preprocessing step."""
|
|
path = PROCESSED_DIR / "features.csv"
|
|
assert path.exists(), f"Missing: {path}"
|
|
|
|
def test_features_shape(self):
|
|
"""Feature matrix should have 4000+ rows and 200+ columns."""
|
|
path = PROCESSED_DIR / "features.csv"
|
|
if not path.exists():
|
|
pytest.skip("features.csv not available")
|
|
df = pd.read_csv(path, index_col=0)
|
|
assert df.shape[0] >= 4000, (
|
|
f"Expected >= 4000 rows, got {df.shape[0]}"
|
|
)
|
|
assert df.shape[1] >= 200, (
|
|
f"Expected >= 200 columns, got {df.shape[1]}"
|
|
)
|
|
|
|
def test_prices_csv_exists(self):
|
|
"""prices.csv should have been downloaded."""
|
|
path = RAW_DIR / "prices.csv"
|
|
assert path.exists(), f"Missing: {path}"
|
|
|
|
def test_macro_csv_exists(self):
|
|
"""macro.csv should have been downloaded."""
|
|
path = RAW_DIR / "macro.csv"
|
|
assert path.exists(), f"Missing: {path}"
|
|
|
|
|
|
# ============================================================================
|
|
# MODEL & EXPERIMENT RESULTS
|
|
# ============================================================================
|
|
|
|
class TestExperimentResults:
|
|
"""Verify model comparison and experiment output files."""
|
|
|
|
def test_model_comparison_csv(self):
|
|
"""model_comparison.csv should exist with expected columns."""
|
|
path = RESULTS_DIR / "model_comparison.csv"
|
|
assert path.exists(), f"Missing: {path}"
|
|
df = pd.read_csv(path)
|
|
expected_cols = {"ticker", "model", "rmse", "r2", "dir_acc", "ic"}
|
|
missing = expected_cols - set(df.columns)
|
|
assert len(missing) == 0, f"Missing columns in model_comparison.csv: {missing}"
|
|
|
|
def test_experiment_results(self):
|
|
"""all_experiments.csv should exist and contain 30+ rows."""
|
|
path = RESULTS_DIR / "all_experiments.csv"
|
|
assert path.exists(), f"Missing: {path}"
|
|
df = pd.read_csv(path)
|
|
assert len(df) >= 30, (
|
|
f"Expected >= 30 experiment rows, got {len(df)}"
|
|
)
|
|
|
|
def test_best_sharpe_positive(self):
|
|
"""The best experiment Sharpe ratio should be strictly positive."""
|
|
path = RESULTS_DIR / "all_experiments.csv"
|
|
if not path.exists():
|
|
pytest.skip("all_experiments.csv not available")
|
|
df = pd.read_csv(path)
|
|
best_sharpe = df["sharpe"].max()
|
|
assert best_sharpe > 0, f"Best Sharpe is non-positive: {best_sharpe}"
|
|
|
|
def test_walk_forward_returns(self):
|
|
"""walk_forward_returns.csv should exist."""
|
|
path = RESULTS_DIR / "walk_forward_returns.csv"
|
|
assert path.exists(), f"Missing: {path}"
|
|
|
|
|
|
# ============================================================================
|
|
# LEAKAGE CHECK
|
|
# ============================================================================
|
|
|
|
class TestNoFutureLeakage:
|
|
"""Verify that the experiment code excludes return columns from predictors."""
|
|
|
|
def test_no_future_leakage(self):
|
|
"""Feature columns used as predictors must not contain '_ret_'.
|
|
|
|
The experiment code's ``select_features`` function should filter
|
|
out return columns to prevent look-ahead bias. We verify this by
|
|
importing the function and checking its output on the actual
|
|
feature set.
|
|
"""
|
|
features_path = PROCESSED_DIR / "features.csv"
|
|
if not features_path.exists():
|
|
pytest.skip("features.csv not available")
|
|
|
|
# Read feature columns
|
|
df = pd.read_csv(features_path, index_col=0, nrows=1)
|
|
|
|
# Import the experiment's select_features function
|
|
import importlib.util
|
|
experiment_path = PROJECT_ROOT / "research" / "experiment.py"
|
|
if not experiment_path.exists():
|
|
pytest.skip("research/experiment.py not available")
|
|
|
|
spec = importlib.util.spec_from_file_location(
|
|
"experiment_module", str(experiment_path)
|
|
)
|
|
mod = importlib.util.module_from_spec(spec)
|
|
|
|
# We only need select_features, so suppress side effects
|
|
import sys
|
|
old_argv = sys.argv
|
|
sys.argv = ["test"]
|
|
try:
|
|
spec.loader.exec_module(mod)
|
|
except SystemExit:
|
|
pass
|
|
finally:
|
|
sys.argv = old_argv
|
|
|
|
selected = mod.select_features(df)
|
|
leaky = [c for c in selected if "_ret_" in c]
|
|
assert len(leaky) == 0, (
|
|
f"Leakage detected: {len(leaky)} return columns in predictors: "
|
|
f"{leaky[:10]}"
|
|
)
|
|
|
|
|
|
# ============================================================================
|
|
# BENCHMARK SANITY CHECKS
|
|
# ============================================================================
|
|
|
|
class TestBenchmarks:
|
|
"""Ensure benchmark Sharpe ratios are in reasonable ranges."""
|
|
|
|
@pytest.fixture
|
|
def prices(self):
|
|
path = RAW_DIR / "prices.csv"
|
|
if not path.exists():
|
|
pytest.skip("prices.csv not available")
|
|
return pd.read_csv(path, index_col=0, parse_dates=True)
|
|
|
|
def test_benchmark_sharpe_reasonable(self, prices):
|
|
"""SPY Sharpe should be between 0 and 2; Equal Weight between -1 and 2."""
|
|
# --- SPY ---
|
|
spy_ret = prices["SPY"].pct_change().dropna()
|
|
spy_ann_ret = spy_ret.mean() * 252
|
|
spy_ann_vol = spy_ret.std() * np.sqrt(252)
|
|
spy_sharpe = spy_ann_ret / spy_ann_vol if spy_ann_vol > 0 else 0.0
|
|
assert 0 < spy_sharpe < 2, f"SPY Sharpe out of range: {spy_sharpe:.4f}"
|
|
|
|
# --- Equal Weight ---
|
|
ew_ret = prices.pct_change().dropna().mean(axis=1)
|
|
ew_ann_ret = ew_ret.mean() * 252
|
|
ew_ann_vol = ew_ret.std() * np.sqrt(252)
|
|
ew_sharpe = ew_ann_ret / ew_ann_vol if ew_ann_vol > 0 else 0.0
|
|
assert -1 < ew_sharpe < 2, f"Equal Weight Sharpe out of range: {ew_sharpe:.4f}"
|
|
|
|
|
|
# ============================================================================
|
|
# DELIVERABLES
|
|
# ============================================================================
|
|
|
|
class TestDeliverables:
|
|
"""Verify that final deliverable files exist."""
|
|
|
|
def test_deliverables_exist(self):
|
|
"""PDF, DOCX, and XLSX should all be present in deliverables/."""
|
|
assert DELIVERABLES_DIR.exists(), f"Directory missing: {DELIVERABLES_DIR}"
|
|
|
|
pdf_files = list(DELIVERABLES_DIR.glob("*.pdf"))
|
|
docx_files = list(DELIVERABLES_DIR.glob("*.docx"))
|
|
xlsx_files = list(DELIVERABLES_DIR.glob("*.xlsx"))
|
|
|
|
assert len(pdf_files) >= 1, (
|
|
f"No PDF files in {DELIVERABLES_DIR}: {list(DELIVERABLES_DIR.iterdir())}"
|
|
)
|
|
assert len(docx_files) >= 1, (
|
|
f"No DOCX files in {DELIVERABLES_DIR}: {list(DELIVERABLES_DIR.iterdir())}"
|
|
)
|
|
assert len(xlsx_files) >= 1, (
|
|
f"No XLSX files in {DELIVERABLES_DIR}: {list(DELIVERABLES_DIR.iterdir())}"
|
|
)
|