Download backtest/engine/walkforward.py from whassan/Rukku: direct link, hf CLI and curl.
- Browser
- Download file 3.37 kB
-
https://huggingface.co/spaces/whassan/Rukku/resolve/main/backtest/engine/walkforward.py
- Command line
-
hf download hf://spaces/whassan/Rukku/backtest/engine/walkforward.py
-
curl -L -o walkforward.py https://huggingface.co/spaces/whassan/Rukku/resolve/main/backtest/engine/walkforward.py
3.37 kB
| """Walk-forward backtesting engine. | |
| Executes actual model inference to analyze predictions over time. | |
| """ | |
| import os | |
| import time | |
| from dataclasses import dataclass, field | |
| from enum import Enum | |
| from typing import Dict, List, Optional | |
| import pandas as pd | |
| import numpy as np | |
| from backtest.engine.exceptions import EngineError | |
| from models.base import ForecastModel | |
| class BacktestStatus(Enum): | |
| PENDING = "PENDING" | |
| RUNNING = "RUNNING" | |
| COMPLETED = "COMPLETED" | |
| FAILED = "FAILED" | |
| CANCELLED = "CANCELLED" | |
| class BacktestConfig: | |
| start_date: str | |
| end_date: str | |
| assets: List[str] | |
| horizon: int | |
| frequency: str | |
| vintage_mode: str | |
| random_seed: int | |
| execution_timestamp: str = "" | |
| class PredictionRecord: | |
| timestamp: str | |
| asset: str | |
| horizon: int | |
| predictions: dict | |
| locked: bool = False | |
| class BacktestResult: | |
| config: BacktestConfig | |
| status: BacktestStatus | |
| error: Optional[str] = None | |
| prediction_records: List[PredictionRecord] = field(default_factory=list) | |
| benchmark_results: Dict[str, float] = field(default_factory=dict) | |
| provenance: dict = field(default_factory=dict) | |
| def run_walk_forward_backtest( | |
| config: BacktestConfig, | |
| model: ForecastModel, | |
| historical_data: Dict[str, pd.DataFrame] | |
| ) -> BacktestResult: | |
| """Run a real walk-forward backtest by feeding sliding windows to the model.""" | |
| if not model.health_check()["status"] == "ok": | |
| return BacktestResult( | |
| config=config, | |
| status=BacktestStatus.FAILED, | |
| error=model.health_check()["reason"] | |
| ) | |
| records = [] | |
| # We will step through the historical data | |
| # For a realistic mock of walk-forward, we'd loop over dates. | |
| # To keep this fast for demonstration but structurally real, we take 5 slices. | |
| for asset in config.assets: | |
| df = historical_data.get(asset) | |
| if df is None or df.empty: | |
| continue | |
| # Example walk forward: predict at 5 recent points | |
| total_len = len(df) | |
| if total_len < 100: | |
| continue | |
| step = max(1, total_len // 5) | |
| indices_to_predict = range(100, total_len, step) | |
| for idx in indices_to_predict: | |
| window = df.iloc[:idx] | |
| timestamp = str(window.index[-1].date()) | |
| try: | |
| # REAL INFERENCE CALL | |
| pred_result = model.predict(window, horizon=config.horizon) | |
| records.append( | |
| PredictionRecord( | |
| timestamp=timestamp, | |
| asset=asset, | |
| horizon=config.horizon, | |
| predictions=pred_result, | |
| locked=True | |
| ) | |
| ) | |
| except Exception as e: | |
| return BacktestResult( | |
| config=config, | |
| status=BacktestStatus.FAILED, | |
| error=f"Inference failed at {timestamp}: {str(e)}" | |
| ) | |
| return BacktestResult( | |
| config=config, | |
| status=BacktestStatus.COMPLETED, | |
| prediction_records=records, | |
| benchmark_results={}, | |
| provenance={ | |
| "model_metadata": model.metadata(), | |
| "execution_time": time.time() | |
| } | |
| ) | |