Upload real_treading_FIXED contents
Browse files- .gitignore +1 -3
- CHANGES.md +164 -0
- README.md +251 -0
- app.py +480 -0
- backtest/__init__.py +0 -0
- backtest/backtester.py +170 -0
- config.py +60 -0
- data/__init__.py +0 -0
- data/historical.py +157 -0
- features/__init__.py +0 -0
- features/feature_pipeline.py +127 -0
- indicators/__init__.py +0 -0
- indicators/indicators.py +178 -0
- live_runner.py +121 -0
- models/__init__.py +0 -0
- models/arima_garch_model.py +109 -0
- models/arima_model.py +77 -0
- models/auto_arima_model.py +112 -0
- models/base_model.py +23 -0
- models/dependencies.py +50 -0
- models/moirai_model.py +105 -0
- models/registry.py +66 -0
- models/timesfm_model.py +113 -0
- requirements.txt +38 -0
- tests/__init__.py +0 -0
- tests/test_backtester_alignment.py +211 -0
- tests/test_data_layer.py +245 -0
- tests/test_feature_pipeline.py +271 -0
- tests/test_helpers.py +147 -0
- tests/test_indicators.py +166 -0
- tests/test_models_with_features.py +157 -0
- utils/__init__.py +0 -0
- utils/helpers.py +64 -0
.gitignore
CHANGED
|
@@ -4,11 +4,9 @@ __pycache__/
|
|
| 4 |
.ipynb_checkpoints/
|
| 5 |
.env
|
| 6 |
*.egg-info/
|
|
|
|
| 7 |
|
| 8 |
# runtime-generated, not source
|
| 9 |
-
data_cache/*.csv
|
| 10 |
outputs/*.csv
|
| 11 |
outputs/*.png
|
| 12 |
|
| 13 |
-
!data_cache/.gitkeep
|
| 14 |
-
!outputs/.gitkeep
|
|
|
|
| 4 |
.ipynb_checkpoints/
|
| 5 |
.env
|
| 6 |
*.egg-info/
|
| 7 |
+
venv/
|
| 8 |
|
| 9 |
# runtime-generated, not source
|
|
|
|
| 10 |
outputs/*.csv
|
| 11 |
outputs/*.png
|
| 12 |
|
|
|
|
|
|
CHANGES.md
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Debug & Fix Log
|
| 2 |
+
|
| 3 |
+
Every item below was reproduced by execution before it was changed, and
|
| 4 |
+
re-verified by execution after. Line references are to the shipped files.
|
| 5 |
+
|
| 6 |
+
Final state: `python -m compileall` clean, `python -m unittest discover -s
|
| 7 |
+
tests` = **83 tests, OK (skipped=7)**. The 7 skips are the model tests whose
|
| 8 |
+
backend (`statsmodels`, `arch`, `uni2ts`, `timesfm`) is not installed in the
|
| 9 |
+
offline environment this was debugged in; they run on a full
|
| 10 |
+
`pip install -r requirements.txt`.
|
| 11 |
+
|
| 12 |
+
---
|
| 13 |
+
|
| 14 |
+
## Bugs fixed
|
| 15 |
+
|
| 16 |
+
### 1. Requested lookback was ignored on daily data
|
| 17 |
+
`data/historical.py`. The daily path asked Yahoo for `{"period": "max"}`
|
| 18 |
+
regardless of `lookback_days`, so a 30-day request returned **3650 candles**.
|
| 19 |
+
Backtests silently ran over a different period than the UI asked for.
|
| 20 |
+
**Fix:** every path now computes an explicit `start`/`end` window from the
|
| 21 |
+
requested lookback. Covered by `TestLookbackIsHonored`.
|
| 22 |
+
|
| 23 |
+
### 2. The 1-minute chunking loop could never run a second request
|
| 24 |
+
`data/historical.py`. Yahoo serves 1m in 7-day slices but retains ~30 days.
|
| 25 |
+
The loop's bound made more than one request unreachable: a 30-day 1m request
|
| 26 |
+
issued **1 request and returned 7 days**.
|
| 27 |
+
**Fix:** `_native_fetch()` splits the window by `max_request_days`, clamps the
|
| 28 |
+
total span to `max_days`, keeps chunks contiguous, and paces requests. An
|
| 29 |
+
empty chunk (market closure) no longer aborts the remaining chunks. Covered
|
| 30 |
+
by `TestChunkedFetching`.
|
| 31 |
+
|
| 32 |
+
### 3. `KeyError: "['Volume'] not in index"` on partial vendor frames
|
| 33 |
+
`data/historical.py`. Columns were selected unconditionally, so any response
|
| 34 |
+
missing one OHLCV column crashed the fetch instead of reporting it.
|
| 35 |
+
**Fix:** tolerant column filter (keeps OHLCV, drops extras such as
|
| 36 |
+
`Dividends`), then an explicit completeness check that raises `DataFetchError`
|
| 37 |
+
naming the interval's real limit.
|
| 38 |
+
|
| 39 |
+
### 4. Write-only cache
|
| 40 |
+
`data/historical.py` wrote `data_cache/*.csv` on every fetch; no code path
|
| 41 |
+
ever read them back, and the `refresh=False` parameter threaded through
|
| 42 |
+
callers was dead. **Fix:** cache removed entirely, along with
|
| 43 |
+
`DATA_CACHE_DIR`, the `refresh=` parameters, and the orphaned
|
| 44 |
+
`data_cache/BTC-USD_5m.csv` artifact.
|
| 45 |
+
|
| 46 |
+
### 5. 4h and 1d live prediction could never work
|
| 47 |
+
`app.py`, `live_runner.py`. Both fetched a fixed 2-day window: **4h yielded
|
| 48 |
+
13 candles and 1d yielded 2**, below every model's minimum (ARIMA 20,
|
| 49 |
+
ARIMA-GARCH 30, TimesFM 32). Those two timeframes always failed.
|
| 50 |
+
**Fix:** `history_days_for_candles(timeframe, PREDICTION_HISTORY_CANDLES)`
|
| 51 |
+
sizes the fetch per timeframe, clamped to what the source interval can serve.
|
| 52 |
+
`TestLiveSizingFitsSourceLimits` asserts the sizing stays inside the source
|
| 53 |
+
limit for every timeframe, so this cannot regress silently.
|
| 54 |
+
|
| 55 |
+
### 6. A missing optional backend broke the whole app, not one model
|
| 56 |
+
`models/`. `import statsmodels` ran at module import, so
|
| 57 |
+
`ModuleNotFoundError: No module named 'statsmodels'` propagated out of the
|
| 58 |
+
registry and took down unrelated models and the UI.
|
| 59 |
+
**Fix:** `models/dependencies.py` imports each backend lazily at use time and
|
| 60 |
+
raises an actionable message (`ARIMA needs the 'statsmodels' package. Install
|
| 61 |
+
with: pip install statsmodels ...`). Verified live: the runner reported the
|
| 62 |
+
missing Moirai backend per poll and kept running.
|
| 63 |
+
|
| 64 |
+
### 7. Feature warm-up padding still produced NaN rows across market gaps
|
| 65 |
+
`features/feature_pipeline.py`. Padding fetched extra history, but a weekend
|
| 66 |
+
gap left leading rows whose indicators were still undefined, so
|
| 67 |
+
`validate_features` raised `feature window contains NaN in
|
| 68 |
+
['BB_Upper','BB_Lower','SMA_20']`.
|
| 69 |
+
**Fix:** leading incomplete rows are trimmed after padding. A NaN appearing
|
| 70 |
+
*inside* the frame still reaches `validate_features` — that one is a real
|
| 71 |
+
data problem and must not be hidden. Re-run of the reproduction: 4 rows
|
| 72 |
+
returned, 0 still NaN, validation passed.
|
| 73 |
+
|
| 74 |
+
### 8. The last graded candle was the still-forming candle
|
| 75 |
+
`backtest/backtester.py` via `app.py`. Yahoo's final intraday row is the
|
| 76 |
+
candle currently forming; its Close is just the latest trade. The backtest
|
| 77 |
+
graded predictions against it, scoring against a moving target.
|
| 78 |
+
**Fix:** `drop_forming_candle()` removes that row (and its aligned feature
|
| 79 |
+
row) before the walk-forward loop.
|
| 80 |
+
|
| 81 |
+
### 9. Model modules silenced warnings process-wide
|
| 82 |
+
`models/*.py` called `warnings.filterwarnings("ignore")` at module level.
|
| 83 |
+
Measured effect: 1 unrelated warning visible before import, 0 after.
|
| 84 |
+
**Fix:** a `quiet_fit()` context manager scoped to the fit calls only.
|
| 85 |
+
Verified that warnings raised outside a fit are still delivered.
|
| 86 |
+
|
| 87 |
+
### 10. Indicators invented a confident "neutral" reading
|
| 88 |
+
`indicators/indicators.py` applied `fillna(50)`, fabricating 14 RSI rows, 13
|
| 89 |
+
`Stoch_%K` rows and 15 `Stoch_%D` rows out of no data — which then fed both
|
| 90 |
+
the UI and the covariate pipeline.
|
| 91 |
+
**Fix:** warm-up stays `NaN`; `latest_signals()` reports `n/a` /
|
| 92 |
+
`Insufficient data`. Wilder RMA seeding, population std for Bollinger, and
|
| 93 |
+
the zero-range Stochastic case are now pinned by `tests/test_indicators.py`.
|
| 94 |
+
|
| 95 |
+
### 11. Ctrl+C during the poll interval exited with a traceback
|
| 96 |
+
`live_runner.py`: `time.sleep()` sat outside the `try`, so an interrupt
|
| 97 |
+
between polls (the overwhelmingly likely moment) crashed instead of stopping.
|
| 98 |
+
**Fix:** the whole loop including the sleep is inside the handler. Verified
|
| 99 |
+
by sending a real SIGINT: return code 0, no traceback, final line `Stopped.`
|
| 100 |
+
|
| 101 |
+
### 12. Interval limits conflated retention with request width
|
| 102 |
+
`config.py` stored one number per interval, which is what made #1 and #2
|
| 103 |
+
possible. **Fix:** `YF_NATIVE_INTERVALS` now carries `max_days` (how far back
|
| 104 |
+
Yahoo retains) and `max_request_days` (how wide one request may be)
|
| 105 |
+
separately.
|
| 106 |
+
|
| 107 |
+
---
|
| 108 |
+
|
| 109 |
+
## Dead code removed
|
| 110 |
+
|
| 111 |
+
- `data/live.py` — entire module, referenced by nothing.
|
| 112 |
+
- `is_probably_valid_symbol()` and its `re` import — never called.
|
| 113 |
+
- `is_available()` and five copies of `_check_dependencies()` — never called;
|
| 114 |
+
superseded by the lazy imports in #6.
|
| 115 |
+
- `refresh=` parameters, `DATA_CACHE_DIR`, `RANDOM_SEED` (set, never read).
|
| 116 |
+
- Module-level `warnings.filterwarnings` calls (#9).
|
| 117 |
+
- A no-op `pass` block in `tests/test_backtester_alignment.py` that asserted
|
| 118 |
+
nothing — replaced with a real raw-column alignment assertion.
|
| 119 |
+
- A function-local `from math import ...` duplicating the module import.
|
| 120 |
+
|
| 121 |
+
Post-removal greps for every removed symbol return 0 hits, and the suite was
|
| 122 |
+
re-run after each removal.
|
| 123 |
+
|
| 124 |
+
---
|
| 125 |
+
|
| 126 |
+
## Tests
|
| 127 |
+
|
| 128 |
+
35 tests before, **83 after** (same 7 backend skips).
|
| 129 |
+
|
| 130 |
+
| File | Tests | Covers |
|
| 131 |
+
|---|---|---|
|
| 132 |
+
| `test_feature_pipeline.py` | 21 | no-lookahead, shapes, warm-up padding |
|
| 133 |
+
| `test_backtester_alignment.py` | 6 | walk-forward window and raw-column alignment |
|
| 134 |
+
| `test_models_with_features.py` | 8 (7 skip) | each model's real covariate path |
|
| 135 |
+
| `test_data_layer.py` | 14 | lookback honoured, chunking, clamping, resampling |
|
| 136 |
+
| `test_helpers.py` | 18 | history sizing, step inference, forming-candle drop |
|
| 137 |
+
| `test_indicators.py` | 16 | Wilder/std/zero-range conventions, warm-up NaN |
|
| 138 |
+
|
| 139 |
+
`test_data_layer.py` substitutes exactly one seam — `data.historical._fetch_yf`,
|
| 140 |
+
the single function that calls the vendor library — so request windowing can
|
| 141 |
+
be asserted without network. No shipped code path is mocked, and no stub file
|
| 142 |
+
is part of the project.
|
| 143 |
+
|
| 144 |
+
---
|
| 145 |
+
|
| 146 |
+
## Verified by execution
|
| 147 |
+
|
| 148 |
+
- `python -m compileall -q .` → exit 0
|
| 149 |
+
- `python -m unittest discover -s tests` → `Ran 83 tests ... OK (skipped=7)`
|
| 150 |
+
- Real SIGINT to `live_runner.py` → rc 0, no traceback, `Stopped.`
|
| 151 |
+
- Missing-backend path → actionable message per poll, loop survives
|
| 152 |
+
- Reproduction scripts for #1, #2, #3, #5, #7, #8, #9, #10 re-run after the
|
| 153 |
+
fixes and now report the corrected behaviour
|
| 154 |
+
|
| 155 |
+
## Not verifiable in this environment (no network)
|
| 156 |
+
|
| 157 |
+
`statsmodels`, `arch`, `uni2ts`, `gluonts`, `timesfm`, `torch`, `yfinance`
|
| 158 |
+
and `gradio` could not be installed, so real model fits, a real Yahoo
|
| 159 |
+
response and a Gradio launch were not executed here. Those paths were fixed
|
| 160 |
+
against their import and error contracts, and the model tests skip rather
|
| 161 |
+
than pretend to pass. Also unverified offline: the two Hugging Face
|
| 162 |
+
checkpoint strings in `config.py`, and `MATIC-USD` in the default symbol list
|
| 163 |
+
(Polygon's ticker moved to `POL-USD` in 2024) — both left as-is rather than
|
| 164 |
+
changed on a guess.
|
README.md
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Forex Crypto Prediction
|
| 3 |
+
emoji: 📈
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: green
|
| 6 |
+
sdk: gradio
|
| 7 |
+
app_file: app.py
|
| 8 |
+
pinned: false
|
| 9 |
+
python_version: "3.11"
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# 📈 Forex & Crypto Prediction Dashboard
|
| 13 |
+
|
| 14 |
+
Multi-timeframe forex & crypto price prediction with **ARIMA**,
|
| 15 |
+
**Auto-ARIMA**, **ARIMA-GARCH**, **Moirai** (Salesforce) and **TimesFM**
|
| 16 |
+
(Google). Each model is backtested **separately**, with a candle-by-candle
|
| 17 |
+
correct/incorrect verification log. Pure Python, sized for a CPU-only
|
| 18 |
+
Hugging Face Space (2 vCPU / 16GB RAM).
|
| 19 |
+
|
| 20 |
+
**Educational / research project — not financial advice.** Forex and crypto
|
| 21 |
+
trading carries substantial risk of loss.
|
| 22 |
+
|
| 23 |
+
## What's inside
|
| 24 |
+
|
| 25 |
+
- **Data**: [yfinance](https://github.com/ranaroussi/yfinance) (Yahoo
|
| 26 |
+
Finance), free and key-less. "Live" means polling on a timer — Yahoo has
|
| 27 |
+
no free websocket feed.
|
| 28 |
+
- **Any symbol** — dropdowns of common forex (`EURUSD=X`, ...) and crypto
|
| 29 |
+
(`BTC-USD`, ...) pairs, plus any yfinance ticker typed in by hand.
|
| 30 |
+
- **Timeframes** 1m, 5m, 10m, 15m, 30m, 1h, 4h, 1d. Intervals Yahoo does not
|
| 31 |
+
serve natively (10m, 4h) are resampled from a smaller native interval.
|
| 32 |
+
- **5 forecasting models** behind one interface (`models/base_model.py`):
|
| 33 |
+
- **ARIMA** (`statsmodels`) — brute-force AIC grid search for (p, d, q).
|
| 34 |
+
- **Auto-ARIMA** (`statsmodels`) — Hyndman-Khandakar-style stepwise
|
| 35 |
+
search, implemented on statsmodels rather than depending on `pmdarima`.
|
| 36 |
+
- **ARIMA-GARCH** (`statsmodels` + `arch`) — ARIMA for the conditional
|
| 37 |
+
mean, GARCH(1,1) for the conditional variance. The volatility forecast
|
| 38 |
+
stays on the instance as `last_volatility_forecast`.
|
| 39 |
+
- **Moirai** (`uni2ts`) — pretrained, zero-shot.
|
| 40 |
+
- **TimesFM 2.5** (`timesfm`) — pretrained, zero-shot.
|
| 41 |
+
- **5 technical indicators** implemented on pandas (no TA dependency): RSI,
|
| 42 |
+
MACD, Bollinger Bands, SMA/EMA, Stochastic. They are informational and
|
| 43 |
+
never mixed into model accuracy. During an indicator's warm-up period the
|
| 44 |
+
value is genuinely undefined, so it stays `NaN` and the UI reports
|
| 45 |
+
"Insufficient data" instead of a neutral-looking filler number.
|
| 46 |
+
- **Walk-forward backtesting** with a separate accuracy card per model
|
| 47 |
+
(correct / incorrect / accuracy % / MAE / RMSE, never averaged across
|
| 48 |
+
models) plus the per-candle prediction log behind it.
|
| 49 |
+
- **Live tab**: predicts the next candle, then grades it once that candle has
|
| 50 |
+
actually closed. `live_runner.py` does the same unattended from the CLI,
|
| 51 |
+
appending to CSV.
|
| 52 |
+
|
| 53 |
+
## Project layout
|
| 54 |
+
|
| 55 |
+
```
|
| 56 |
+
config.py symbols, timeframes, interval limits, checkpoints
|
| 57 |
+
app.py Gradio dashboard (entry point for the Space)
|
| 58 |
+
live_runner.py standalone CLI for unattended live logging
|
| 59 |
+
data/
|
| 60 |
+
historical.py yfinance fetch, chunking, resampling
|
| 61 |
+
indicators/
|
| 62 |
+
indicators.py RSI, MACD, Bollinger Bands, SMA/EMA, Stochastic
|
| 63 |
+
features/
|
| 64 |
+
feature_pipeline.py leak-free covariate pipeline shared by backtest,
|
| 65 |
+
live prediction and the Prediction tab
|
| 66 |
+
models/
|
| 67 |
+
base_model.py shared interface all 5 models implement
|
| 68 |
+
dependencies.py lazy optional-dependency imports + fit-scoped quiet
|
| 69 |
+
arima_model.py ARIMA (statsmodels), cached order search
|
| 70 |
+
auto_arima_model.py Auto-ARIMA (statsmodels), cached stepwise search
|
| 71 |
+
arima_garch_model.py ARIMA-GARCH (statsmodels + arch)
|
| 72 |
+
moirai_model.py Moirai (uni2ts + GluonTS)
|
| 73 |
+
timesfm_model.py TimesFM 2.5 (timesfm[torch])
|
| 74 |
+
registry.py lazy-loading model factory
|
| 75 |
+
backtest/
|
| 76 |
+
backtester.py walk-forward loop + per-model accuracy summary
|
| 77 |
+
utils/
|
| 78 |
+
helpers.py history sizing, step inference, candle hygiene
|
| 79 |
+
tests/
|
| 80 |
+
test_feature_pipeline.py no-lookahead + shape checks
|
| 81 |
+
test_backtester_alignment.py walk-forward window alignment
|
| 82 |
+
test_models_with_features.py per-model covariate path (skips when a
|
| 83 |
+
model's backend is not installed)
|
| 84 |
+
test_data_layer.py fetch windowing, chunking, resampling
|
| 85 |
+
test_helpers.py history sizing and candle hygiene
|
| 86 |
+
test_indicators.py indicator conventions and warm-up NaN
|
| 87 |
+
requirements.txt
|
| 88 |
+
```
|
| 89 |
+
|
| 90 |
+
## Running locally
|
| 91 |
+
|
| 92 |
+
```bash
|
| 93 |
+
python -m venv venv
|
| 94 |
+
source venv/bin/activate # Windows: venv\Scripts\activate
|
| 95 |
+
pip install -r requirements.txt
|
| 96 |
+
python app.py
|
| 97 |
+
```
|
| 98 |
+
|
| 99 |
+
Open the URL Gradio prints (usually `http://127.0.0.1:7860`).
|
| 100 |
+
|
| 101 |
+
## Running the tests
|
| 102 |
+
|
| 103 |
+
```bash
|
| 104 |
+
python -m unittest discover -s tests -v
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
`test_feature_pipeline.py`, `test_backtester_alignment.py`,
|
| 108 |
+
`test_data_layer.py`, `test_helpers.py` and `test_indicators.py` need only
|
| 109 |
+
`pandas`/`numpy` and always run in full — they are what proves the
|
| 110 |
+
leak-free, window-alignment, fetch-sizing and indicator claims above by
|
| 111 |
+
execution. `test_models_with_features.py` exercises each model's real
|
| 112 |
+
`features=` path and skips (never fails) whichever backend is missing;
|
| 113 |
+
install `requirements.txt` fully to run all of it.
|
| 114 |
+
|
| 115 |
+
`test_data_layer.py` substitutes the one vendor call
|
| 116 |
+
(`data.historical._fetch_yf`) with a recording stand-in so request
|
| 117 |
+
windowing, chunking and stitching can be asserted offline. Nothing in the
|
| 118 |
+
shipped application code is mocked or simulated.
|
| 119 |
+
|
| 120 |
+
## Live CLI
|
| 121 |
+
|
| 122 |
+
```bash
|
| 123 |
+
python live_runner.py --symbol BTC-USD --timeframe 5m --model ARIMA
|
| 124 |
+
python live_runner.py --symbol EURUSD=X --timeframe 15m --model TimesFM --poll-seconds 120
|
| 125 |
+
python live_runner.py --symbol BTC-USD --timeframe 15m --model ARIMA --use-features
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
Ctrl+C stops it cleanly at any point, including mid-sleep between polls.
|
| 129 |
+
Each verified candle is appended to
|
| 130 |
+
`outputs/live_<symbol>_<timeframe>_<model>[_featured].csv`.
|
| 131 |
+
|
| 132 |
+
## Deploying to Hugging Face Spaces
|
| 133 |
+
|
| 134 |
+
1. Create a Space → SDK **Gradio** → the free 2 vCPU / 16GB CPU tier is
|
| 135 |
+
enough for all 5 models at their default (small) checkpoints.
|
| 136 |
+
2. Upload the project with its folder structure intact.
|
| 137 |
+
3. The YAML block at the top of this README is the Space configuration
|
| 138 |
+
(`sdk: gradio`, `app_file: app.py`).
|
| 139 |
+
4. Push. Spaces installs `requirements.txt` and launches `app.py`. ARIMA
|
| 140 |
+
works immediately; Moirai/TimesFM download weights on first use.
|
| 141 |
+
|
| 142 |
+
## Models on CPU-only hardware
|
| 143 |
+
|
| 144 |
+
| Model | Package | Approx. size | Notes |
|
| 145 |
+
|---|---|---|---|
|
| 146 |
+
| ARIMA | `statsmodels` | tiny | Fastest. Order searched once per instance (brute-force AIC grid), then reused. |
|
| 147 |
+
| Auto-ARIMA | `statsmodels` | tiny | Stepwise search, usually fewer candidate fits than the grid. |
|
| 148 |
+
| ARIMA-GARCH | `statsmodels` + `arch` | tiny | Two fits per prediction (mean + volatility). |
|
| 149 |
+
| Moirai (`moirai-1.1-R-small`) | `uni2ts` | ~14M params | Zero-shot. |
|
| 150 |
+
| TimesFM 2.5 (`timesfm-2.5-200m`) | `timesfm[torch]` | ~800MB download, ~4GB RAM | Zero-shot. |
|
| 151 |
+
|
| 152 |
+
The foundation models are slower per prediction on CPU, which matters most
|
| 153 |
+
in the Backtest tab (one call per candle). Use the **Step** slider to skip
|
| 154 |
+
candles. Checkpoints are configurable in `config.py`.
|
| 155 |
+
|
| 156 |
+
## 10-feature covariate input (optional, off by default)
|
| 157 |
+
|
| 158 |
+
Every model can take more than the Close series: Open, High, Low, Volume,
|
| 159 |
+
RSI(14), MACD (line/signal/histogram), Bollinger (upper/lower), SMA/EMA and
|
| 160 |
+
Stochastic (%K/%D) — 14 numeric columns from 9 usable categories. Off by
|
| 161 |
+
default everywhere (checkbox in Prediction/Live, a 3-way mode in Backtest,
|
| 162 |
+
`--use-features` in `live_runner.py`).
|
| 163 |
+
|
| 164 |
+
Close is excluded because it is the series being forecast (and, for the
|
| 165 |
+
ARIMA family, a design-matrix column perfectly collinear with the dependent
|
| 166 |
+
variable). Bollinger's mid band is excluded because it is defined as
|
| 167 |
+
`sma(close, 20)`, already present as `SMA_20`. Full list and reasoning:
|
| 168 |
+
`features/feature_pipeline.py`.
|
| 169 |
+
|
| 170 |
+
**Leak-free by construction:** every feature value at candle *t* is computed
|
| 171 |
+
only from candles ≤ *t*, and `tests/test_feature_pipeline.py` proves it by
|
| 172 |
+
truncating the input at different points and checking already-computed
|
| 173 |
+
values are identical either way. Where a model's API structurally needs
|
| 174 |
+
covariates for candles that have not happened yet (multi-step ARIMA-family
|
| 175 |
+
forecasts, TimesFM's `forecast_with_covariates`), the last known real
|
| 176 |
+
reading is held constant — a labelled persistence assumption that uses no
|
| 177 |
+
future information. Moirai never needs it: `past_feat_dynamic_real` is
|
| 178 |
+
past-only by design.
|
| 179 |
+
|
| 180 |
+
Indicators need real history before they mean anything, so
|
| 181 |
+
`get_historical_with_features()` fetches warm-up candles *before* the
|
| 182 |
+
requested period, computes the indicators on the padded frame, then trims
|
| 183 |
+
back to the requested period. That is why a features-on backtest no longer
|
| 184 |
+
fails its first ~19 candles with `feature window contains NaN in
|
| 185 |
+
['BB_Upper','BB_Lower','SMA_20']`.
|
| 186 |
+
|
| 187 |
+
| Model | Covariate mechanism |
|
| 188 |
+
|---|---|
|
| 189 |
+
| ARIMA / Auto-ARIMA / ARIMA-GARCH | `statsmodels`' native `exog` (a genuine ARIMAX), including inside the order search |
|
| 190 |
+
| Moirai | `past_feat_dynamic_real` (uni2ts/GluonTS) |
|
| 191 |
+
| TimesFM 2.5 | `forecast_with_covariates()` (needs `timesfm[xreg]`) |
|
| 192 |
+
|
| 193 |
+
The Backtest tab's "Compare both" mode runs each selected model twice —
|
| 194 |
+
Close-only and featured — on the identical symbol, timeframe, window,
|
| 195 |
+
horizon, step and period, and shows both numbers side by side.
|
| 196 |
+
|
| 197 |
+
## How accuracy is measured
|
| 198 |
+
|
| 199 |
+
The model forecasts the next close; the predicted direction (up/down
|
| 200 |
+
relative to the current close) is compared with what actually happened.
|
| 201 |
+
Accuracy % is `correct / (correct + incorrect)` per model. MAE/RMSE are
|
| 202 |
+
reported alongside, rounded to 6 **significant figures** so a real error on
|
| 203 |
+
a sub-cent token is not displayed as `0.0`.
|
| 204 |
+
|
| 205 |
+
"Once that candle closes" is enforced, not assumed:
|
| 206 |
+
|
| 207 |
+
- **Live** (tab and CLI) verifies a prediction only when a *newer* candle
|
| 208 |
+
exists after its target, never merely because the target timestamp has
|
| 209 |
+
appeared. Yahoo's last intraday row is the still-forming candle, whose
|
| 210 |
+
Close is only the latest trade so far.
|
| 211 |
+
- **Backtest** drops that still-forming last candle before walking forward,
|
| 212 |
+
so the final graded prediction is never scored against a moving target.
|
| 213 |
+
- The Live fetch window is sized to cover both the model's own history
|
| 214 |
+
requirement (200 candles for the timeframe) and the oldest still-pending
|
| 215 |
+
prediction, clamped to what the source interval can serve. A row whose
|
| 216 |
+
target is older than that limit can ever reach is labelled
|
| 217 |
+
`unresolvable (past history limit)` instead of sitting as "pending"
|
| 218 |
+
forever and silently shrinking the denominator.
|
| 219 |
+
|
| 220 |
+
## Known limitations
|
| 221 |
+
|
| 222 |
+
- **Yahoo history limits** (Yahoo's, not this project's): 1m ≈ last 30 days
|
| 223 |
+
and at most 7 days per request — wider 1m windows are fetched in several
|
| 224 |
+
stitched requests; other intraday intervals ≈ 60 days; hourly ≈ 730 days;
|
| 225 |
+
daily and above, full history. Requests outside a limit are clamped, and a
|
| 226 |
+
fetch that returns nothing usable raises an error naming the limit.
|
| 227 |
+
- **"Live" is polling, not push.** Suitable for candle-close decisions, not
|
| 228 |
+
tick-by-tick use.
|
| 229 |
+
- **"All symbols"** means whatever Yahoo covers; there is no finite list to
|
| 230 |
+
ship, so any ticker can be typed in.
|
| 231 |
+
- **Small checkpoints** were chosen for 2 vCPU / 16GB. Larger ones may
|
| 232 |
+
forecast better but need more RAM and CPU time.
|
| 233 |
+
- Candle data is sorted and de-duplicated on every fetch path before it
|
| 234 |
+
reaches the backtester or indicators, because the walk-forward loop
|
| 235 |
+
assumes strictly oldest→newest input.
|
| 236 |
+
- **Not verifiable offline** (no network in the environment this was
|
| 237 |
+
debugged in), so confirm on first run in your own environment: the two HF
|
| 238 |
+
Hub checkpoint strings in `config.py` resolve; `uni2ts`/`timesfm` still
|
| 239 |
+
expose the covariate APIs used here (both are active research projects);
|
| 240 |
+
and the featured path on Moirai/TimesFM. The ARIMA-family covariate path
|
| 241 |
+
uses long-stable `statsmodels` APIs. Every model validates its own
|
| 242 |
+
forecast is finite before returning, so a bad forecast becomes a visible
|
| 243 |
+
"failed" row instead of silently corrupting the accuracy numbers.
|
| 244 |
+
- **Multi-step forecasts (horizon > 1) with features on** hold each
|
| 245 |
+
covariate's last real value constant for steps beyond the first, so a
|
| 246 |
+
horizon=5 featured forecast's covariates are only as fresh as candle 1's.
|
| 247 |
+
|
| 248 |
+
## Disclaimer
|
| 249 |
+
|
| 250 |
+
This project is for education and research. It is not financial advice, and
|
| 251 |
+
backtested accuracy is not a promise of future performance.
|
app.py
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Forex & Crypto Prediction Dashboard — Gradio app, entry point for the
|
| 3 |
+
Hugging Face Space (see README.md for the Space YAML header / deployment).
|
| 4 |
+
|
| 5 |
+
Tabs:
|
| 6 |
+
1. Chart & Indicators - candlestick chart + the top 5 technical indicators
|
| 7 |
+
2. Prediction - ARIMA / Auto-ARIMA / ARIMA-GARCH / Moirai / TimesFM
|
| 8 |
+
forecasts, shown together on one chart for
|
| 9 |
+
visual comparison
|
| 10 |
+
3. Backtest - walk-forward backtest; each model gets its own
|
| 11 |
+
SEPARATE accuracy card + per-candle verify log
|
| 12 |
+
(numbers are never averaged across models)
|
| 13 |
+
4. Live - poll the newest candle, predict the next one, and
|
| 14 |
+
verify the previous prediction once it lands
|
| 15 |
+
|
| 16 |
+
Educational project — nothing here is financial advice.
|
| 17 |
+
"""
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
import plotly.graph_objects as go
|
| 21 |
+
import gradio as gr
|
| 22 |
+
|
| 23 |
+
from config import ALL_DEFAULT_SYMBOLS, CUSTOM_TIMEFRAMES, MODEL_NAMES, YF_NATIVE_INTERVALS
|
| 24 |
+
from data.historical import get_historical, get_historical_with_features, DataFetchError
|
| 25 |
+
from indicators.indicators import add_all_indicators, latest_signals
|
| 26 |
+
from models.registry import get_model, fresh_model
|
| 27 |
+
from backtest.backtester import (
|
| 28 |
+
run_all_models_backtest, run_comparison_backtest,
|
| 29 |
+
BASELINE_LABEL, FEATURED_LABEL,
|
| 30 |
+
)
|
| 31 |
+
from utils.helpers import (PREDICTION_HISTORY_CANDLES, drop_forming_candle, future_index,
|
| 32 |
+
history_days_for_candles, infer_step)
|
| 33 |
+
|
| 34 |
+
TIMEFRAME_CHOICES = list(CUSTOM_TIMEFRAMES.keys())
|
| 35 |
+
DISCLAIMER = (
|
| 36 |
+
"**Educational / research project — not financial advice.** "
|
| 37 |
+
"Forex and crypto trading carries substantial risk of loss."
|
| 38 |
+
)
|
| 39 |
+
FEATURES_HELP = (
|
| 40 |
+
"**10-feature input** feeds each model Open/High/Low/Volume plus RSI, MACD, "
|
| 41 |
+
"Bollinger Bands, SMA/EMA and Stochastic — computed leak-free (only data "
|
| 42 |
+
"available at each prediction's own point in time) — in addition to the "
|
| 43 |
+
"Close-price series every model already uses. Off by default; this changes "
|
| 44 |
+
"nothing about the original Close-only behavior unless you turn it on. "
|
| 45 |
+
"See features/feature_pipeline.py for exactly what's computed and how "
|
| 46 |
+
"each model consumes it."
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# ---------------------------------------------------------------------------
|
| 51 |
+
# Tab 1: Chart & Indicators
|
| 52 |
+
# ---------------------------------------------------------------------------
|
| 53 |
+
def make_candlestick_figure(df: pd.DataFrame, symbol: str, timeframe: str) -> go.Figure:
|
| 54 |
+
fig = go.Figure(data=[go.Candlestick(
|
| 55 |
+
x=df.index, open=df["Open"], high=df["High"], low=df["Low"], close=df["Close"],
|
| 56 |
+
name=symbol,
|
| 57 |
+
)])
|
| 58 |
+
if "SMA_20" in df:
|
| 59 |
+
fig.add_trace(go.Scatter(x=df.index, y=df["SMA_20"], name="SMA 20", line=dict(width=1)))
|
| 60 |
+
if "EMA_20" in df:
|
| 61 |
+
fig.add_trace(go.Scatter(x=df.index, y=df["EMA_20"], name="EMA 20", line=dict(width=1)))
|
| 62 |
+
if "BB_Upper" in df:
|
| 63 |
+
fig.add_trace(go.Scatter(x=df.index, y=df["BB_Upper"], name="BB Upper",
|
| 64 |
+
line=dict(width=1, dash="dot")))
|
| 65 |
+
fig.add_trace(go.Scatter(x=df.index, y=df["BB_Lower"], name="BB Lower",
|
| 66 |
+
line=dict(width=1, dash="dot")))
|
| 67 |
+
fig.update_layout(title=f"{symbol} — {timeframe}", xaxis_rangeslider_visible=False,
|
| 68 |
+
height=480, margin=dict(l=10, r=10, t=40, b=10))
|
| 69 |
+
return fig
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def fetch_and_chart(symbol, timeframe, lookback_days):
|
| 73 |
+
try:
|
| 74 |
+
df = get_historical(symbol, timeframe, lookback_days=int(lookback_days))
|
| 75 |
+
df_ind = add_all_indicators(df)
|
| 76 |
+
fig = make_candlestick_figure(df_ind, symbol, timeframe)
|
| 77 |
+
signals = latest_signals(df_ind)
|
| 78 |
+
signal_rows = [[name, str(v["value"]), v["signal"]] for name, v in signals.items()]
|
| 79 |
+
status = f"Loaded {len(df)} candles for {symbol} ({timeframe})."
|
| 80 |
+
return fig, signal_rows, status
|
| 81 |
+
except DataFetchError as e:
|
| 82 |
+
return None, [], f"Data error: {e}"
|
| 83 |
+
except Exception as e:
|
| 84 |
+
return None, [], f"Unexpected error: {e}"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ---------------------------------------------------------------------------
|
| 88 |
+
# Tab 2: Prediction
|
| 89 |
+
# ---------------------------------------------------------------------------
|
| 90 |
+
def run_prediction(symbol, timeframe, selected_models, horizon, lookback_days, use_features):
|
| 91 |
+
if not selected_models:
|
| 92 |
+
return None, "Pick at least one model."
|
| 93 |
+
try:
|
| 94 |
+
df, features_df = get_historical_with_features(
|
| 95 |
+
symbol, timeframe, lookback_days=int(lookback_days), use_features=use_features,
|
| 96 |
+
)
|
| 97 |
+
except Exception as e:
|
| 98 |
+
return None, f"Data error: {e}"
|
| 99 |
+
|
| 100 |
+
close = df["Close"]
|
| 101 |
+
horizon = int(horizon)
|
| 102 |
+
step = infer_step(df.index)
|
| 103 |
+
|
| 104 |
+
fig = go.Figure()
|
| 105 |
+
tail = close.iloc[-150:]
|
| 106 |
+
fig.add_trace(go.Scatter(x=tail.index, y=tail.values, name="Actual Close",
|
| 107 |
+
line=dict(color="#888888")))
|
| 108 |
+
|
| 109 |
+
mode_label = f" [{FEATURED_LABEL}]" if use_features else ""
|
| 110 |
+
summary_lines = []
|
| 111 |
+
for name in selected_models:
|
| 112 |
+
try:
|
| 113 |
+
model = get_model(name, symbol, timeframe, use_features=use_features)
|
| 114 |
+
forecast = model.predict(close, horizon=horizon, features=features_df)
|
| 115 |
+
fc_index = future_index(df.index[-1], step, len(forecast))
|
| 116 |
+
fig.add_trace(go.Scatter(x=fc_index, y=forecast, name=f"{name}{mode_label} forecast",
|
| 117 |
+
mode="lines+markers"))
|
| 118 |
+
direction = "UP" if forecast[-1] > close.iloc[-1] else "DOWN"
|
| 119 |
+
summary_lines.append(f"**{name}**{mode_label} — next close (approx.) `{forecast[-1]:.5f}` ({direction})")
|
| 120 |
+
except Exception as e:
|
| 121 |
+
summary_lines.append(f"**{name}**{mode_label} — failed: {e}")
|
| 122 |
+
|
| 123 |
+
fig.update_layout(title=f"{symbol} — {timeframe} forecast ({horizon} candle(s) ahead)",
|
| 124 |
+
height=450, margin=dict(l=10, r=10, t=40, b=10))
|
| 125 |
+
return fig, "\n\n".join(summary_lines) + "\n\n" + DISCLAIMER
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# ---------------------------------------------------------------------------
|
| 129 |
+
# Tab 3: Backtest
|
| 130 |
+
# ---------------------------------------------------------------------------
|
| 131 |
+
FEATURE_MODE_BASELINE = "Close-only (baseline)"
|
| 132 |
+
FEATURE_MODE_FEATURED = "+10-feature input"
|
| 133 |
+
FEATURE_MODE_COMPARE = "Compare both"
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _summary_row(summary: dict, mode_label: str) -> list:
|
| 137 |
+
return [
|
| 138 |
+
mode_label, summary["model"], summary["total_predictions"], summary["correct"],
|
| 139 |
+
summary["incorrect"], f"{summary['accuracy_pct']}%",
|
| 140 |
+
summary["mae"], summary["rmse"], summary["failed_predictions"],
|
| 141 |
+
]
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def run_backtest_ui(symbol, timeframe, selected_models, window, horizon, step_size,
|
| 145 |
+
lookback_days, feature_mode):
|
| 146 |
+
empty = pd.DataFrame()
|
| 147 |
+
if not selected_models:
|
| 148 |
+
return [], empty, empty, empty, empty, empty, "Pick at least one model."
|
| 149 |
+
|
| 150 |
+
needs_features = feature_mode != FEATURE_MODE_BASELINE
|
| 151 |
+
try:
|
| 152 |
+
df, features_df = get_historical_with_features(
|
| 153 |
+
symbol, timeframe, lookback_days=int(lookback_days),
|
| 154 |
+
use_features=needs_features,
|
| 155 |
+
)
|
| 156 |
+
except Exception as e:
|
| 157 |
+
return [], empty, empty, empty, empty, empty, f"Data error: {e}"
|
| 158 |
+
|
| 159 |
+
# The newest candle is still forming, so its close has not settled and a
|
| 160 |
+
# prediction graded against it would be scored on a moving target.
|
| 161 |
+
df, features_df = drop_forming_candle(df, features_df)
|
| 162 |
+
|
| 163 |
+
window, horizon, step_size = int(window), int(horizon), int(step_size)
|
| 164 |
+
if len(df) < window + horizon + 5:
|
| 165 |
+
return [], empty, empty, empty, empty, empty, (
|
| 166 |
+
f"Only {len(df)} candles available — raise 'Backtest lookback (days)' "
|
| 167 |
+
f"or lower the window size to backtest this symbol/timeframe."
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
# df, window, horizon and step_size are fixed here and reused unchanged
|
| 171 |
+
# by every model and mode below, so the results stay comparable.
|
| 172 |
+
summary_table = []
|
| 173 |
+
detail = {"ARIMA": empty, "Auto-ARIMA": empty, "ARIMA-GARCH": empty,
|
| 174 |
+
"Moirai": empty, "TimesFM": empty}
|
| 175 |
+
|
| 176 |
+
if feature_mode == FEATURE_MODE_COMPARE:
|
| 177 |
+
models = {name: (fresh_model(name), fresh_model(name)) for name in selected_models}
|
| 178 |
+
try:
|
| 179 |
+
per_model_results, per_model_summaries = run_comparison_backtest(
|
| 180 |
+
df, models, features_df, window=window, horizon=horizon, step=step_size,
|
| 181 |
+
)
|
| 182 |
+
except Exception as e:
|
| 183 |
+
return [], empty, empty, empty, empty, empty, f"Backtest error: {e}"
|
| 184 |
+
for name in selected_models:
|
| 185 |
+
for summary in per_model_summaries[name]:
|
| 186 |
+
summary_table.append(_summary_row(summary, summary["mode"]))
|
| 187 |
+
detail[name] = per_model_results[name]
|
| 188 |
+
else:
|
| 189 |
+
use_features = feature_mode == FEATURE_MODE_FEATURED
|
| 190 |
+
mode_label = FEATURED_LABEL if use_features else BASELINE_LABEL
|
| 191 |
+
models = {name: fresh_model(name) for name in selected_models}
|
| 192 |
+
try:
|
| 193 |
+
per_model_results, per_model_summaries = run_all_models_backtest(
|
| 194 |
+
df, models, window=window, horizon=horizon, step=step_size,
|
| 195 |
+
features_df=features_df if use_features else None,
|
| 196 |
+
)
|
| 197 |
+
except Exception as e:
|
| 198 |
+
return [], empty, empty, empty, empty, empty, f"Backtest error: {e}"
|
| 199 |
+
for name in selected_models:
|
| 200 |
+
summary_table.append(_summary_row(per_model_summaries[name], mode_label))
|
| 201 |
+
results = per_model_results[name].copy()
|
| 202 |
+
results.insert(0, "mode", mode_label)
|
| 203 |
+
detail[name] = results
|
| 204 |
+
|
| 205 |
+
status = (f"Backtested {', '.join(selected_models)} on {len(df)} candles of "
|
| 206 |
+
f"{symbol} ({timeframe}) — mode: {feature_mode}.")
|
| 207 |
+
return (summary_table, detail["ARIMA"], detail["Auto-ARIMA"], detail["ARIMA-GARCH"],
|
| 208 |
+
detail["Moirai"], detail["TimesFM"], status)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
# ---------------------------------------------------------------------------
|
| 212 |
+
# Tab 4: Live
|
| 213 |
+
# ---------------------------------------------------------------------------
|
| 214 |
+
LIVE_COLUMNS = ["predicted_at", "mode", "target_time", "current_close", "predicted_close",
|
| 215 |
+
"predicted_direction", "actual_close", "actual_direction", "correct"]
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def _make_empty_live_log() -> pd.DataFrame:
|
| 219 |
+
"""Empty live-log frame with explicit dtypes, so concat-ing typed rows
|
| 220 |
+
onto it does not warn on pandas 3.x."""
|
| 221 |
+
return pd.DataFrame({
|
| 222 |
+
"predicted_at": pd.Series(dtype="object"),
|
| 223 |
+
"mode": pd.Series(dtype="object"),
|
| 224 |
+
"target_time": pd.Series(dtype="object"),
|
| 225 |
+
"current_close": pd.Series(dtype="float64"),
|
| 226 |
+
"predicted_close": pd.Series(dtype="float64"),
|
| 227 |
+
"predicted_direction": pd.Series(dtype="object"),
|
| 228 |
+
"actual_close": pd.Series(dtype="float64"),
|
| 229 |
+
"actual_direction": pd.Series(dtype="object"),
|
| 230 |
+
"correct": pd.Series(dtype="object"),
|
| 231 |
+
})
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _required_lookback_days(log_df, minimum_days: int = 2) -> int:
|
| 235 |
+
"""Days of history needed to reach the oldest still-pending prediction's
|
| 236 |
+
target candle, so rows do not stay pending forever."""
|
| 237 |
+
if log_df is None or len(log_df) == 0:
|
| 238 |
+
return minimum_days
|
| 239 |
+
pending = log_df[log_df["actual_close"].isna()]
|
| 240 |
+
if len(pending) == 0:
|
| 241 |
+
return minimum_days
|
| 242 |
+
# utc=True: object-stored Timestamps can lose their tz after concat.
|
| 243 |
+
oldest_target = pd.to_datetime(pending["target_time"], utc=True).min()
|
| 244 |
+
now = pd.Timestamp.now(tz="UTC")
|
| 245 |
+
age_days = (now - oldest_target).total_seconds() / 86400
|
| 246 |
+
return max(minimum_days, int(age_days) + 2)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def _check_live_impl(symbol, timeframe, model_name, log_df, use_features=False):
|
| 250 |
+
if log_df is None or len(log_df) == 0:
|
| 251 |
+
log_df = _make_empty_live_log()
|
| 252 |
+
else:
|
| 253 |
+
log_df = log_df.copy()
|
| 254 |
+
|
| 255 |
+
# Fetch far enough back for both jobs this function does: verifying the
|
| 256 |
+
# oldest still-pending prediction, and handing the model enough candles
|
| 257 |
+
# to forecast from. Indicator warm-up is padded on top inside
|
| 258 |
+
# get_historical_with_features. Clamping to what the source interval can
|
| 259 |
+
# serve also tells us when a pending row has aged out of reach.
|
| 260 |
+
source_interval = CUSTOM_TIMEFRAMES.get(timeframe, {}).get("source", timeframe)
|
| 261 |
+
max_servable_days = YF_NATIVE_INTERVALS.get(source_interval, {}).get("max_days")
|
| 262 |
+
wanted_days = max(_required_lookback_days(log_df),
|
| 263 |
+
history_days_for_candles(timeframe, PREDICTION_HISTORY_CANDLES))
|
| 264 |
+
fetch_days = min(wanted_days, max_servable_days) if max_servable_days else wanted_days
|
| 265 |
+
|
| 266 |
+
df, features_df = get_historical_with_features(
|
| 267 |
+
symbol, timeframe, lookback_days=fetch_days, use_features=use_features,
|
| 268 |
+
)
|
| 269 |
+
latest_time = df.index[-1]
|
| 270 |
+
latest_close = float(df["Close"].iloc[-1])
|
| 271 |
+
|
| 272 |
+
# 1) Verify pending predictions whose target candle has CLOSED. Requiring
|
| 273 |
+
# a strictly newer candle to exist skips the still-forming candle Yahoo
|
| 274 |
+
# includes in df.index, whose close would be read mid-formation.
|
| 275 |
+
pending_mask = log_df["actual_close"].isna()
|
| 276 |
+
for idx, row in log_df[pending_mask].iterrows():
|
| 277 |
+
if row["target_time"] in df.index and row["target_time"] < latest_time:
|
| 278 |
+
actual_close = float(df.loc[row["target_time"], "Close"])
|
| 279 |
+
actual_direction = "up" if actual_close > row["current_close"] else "down"
|
| 280 |
+
log_df.loc[idx, "actual_close"] = actual_close
|
| 281 |
+
log_df.loc[idx, "actual_direction"] = actual_direction
|
| 282 |
+
log_df.loc[idx, "correct"] = bool(actual_direction == row["predicted_direction"])
|
| 283 |
+
|
| 284 |
+
# 1b) A pending row older than this timeframe's history limit can never be
|
| 285 |
+
# reached by a future fetch, so mark it unresolvable rather than leave
|
| 286 |
+
# it looking like it is still being collected. actual_close stays NaN
|
| 287 |
+
# so it is excluded from the accuracy denominator.
|
| 288 |
+
if max_servable_days is not None:
|
| 289 |
+
cutoff = pd.Timestamp.now(tz="UTC") - pd.Timedelta(days=max_servable_days)
|
| 290 |
+
# Object-stored Timestamps can lose their tz after concat.
|
| 291 |
+
target_times = pd.to_datetime(log_df["target_time"], utc=True)
|
| 292 |
+
unreachable = log_df["actual_close"].isna() & (target_times < cutoff)
|
| 293 |
+
if unreachable.any():
|
| 294 |
+
log_df.loc[unreachable, "actual_direction"] = "unresolvable (past history limit)"
|
| 295 |
+
log_df.loc[unreachable, "correct"] = None
|
| 296 |
+
|
| 297 |
+
# 2) Make a fresh prediction unless one is already pending for this candle.
|
| 298 |
+
# Dedup by timestamp, not close price (a forming candle's close drifts
|
| 299 |
+
# between polls; two distinct candles can coincidentally match prices).
|
| 300 |
+
have_pending_for_latest = False
|
| 301 |
+
if len(log_df):
|
| 302 |
+
last_row = log_df.iloc[-1]
|
| 303 |
+
# pd.Timestamp() normalises object-stored tz-aware timestamps for reliable equality
|
| 304 |
+
have_pending_for_latest = (
|
| 305 |
+
pd.isna(last_row["actual_close"])
|
| 306 |
+
and pd.Timestamp(last_row["predicted_at"]) == pd.Timestamp(latest_time)
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
status_extra = ""
|
| 310 |
+
if not have_pending_for_latest:
|
| 311 |
+
try:
|
| 312 |
+
model = get_model(model_name, symbol, timeframe, use_features=use_features)
|
| 313 |
+
forecast = model.predict(df["Close"], horizon=1, features=features_df)
|
| 314 |
+
predicted_close = float(forecast[-1])
|
| 315 |
+
predicted_direction = "up" if predicted_close > latest_close else "down"
|
| 316 |
+
step = infer_step(df.index)
|
| 317 |
+
new_row = {
|
| 318 |
+
"predicted_at": latest_time,
|
| 319 |
+
"mode": FEATURED_LABEL if use_features else BASELINE_LABEL,
|
| 320 |
+
"target_time": latest_time + step,
|
| 321 |
+
"current_close": latest_close, "predicted_close": predicted_close,
|
| 322 |
+
"predicted_direction": predicted_direction, "actual_close": np.nan,
|
| 323 |
+
"actual_direction": None, "correct": None,
|
| 324 |
+
}
|
| 325 |
+
log_df = pd.concat([log_df, pd.DataFrame([new_row])], ignore_index=True)
|
| 326 |
+
except Exception as e:
|
| 327 |
+
status_extra = f" (prediction failed: {e})"
|
| 328 |
+
|
| 329 |
+
verified = log_df.dropna(subset=["correct"])
|
| 330 |
+
current_mode = FEATURED_LABEL if use_features else BASELINE_LABEL
|
| 331 |
+
# The log can hold rows from both modes if the checkbox was toggled
|
| 332 |
+
# mid-session; accuracy always counts the current mode's rows only.
|
| 333 |
+
verified_this_mode = verified[verified["mode"] == current_mode]
|
| 334 |
+
if len(verified_this_mode):
|
| 335 |
+
acc = round(100 * verified_this_mode["correct"].sum() / len(verified_this_mode), 2)
|
| 336 |
+
acc_text = (f"Running accuracy for {model_name} [{current_mode}]: {acc}% "
|
| 337 |
+
f"({int(verified_this_mode['correct'].sum())}/{len(verified_this_mode)})")
|
| 338 |
+
other_count = len(verified) - len(verified_this_mode)
|
| 339 |
+
if other_count:
|
| 340 |
+
acc_text += f" — {other_count} verified prediction(s) from the other mode are in the table below but not counted here."
|
| 341 |
+
else:
|
| 342 |
+
acc_text = "Collecting data — check again after the next candle closes to see accuracy."
|
| 343 |
+
|
| 344 |
+
status = f"Latest {symbol} candle: {latest_time} — Close {latest_close:.5f}. {acc_text}{status_extra}"
|
| 345 |
+
return status, log_df.tail(20), log_df
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def check_live(symbol, timeframe, model_name, log_df, use_features=False):
|
| 349 |
+
try:
|
| 350 |
+
return _check_live_impl(symbol, timeframe, model_name, log_df, use_features=use_features)
|
| 351 |
+
except Exception as e:
|
| 352 |
+
safe_log = log_df if (log_df is not None and len(log_df)) else _make_empty_live_log()
|
| 353 |
+
return f"Error: {e}", safe_log.tail(20), safe_log
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
# ---------------------------------------------------------------------------
|
| 357 |
+
# UI
|
| 358 |
+
# ---------------------------------------------------------------------------
|
| 359 |
+
with gr.Blocks(title="Forex & Crypto Prediction Dashboard") as demo:
|
| 360 |
+
gr.Markdown(
|
| 361 |
+
"# 📈 Forex & Crypto Prediction Dashboard\n"
|
| 362 |
+
"ARIMA, Auto-ARIMA, ARIMA-GARCH, Moirai (Salesforce) & TimesFM (Google) — "
|
| 363 |
+
"each model's accuracy is tracked and shown **separately**, never averaged "
|
| 364 |
+
"together.\n\n" + DISCLAIMER
|
| 365 |
+
)
|
| 366 |
+
|
| 367 |
+
with gr.Tab("📊 Chart & Indicators"):
|
| 368 |
+
with gr.Row():
|
| 369 |
+
symbol_in1 = gr.Dropdown(choices=ALL_DEFAULT_SYMBOLS, value="EURUSD=X",
|
| 370 |
+
allow_custom_value=True, label="Symbol")
|
| 371 |
+
timeframe_in1 = gr.Dropdown(choices=TIMEFRAME_CHOICES, value="15m", label="Timeframe")
|
| 372 |
+
lookback_in1 = gr.Slider(1, 60, value=5, step=1, label="Lookback (days)")
|
| 373 |
+
fetch_btn = gr.Button("Fetch & Analyze", variant="primary")
|
| 374 |
+
chart_out1 = gr.Plot()
|
| 375 |
+
signals_out = gr.Dataframe(headers=["Indicator", "Value", "Signal"],
|
| 376 |
+
label="Top 5 Indicators (latest reading)")
|
| 377 |
+
status_out1 = gr.Markdown()
|
| 378 |
+
fetch_btn.click(fetch_and_chart, [symbol_in1, timeframe_in1, lookback_in1],
|
| 379 |
+
[chart_out1, signals_out, status_out1])
|
| 380 |
+
|
| 381 |
+
with gr.Tab("🔮 Prediction"):
|
| 382 |
+
with gr.Row():
|
| 383 |
+
symbol_in2 = gr.Dropdown(choices=ALL_DEFAULT_SYMBOLS, value="BTC-USD",
|
| 384 |
+
allow_custom_value=True, label="Symbol")
|
| 385 |
+
timeframe_in2 = gr.Dropdown(choices=TIMEFRAME_CHOICES, value="15m", label="Timeframe")
|
| 386 |
+
with gr.Row():
|
| 387 |
+
models_in2 = gr.CheckboxGroup(choices=MODEL_NAMES, value=["ARIMA"], label="Models")
|
| 388 |
+
horizon_in2 = gr.Slider(1, 10, value=1, step=1, label="Candles ahead")
|
| 389 |
+
lookback_in2 = gr.Slider(1, 60, value=5, step=1, label="Lookback (days)")
|
| 390 |
+
use_features_in2 = gr.Checkbox(value=False, label="Use 10-feature input (OHLCV + RSI/MACD/Bollinger/SMA-EMA/Stochastic)")
|
| 391 |
+
gr.Markdown(
|
| 392 |
+
"Moirai and TimesFM download pretrained weights the first time you use them "
|
| 393 |
+
"(needs internet on the Space; a few hundred MB each, one-time download)."
|
| 394 |
+
)
|
| 395 |
+
predict_btn = gr.Button("Predict", variant="primary")
|
| 396 |
+
chart_out2 = gr.Plot()
|
| 397 |
+
summary_out2 = gr.Markdown()
|
| 398 |
+
predict_btn.click(run_prediction,
|
| 399 |
+
[symbol_in2, timeframe_in2, models_in2, horizon_in2, lookback_in2, use_features_in2],
|
| 400 |
+
[chart_out2, summary_out2])
|
| 401 |
+
|
| 402 |
+
with gr.Tab("🧪 Backtest"):
|
| 403 |
+
gr.Markdown(
|
| 404 |
+
"Each model's accuracy is computed and shown **separately** below — "
|
| 405 |
+
"results are never averaged together. Raise **Step** to speed up "
|
| 406 |
+
"Moirai/TimesFM (slower per-prediction than ARIMA on CPU-only hardware)."
|
| 407 |
+
"\n\n" + FEATURES_HELP
|
| 408 |
+
)
|
| 409 |
+
with gr.Row():
|
| 410 |
+
symbol_in3 = gr.Dropdown(choices=ALL_DEFAULT_SYMBOLS, value="EURUSD=X",
|
| 411 |
+
allow_custom_value=True, label="Symbol")
|
| 412 |
+
timeframe_in3 = gr.Dropdown(choices=TIMEFRAME_CHOICES, value="15m", label="Timeframe")
|
| 413 |
+
with gr.Row():
|
| 414 |
+
models_in3 = gr.CheckboxGroup(choices=MODEL_NAMES, value=["ARIMA"], label="Models to backtest")
|
| 415 |
+
window_in3 = gr.Slider(20, 300, value=60, step=10, label="History window per prediction")
|
| 416 |
+
horizon_in3 = gr.Slider(1, 5, value=1, step=1, label="Horizon (candles ahead)")
|
| 417 |
+
with gr.Row():
|
| 418 |
+
step_in3 = gr.Slider(1, 20, value=1, step=1, label="Step (skip candles between tests)")
|
| 419 |
+
lookback_in3 = gr.Slider(1, 60, value=10, step=1, label="Backtest lookback (days)")
|
| 420 |
+
feature_mode_in3 = gr.Radio(
|
| 421 |
+
choices=[FEATURE_MODE_BASELINE, FEATURE_MODE_FEATURED, FEATURE_MODE_COMPARE],
|
| 422 |
+
value=FEATURE_MODE_BASELINE, label="Feature mode",
|
| 423 |
+
info="'Compare both' runs every selected model twice — Close-only and +10-feature — on the identical "
|
| 424 |
+
"symbol/timeframe/window/horizon/step/period, so you can see whether the extra features actually helped.",
|
| 425 |
+
)
|
| 426 |
+
backtest_btn = gr.Button("Run Backtest", variant="primary")
|
| 427 |
+
summary_out3 = gr.Dataframe(
|
| 428 |
+
headers=["Mode", "Model", "Total", "Correct", "Incorrect", "Accuracy", "MAE", "RMSE", "Failed"],
|
| 429 |
+
label="Per-model accuracy — kept separate, never mixed",
|
| 430 |
+
)
|
| 431 |
+
status_out3 = gr.Markdown()
|
| 432 |
+
with gr.Tabs():
|
| 433 |
+
with gr.Tab("ARIMA — verify log"):
|
| 434 |
+
arima_detail = gr.Dataframe(label="Per-candle: predicted vs actual, correct/incorrect")
|
| 435 |
+
with gr.Tab("Auto-ARIMA — verify log"):
|
| 436 |
+
autoarima_detail = gr.Dataframe(label="Per-candle: predicted vs actual, correct/incorrect")
|
| 437 |
+
with gr.Tab("ARIMA-GARCH — verify log"):
|
| 438 |
+
arimagarch_detail = gr.Dataframe(label="Per-candle: predicted vs actual, correct/incorrect")
|
| 439 |
+
with gr.Tab("Moirai — verify log"):
|
| 440 |
+
moirai_detail = gr.Dataframe(label="Per-candle: predicted vs actual, correct/incorrect")
|
| 441 |
+
with gr.Tab("TimesFM — verify log"):
|
| 442 |
+
timesfm_detail = gr.Dataframe(label="Per-candle: predicted vs actual, correct/incorrect")
|
| 443 |
+
|
| 444 |
+
backtest_btn.click(
|
| 445 |
+
run_backtest_ui,
|
| 446 |
+
[symbol_in3, timeframe_in3, models_in3, window_in3, horizon_in3, step_in3, lookback_in3, feature_mode_in3],
|
| 447 |
+
[summary_out3, arima_detail, autoarima_detail, arimagarch_detail,
|
| 448 |
+
moirai_detail, timesfm_detail, status_out3],
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
with gr.Tab("📡 Live"):
|
| 452 |
+
gr.Markdown(
|
| 453 |
+
"Polls Yahoo Finance for the newest candle each time you click the button, "
|
| 454 |
+
"predicts the next one, and verifies the previous prediction once that candle "
|
| 455 |
+
"has closed. For unattended/continuous logging instead of clicking manually, "
|
| 456 |
+
"run `live_runner.py` in the background (see README)."
|
| 457 |
+
)
|
| 458 |
+
with gr.Row():
|
| 459 |
+
symbol_in4 = gr.Dropdown(choices=ALL_DEFAULT_SYMBOLS, value="BTC-USD",
|
| 460 |
+
allow_custom_value=True, label="Symbol")
|
| 461 |
+
timeframe_in4 = gr.Dropdown(choices=TIMEFRAME_CHOICES, value="5m", label="Timeframe")
|
| 462 |
+
model_in4 = gr.Dropdown(choices=MODEL_NAMES, value="ARIMA", label="Model")
|
| 463 |
+
use_features_in4 = gr.Checkbox(
|
| 464 |
+
value=False, label="Use 10-feature input",
|
| 465 |
+
info="Uses the exact same feature-generation pipeline as the Backtest tab. "
|
| 466 |
+
"Toggling this mid-session keeps both modes' predictions in the log below, "
|
| 467 |
+
"but running accuracy is always computed for the current mode only.",
|
| 468 |
+
)
|
| 469 |
+
live_btn = gr.Button("🔄 Check Latest & Predict Next", variant="primary")
|
| 470 |
+
live_log_state = gr.State(_make_empty_live_log())
|
| 471 |
+
live_status = gr.Markdown()
|
| 472 |
+
live_table = gr.Dataframe(label="Live verification log (this model, this session)")
|
| 473 |
+
live_btn.click(check_live, [symbol_in4, timeframe_in4, model_in4, live_log_state, use_features_in4],
|
| 474 |
+
[live_status, live_table, live_log_state])
|
| 475 |
+
|
| 476 |
+
gr.Markdown("---\n" + DISCLAIMER)
|
| 477 |
+
|
| 478 |
+
|
| 479 |
+
if __name__ == "__main__":
|
| 480 |
+
demo.launch()
|
backtest/__init__.py
ADDED
|
File without changes
|
backtest/backtester.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Walk-forward backtesting and per-candle verification.
|
| 2 |
+
|
| 3 |
+
Each model's results are kept in a separate DataFrame and never blended with
|
| 4 |
+
another model's numbers. Every step logs the predicted close, the real close
|
| 5 |
+
once known, predicted vs actual direction, and whether it was correct.
|
| 6 |
+
|
| 7 |
+
`features_df`, when given, must already be positionally aligned with
|
| 8 |
+
df["Close"] (typically from data.historical.get_historical_with_features).
|
| 9 |
+
The same [i - window : i] slice used for the price history is used for the
|
| 10 |
+
features, so covariates are exactly as leak-free as the history itself.
|
| 11 |
+
`features_df=None` is the Close-only backtest.
|
| 12 |
+
"""
|
| 13 |
+
from math import floor, log10
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import pandas as pd
|
| 17 |
+
|
| 18 |
+
from features.feature_pipeline import slice_features
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _round_sig(x, sig: int = 6):
|
| 22 |
+
"""Round to `sig` significant figures, so MAE/RMSE stay readable across
|
| 23 |
+
assets priced from fractions of a cent to tens of thousands.
|
| 24 |
+
"""
|
| 25 |
+
if x is None or not np.isfinite(x) or x == 0:
|
| 26 |
+
return x
|
| 27 |
+
decimals = sig - 1 - floor(log10(abs(x)))
|
| 28 |
+
return round(x, decimals)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def backtest_model(df: pd.DataFrame, model, window: int = 100, horizon: int = 1,
|
| 32 |
+
step: int = 1, features_df: pd.DataFrame = None) -> pd.DataFrame:
|
| 33 |
+
"""Walk forward through `df` (needs a 'Close' column, oldest -> newest).
|
| 34 |
+
At each step the last `window` closes go to `model.predict()` and the
|
| 35 |
+
forecast is compared with the real close.
|
| 36 |
+
|
| 37 |
+
`step` > 1 skips candles between predictions, which speeds up the slower
|
| 38 |
+
foundation models on CPU-only hardware.
|
| 39 |
+
"""
|
| 40 |
+
close = df["Close"].reset_index(drop=True)
|
| 41 |
+
timestamps = list(df.index) # positional access, no label ambiguity
|
| 42 |
+
|
| 43 |
+
last_i = len(close) - horizon
|
| 44 |
+
rows = []
|
| 45 |
+
for i in range(window, last_i + 1, step):
|
| 46 |
+
history = close.iloc[i - window:i]
|
| 47 |
+
feature_window = slice_features(features_df, i - window, i) if features_df is not None else None
|
| 48 |
+
current_close = float(close.iloc[i - 1])
|
| 49 |
+
target_idx = i + horizon - 1
|
| 50 |
+
actual_next_close = float(close.iloc[target_idx])
|
| 51 |
+
|
| 52 |
+
try:
|
| 53 |
+
forecast = model.predict(history, horizon=horizon, features=feature_window)
|
| 54 |
+
predicted_next_close = float(forecast[-1])
|
| 55 |
+
if not np.isfinite(predicted_next_close):
|
| 56 |
+
raise ValueError(f"non-finite forecast value: {predicted_next_close!r}")
|
| 57 |
+
except Exception as e:
|
| 58 |
+
rows.append({
|
| 59 |
+
"datetime": timestamps[target_idx],
|
| 60 |
+
"current_close": current_close,
|
| 61 |
+
"predicted_close": np.nan,
|
| 62 |
+
"actual_close": actual_next_close,
|
| 63 |
+
"predicted_direction": None,
|
| 64 |
+
"actual_direction": None,
|
| 65 |
+
"correct": None,
|
| 66 |
+
"error": str(e),
|
| 67 |
+
})
|
| 68 |
+
continue
|
| 69 |
+
|
| 70 |
+
predicted_direction = "up" if predicted_next_close > current_close else "down"
|
| 71 |
+
actual_direction = "up" if actual_next_close > current_close else "down"
|
| 72 |
+
correct = predicted_direction == actual_direction
|
| 73 |
+
|
| 74 |
+
rows.append({
|
| 75 |
+
"datetime": timestamps[target_idx],
|
| 76 |
+
"current_close": current_close,
|
| 77 |
+
"predicted_close": predicted_next_close,
|
| 78 |
+
"actual_close": actual_next_close,
|
| 79 |
+
"predicted_direction": predicted_direction,
|
| 80 |
+
"actual_direction": actual_direction,
|
| 81 |
+
"correct": correct,
|
| 82 |
+
"error": None,
|
| 83 |
+
})
|
| 84 |
+
|
| 85 |
+
return pd.DataFrame(rows)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def summarize_backtest(results: pd.DataFrame, model_name: str) -> dict:
|
| 89 |
+
"""One model's accuracy summary. Always kept separate per model — never
|
| 90 |
+
combined with another model's numbers."""
|
| 91 |
+
if results.empty:
|
| 92 |
+
return {
|
| 93 |
+
"model": model_name, "total_predictions": 0, "correct": 0, "incorrect": 0,
|
| 94 |
+
"accuracy_pct": 0.0, "mae": None, "rmse": None, "failed_predictions": 0,
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
valid = results.dropna(subset=["correct"])
|
| 98 |
+
total = len(valid)
|
| 99 |
+
correct = int(valid["correct"].sum()) if total else 0
|
| 100 |
+
incorrect = total - correct
|
| 101 |
+
accuracy = round(100 * correct / total, 2) if total else 0.0
|
| 102 |
+
|
| 103 |
+
price_valid = results.dropna(subset=["predicted_close", "actual_close"])
|
| 104 |
+
if len(price_valid):
|
| 105 |
+
errors = price_valid["predicted_close"] - price_valid["actual_close"]
|
| 106 |
+
mae = float(np.mean(np.abs(errors)))
|
| 107 |
+
rmse = float(np.sqrt(np.mean(errors ** 2)))
|
| 108 |
+
else:
|
| 109 |
+
mae = rmse = None
|
| 110 |
+
|
| 111 |
+
failed = int(results["error"].notna().sum())
|
| 112 |
+
|
| 113 |
+
return {
|
| 114 |
+
"model": model_name,
|
| 115 |
+
"total_predictions": total,
|
| 116 |
+
"correct": correct,
|
| 117 |
+
"incorrect": incorrect,
|
| 118 |
+
"accuracy_pct": accuracy,
|
| 119 |
+
"mae": _round_sig(mae) if mae is not None else None,
|
| 120 |
+
"rmse": _round_sig(rmse) if rmse is not None else None,
|
| 121 |
+
"failed_predictions": failed,
|
| 122 |
+
}
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def run_all_models_backtest(df: pd.DataFrame, models: dict, window: int = 100,
|
| 126 |
+
horizon: int = 1, step: int = 1, features_df: pd.DataFrame = None):
|
| 127 |
+
"""Backtest every model in `models` ({name: model_instance}).
|
| 128 |
+
Returns (per_model_results, per_model_summary) keyed by model name.
|
| 129 |
+
"""
|
| 130 |
+
per_model_results = {}
|
| 131 |
+
per_model_summary = {}
|
| 132 |
+
for name, model in models.items():
|
| 133 |
+
results = backtest_model(df, model, window=window, horizon=horizon, step=step,
|
| 134 |
+
features_df=features_df)
|
| 135 |
+
per_model_results[name] = results
|
| 136 |
+
per_model_summary[name] = summarize_backtest(results, name)
|
| 137 |
+
return per_model_results, per_model_summary
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
BASELINE_LABEL = "Close-only"
|
| 141 |
+
FEATURED_LABEL = "+10 Features"
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def run_comparison_backtest(df: pd.DataFrame, models: dict, features_df: pd.DataFrame,
|
| 145 |
+
window: int = 100, horizon: int = 1, step: int = 1):
|
| 146 |
+
"""Run every model in `models` twice on identical data: Close-only and
|
| 147 |
+
with features. `models` maps name -> (baseline_model, featured_model).
|
| 148 |
+
Each results frame gets a "mode" column and each summary a "mode" key so
|
| 149 |
+
the runs can be compared without being blended.
|
| 150 |
+
"""
|
| 151 |
+
per_model_results = {}
|
| 152 |
+
per_model_summary = {}
|
| 153 |
+
for name, model_pair in models.items():
|
| 154 |
+
baseline_model, featured_model = model_pair
|
| 155 |
+
results_list, summary_list = [], []
|
| 156 |
+
for label, model, feats in (
|
| 157 |
+
(BASELINE_LABEL, baseline_model, None),
|
| 158 |
+
(FEATURED_LABEL, featured_model, features_df),
|
| 159 |
+
):
|
| 160 |
+
results = backtest_model(df, model, window=window, horizon=horizon, step=step,
|
| 161 |
+
features_df=feats)
|
| 162 |
+
summary = summarize_backtest(results, name)
|
| 163 |
+
summary["mode"] = label
|
| 164 |
+
results = results.copy()
|
| 165 |
+
results.insert(0, "mode", label)
|
| 166 |
+
results_list.append(results)
|
| 167 |
+
summary_list.append(summary)
|
| 168 |
+
per_model_results[name] = pd.concat(results_list, ignore_index=True)
|
| 169 |
+
per_model_summary[name] = summary_list
|
| 170 |
+
return per_model_results, per_model_summary
|
config.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Central configuration: symbols, timeframes, data-source limits, checkpoints."""
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
| 5 |
+
OUTPUT_DIR = os.path.join(BASE_DIR, "outputs")
|
| 6 |
+
|
| 7 |
+
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
| 8 |
+
|
| 9 |
+
# Forex pairs use the "=X" suffix, crypto pairs "-USD". The UI's symbol
|
| 10 |
+
# dropdown also accepts any other yfinance-valid ticker typed in directly,
|
| 11 |
+
# so this list is a starting set rather than a limit.
|
| 12 |
+
DEFAULT_FOREX_SYMBOLS = [
|
| 13 |
+
"EURUSD=X", "GBPUSD=X", "USDJPY=X", "USDCHF=X", "AUDUSD=X",
|
| 14 |
+
"USDCAD=X", "NZDUSD=X", "EURJPY=X", "EURGBP=X", "GBPJPY=X",
|
| 15 |
+
]
|
| 16 |
+
|
| 17 |
+
DEFAULT_CRYPTO_SYMBOLS = [
|
| 18 |
+
"BTC-USD", "ETH-USD", "BNB-USD", "XRP-USD", "SOL-USD",
|
| 19 |
+
"ADA-USD", "DOGE-USD", "DOT-USD", "LTC-USD", "MATIC-USD",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
ALL_DEFAULT_SYMBOLS = DEFAULT_FOREX_SYMBOLS + DEFAULT_CRYPTO_SYMBOLS
|
| 23 |
+
|
| 24 |
+
# Yahoo Finance limits each interval two ways: how far back it is retained
|
| 25 |
+
# (max_days) and how wide one request may be (max_request_days). Windows
|
| 26 |
+
# wider than max_request_days must be fetched in chunks. None = no limit.
|
| 27 |
+
YF_NATIVE_INTERVALS = {
|
| 28 |
+
"1m": {"max_days": 30, "max_request_days": 7},
|
| 29 |
+
"2m": {"max_days": 60, "max_request_days": 60},
|
| 30 |
+
"5m": {"max_days": 60, "max_request_days": 60},
|
| 31 |
+
"15m": {"max_days": 60, "max_request_days": 60},
|
| 32 |
+
"30m": {"max_days": 60, "max_request_days": 60},
|
| 33 |
+
"60m": {"max_days": 730, "max_request_days": 730},
|
| 34 |
+
"90m": {"max_days": 60, "max_request_days": 60},
|
| 35 |
+
"1d": {"max_days": None, "max_request_days": None},
|
| 36 |
+
"1wk": {"max_days": None, "max_request_days": None},
|
| 37 |
+
"1mo": {"max_days": None, "max_request_days": None},
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
# Timeframes offered in the UI.
|
| 41 |
+
# `rule: None` -> already a native Yahoo interval, returned as fetched.
|
| 42 |
+
# `rule: "..."` -> resampled up from a smaller native interval.
|
| 43 |
+
# "1h" is Yahoo's "60m" under a friendlier name; resampling it would only
|
| 44 |
+
# re-label candle timestamps to bucket starts, so it passes through.
|
| 45 |
+
CUSTOM_TIMEFRAMES = {
|
| 46 |
+
"1m": {"source": "1m", "rule": None},
|
| 47 |
+
"5m": {"source": "5m", "rule": None},
|
| 48 |
+
"10m": {"source": "5m", "rule": "10min"},
|
| 49 |
+
"15m": {"source": "15m", "rule": None},
|
| 50 |
+
"30m": {"source": "30m", "rule": None},
|
| 51 |
+
"1h": {"source": "60m", "rule": None},
|
| 52 |
+
"4h": {"source": "60m", "rule": "4h"},
|
| 53 |
+
"1d": {"source": "1d", "rule": None},
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
MODEL_NAMES = ["ARIMA", "Auto-ARIMA", "ARIMA-GARCH", "Moirai", "TimesFM"]
|
| 57 |
+
|
| 58 |
+
# Small CPU-friendly checkpoints; change these for GPU hardware.
|
| 59 |
+
MOIRAI_CHECKPOINT = "Salesforce/moirai-1.1-R-small"
|
| 60 |
+
TIMESFM_CHECKPOINT = "google/timesfm-2.5-200m-pytorch"
|
data/__init__.py
ADDED
|
File without changes
|
data/historical.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Historical OHLCV data via yfinance - free, no API key needed.
|
| 2 |
+
|
| 3 |
+
Two things this module does beyond a plain download:
|
| 4 |
+
1. Resampling: timeframes that Yahoo does not serve natively (e.g. "10m",
|
| 5 |
+
"4h" in config.CUSTOM_TIMEFRAMES) are aggregated from a smaller native
|
| 6 |
+
interval.
|
| 7 |
+
2. Chunked fetching: a window wider than the interval's per-request limit
|
| 8 |
+
(config.YF_NATIVE_INTERVALS[...]["max_request_days"], e.g. 7 days for
|
| 9 |
+
1m candles) is split into several requests and stitched together
|
| 10 |
+
instead of being silently truncated.
|
| 11 |
+
"""
|
| 12 |
+
import time
|
| 13 |
+
from datetime import datetime, timedelta, timezone
|
| 14 |
+
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
from config import YF_NATIVE_INTERVALS, CUSTOM_TIMEFRAMES
|
| 18 |
+
from features.feature_pipeline import compute_feature_frame_for_period
|
| 19 |
+
from utils.helpers import feature_warmup_days
|
| 20 |
+
|
| 21 |
+
OHLCV_COLUMNS = ["Open", "High", "Low", "Close", "Volume"]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class DataFetchError(Exception):
|
| 25 |
+
"""Raised for anything that stops us returning usable candles."""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _fetch_yf(symbol: str, interval: str, start: datetime, end: datetime) -> pd.DataFrame:
|
| 29 |
+
"""The only call into yfinance; imported here so the rest of the module
|
| 30 |
+
stays importable (and unit-testable) without a network round trip."""
|
| 31 |
+
import yfinance as yf
|
| 32 |
+
|
| 33 |
+
return yf.Ticker(symbol).history(start=start, end=end, interval=interval)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _download_window(symbol: str, interval: str, start: datetime, end: datetime) -> pd.DataFrame:
|
| 37 |
+
df = _fetch_yf(symbol, interval, start, end)
|
| 38 |
+
if df is None or df.empty:
|
| 39 |
+
return pd.DataFrame()
|
| 40 |
+
df = df.rename(columns=str.title)
|
| 41 |
+
df.index.name = "Datetime"
|
| 42 |
+
keep = [c for c in OHLCV_COLUMNS if c in df.columns]
|
| 43 |
+
return df[keep]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _finalize_ohlcv(df: pd.DataFrame) -> pd.DataFrame:
|
| 47 |
+
"""Strictly ascending, duplicate-free timestamps, so the backtester's
|
| 48 |
+
positional walk-forward loop always sees a consistently ordered frame."""
|
| 49 |
+
if df is None or df.empty:
|
| 50 |
+
return df
|
| 51 |
+
df = df.sort_index()
|
| 52 |
+
return df[~df.index.duplicated(keep="last")]
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _native_fetch(symbol: str, interval: str, days: int) -> pd.DataFrame:
|
| 56 |
+
"""Fetch raw OHLCV candles at a yfinance-native interval, in as many
|
| 57 |
+
requests as the interval's per-request limit requires."""
|
| 58 |
+
if interval not in YF_NATIVE_INTERVALS:
|
| 59 |
+
raise DataFetchError(f"'{interval}' is not a native yfinance interval.")
|
| 60 |
+
|
| 61 |
+
limits = YF_NATIVE_INTERVALS[interval]
|
| 62 |
+
max_days, request_days = limits["max_days"], limits["max_request_days"]
|
| 63 |
+
if max_days is not None:
|
| 64 |
+
days = min(days, max_days)
|
| 65 |
+
if request_days is None:
|
| 66 |
+
request_days = days
|
| 67 |
+
|
| 68 |
+
frames = []
|
| 69 |
+
window_end = datetime.now(timezone.utc)
|
| 70 |
+
remaining = days
|
| 71 |
+
while remaining > 0:
|
| 72 |
+
window_days = min(request_days, remaining)
|
| 73 |
+
window_start = window_end - timedelta(days=window_days)
|
| 74 |
+
frame = _download_window(symbol, interval, window_start, window_end)
|
| 75 |
+
if not frame.empty:
|
| 76 |
+
frames.append(frame)
|
| 77 |
+
window_end = window_start
|
| 78 |
+
remaining -= window_days
|
| 79 |
+
if remaining > 0:
|
| 80 |
+
time.sleep(0.2) # space out consecutive requests to Yahoo
|
| 81 |
+
|
| 82 |
+
df = _finalize_ohlcv(pd.concat(frames)) if frames else pd.DataFrame()
|
| 83 |
+
if df.empty or "Close" not in df.columns:
|
| 84 |
+
limit_note = (f" Yahoo keeps at most {max_days} days of '{interval}' history."
|
| 85 |
+
if max_days is not None else "")
|
| 86 |
+
raise DataFetchError(
|
| 87 |
+
f"No usable data returned for '{symbol}' at interval '{interval}' "
|
| 88 |
+
f"over the last {days} day(s). Check it's a valid yfinance ticker "
|
| 89 |
+
f"(e.g. EURUSD=X, BTC-USD) and that the market has traded recently."
|
| 90 |
+
+ limit_note
|
| 91 |
+
)
|
| 92 |
+
return df
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def resample_ohlc(df: pd.DataFrame, rule: str) -> pd.DataFrame:
|
| 96 |
+
"""Aggregate candles up to a coarser timeframe, e.g. 5m candles -> 10m candles."""
|
| 97 |
+
agg = {"Open": "first", "High": "max", "Low": "min", "Close": "last", "Volume": "sum"}
|
| 98 |
+
agg = {k: v for k, v in agg.items() if k in df.columns}
|
| 99 |
+
return df.resample(rule).agg(agg).dropna(how="any")
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def get_historical(symbol: str, timeframe: str, lookback_days: int = None) -> pd.DataFrame:
|
| 103 |
+
"""Fetch `lookback_days` of candles for `symbol` at `timeframe`.
|
| 104 |
+
|
| 105 |
+
`timeframe` may be a native yfinance interval (config.YF_NATIVE_INTERVALS)
|
| 106 |
+
or one of config.CUSTOM_TIMEFRAMES (e.g. "10m", "4h"), which is built by
|
| 107 |
+
resampling a smaller native interval.
|
| 108 |
+
"""
|
| 109 |
+
if not symbol or not symbol.strip():
|
| 110 |
+
raise DataFetchError("No symbol given.")
|
| 111 |
+
symbol = symbol.strip()
|
| 112 |
+
|
| 113 |
+
if timeframe in CUSTOM_TIMEFRAMES:
|
| 114 |
+
spec = CUSTOM_TIMEFRAMES[timeframe]
|
| 115 |
+
source_interval, rule = spec["source"], spec["rule"]
|
| 116 |
+
elif timeframe in YF_NATIVE_INTERVALS:
|
| 117 |
+
source_interval, rule = timeframe, None
|
| 118 |
+
else:
|
| 119 |
+
raise DataFetchError(
|
| 120 |
+
f"Unknown timeframe '{timeframe}'. Valid options: "
|
| 121 |
+
f"{', '.join(CUSTOM_TIMEFRAMES.keys())}"
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
max_days = YF_NATIVE_INTERVALS[source_interval]["max_days"]
|
| 125 |
+
requested = int(lookback_days) if lookback_days is not None else 0
|
| 126 |
+
days = requested if requested > 0 else (max_days if max_days else 730)
|
| 127 |
+
|
| 128 |
+
df = _native_fetch(symbol, source_interval, days)
|
| 129 |
+
|
| 130 |
+
if rule:
|
| 131 |
+
df = resample_ohlc(df, rule)
|
| 132 |
+
if df.empty:
|
| 133 |
+
raise DataFetchError(
|
| 134 |
+
f"Not enough '{source_interval}' candles to build '{timeframe}' bars. "
|
| 135 |
+
f"Try a longer lookback."
|
| 136 |
+
)
|
| 137 |
+
|
| 138 |
+
return df
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def get_historical_with_features(symbol: str, timeframe: str, lookback_days: int,
|
| 142 |
+
use_features: bool):
|
| 143 |
+
"""Single fetch entry point for app.py and live_runner.py.
|
| 144 |
+
Returns (df, features_df); features_df is None when use_features=False.
|
| 145 |
+
|
| 146 |
+
With use_features=True it fetches feature_warmup_days() of extra history
|
| 147 |
+
in front, computes the indicators on the padded frame and trims both
|
| 148 |
+
frames back to the requested period, so no leading NaN row reaches a
|
| 149 |
+
model.
|
| 150 |
+
"""
|
| 151 |
+
if not use_features:
|
| 152 |
+
return get_historical(symbol, timeframe, lookback_days=int(lookback_days)), None
|
| 153 |
+
|
| 154 |
+
padding_days = feature_warmup_days(timeframe, minimum_days=0)
|
| 155 |
+
df_padded = get_historical(symbol, timeframe,
|
| 156 |
+
lookback_days=int(lookback_days) + padding_days)
|
| 157 |
+
return compute_feature_frame_for_period(df_padded, keep_days=int(lookback_days))
|
features/__init__.py
ADDED
|
File without changes
|
features/feature_pipeline.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared feature engineering used by the backtester, the app and
|
| 2 |
+
live_runner, so backtest and live runs see identical features.
|
| 3 |
+
|
| 4 |
+
FEATURE_COLUMNS (14): 4 raw (Open/High/Low/Volume) + RSI_14 + MACD/Signal/
|
| 5 |
+
Hist + BB_Upper/BB_Lower + SMA_20/EMA_20 + Stoch_%K/%D.
|
| 6 |
+
|
| 7 |
+
Close is excluded (it is the forecast target, and as exog it would be
|
| 8 |
+
perfectly collinear); BB_Mid is excluded (identical to SMA_20).
|
| 9 |
+
|
| 10 |
+
Every indicator is causal (trailing rolling/ewm only), so computing once
|
| 11 |
+
over the full history and slicing windows afterwards is bit-identical to
|
| 12 |
+
recomputing per window - covered by tests/test_feature_pipeline.py.
|
| 13 |
+
"""
|
| 14 |
+
import numpy as np
|
| 15 |
+
import pandas as pd
|
| 16 |
+
|
| 17 |
+
from indicators.indicators import add_all_indicators
|
| 18 |
+
|
| 19 |
+
REQUIRED_OHLCV_COLUMNS = ["Open", "High", "Low", "Close", "Volume"]
|
| 20 |
+
|
| 21 |
+
# Fixed order: every model's exog/covariate array lines up with this list.
|
| 22 |
+
FEATURE_COLUMNS = [
|
| 23 |
+
"Open", "High", "Low", "Volume",
|
| 24 |
+
"RSI_14",
|
| 25 |
+
"MACD", "MACD_Signal", "MACD_Hist",
|
| 26 |
+
"BB_Upper", "BB_Lower",
|
| 27 |
+
"SMA_20", "EMA_20",
|
| 28 |
+
"Stoch_%K", "Stoch_%D",
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def compute_feature_frame(df: pd.DataFrame) -> pd.DataFrame:
|
| 33 |
+
"""Indicators for a full OHLCV frame (oldest -> newest), returned as
|
| 34 |
+
FEATURE_COLUMNS re-indexed 0..len(df)-1 so it lines up positionally with
|
| 35 |
+
`df["Close"].reset_index(drop=True)`.
|
| 36 |
+
"""
|
| 37 |
+
missing = [c for c in REQUIRED_OHLCV_COLUMNS if c not in df.columns]
|
| 38 |
+
if missing:
|
| 39 |
+
raise ValueError(
|
| 40 |
+
f"compute_feature_frame needs an OHLCV DataFrame; missing column(s): {missing}."
|
| 41 |
+
)
|
| 42 |
+
with_indicators = add_all_indicators(df)
|
| 43 |
+
return with_indicators[FEATURE_COLUMNS].reset_index(drop=True).astype(float)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def slice_features(features: pd.DataFrame, start: int, end: int) -> pd.DataFrame:
|
| 47 |
+
"""features.iloc[start:end], re-indexed 0..n-1 - the same positional
|
| 48 |
+
window the backtester cuts out of `close`."""
|
| 49 |
+
return features.iloc[start:end].reset_index(drop=True)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def compute_feature_frame_for_period(df_padded: pd.DataFrame, keep_days: float):
|
| 53 |
+
"""Compute indicators on a padded frame, then return only the last
|
| 54 |
+
`keep_days` of it as (df_trimmed, features_trimmed).
|
| 55 |
+
|
| 56 |
+
The padding candles give the slower indicators (SMA_20/Bollinger need 20
|
| 57 |
+
candles) real warm-up data, so the returned rows are not NaN merely for
|
| 58 |
+
lack of history. Market closures can still leave the front of the
|
| 59 |
+
requested period without enough warm-up candles - those leading rows are
|
| 60 |
+
dropped rather than returned as NaN, since a model cannot use them.
|
| 61 |
+
Later NaNs are left in place for validate_features() to report.
|
| 62 |
+
|
| 63 |
+
features_trimmed is re-indexed 0..n-1 and positionally aligned with
|
| 64 |
+
df_trimmed["Close"].reset_index(drop=True).
|
| 65 |
+
"""
|
| 66 |
+
features_padded = compute_feature_frame(df_padded)
|
| 67 |
+
cutoff = df_padded.index[-1] - pd.Timedelta(days=keep_days)
|
| 68 |
+
positions = np.flatnonzero(df_padded.index >= cutoff)
|
| 69 |
+
|
| 70 |
+
complete = ~features_padded.isna().any(axis=1).to_numpy()
|
| 71 |
+
if complete.any():
|
| 72 |
+
positions = positions[positions >= int(np.argmax(complete))]
|
| 73 |
+
else:
|
| 74 |
+
positions = positions[:0]
|
| 75 |
+
|
| 76 |
+
if len(positions) == 0:
|
| 77 |
+
raise ValueError(
|
| 78 |
+
f"No candle in the requested period has complete indicator values: "
|
| 79 |
+
f"only {len(df_padded)} candles were fetched, and the slowest "
|
| 80 |
+
f"indicator needs 20 candles of warm-up before the period starts. "
|
| 81 |
+
f"Increase the lookback (markets that close, e.g. forex over a "
|
| 82 |
+
f"weekend, need more calendar days to reach the same candle count)."
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
return df_padded.iloc[positions], features_padded.iloc[positions].reset_index(drop=True)
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def validate_features(features: pd.DataFrame, expected_len: int, model_name: str,
|
| 89 |
+
check_nan: bool = True) -> None:
|
| 90 |
+
"""Reject a misaligned or NaN feature window instead of letting a model
|
| 91 |
+
silently train on it.
|
| 92 |
+
|
| 93 |
+
NaNs mean the fetched history lacks real warm-up before the window; the
|
| 94 |
+
fix is more history, not a fabricated fill value.
|
| 95 |
+
|
| 96 |
+
`check_nan=False` keeps only the length check, for models that use just
|
| 97 |
+
the tail of what they are handed (Moirai, TimesFM): they validate the
|
| 98 |
+
full window for alignment first, then the truncated tail for NaNs.
|
| 99 |
+
"""
|
| 100 |
+
if len(features) != expected_len:
|
| 101 |
+
raise ValueError(
|
| 102 |
+
f"{model_name}: feature window has {len(features)} rows, expected "
|
| 103 |
+
f"{expected_len} to match the price history it must line up with."
|
| 104 |
+
)
|
| 105 |
+
if check_nan and features.isna().any().any():
|
| 106 |
+
bad_cols = features.columns[features.isna().any()].tolist()
|
| 107 |
+
raise ValueError(
|
| 108 |
+
f"{model_name}: feature window contains NaN in {bad_cols}. This "
|
| 109 |
+
f"usually means there isn't enough real history before this window "
|
| 110 |
+
f"for the slower indicators (SMA/Bollinger need 20 prior candles) "
|
| 111 |
+
f"to warm up on -- increase the lookback/history and try again."
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def carry_forward_future(feature_window: pd.DataFrame, horizon: int) -> pd.DataFrame:
|
| 116 |
+
"""Repeat the last observed feature row `horizon` times to supply the
|
| 117 |
+
future-step exog that statsmodels' ARIMA.forecast() and TimesFM's
|
| 118 |
+
forecast_with_covariates() require. Future indicator values depend on
|
| 119 |
+
candles that have not happened yet, so last-known-value persistence is
|
| 120 |
+
used; it introduces no future information.
|
| 121 |
+
"""
|
| 122 |
+
if horizon < 1:
|
| 123 |
+
raise ValueError("carry_forward_future: horizon must be >= 1.")
|
| 124 |
+
if len(feature_window) == 0:
|
| 125 |
+
raise ValueError("carry_forward_future: feature_window is empty.")
|
| 126 |
+
last_row = feature_window.iloc[[-1]]
|
| 127 |
+
return pd.concat([last_row] * horizon, ignore_index=True)
|
indicators/__init__.py
ADDED
|
File without changes
|
indicators/indicators.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Top 5 technical indicators for the chart/analysis tab.
|
| 2 |
+
|
| 3 |
+
Implemented directly with pandas/numpy so there is no extra TA dependency:
|
| 4 |
+
RSI, MACD, Bollinger Bands, SMA/EMA and the Stochastic Oscillator.
|
| 5 |
+
|
| 6 |
+
These are informational; model accuracy numbers come only from the
|
| 7 |
+
forecasting models in backtest/backtester.py.
|
| 8 |
+
|
| 9 |
+
During an indicator's warm-up period its value is genuinely undefined and is
|
| 10 |
+
returned as NaN rather than a filler value - callers either pad the history
|
| 11 |
+
(features/feature_pipeline.py) or report "insufficient data".
|
| 12 |
+
"""
|
| 13 |
+
import numpy as np
|
| 14 |
+
import pandas as pd
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def sma(series: pd.Series, window: int) -> pd.Series:
|
| 18 |
+
return series.rolling(window=window).mean()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def ema(series: pd.Series, window: int) -> pd.Series:
|
| 22 |
+
return series.ewm(span=window, adjust=False).mean()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def _wilder_rma(values: pd.Series, window: int) -> pd.Series:
|
| 26 |
+
"""Wilder's smoothed moving average: the first output is the simple
|
| 27 |
+
average of the first `window` values, then prev*(window-1)/window +
|
| 28 |
+
current/window.
|
| 29 |
+
|
| 30 |
+
`ewm(alpha=1/window, adjust=False)` is not equivalent - it seeds from the
|
| 31 |
+
first observation instead of a window-length average and needs roughly
|
| 32 |
+
100 bars to converge, which distorts short lookbacks (the Chart tab
|
| 33 |
+
allows one day).
|
| 34 |
+
"""
|
| 35 |
+
arr = values.to_numpy(dtype=float)
|
| 36 |
+
n = len(arr)
|
| 37 |
+
out = np.full(n, np.nan)
|
| 38 |
+
first_valid_pos = 0
|
| 39 |
+
while first_valid_pos < n and np.isnan(arr[first_valid_pos]):
|
| 40 |
+
first_valid_pos += 1
|
| 41 |
+
seed_end = first_valid_pos + window
|
| 42 |
+
if seed_end > n:
|
| 43 |
+
return pd.Series(out, index=values.index)
|
| 44 |
+
prev = arr[first_valid_pos:seed_end].mean()
|
| 45 |
+
out[seed_end - 1] = prev
|
| 46 |
+
for i in range(seed_end, n):
|
| 47 |
+
prev = (prev * (window - 1) + arr[i]) / window
|
| 48 |
+
out[i] = prev
|
| 49 |
+
return pd.Series(out, index=values.index)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def rsi(series: pd.Series, window: int = 14) -> pd.Series:
|
| 53 |
+
delta = series.diff()
|
| 54 |
+
gain = delta.clip(lower=0)
|
| 55 |
+
loss = -delta.clip(upper=0)
|
| 56 |
+
avg_gain = _wilder_rma(gain, window)
|
| 57 |
+
avg_loss = _wilder_rma(loss, window)
|
| 58 |
+
rs = avg_gain / avg_loss.replace(0, np.nan)
|
| 59 |
+
out = 100 - (100 / (1 + rs))
|
| 60 |
+
# Wilder defines a window with gains but no losses as 100; a window with
|
| 61 |
+
# neither (a flat market) as neutral. Warm-up rows stay NaN.
|
| 62 |
+
out = out.mask((avg_loss == 0) & (avg_gain > 0), 100.0)
|
| 63 |
+
return out.mask((avg_loss == 0) & (avg_gain == 0), 50.0)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def macd(series: pd.Series, fast: int = 12, slow: int = 26, signal: int = 9):
|
| 67 |
+
fast_ema = ema(series, fast)
|
| 68 |
+
slow_ema = ema(series, slow)
|
| 69 |
+
macd_line = fast_ema - slow_ema
|
| 70 |
+
signal_line = ema(macd_line, signal)
|
| 71 |
+
histogram = macd_line - signal_line
|
| 72 |
+
return macd_line, signal_line, histogram
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def bollinger_bands(series: pd.Series, window: int = 20, num_std: float = 2.0):
|
| 76 |
+
mid = sma(series, window)
|
| 77 |
+
# Population std (ddof=0), as Bollinger defines the bands; pandas' default
|
| 78 |
+
# sample std would make them ~2-3% too wide at window=20.
|
| 79 |
+
std = series.rolling(window=window).std(ddof=0)
|
| 80 |
+
return mid + num_std * std, mid, mid - num_std * std
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def stochastic_oscillator(high: pd.Series, low: pd.Series, close: pd.Series,
|
| 84 |
+
k_window: int = 14, d_window: int = 3):
|
| 85 |
+
lowest_low = low.rolling(window=k_window).min()
|
| 86 |
+
highest_high = high.rolling(window=k_window).max()
|
| 87 |
+
span = highest_high - lowest_low
|
| 88 |
+
percent_k = 100 * (close - lowest_low) / span.replace(0, np.nan)
|
| 89 |
+
# No range at all puts price at both extremes at once: neutral by definition.
|
| 90 |
+
percent_k = percent_k.mask(span == 0, 50.0)
|
| 91 |
+
percent_d = percent_k.rolling(window=d_window).mean()
|
| 92 |
+
return percent_k, percent_d
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def add_all_indicators(df: pd.DataFrame) -> pd.DataFrame:
|
| 96 |
+
"""Return a copy of df with all 5 indicators added as columns."""
|
| 97 |
+
out = df.copy()
|
| 98 |
+
out["SMA_20"] = sma(out["Close"], 20)
|
| 99 |
+
out["EMA_20"] = ema(out["Close"], 20)
|
| 100 |
+
out["RSI_14"] = rsi(out["Close"], 14)
|
| 101 |
+
|
| 102 |
+
macd_line, signal_line, hist = macd(out["Close"])
|
| 103 |
+
out["MACD"] = macd_line
|
| 104 |
+
out["MACD_Signal"] = signal_line
|
| 105 |
+
out["MACD_Hist"] = hist
|
| 106 |
+
|
| 107 |
+
upper, mid, lower = bollinger_bands(out["Close"])
|
| 108 |
+
out["BB_Upper"] = upper
|
| 109 |
+
out["BB_Mid"] = mid
|
| 110 |
+
out["BB_Lower"] = lower
|
| 111 |
+
|
| 112 |
+
k, d = stochastic_oscillator(out["High"], out["Low"], out["Close"])
|
| 113 |
+
out["Stoch_%K"] = k
|
| 114 |
+
out["Stoch_%D"] = d
|
| 115 |
+
|
| 116 |
+
return out
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _round(value, digits):
|
| 120 |
+
return round(float(value), digits) if pd.notna(value) else "n/a"
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def latest_signals(df_with_indicators: pd.DataFrame) -> dict:
|
| 124 |
+
"""Rule-based read of the latest indicator values, for display only.
|
| 125 |
+
Indicators that have not finished warming up report insufficient data
|
| 126 |
+
instead of a neutral-looking reading."""
|
| 127 |
+
last = df_with_indicators.iloc[-1]
|
| 128 |
+
signals = {}
|
| 129 |
+
|
| 130 |
+
rsi_value = last["RSI_14"]
|
| 131 |
+
signals["RSI (14)"] = {
|
| 132 |
+
"value": _round(rsi_value, 2),
|
| 133 |
+
"signal": (
|
| 134 |
+
"Insufficient data" if pd.isna(rsi_value)
|
| 135 |
+
else "Overbought" if rsi_value > 70
|
| 136 |
+
else "Oversold" if rsi_value < 30
|
| 137 |
+
else "Neutral"
|
| 138 |
+
),
|
| 139 |
+
}
|
| 140 |
+
macd_ready = pd.notna(last["MACD"]) and pd.notna(last["MACD_Signal"])
|
| 141 |
+
signals["MACD"] = {
|
| 142 |
+
"value": _round(last["MACD"], 5),
|
| 143 |
+
"signal": (
|
| 144 |
+
"Insufficient data" if not macd_ready
|
| 145 |
+
else "Bullish (above signal)" if last["MACD"] > last["MACD_Signal"]
|
| 146 |
+
else "Bearish (below signal)"
|
| 147 |
+
),
|
| 148 |
+
}
|
| 149 |
+
bb_ready = pd.notna(last["BB_Upper"]) and pd.notna(last["BB_Lower"])
|
| 150 |
+
signals["Bollinger Bands"] = {
|
| 151 |
+
"value": _round(last["Close"], 5),
|
| 152 |
+
"signal": (
|
| 153 |
+
"Insufficient data" if not bb_ready
|
| 154 |
+
else "Above Upper Band" if last["Close"] > last["BB_Upper"]
|
| 155 |
+
else "Below Lower Band" if last["Close"] < last["BB_Lower"]
|
| 156 |
+
else "Inside Bands"
|
| 157 |
+
),
|
| 158 |
+
}
|
| 159 |
+
sma_ready = pd.notna(last["SMA_20"])
|
| 160 |
+
signals["Moving Averages"] = {
|
| 161 |
+
"value": f"SMA20={_round(last['SMA_20'], 5)}, EMA20={_round(last['EMA_20'], 5)}",
|
| 162 |
+
"signal": (
|
| 163 |
+
"Insufficient data for SMA" if not sma_ready
|
| 164 |
+
else "Price Above MA (Uptrend)" if last["Close"] > last["SMA_20"]
|
| 165 |
+
else "Price Below MA (Downtrend)"
|
| 166 |
+
),
|
| 167 |
+
}
|
| 168 |
+
stoch_value = last["Stoch_%K"]
|
| 169 |
+
signals["Stochastic (14,3)"] = {
|
| 170 |
+
"value": _round(stoch_value, 2),
|
| 171 |
+
"signal": (
|
| 172 |
+
"Insufficient data" if pd.isna(stoch_value)
|
| 173 |
+
else "Overbought" if stoch_value > 80
|
| 174 |
+
else "Oversold" if stoch_value < 20
|
| 175 |
+
else "Neutral"
|
| 176 |
+
),
|
| 177 |
+
}
|
| 178 |
+
return signals
|
live_runner.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Standalone continuous 'live' prediction logger - an alternative to
|
| 2 |
+
clicking the Live tab in app.py by hand:
|
| 3 |
+
|
| 4 |
+
python live_runner.py --symbol BTC-USD --timeframe 5m --model ARIMA
|
| 5 |
+
python live_runner.py --symbol EURUSD=X --timeframe 15m --model TimesFM --poll-seconds 120
|
| 6 |
+
python live_runner.py --symbol BTC-USD --timeframe 15m --model ARIMA --use-features
|
| 7 |
+
|
| 8 |
+
Every prediction and its later verification (once the target candle closes)
|
| 9 |
+
is appended to outputs/live_<symbol>_<timeframe>_<model>[_featured].csv.
|
| 10 |
+
|
| 11 |
+
--use-features runs the same feature pipeline as the Backtest tab and logs
|
| 12 |
+
to a separate CSV, so baseline and featured runs never share a file.
|
| 13 |
+
"""
|
| 14 |
+
import argparse
|
| 15 |
+
import os
|
| 16 |
+
import time
|
| 17 |
+
from datetime import datetime, timezone
|
| 18 |
+
|
| 19 |
+
import pandas as pd
|
| 20 |
+
|
| 21 |
+
from data.historical import get_historical_with_features, DataFetchError
|
| 22 |
+
from models.registry import get_model
|
| 23 |
+
from utils.helpers import PREDICTION_HISTORY_CANDLES, history_days_for_candles, infer_step
|
| 24 |
+
from config import OUTPUT_DIR, CUSTOM_TIMEFRAMES, YF_NATIVE_INTERVALS
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def main():
|
| 28 |
+
parser = argparse.ArgumentParser(description="Continuous live prediction logger.")
|
| 29 |
+
parser.add_argument("--symbol", required=True, help="e.g. BTC-USD, EURUSD=X")
|
| 30 |
+
parser.add_argument("--timeframe", required=True, help="e.g. 1m, 5m, 15m, 1h")
|
| 31 |
+
parser.add_argument("--model", required=True,
|
| 32 |
+
choices=["ARIMA", "Auto-ARIMA", "ARIMA-GARCH", "Moirai", "TimesFM"])
|
| 33 |
+
parser.add_argument("--poll-seconds", type=int, default=60,
|
| 34 |
+
help="How often to check for a new candle (default: 60s)")
|
| 35 |
+
parser.add_argument("--use-features", action="store_true",
|
| 36 |
+
help="Feed OHLCV+RSI/MACD/Bollinger/SMA-EMA/Stochastic to the model "
|
| 37 |
+
"(same leak-free pipeline as the Backtest tab), not just Close.")
|
| 38 |
+
args = parser.parse_args()
|
| 39 |
+
|
| 40 |
+
safe_symbol = args.symbol.replace("=", "_").replace("/", "_")
|
| 41 |
+
suffix = "_featured" if args.use_features else ""
|
| 42 |
+
log_path = os.path.join(OUTPUT_DIR, f"live_{safe_symbol}_{args.timeframe}_{args.model}{suffix}.csv")
|
| 43 |
+
model = get_model(args.model, args.symbol, args.timeframe, use_features=args.use_features)
|
| 44 |
+
|
| 45 |
+
# Enough candles for the model to forecast from (every model has a
|
| 46 |
+
# minimum history requirement), clamped to what the source interval can
|
| 47 |
+
# serve. Indicator warm-up padding is added on top inside
|
| 48 |
+
# get_historical_with_features.
|
| 49 |
+
source_interval = CUSTOM_TIMEFRAMES.get(args.timeframe, {}).get("source", args.timeframe)
|
| 50 |
+
max_servable_days = YF_NATIVE_INTERVALS.get(source_interval, {}).get("max_days")
|
| 51 |
+
wanted_days = history_days_for_candles(args.timeframe, PREDICTION_HISTORY_CANDLES, minimum_days=2)
|
| 52 |
+
fetch_days = min(wanted_days, max_servable_days) if max_servable_days else wanted_days
|
| 53 |
+
|
| 54 |
+
pending = None # dict: target_time, current_close, predicted_close, predicted_direction
|
| 55 |
+
correct_count = 0
|
| 56 |
+
total_count = 0
|
| 57 |
+
|
| 58 |
+
print(f"[live_runner] {args.symbol} [{args.timeframe}] using {args.model}"
|
| 59 |
+
f"{' (+10 features)' if args.use_features else ''}. "
|
| 60 |
+
f"Fetching {fetch_days} day(s) of history per poll. "
|
| 61 |
+
f"Logging to {log_path}. Ctrl+C to stop.")
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
while True:
|
| 65 |
+
try:
|
| 66 |
+
df, features_df = get_historical_with_features(
|
| 67 |
+
args.symbol, args.timeframe, lookback_days=fetch_days,
|
| 68 |
+
use_features=args.use_features,
|
| 69 |
+
)
|
| 70 |
+
latest_time = df.index[-1]
|
| 71 |
+
latest_close = float(df["Close"].iloc[-1])
|
| 72 |
+
|
| 73 |
+
# Verify only once a strictly newer candle exists: the target
|
| 74 |
+
# candle appears in df.index the instant it starts forming,
|
| 75 |
+
# when its close is still moving.
|
| 76 |
+
if (pending is not None and pending["target_time"] in df.index
|
| 77 |
+
and pending["target_time"] < latest_time):
|
| 78 |
+
actual_close = float(df.loc[pending["target_time"], "Close"])
|
| 79 |
+
actual_direction = "up" if actual_close > pending["current_close"] else "down"
|
| 80 |
+
correct = actual_direction == pending["predicted_direction"]
|
| 81 |
+
total_count += 1
|
| 82 |
+
correct_count += int(correct)
|
| 83 |
+
|
| 84 |
+
row = {
|
| 85 |
+
**pending, "actual_close": actual_close, "actual_direction": actual_direction,
|
| 86 |
+
"correct": correct, "logged_at": datetime.now(timezone.utc).isoformat(),
|
| 87 |
+
}
|
| 88 |
+
pd.DataFrame([row]).to_csv(log_path, mode="a",
|
| 89 |
+
header=not os.path.exists(log_path), index=False)
|
| 90 |
+
acc = round(100 * correct_count / total_count, 2)
|
| 91 |
+
print(f"[{datetime.now(timezone.utc).isoformat()}] Verified: predicted "
|
| 92 |
+
f"{pending['predicted_direction']}, actual {actual_direction} -> "
|
| 93 |
+
f"{'CORRECT' if correct else 'WRONG'} (running accuracy: {acc}%, n={total_count})")
|
| 94 |
+
pending = None
|
| 95 |
+
|
| 96 |
+
if pending is None:
|
| 97 |
+
forecast = model.predict(df["Close"], horizon=1, features=features_df)
|
| 98 |
+
predicted_close = float(forecast[-1])
|
| 99 |
+
predicted_direction = "up" if predicted_close > latest_close else "down"
|
| 100 |
+
step = infer_step(df.index)
|
| 101 |
+
pending = {
|
| 102 |
+
"target_time": latest_time + step, "current_close": latest_close,
|
| 103 |
+
"predicted_close": predicted_close, "predicted_direction": predicted_direction,
|
| 104 |
+
}
|
| 105 |
+
print(f"[{datetime.now(timezone.utc).isoformat()}] New prediction: "
|
| 106 |
+
f"{args.symbol} next candle -> {predicted_direction} ({predicted_close:.5f})")
|
| 107 |
+
|
| 108 |
+
except DataFetchError as e:
|
| 109 |
+
print(f"[{datetime.now(timezone.utc).isoformat()}] Data error: {e}")
|
| 110 |
+
except Exception as e:
|
| 111 |
+
print(f"[{datetime.now(timezone.utc).isoformat()}] Error: {e}")
|
| 112 |
+
|
| 113 |
+
time.sleep(args.poll_seconds)
|
| 114 |
+
except KeyboardInterrupt:
|
| 115 |
+
# Ctrl+C most often lands during the sleep between polls, which is
|
| 116 |
+
# outside the per-iteration handlers above.
|
| 117 |
+
print("Stopped.")
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
if __name__ == "__main__":
|
| 121 |
+
main()
|
models/__init__.py
ADDED
|
File without changes
|
models/arima_garch_model.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ARIMA-GARCH: conditional mean plus conditional variance.
|
| 2 |
+
|
| 3 |
+
1. ARIMA(p, 0, q) on log returns -> conditional mean.
|
| 4 |
+
2. GARCH(1,1) on the ARIMA residuals -> conditional variance.
|
| 5 |
+
price[t+h] = price[t] * exp(cumulative log-return forecast)
|
| 6 |
+
|
| 7 |
+
last_volatility_forecast holds the per-step return std-dev from the most
|
| 8 |
+
recent predict() call (informational: confidence bands, position sizing).
|
| 9 |
+
`features` is used as ARIMAX exog on the mean model only.
|
| 10 |
+
"""
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
from models.base_model import BaseForecastModel
|
| 15 |
+
from models.dependencies import import_arch_model, import_arima, quiet_fit
|
| 16 |
+
from features.feature_pipeline import carry_forward_future, validate_features
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class ArimaGarchModel(BaseForecastModel):
|
| 20 |
+
name = "ARIMA-GARCH"
|
| 21 |
+
|
| 22 |
+
def __init__(self, max_p=3, max_q=3, order=None, garch_p=1, garch_q=1,
|
| 23 |
+
refit_order_every=None):
|
| 24 |
+
self.max_p = max_p
|
| 25 |
+
self.max_q = max_q
|
| 26 |
+
self._cached_order = order # (p, 0, q), searched on the RETURNS series
|
| 27 |
+
self.garch_p = garch_p
|
| 28 |
+
self.garch_q = garch_q
|
| 29 |
+
self.refit_order_every = refit_order_every
|
| 30 |
+
self._calls_since_search = 0
|
| 31 |
+
self.last_volatility_forecast = None
|
| 32 |
+
|
| 33 |
+
def _best_order(self, returns: pd.Series, exog: pd.DataFrame = None):
|
| 34 |
+
arima = import_arima(self.name)
|
| 35 |
+
best_aic = np.inf
|
| 36 |
+
best_order = (1, 0, 1)
|
| 37 |
+
with quiet_fit():
|
| 38 |
+
for p in range(self.max_p + 1):
|
| 39 |
+
for q in range(self.max_q + 1):
|
| 40 |
+
if p == 0 and q == 0:
|
| 41 |
+
continue
|
| 42 |
+
try:
|
| 43 |
+
fit = arima(returns, exog=exog, order=(p, 0, q)).fit()
|
| 44 |
+
except Exception:
|
| 45 |
+
continue
|
| 46 |
+
if fit.aic < best_aic:
|
| 47 |
+
best_aic = fit.aic
|
| 48 |
+
best_order = (p, 0, q)
|
| 49 |
+
return best_order
|
| 50 |
+
|
| 51 |
+
def predict(self, history: pd.Series, horizon: int = 1, features: pd.DataFrame = None) -> list:
|
| 52 |
+
prices = pd.Series(history).astype(float).reset_index(drop=True)
|
| 53 |
+
if len(prices) < 30:
|
| 54 |
+
raise ValueError("ARIMA-GARCH needs at least 30 candles of history.")
|
| 55 |
+
if (prices <= 0).any():
|
| 56 |
+
raise ValueError("ARIMA-GARCH needs strictly positive prices (it uses log returns).")
|
| 57 |
+
|
| 58 |
+
arima = import_arima(self.name)
|
| 59 |
+
arch_model = import_arch_model(self.name)
|
| 60 |
+
|
| 61 |
+
log_returns = np.log(prices / prices.shift(1)).dropna().reset_index(drop=True)
|
| 62 |
+
|
| 63 |
+
exog = None
|
| 64 |
+
if features is not None:
|
| 65 |
+
validate_features(features, expected_len=len(prices), model_name="ARIMA-GARCH")
|
| 66 |
+
# log_returns[i] is the return INTO candle i+1, so features row 0
|
| 67 |
+
# has no matching return.
|
| 68 |
+
exog = features.iloc[1:].reset_index(drop=True)
|
| 69 |
+
|
| 70 |
+
need_search = self._cached_order is None
|
| 71 |
+
if self.refit_order_every and self._calls_since_search >= self.refit_order_every:
|
| 72 |
+
need_search = True
|
| 73 |
+
if need_search:
|
| 74 |
+
self._cached_order = self._best_order(log_returns, exog=exog)
|
| 75 |
+
self._calls_since_search = 0
|
| 76 |
+
self._calls_since_search += 1
|
| 77 |
+
|
| 78 |
+
with quiet_fit():
|
| 79 |
+
mean_fit = arima(log_returns, exog=exog, order=self._cached_order).fit()
|
| 80 |
+
if exog is not None:
|
| 81 |
+
future_exog = carry_forward_future(exog, horizon)
|
| 82 |
+
mean_forecast = np.asarray(mean_fit.forecast(steps=horizon, exog=future_exog), dtype=float)
|
| 83 |
+
else:
|
| 84 |
+
mean_forecast = np.asarray(mean_fit.forecast(steps=horizon), dtype=float)
|
| 85 |
+
|
| 86 |
+
# arch_model optimizes more reliably on returns of order ~1 than on
|
| 87 |
+
# raw log-returns (~1e-4), so fit scaled up and undo it afterwards.
|
| 88 |
+
resid = pd.Series(mean_fit.resid).dropna()
|
| 89 |
+
scale = 100.0
|
| 90 |
+
garch_fit = arch_model(
|
| 91 |
+
resid * scale, mean="Zero", vol="GARCH", p=self.garch_p, q=self.garch_q,
|
| 92 |
+
dist="normal", rescale=False,
|
| 93 |
+
).fit(disp="off")
|
| 94 |
+
garch_forecast = garch_fit.forecast(horizon=horizon, reindex=False)
|
| 95 |
+
|
| 96 |
+
variance = np.asarray(garch_forecast.variance.values[-1], dtype=float) / (scale ** 2)
|
| 97 |
+
self.last_volatility_forecast = [float(x) for x in np.sqrt(variance)]
|
| 98 |
+
|
| 99 |
+
last_price = float(prices.iloc[-1])
|
| 100 |
+
prices_out = []
|
| 101 |
+
cum_log_return = 0.0
|
| 102 |
+
for r in mean_forecast:
|
| 103 |
+
cum_log_return += float(r)
|
| 104 |
+
prices_out.append(last_price * float(np.exp(cum_log_return)))
|
| 105 |
+
|
| 106 |
+
if not all(np.isfinite(x) for x in prices_out):
|
| 107 |
+
raise ValueError(f"ARIMA-GARCH produced a non-finite forecast for order {self._cached_order}.")
|
| 108 |
+
|
| 109 |
+
return prices_out
|
models/arima_model.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ARIMA baseline built on statsmodels.
|
| 2 |
+
|
| 3 |
+
(p, d, q) is picked once by AIC grid search on the first predict() call and
|
| 4 |
+
reused afterwards. Pass order=(p, d, q) to skip the search, or
|
| 5 |
+
refit_order_every=N to re-search every N calls. `features` is used as
|
| 6 |
+
ARIMAX exog, with future rows built by carry_forward_future().
|
| 7 |
+
"""
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
from models.base_model import BaseForecastModel
|
| 12 |
+
from models.dependencies import import_arima, quiet_fit
|
| 13 |
+
from features.feature_pipeline import carry_forward_future, validate_features
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class ArimaModel(BaseForecastModel):
|
| 17 |
+
name = "ARIMA"
|
| 18 |
+
|
| 19 |
+
def __init__(self, max_p=3, max_d=2, max_q=3, order=None, refit_order_every=None):
|
| 20 |
+
self.max_p = max_p
|
| 21 |
+
self.max_d = max_d
|
| 22 |
+
self.max_q = max_q
|
| 23 |
+
self._cached_order = order
|
| 24 |
+
self.refit_order_every = refit_order_every
|
| 25 |
+
self._calls_since_search = 0
|
| 26 |
+
|
| 27 |
+
def _best_order(self, series: pd.Series, exog: pd.DataFrame = None):
|
| 28 |
+
arima = import_arima(self.name)
|
| 29 |
+
best_aic = np.inf
|
| 30 |
+
best_order = (1, 1, 1)
|
| 31 |
+
with quiet_fit():
|
| 32 |
+
for p in range(self.max_p + 1):
|
| 33 |
+
for d in range(self.max_d + 1):
|
| 34 |
+
for q in range(self.max_q + 1):
|
| 35 |
+
if p == 0 and q == 0:
|
| 36 |
+
continue
|
| 37 |
+
try:
|
| 38 |
+
fit = arima(series, exog=exog, order=(p, d, q)).fit()
|
| 39 |
+
except Exception:
|
| 40 |
+
continue
|
| 41 |
+
if fit.aic < best_aic:
|
| 42 |
+
best_aic = fit.aic
|
| 43 |
+
best_order = (p, d, q)
|
| 44 |
+
return best_order
|
| 45 |
+
|
| 46 |
+
def predict(self, history: pd.Series, horizon: int = 1, features: pd.DataFrame = None) -> list:
|
| 47 |
+
series = pd.Series(history).astype(float).reset_index(drop=True)
|
| 48 |
+
if len(series) < 20:
|
| 49 |
+
raise ValueError("ARIMA needs at least 20 candles of history.")
|
| 50 |
+
arima = import_arima(self.name)
|
| 51 |
+
|
| 52 |
+
exog = None
|
| 53 |
+
if features is not None:
|
| 54 |
+
validate_features(features, expected_len=len(series), model_name="ARIMA")
|
| 55 |
+
exog = features.reset_index(drop=True)
|
| 56 |
+
|
| 57 |
+
need_search = self._cached_order is None
|
| 58 |
+
if self.refit_order_every and self._calls_since_search >= self.refit_order_every:
|
| 59 |
+
need_search = True
|
| 60 |
+
|
| 61 |
+
if need_search:
|
| 62 |
+
self._cached_order = self._best_order(series, exog=exog)
|
| 63 |
+
self._calls_since_search = 0
|
| 64 |
+
|
| 65 |
+
self._calls_since_search += 1
|
| 66 |
+
|
| 67 |
+
with quiet_fit():
|
| 68 |
+
fit = arima(series, exog=exog, order=self._cached_order).fit()
|
| 69 |
+
if exog is not None:
|
| 70 |
+
future_exog = carry_forward_future(exog, horizon)
|
| 71 |
+
forecast = np.asarray(fit.forecast(steps=horizon, exog=future_exog), dtype=float)
|
| 72 |
+
else:
|
| 73 |
+
forecast = np.asarray(fit.forecast(steps=horizon), dtype=float)
|
| 74 |
+
|
| 75 |
+
if not np.all(np.isfinite(forecast)):
|
| 76 |
+
raise ValueError(f"ARIMA produced a non-finite forecast for order {self._cached_order}.")
|
| 77 |
+
return [float(x) for x in forecast]
|
models/auto_arima_model.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Auto-ARIMA: Hyndman-Khandakar style order selection on pure statsmodels.
|
| 2 |
+
|
| 3 |
+
A KPSS unit-root test picks d, then a greedy AIC neighbour search picks
|
| 4 |
+
(p, q). The order is found once on the first predict() call and reused; pass
|
| 5 |
+
order=(p, d, q) to skip the search or refit_order_every=N to re-search.
|
| 6 |
+
`features` is used as ARIMAX exog, as in arima_model.py.
|
| 7 |
+
"""
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
|
| 11 |
+
from models.base_model import BaseForecastModel
|
| 12 |
+
from models.dependencies import import_arima, import_kpss, quiet_fit
|
| 13 |
+
from features.feature_pipeline import carry_forward_future, validate_features
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class AutoArimaModel(BaseForecastModel):
|
| 17 |
+
name = "Auto-ARIMA"
|
| 18 |
+
|
| 19 |
+
def __init__(self, max_p=5, max_q=5, max_d=2, order=None, refit_order_every=None):
|
| 20 |
+
self.max_p = max_p
|
| 21 |
+
self.max_q = max_q
|
| 22 |
+
self.max_d = max_d
|
| 23 |
+
self._cached_order = order
|
| 24 |
+
self.refit_order_every = refit_order_every
|
| 25 |
+
self._calls_since_search = 0
|
| 26 |
+
|
| 27 |
+
def _find_d(self, series: pd.Series) -> int:
|
| 28 |
+
kpss = import_kpss(self.name)
|
| 29 |
+
s = series.copy()
|
| 30 |
+
d = 0
|
| 31 |
+
with quiet_fit():
|
| 32 |
+
while d < self.max_d:
|
| 33 |
+
try:
|
| 34 |
+
_, p_value, _, _ = kpss(s, regression="c", nlags="auto")
|
| 35 |
+
except Exception:
|
| 36 |
+
break
|
| 37 |
+
if p_value >= 0.05: # KPSS null is stationarity: high p -> stop differencing
|
| 38 |
+
break
|
| 39 |
+
s = s.diff().dropna()
|
| 40 |
+
d += 1
|
| 41 |
+
return d
|
| 42 |
+
|
| 43 |
+
def _aic(self, series: pd.Series, order, exog: pd.DataFrame = None) -> float:
|
| 44 |
+
arima = import_arima(self.name)
|
| 45 |
+
try:
|
| 46 |
+
return arima(series, exog=exog, order=order).fit().aic
|
| 47 |
+
except Exception:
|
| 48 |
+
return np.inf
|
| 49 |
+
|
| 50 |
+
def _stepwise_search(self, series: pd.Series, d: int, exog: pd.DataFrame = None):
|
| 51 |
+
starting_points = [(0, 0), (1, 0), (0, 1), (2, 2)]
|
| 52 |
+
best_order, best_aic = None, np.inf
|
| 53 |
+
with quiet_fit():
|
| 54 |
+
for p, q in starting_points:
|
| 55 |
+
if p > self.max_p or q > self.max_q:
|
| 56 |
+
continue
|
| 57 |
+
aic = self._aic(series, (p, d, q), exog=exog)
|
| 58 |
+
if aic < best_aic:
|
| 59 |
+
best_aic, best_order = aic, (p, q)
|
| 60 |
+
|
| 61 |
+
if best_order is None:
|
| 62 |
+
best_order, best_aic = (0, 0), self._aic(series, (0, d, 0), exog=exog)
|
| 63 |
+
|
| 64 |
+
improved = True
|
| 65 |
+
while improved:
|
| 66 |
+
improved = False
|
| 67 |
+
p0, q0 = best_order
|
| 68 |
+
for p, q in [(p0 + 1, q0), (p0 - 1, q0), (p0, q0 + 1), (p0, q0 - 1),
|
| 69 |
+
(p0 + 1, q0 + 1), (p0 - 1, q0 - 1)]:
|
| 70 |
+
if p < 0 or q < 0 or p > self.max_p or q > self.max_q:
|
| 71 |
+
continue
|
| 72 |
+
aic = self._aic(series, (p, d, q), exog=exog)
|
| 73 |
+
if aic < best_aic - 1e-6:
|
| 74 |
+
best_aic, best_order = aic, (p, q)
|
| 75 |
+
improved = True
|
| 76 |
+
|
| 77 |
+
p, q = best_order
|
| 78 |
+
return (p, d, q)
|
| 79 |
+
|
| 80 |
+
def predict(self, history: pd.Series, horizon: int = 1, features: pd.DataFrame = None) -> list:
|
| 81 |
+
series = pd.Series(history).astype(float).reset_index(drop=True)
|
| 82 |
+
if len(series) < 20:
|
| 83 |
+
raise ValueError("Auto-ARIMA needs at least 20 candles of history.")
|
| 84 |
+
arima = import_arima(self.name)
|
| 85 |
+
|
| 86 |
+
exog = None
|
| 87 |
+
if features is not None:
|
| 88 |
+
validate_features(features, expected_len=len(series), model_name="Auto-ARIMA")
|
| 89 |
+
exog = features.reset_index(drop=True)
|
| 90 |
+
|
| 91 |
+
need_search = self._cached_order is None
|
| 92 |
+
if self.refit_order_every and self._calls_since_search >= self.refit_order_every:
|
| 93 |
+
need_search = True
|
| 94 |
+
|
| 95 |
+
if need_search:
|
| 96 |
+
d = self._find_d(series)
|
| 97 |
+
self._cached_order = self._stepwise_search(series, d, exog=exog)
|
| 98 |
+
self._calls_since_search = 0
|
| 99 |
+
|
| 100 |
+
self._calls_since_search += 1
|
| 101 |
+
|
| 102 |
+
with quiet_fit():
|
| 103 |
+
fit = arima(series, exog=exog, order=self._cached_order).fit()
|
| 104 |
+
if exog is not None:
|
| 105 |
+
future_exog = carry_forward_future(exog, horizon)
|
| 106 |
+
forecast = np.asarray(fit.forecast(steps=horizon, exog=future_exog), dtype=float)
|
| 107 |
+
else:
|
| 108 |
+
forecast = np.asarray(fit.forecast(steps=horizon), dtype=float)
|
| 109 |
+
|
| 110 |
+
if not np.all(np.isfinite(forecast)):
|
| 111 |
+
raise ValueError(f"Auto-ARIMA produced a non-finite forecast for order {self._cached_order}.")
|
| 112 |
+
return [float(x) for x in forecast]
|
models/base_model.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Common interface implemented by every forecasting model, so the backtester
|
| 2 |
+
and UI can treat them interchangeably."""
|
| 3 |
+
from abc import ABC, abstractmethod
|
| 4 |
+
|
| 5 |
+
import pandas as pd
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class BaseForecastModel(ABC):
|
| 9 |
+
name = "base"
|
| 10 |
+
|
| 11 |
+
@abstractmethod
|
| 12 |
+
def predict(self, history: pd.Series, horizon: int = 1, features: pd.DataFrame = None) -> list:
|
| 13 |
+
"""Forecast `horizon` future closing prices from past closes
|
| 14 |
+
(oldest -> newest).
|
| 15 |
+
|
| 16 |
+
`features`, when given, holds one row per candle of `history`, in the
|
| 17 |
+
same order, containing only values already known as of that candle
|
| 18 |
+
(see features/feature_pipeline.py). `features=None` is Close-only.
|
| 19 |
+
|
| 20 |
+
Raise ImportError for a missing dependency and ValueError for bad
|
| 21 |
+
input: callers report those per model and keep the others running.
|
| 22 |
+
"""
|
| 23 |
+
raise NotImplementedError
|
models/dependencies.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Optional third-party dependencies for the statistical models.
|
| 2 |
+
|
| 3 |
+
Imported on first use rather than at module import so the registry, the UI
|
| 4 |
+
and the test suite can load every model class in an environment where only
|
| 5 |
+
some backends are installed, and so a missing package surfaces as an
|
| 6 |
+
actionable message instead of a bare ModuleNotFoundError.
|
| 7 |
+
"""
|
| 8 |
+
import contextlib
|
| 9 |
+
import warnings
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _missing(package: str, model: str, error: Exception) -> ImportError:
|
| 13 |
+
return ImportError(
|
| 14 |
+
f"{model} needs the '{package}' package. Install with:\n"
|
| 15 |
+
f" pip install {package}\n"
|
| 16 |
+
f"(original error: {error})"
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def import_arima(model_name: str):
|
| 21 |
+
try:
|
| 22 |
+
from statsmodels.tsa.arima.model import ARIMA
|
| 23 |
+
except ImportError as e:
|
| 24 |
+
raise _missing("statsmodels", model_name, e) from e
|
| 25 |
+
return ARIMA
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def import_kpss(model_name: str):
|
| 29 |
+
try:
|
| 30 |
+
from statsmodels.tsa.stattools import kpss
|
| 31 |
+
except ImportError as e:
|
| 32 |
+
raise _missing("statsmodels", model_name, e) from e
|
| 33 |
+
return kpss
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def import_arch_model(model_name: str):
|
| 37 |
+
try:
|
| 38 |
+
from arch import arch_model
|
| 39 |
+
except ImportError as e:
|
| 40 |
+
raise _missing("arch", model_name, e) from e
|
| 41 |
+
return arch_model
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@contextlib.contextmanager
|
| 45 |
+
def quiet_fit():
|
| 46 |
+
"""Silence convergence/frequency warnings for the duration of a model fit
|
| 47 |
+
only, instead of globally muting warnings for the whole process."""
|
| 48 |
+
with warnings.catch_warnings():
|
| 49 |
+
warnings.simplefilter("ignore")
|
| 50 |
+
yield
|
models/moirai_model.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Salesforce Moirai — pretrained time-series foundation model via `uni2ts`.
|
| 3 |
+
|
| 4 |
+
Requires: pip install uni2ts torch
|
| 5 |
+
First use downloads weights from Hugging Face (cached under ~/.cache/huggingface/).
|
| 6 |
+
|
| 7 |
+
Accepts features= via past_feat_dynamic_real (past-only covariates natively
|
| 8 |
+
supported by GluonTS/uni2ts; no carry_forward_future needed — Moirai does
|
| 9 |
+
not require future covariate values by design).
|
| 10 |
+
"""
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
from models.base_model import BaseForecastModel
|
| 15 |
+
from config import MOIRAI_CHECKPOINT
|
| 16 |
+
from features.feature_pipeline import validate_features
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class MoiraiModel(BaseForecastModel):
|
| 20 |
+
name = "Moirai"
|
| 21 |
+
|
| 22 |
+
def __init__(self, checkpoint: str = MOIRAI_CHECKPOINT, context_length: int = 200,
|
| 23 |
+
num_samples: int = 100):
|
| 24 |
+
self.checkpoint = checkpoint
|
| 25 |
+
self.context_length = context_length
|
| 26 |
+
self.num_samples = num_samples
|
| 27 |
+
self._module = None # cached after first load so repeat calls in the
|
| 28 |
+
# same running app don't re-download / re-init the pretrained weights
|
| 29 |
+
|
| 30 |
+
def _get_module(self):
|
| 31 |
+
from uni2ts.model.moirai import MoiraiModule
|
| 32 |
+
if self._module is None:
|
| 33 |
+
self._module = MoiraiModule.from_pretrained(self.checkpoint)
|
| 34 |
+
return self._module
|
| 35 |
+
|
| 36 |
+
def predict(self, history: pd.Series, horizon: int = 1, features: pd.DataFrame = None) -> list:
|
| 37 |
+
try:
|
| 38 |
+
from uni2ts.model.moirai import MoiraiForecast
|
| 39 |
+
from gluonts.dataset.pandas import PandasDataset
|
| 40 |
+
except ImportError as e:
|
| 41 |
+
raise ImportError(
|
| 42 |
+
"Moirai needs the 'uni2ts' and 'gluonts' packages. Install with:\n"
|
| 43 |
+
" pip install uni2ts torch\n"
|
| 44 |
+
f"(original error: {e})"
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
values = np.asarray(history, dtype=np.float32)
|
| 48 |
+
if len(values) < 10:
|
| 49 |
+
raise ValueError("Moirai needs at least 10 candles of history.")
|
| 50 |
+
|
| 51 |
+
if features is not None:
|
| 52 |
+
# Length-only here (against the FULL history) -- catches a
|
| 53 |
+
# genuinely misaligned caller early. NaN is checked below,
|
| 54 |
+
# only for the truncated tail actually used (see
|
| 55 |
+
# validate_features' docstring for why the split matters).
|
| 56 |
+
validate_features(features, expected_len=len(values), model_name="Moirai", check_nan=False)
|
| 57 |
+
|
| 58 |
+
context = values[-self.context_length:] if len(values) > self.context_length else values
|
| 59 |
+
|
| 60 |
+
# Moirai/GluonTS need a DatetimeIndex but only the VALUES matter for a
|
| 61 |
+
# point forecast — the real candle timestamps are re-attached in
|
| 62 |
+
# app.py, so a clean synthetic per-minute index is fine here.
|
| 63 |
+
# (Timestamp.now("UTC"), not the deprecated Timestamp.utcnow() —
|
| 64 |
+
# pandas already warns that utcnow() will be removed in a future
|
| 65 |
+
# release.)
|
| 66 |
+
idx = pd.date_range(end=pd.Timestamp.now("UTC").floor("min"), periods=len(context), freq="min")
|
| 67 |
+
data = {"target": context}
|
| 68 |
+
|
| 69 |
+
feat_cols = []
|
| 70 |
+
if features is not None:
|
| 71 |
+
# Same tail-truncation as `context` above, so every column in
|
| 72 |
+
# `data` still describes the same set of candles, row for row.
|
| 73 |
+
feat_context = features.iloc[-len(context):].reset_index(drop=True)
|
| 74 |
+
validate_features(feat_context, expected_len=len(context), model_name="Moirai")
|
| 75 |
+
for col in feat_context.columns:
|
| 76 |
+
data[col] = feat_context[col].to_numpy(dtype=np.float32)
|
| 77 |
+
feat_cols = list(feat_context.columns)
|
| 78 |
+
|
| 79 |
+
series_df = pd.DataFrame(data, index=idx)
|
| 80 |
+
dataset = PandasDataset(
|
| 81 |
+
series_df, target="target",
|
| 82 |
+
past_feat_dynamic_real=feat_cols if feat_cols else None,
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
module = self._get_module()
|
| 86 |
+
forecaster = MoiraiForecast(
|
| 87 |
+
module=module,
|
| 88 |
+
prediction_length=horizon,
|
| 89 |
+
context_length=len(context),
|
| 90 |
+
patch_size="auto",
|
| 91 |
+
num_samples=self.num_samples,
|
| 92 |
+
target_dim=1,
|
| 93 |
+
feat_dynamic_real_dim=0,
|
| 94 |
+
past_feat_dynamic_real_dim=len(feat_cols),
|
| 95 |
+
)
|
| 96 |
+
predictor = forecaster.create_predictor(batch_size=1)
|
| 97 |
+
forecast = next(iter(predictor.predict(dataset)))
|
| 98 |
+
|
| 99 |
+
# forecast.samples has shape (num_samples, horizon) — take the
|
| 100 |
+
# per-step median across samples as the point forecast.
|
| 101 |
+
point_forecast = np.median(forecast.samples, axis=0)
|
| 102 |
+
out = [float(x) for x in point_forecast]
|
| 103 |
+
if not all(np.isfinite(x) for x in out):
|
| 104 |
+
raise ValueError("Moirai produced a non-finite forecast (NaN/inf) for this window.")
|
| 105 |
+
return out
|
models/registry.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model factory with lazy imports: importing this module does not pull in
|
| 2 |
+
torch/uni2ts/timesfm, and get_model("ARIMA") never touches the heavier
|
| 3 |
+
foundation-model code paths.
|
| 4 |
+
|
| 5 |
+
ARIMA / Auto-ARIMA / ARIMA-GARCH search a (p, d, q) order on their first
|
| 6 |
+
predict() call and reuse it, so they are cached per (name, symbol,
|
| 7 |
+
timeframe, features on/off): an order fitted to EURUSD without exog must not
|
| 8 |
+
be reused for BTC-USD or for a features-on call, which would silently fit
|
| 9 |
+
the wrong dynamics. Moirai / TimesFM are zero-shot and cache only their
|
| 10 |
+
pretrained weights, so they are shared by name.
|
| 11 |
+
"""
|
| 12 |
+
from models.base_model import BaseForecastModel
|
| 13 |
+
|
| 14 |
+
# Models that internally cache a fitted (p, d, q) order.
|
| 15 |
+
_ORDER_SEARCH_MODELS = {"ARIMA", "Auto-ARIMA", "ARIMA-GARCH"}
|
| 16 |
+
|
| 17 |
+
_CACHE: dict = {}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def _build_model(name: str) -> BaseForecastModel:
|
| 21 |
+
if name == "ARIMA":
|
| 22 |
+
from models.arima_model import ArimaModel
|
| 23 |
+
return ArimaModel()
|
| 24 |
+
elif name == "Auto-ARIMA":
|
| 25 |
+
from models.auto_arima_model import AutoArimaModel
|
| 26 |
+
return AutoArimaModel()
|
| 27 |
+
elif name == "ARIMA-GARCH":
|
| 28 |
+
from models.arima_garch_model import ArimaGarchModel
|
| 29 |
+
return ArimaGarchModel()
|
| 30 |
+
elif name == "Moirai":
|
| 31 |
+
from models.moirai_model import MoiraiModel
|
| 32 |
+
return MoiraiModel()
|
| 33 |
+
elif name == "TimesFM":
|
| 34 |
+
from models.timesfm_model import TimesFMModel
|
| 35 |
+
return TimesFMModel()
|
| 36 |
+
raise ValueError(
|
| 37 |
+
f"Unknown model '{name}'. Expected one of: "
|
| 38 |
+
"ARIMA, Auto-ARIMA, ARIMA-GARCH, Moirai, TimesFM."
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def get_model(name: str, symbol: str = None, timeframe: str = None,
|
| 43 |
+
use_features: bool = False) -> BaseForecastModel:
|
| 44 |
+
"""Cached model factory. Pass the symbol/timeframe/use_features you are
|
| 45 |
+
about to predict with, so an order-searching model does not reuse an
|
| 46 |
+
order fitted under different conditions (see module docstring). Calling
|
| 47 |
+
with just `name` works for single-symbol scripts.
|
| 48 |
+
"""
|
| 49 |
+
if name in _ORDER_SEARCH_MODELS:
|
| 50 |
+
variant = "featured" if use_features else "base"
|
| 51 |
+
key = (name, symbol, timeframe, variant)
|
| 52 |
+
else:
|
| 53 |
+
key = name
|
| 54 |
+
if key in _CACHE:
|
| 55 |
+
return _CACHE[key]
|
| 56 |
+
|
| 57 |
+
model = _build_model(name)
|
| 58 |
+
_CACHE[key] = model
|
| 59 |
+
return model
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def fresh_model(name: str) -> BaseForecastModel:
|
| 63 |
+
"""Like get_model but always a new instance, so a backtest runs its own
|
| 64 |
+
order search instead of inheriting one from a previous run.
|
| 65 |
+
"""
|
| 66 |
+
return _build_model(name)
|
models/timesfm_model.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Google TimesFM 2.5 — pretrained time-series foundation model via `timesfm`.
|
| 3 |
+
|
| 4 |
+
Requires: pip install timesfm[torch]
|
| 5 |
+
First use downloads weights from Hugging Face (~800MB, cached afterwards).
|
| 6 |
+
|
| 7 |
+
Accepts features= via forecast_with_covariates() (requires timesfm[torch,xreg]).
|
| 8 |
+
Covariate arrays must span context + horizon; the horizon portion is built
|
| 9 |
+
by carry_forward_future() since future indicator values are unknown.
|
| 10 |
+
"""
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
from models.base_model import BaseForecastModel
|
| 15 |
+
from config import TIMESFM_CHECKPOINT
|
| 16 |
+
from features.feature_pipeline import carry_forward_future, validate_features
|
| 17 |
+
|
| 18 |
+
_MAX_HORIZON = 64 # generous fixed ceiling set once at compile time
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class TimesFMModel(BaseForecastModel):
|
| 22 |
+
name = "TimesFM"
|
| 23 |
+
|
| 24 |
+
def __init__(self, checkpoint: str = TIMESFM_CHECKPOINT, max_context: int = 512):
|
| 25 |
+
self.checkpoint = checkpoint
|
| 26 |
+
self.max_context = max_context
|
| 27 |
+
self._model = None # cached after first load+compile (same process)
|
| 28 |
+
|
| 29 |
+
def _load(self):
|
| 30 |
+
import torch
|
| 31 |
+
import timesfm
|
| 32 |
+
|
| 33 |
+
if self._model is None:
|
| 34 |
+
torch.set_float32_matmul_precision("high")
|
| 35 |
+
model = timesfm.TimesFM_2p5_200M_torch.from_pretrained(self.checkpoint)
|
| 36 |
+
model.compile(timesfm.ForecastConfig(
|
| 37 |
+
max_context=self.max_context,
|
| 38 |
+
max_horizon=_MAX_HORIZON,
|
| 39 |
+
normalize_inputs=True,
|
| 40 |
+
use_continuous_quantile_head=True,
|
| 41 |
+
force_flip_invariance=True,
|
| 42 |
+
infer_is_positive=True, # forex/crypto prices are always > 0
|
| 43 |
+
fix_quantile_crossing=True,
|
| 44 |
+
))
|
| 45 |
+
self._model = model
|
| 46 |
+
return self._model
|
| 47 |
+
|
| 48 |
+
def predict(self, history: pd.Series, horizon: int = 1, features: pd.DataFrame = None) -> list:
|
| 49 |
+
try:
|
| 50 |
+
import timesfm # noqa
|
| 51 |
+
except ImportError as e:
|
| 52 |
+
raise ImportError(
|
| 53 |
+
"TimesFM needs the 'timesfm' package. Install with:\n"
|
| 54 |
+
" pip install timesfm[torch]\n"
|
| 55 |
+
f"(original error: {e})"
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
values = np.asarray(history, dtype=np.float32)
|
| 59 |
+
if len(values) < 32:
|
| 60 |
+
raise ValueError("TimesFM needs at least 32 candles of history.")
|
| 61 |
+
if horizon > _MAX_HORIZON:
|
| 62 |
+
raise ValueError(f"This TimesFM wrapper supports at most {_MAX_HORIZON} candles ahead.")
|
| 63 |
+
|
| 64 |
+
if features is not None:
|
| 65 |
+
# Length-only here (against the FULL history) -- catches a
|
| 66 |
+
# genuinely misaligned caller early. NaN is checked below,
|
| 67 |
+
# only for the truncated tail actually used (see
|
| 68 |
+
# validate_features' docstring for why the split matters).
|
| 69 |
+
validate_features(features, expected_len=len(values), model_name="TimesFM", check_nan=False)
|
| 70 |
+
|
| 71 |
+
context = values[-self.max_context:] if len(values) > self.max_context else values
|
| 72 |
+
model = self._load()
|
| 73 |
+
|
| 74 |
+
if features is None:
|
| 75 |
+
point_forecast, _quantiles = model.forecast(horizon=horizon, inputs=[context])
|
| 76 |
+
else:
|
| 77 |
+
# Same tail-truncation as `context` above, so every covariate
|
| 78 |
+
# column still describes the same candles as `context`, in order.
|
| 79 |
+
feat_context = features.iloc[-len(context):].reset_index(drop=True)
|
| 80 |
+
validate_features(feat_context, expected_len=len(context), model_name="TimesFM")
|
| 81 |
+
feat_future = carry_forward_future(feat_context, horizon)
|
| 82 |
+
|
| 83 |
+
dynamic_numerical_covariates = {}
|
| 84 |
+
for col in feat_context.columns:
|
| 85 |
+
full_array = np.concatenate([
|
| 86 |
+
feat_context[col].to_numpy(dtype=np.float32),
|
| 87 |
+
feat_future[col].to_numpy(dtype=np.float32),
|
| 88 |
+
])
|
| 89 |
+
dynamic_numerical_covariates[col] = [full_array] # batch of 1 series
|
| 90 |
+
|
| 91 |
+
try:
|
| 92 |
+
point_forecast, _quantiles = model.forecast_with_covariates(
|
| 93 |
+
inputs=[context],
|
| 94 |
+
dynamic_numerical_covariates=dynamic_numerical_covariates,
|
| 95 |
+
xreg_mode="xreg + timesfm",
|
| 96 |
+
)
|
| 97 |
+
except (ImportError, AttributeError) as e:
|
| 98 |
+
raise ImportError(
|
| 99 |
+
"TimesFM's covariate forecasting needs the 'xreg' extra "
|
| 100 |
+
"(scikit-learn + JAX). Install with:\n"
|
| 101 |
+
" pip install timesfm[torch,xreg]\n"
|
| 102 |
+
f"(original error: {e})"
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
out = [float(x) for x in point_forecast[0]]
|
| 106 |
+
|
| 107 |
+
if not all(np.isfinite(x) for x in out):
|
| 108 |
+
raise ValueError(
|
| 109 |
+
"TimesFM returned a non-finite forecast (NaN/inf) for this window. "
|
| 110 |
+
"This is usually a sign the input window is degenerate (e.g. a flat "
|
| 111 |
+
"or near-constant price run) — try a different window size or symbol."
|
| 112 |
+
)
|
| 113 |
+
return out
|
requirements.txt
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 2 |
+
|
| 3 |
+
# --- core data / numerics ---
|
| 4 |
+
# floor is 2.1, not just "2.0": the code's resample/date_range rules use the
|
| 5 |
+
# lowercase offset aliases ("10min", "4h", "min") -- confirmed these work on
|
| 6 |
+
# 2.1.4 through the current 3.0.x, and confirmed pandas 3.0 now HARD-ERRORS
|
| 7 |
+
# on the old uppercase forms ("4H", "10T") rather than just warning, so
|
| 8 |
+
# lowercase was the right choice; 2.1 is the safe, verified floor for it.
|
| 9 |
+
pandas>=2.1
|
| 10 |
+
numpy>=1.24
|
| 11 |
+
|
| 12 |
+
# --- market data (free, no API key) ---
|
| 13 |
+
yfinance>=0.2.40
|
| 14 |
+
|
| 15 |
+
# --- UI & charts ---
|
| 16 |
+
gradio>=4.36
|
| 17 |
+
plotly>=5.20
|
| 18 |
+
|
| 19 |
+
# --- ARIMA / Auto-ARIMA / ARIMA-GARCH ---
|
| 20 |
+
statsmodels>=0.14
|
| 21 |
+
arch>=6.3
|
| 22 |
+
|
| 23 |
+
# --- Moirai (Salesforce) — https://github.com/SalesforceAIResearch/uni2ts ---
|
| 24 |
+
uni2ts
|
| 25 |
+
gluonts
|
| 26 |
+
|
| 27 |
+
# --- TimesFM 2.5 (Google) — https://github.com/google-research/timesfm ---
|
| 28 |
+
# [xreg] is only needed for the 10-feature covariate path (models/timesfm_model.py's
|
| 29 |
+
# forecast_with_covariates()) -- it pulls in scikit-learn + JAX/jaxlib on top of
|
| 30 |
+
# [torch]. Plain Close-only TimesFM forecasting never touches xreg and would work
|
| 31 |
+
# fine with just timesfm[torch], but since this project's `features=` support is
|
| 32 |
+
# meant to work out of the box, both extras are requested together here.
|
| 33 |
+
timesfm[torch,xreg]
|
| 34 |
+
|
| 35 |
+
# --- shared deep-learning backend ---
|
| 36 |
+
torch
|
| 37 |
+
einops
|
| 38 |
+
huggingface_hub
|
tests/__init__.py
ADDED
|
File without changes
|
tests/test_backtester_alignment.py
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Checks that the walk-forward loop slices the same candles for `history`
|
| 2 |
+
and `features` at every step, and never reaches past the candle being
|
| 3 |
+
predicted from. Dependency-free: the loop is driven by a checking stand-in
|
| 4 |
+
model instead of a real forecaster.
|
| 5 |
+
|
| 6 |
+
Run with: python -m unittest tests.test_backtester_alignment -v
|
| 7 |
+
"""
|
| 8 |
+
import unittest
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pandas as pd
|
| 12 |
+
|
| 13 |
+
from backtest.backtester import backtest_model, run_all_models_backtest, run_comparison_backtest
|
| 14 |
+
from features.feature_pipeline import FEATURE_COLUMNS, compute_feature_frame
|
| 15 |
+
from models.base_model import BaseForecastModel
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _synthetic_ohlcv(n: int, seed: int = 7) -> pd.DataFrame:
|
| 19 |
+
rng = np.random.default_rng(seed)
|
| 20 |
+
steps = rng.normal(loc=0.0, scale=0.4, size=n)
|
| 21 |
+
close = 100 + np.cumsum(steps)
|
| 22 |
+
close = np.abs(close) + 5.0
|
| 23 |
+
open_ = close + rng.normal(0, 0.1, n)
|
| 24 |
+
high = np.maximum(open_, close) + np.abs(rng.normal(0, 0.2, n))
|
| 25 |
+
low = np.minimum(open_, close) - np.abs(rng.normal(0, 0.2, n))
|
| 26 |
+
volume = rng.integers(100, 10000, n).astype(float)
|
| 27 |
+
idx = pd.date_range("2024-01-01", periods=n, freq="min")
|
| 28 |
+
return pd.DataFrame(
|
| 29 |
+
{"Open": open_, "High": high, "Low": low, "Close": close, "Volume": volume}, index=idx
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class _AlignmentCheckingModel(BaseForecastModel):
|
| 34 |
+
"""Stand-in model that asserts, on every call, that the `history` and
|
| 35 |
+
`features` windows are the same length and cover the same candles: the
|
| 36 |
+
features window's raw passthrough columns must equal the source OHLCV
|
| 37 |
+
rows for exactly the candles `history` spans, so a window shifted in
|
| 38 |
+
either direction (a leak, or plain misalignment) fails. AssertionError is
|
| 39 |
+
recorded by the backtester as a failed row, so a run with zero failures
|
| 40 |
+
is the proof of alignment."""
|
| 41 |
+
|
| 42 |
+
name = "AlignmentChecker"
|
| 43 |
+
|
| 44 |
+
RAW_COLUMNS = ["Open", "High", "Low", "Volume"]
|
| 45 |
+
|
| 46 |
+
def __init__(self, df: pd.DataFrame):
|
| 47 |
+
# The backtester hands over only a window at a time, so the full
|
| 48 |
+
# series is needed to locate where that window came from.
|
| 49 |
+
self.full_close = df["Close"].reset_index(drop=True)
|
| 50 |
+
self.raw = df[self.RAW_COLUMNS].reset_index(drop=True)
|
| 51 |
+
|
| 52 |
+
def predict(self, history, horizon=1, features=None):
|
| 53 |
+
history = pd.Series(history).reset_index(drop=True)
|
| 54 |
+
|
| 55 |
+
if features is not None:
|
| 56 |
+
assert len(features) == len(history), (
|
| 57 |
+
f"length mismatch: history={len(history)} features={len(features)}"
|
| 58 |
+
)
|
| 59 |
+
assert list(features.columns) == FEATURE_COLUMNS
|
| 60 |
+
|
| 61 |
+
n = len(self.full_close)
|
| 62 |
+
w = len(history)
|
| 63 |
+
match_start = None
|
| 64 |
+
for start in range(0, n - w + 1):
|
| 65 |
+
if np.allclose(self.full_close.iloc[start:start + w].to_numpy(), history.to_numpy()):
|
| 66 |
+
match_start = start
|
| 67 |
+
break
|
| 68 |
+
assert match_start is not None, "history window not found in full series -- corrupted slice"
|
| 69 |
+
|
| 70 |
+
if features is not None:
|
| 71 |
+
expected = self.raw.iloc[match_start:match_start + w].to_numpy()
|
| 72 |
+
got = features[self.RAW_COLUMNS].to_numpy()
|
| 73 |
+
assert np.allclose(got, expected), (
|
| 74 |
+
f"features window is shifted relative to history at position {match_start}"
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
return [float(history.iloc[-1])] * horizon
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class TestBacktesterAlignment(unittest.TestCase):
|
| 81 |
+
def setUp(self):
|
| 82 |
+
self.df = _synthetic_ohlcv(200, seed=11)
|
| 83 |
+
self.features_df = compute_feature_frame(self.df)
|
| 84 |
+
|
| 85 |
+
def test_no_failed_rows_with_features(self):
|
| 86 |
+
"""If history/features were ever misaligned in length or shape,
|
| 87 |
+
the AlignmentChecker model raises -> backtester logs a 'failed'
|
| 88 |
+
row -> this assertion catches it."""
|
| 89 |
+
model = _AlignmentCheckingModel(self.df)
|
| 90 |
+
results = backtest_model(self.df, model, window=40, horizon=1, step=1,
|
| 91 |
+
features_df=self.features_df)
|
| 92 |
+
failed = results["error"].notna().sum()
|
| 93 |
+
self.assertEqual(failed, 0, f"{failed} rows failed alignment checks:\n"
|
| 94 |
+
f"{results[results['error'].notna()]}")
|
| 95 |
+
self.assertGreater(len(results), 0)
|
| 96 |
+
|
| 97 |
+
def test_features_window_matches_close_window_exactly(self):
|
| 98 |
+
"""Directly re-derive what backtest_model *should* have sliced at
|
| 99 |
+
each step and compare against a hand-rolled reference loop -- the
|
| 100 |
+
strongest possible check that (start, end) is identical for both."""
|
| 101 |
+
close = self.df["Close"].reset_index(drop=True)
|
| 102 |
+
window, horizon, step = 35, 2, 3
|
| 103 |
+
last_i = len(close) - horizon
|
| 104 |
+
|
| 105 |
+
for i in range(window, last_i + 1, step):
|
| 106 |
+
expected_close_window = close.iloc[i - window:i].reset_index(drop=True)
|
| 107 |
+
expected_feat_window = self.features_df.iloc[i - window:i].reset_index(drop=True)
|
| 108 |
+
# The Volume column is a raw passthrough (not an indicator
|
| 109 |
+
# derived from Close), so comparing it against the source df
|
| 110 |
+
# directly is a strong, independent check that the SAME i-window
|
| 111 |
+
# was used for both series (an off-by-one would desync them).
|
| 112 |
+
source_volume = self.df["Volume"].reset_index(drop=True).iloc[i - window:i].reset_index(drop=True)
|
| 113 |
+
pd.testing.assert_series_equal(
|
| 114 |
+
expected_feat_window["Volume"], source_volume, check_names=False
|
| 115 |
+
)
|
| 116 |
+
self.assertEqual(len(expected_close_window), len(expected_feat_window))
|
| 117 |
+
|
| 118 |
+
def test_baseline_mode_never_touches_features_module(self):
|
| 119 |
+
"""Not passing features_df= at all (the default) must be
|
| 120 |
+
byte-for-byte the old behavior -- confirmed by never even needing
|
| 121 |
+
a features_df (features=None reaches the model every single call)."""
|
| 122 |
+
class RecordsFeatureArg(BaseForecastModel):
|
| 123 |
+
name = "Recorder"
|
| 124 |
+
saw_features = []
|
| 125 |
+
|
| 126 |
+
def predict(self, history, horizon=1, features=None):
|
| 127 |
+
RecordsFeatureArg.saw_features.append(features)
|
| 128 |
+
return [float(pd.Series(history).iloc[-1])] * horizon
|
| 129 |
+
|
| 130 |
+
RecordsFeatureArg.saw_features.clear()
|
| 131 |
+
_ = backtest_model(self.df, RecordsFeatureArg(), window=40, horizon=1, step=5)
|
| 132 |
+
self.assertTrue(len(RecordsFeatureArg.saw_features) > 0)
|
| 133 |
+
self.assertTrue(all(f is None for f in RecordsFeatureArg.saw_features))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class TestRunAllModelsBacktestFeaturesDf(unittest.TestCase):
|
| 137 |
+
def setUp(self):
|
| 138 |
+
self.df = _synthetic_ohlcv(150, seed=13)
|
| 139 |
+
self.features_df = compute_feature_frame(self.df)
|
| 140 |
+
|
| 141 |
+
def test_features_df_none_passes_none_through(self):
|
| 142 |
+
class Recorder(BaseForecastModel):
|
| 143 |
+
name = "Recorder"
|
| 144 |
+
|
| 145 |
+
def __init__(self):
|
| 146 |
+
self.seen = []
|
| 147 |
+
|
| 148 |
+
def predict(self, history, horizon=1, features=None):
|
| 149 |
+
self.seen.append(features is None)
|
| 150 |
+
return [float(pd.Series(history).iloc[-1])] * horizon
|
| 151 |
+
|
| 152 |
+
m = Recorder()
|
| 153 |
+
run_all_models_backtest(self.df, {"Recorder": m}, window=40, horizon=1, step=10,
|
| 154 |
+
features_df=None)
|
| 155 |
+
self.assertTrue(all(m.seen)) # every call saw features=None
|
| 156 |
+
|
| 157 |
+
def test_features_df_given_passes_dataframe_through(self):
|
| 158 |
+
class Recorder(BaseForecastModel):
|
| 159 |
+
name = "Recorder"
|
| 160 |
+
|
| 161 |
+
def __init__(self):
|
| 162 |
+
self.seen = []
|
| 163 |
+
|
| 164 |
+
def predict(self, history, horizon=1, features=None):
|
| 165 |
+
self.seen.append(features is not None and len(features) == len(history))
|
| 166 |
+
return [float(pd.Series(history).iloc[-1])] * horizon
|
| 167 |
+
|
| 168 |
+
m = Recorder()
|
| 169 |
+
run_all_models_backtest(self.df, {"Recorder": m}, window=40, horizon=1, step=10,
|
| 170 |
+
features_df=self.features_df)
|
| 171 |
+
self.assertTrue(len(m.seen) > 0)
|
| 172 |
+
self.assertTrue(all(m.seen))
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
class TestRunComparisonBacktest(unittest.TestCase):
|
| 176 |
+
def setUp(self):
|
| 177 |
+
self.df = _synthetic_ohlcv(150, seed=17)
|
| 178 |
+
self.features_df = compute_feature_frame(self.df)
|
| 179 |
+
|
| 180 |
+
def test_both_modes_run_and_are_labeled_separately(self):
|
| 181 |
+
class Recorder(BaseForecastModel):
|
| 182 |
+
name = "Recorder"
|
| 183 |
+
|
| 184 |
+
def __init__(self):
|
| 185 |
+
self.seen_features = []
|
| 186 |
+
|
| 187 |
+
def predict(self, history, horizon=1, features=None):
|
| 188 |
+
self.seen_features.append(features is not None)
|
| 189 |
+
return [float(pd.Series(history).iloc[-1])] * horizon
|
| 190 |
+
|
| 191 |
+
baseline_model, featured_model = Recorder(), Recorder()
|
| 192 |
+
results, summaries = run_comparison_backtest(
|
| 193 |
+
self.df, {"Recorder": (baseline_model, featured_model)}, self.features_df,
|
| 194 |
+
window=40, horizon=1, step=10,
|
| 195 |
+
)
|
| 196 |
+
# baseline instance never saw features; featured instance always did
|
| 197 |
+
self.assertTrue(all(f is False for f in baseline_model.seen_features))
|
| 198 |
+
self.assertTrue(all(f is True for f in featured_model.seen_features))
|
| 199 |
+
|
| 200 |
+
# results carry a "mode" column with exactly the two expected labels
|
| 201 |
+
modes_present = set(results["Recorder"]["mode"].unique())
|
| 202 |
+
self.assertEqual(modes_present, {"Close-only", "+10 Features"})
|
| 203 |
+
|
| 204 |
+
# summaries: one dict per mode, never merged into a single number
|
| 205 |
+
self.assertEqual(len(summaries["Recorder"]), 2)
|
| 206 |
+
labels = {s["mode"] for s in summaries["Recorder"]}
|
| 207 |
+
self.assertEqual(labels, {"Close-only", "+10 Features"})
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
if __name__ == "__main__":
|
| 211 |
+
unittest.main()
|
tests/test_data_layer.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Data-layer tests. The single vendor call (data.historical._fetch_yf) is
|
| 2 |
+
replaced by a recording stand-in, so request windowing, chunking, clamping,
|
| 3 |
+
stitching and resampling are exercised without a network round trip. Only
|
| 4 |
+
that seam is substituted - every behaviour asserted below is the project's
|
| 5 |
+
own logic.
|
| 6 |
+
|
| 7 |
+
Candle spacing inside each returned window is deliberately coarse to keep
|
| 8 |
+
the frames small; what these tests assert is the requested windows and the
|
| 9 |
+
stitched/resampled result, not the row spacing.
|
| 10 |
+
|
| 11 |
+
Run with: python -m unittest tests.test_data_layer -v
|
| 12 |
+
"""
|
| 13 |
+
import math
|
| 14 |
+
import unittest
|
| 15 |
+
from datetime import timedelta
|
| 16 |
+
from unittest import mock
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
|
| 21 |
+
from config import YF_NATIVE_INTERVALS
|
| 22 |
+
from data.historical import (OHLCV_COLUMNS, DataFetchError, get_historical,
|
| 23 |
+
get_historical_with_features, resample_ohlc)
|
| 24 |
+
from features.feature_pipeline import FEATURE_COLUMNS
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def _window_candles(start, end, freq: str) -> pd.DataFrame:
|
| 28 |
+
idx = pd.date_range(start=start, end=end, freq=freq, inclusive="left")
|
| 29 |
+
if len(idx) == 0:
|
| 30 |
+
return pd.DataFrame()
|
| 31 |
+
n = len(idx)
|
| 32 |
+
base = 100.0 + np.arange(n, dtype=float) * 0.1
|
| 33 |
+
return pd.DataFrame(
|
| 34 |
+
{
|
| 35 |
+
"Open": base,
|
| 36 |
+
"High": base + 0.5,
|
| 37 |
+
"Low": base - 0.5,
|
| 38 |
+
"Close": base + 0.2,
|
| 39 |
+
"Volume": np.arange(n, dtype=float) + 1.0,
|
| 40 |
+
"Dividends": np.zeros(n), # yfinance ships extra columns
|
| 41 |
+
},
|
| 42 |
+
index=idx,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class _RecordingFetcher:
|
| 47 |
+
"""Stands in for the yfinance call, recording every requested window."""
|
| 48 |
+
|
| 49 |
+
def __init__(self, freq: str = "1h", empty_calls=()):
|
| 50 |
+
self.freq = freq
|
| 51 |
+
self.empty_calls = set(empty_calls)
|
| 52 |
+
self.calls = []
|
| 53 |
+
self.frames = []
|
| 54 |
+
|
| 55 |
+
def __call__(self, symbol, interval, start, end):
|
| 56 |
+
self.calls.append({"symbol": symbol, "interval": interval,
|
| 57 |
+
"start": start, "end": end})
|
| 58 |
+
if len(self.calls) in self.empty_calls:
|
| 59 |
+
return pd.DataFrame()
|
| 60 |
+
frame = _window_candles(start, end, self.freq)
|
| 61 |
+
self.frames.append(frame)
|
| 62 |
+
return frame
|
| 63 |
+
|
| 64 |
+
@property
|
| 65 |
+
def spans(self):
|
| 66 |
+
return [c["end"] - c["start"] for c in self.calls]
|
| 67 |
+
|
| 68 |
+
@property
|
| 69 |
+
def total_span(self):
|
| 70 |
+
return (max(c["end"] for c in self.calls)
|
| 71 |
+
- min(c["start"] for c in self.calls))
|
| 72 |
+
|
| 73 |
+
def raw(self) -> pd.DataFrame:
|
| 74 |
+
return pd.concat(self.frames).sort_index()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class TestLookbackIsHonored(unittest.TestCase):
|
| 78 |
+
def test_daily_lookback_requests_exactly_that_window(self):
|
| 79 |
+
fetcher = _RecordingFetcher(freq="1D")
|
| 80 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 81 |
+
df = get_historical("BTC-USD", "1d", lookback_days=30)
|
| 82 |
+
|
| 83 |
+
self.assertEqual(len(fetcher.calls), 1)
|
| 84 |
+
self.assertEqual(fetcher.calls[0]["interval"], "1d")
|
| 85 |
+
self.assertEqual(fetcher.spans[0], timedelta(days=30))
|
| 86 |
+
self.assertLessEqual(len(df), 31)
|
| 87 |
+
self.assertGreater(len(df), 0)
|
| 88 |
+
|
| 89 |
+
def test_returned_frame_is_ordered_and_ohlcv_only(self):
|
| 90 |
+
fetcher = _RecordingFetcher(freq="1D")
|
| 91 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 92 |
+
df = get_historical("BTC-USD", "1d", lookback_days=10)
|
| 93 |
+
|
| 94 |
+
self.assertEqual(list(df.columns), OHLCV_COLUMNS)
|
| 95 |
+
self.assertNotIn("Dividends", df.columns)
|
| 96 |
+
self.assertTrue(df.index.is_monotonic_increasing)
|
| 97 |
+
self.assertFalse(df.index.duplicated().any())
|
| 98 |
+
|
| 99 |
+
def test_no_lookback_falls_back_to_the_interval_limit(self):
|
| 100 |
+
fetcher = _RecordingFetcher(freq="1h")
|
| 101 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 102 |
+
get_historical("BTC-USD", "60m")
|
| 103 |
+
|
| 104 |
+
self.assertEqual(fetcher.total_span,
|
| 105 |
+
timedelta(days=YF_NATIVE_INTERVALS["60m"]["max_days"]))
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class TestChunkedFetching(unittest.TestCase):
|
| 109 |
+
def setUp(self):
|
| 110 |
+
self.limits = YF_NATIVE_INTERVALS["1m"]
|
| 111 |
+
|
| 112 |
+
def test_window_wider_than_the_request_limit_is_split(self):
|
| 113 |
+
requested = 30
|
| 114 |
+
fetcher = _RecordingFetcher(freq="1h")
|
| 115 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 116 |
+
df = get_historical("BTC-USD", "1m", lookback_days=requested)
|
| 117 |
+
|
| 118 |
+
request_days = self.limits["max_request_days"]
|
| 119 |
+
self.assertEqual(len(fetcher.calls), math.ceil(requested / request_days))
|
| 120 |
+
for span in fetcher.spans:
|
| 121 |
+
self.assertLessEqual(span, timedelta(days=request_days))
|
| 122 |
+
self.assertEqual(sum(fetcher.spans, timedelta()), timedelta(days=requested))
|
| 123 |
+
self.assertEqual(fetcher.total_span, timedelta(days=requested))
|
| 124 |
+
self.assertGreater(len(df), 0)
|
| 125 |
+
|
| 126 |
+
def test_chunks_are_contiguous_with_no_gap_or_overlap(self):
|
| 127 |
+
fetcher = _RecordingFetcher(freq="1h")
|
| 128 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 129 |
+
get_historical("BTC-USD", "1m", lookback_days=20)
|
| 130 |
+
|
| 131 |
+
for newer, older in zip(fetcher.calls, fetcher.calls[1:]):
|
| 132 |
+
self.assertEqual(newer["start"], older["end"])
|
| 133 |
+
|
| 134 |
+
def test_lookback_beyond_the_source_limit_is_clamped(self):
|
| 135 |
+
fetcher = _RecordingFetcher(freq="1h")
|
| 136 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 137 |
+
get_historical("BTC-USD", "1m", lookback_days=90)
|
| 138 |
+
|
| 139 |
+
max_days = self.limits["max_days"]
|
| 140 |
+
self.assertEqual(fetcher.total_span, timedelta(days=max_days))
|
| 141 |
+
self.assertEqual(len(fetcher.calls),
|
| 142 |
+
math.ceil(max_days / self.limits["max_request_days"]))
|
| 143 |
+
|
| 144 |
+
def test_one_empty_chunk_does_not_abort_the_fetch(self):
|
| 145 |
+
fetcher = _RecordingFetcher(freq="1h", empty_calls=(2,))
|
| 146 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 147 |
+
df = get_historical("BTC-USD", "1m", lookback_days=30)
|
| 148 |
+
|
| 149 |
+
self.assertEqual(len(fetcher.calls), 5)
|
| 150 |
+
self.assertEqual(len(df), len(fetcher.raw()))
|
| 151 |
+
self.assertGreater(len(df), 0)
|
| 152 |
+
|
| 153 |
+
def test_all_chunks_empty_reports_the_source_limit(self):
|
| 154 |
+
fetcher = _RecordingFetcher(freq="1h", empty_calls=range(1, 6))
|
| 155 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 156 |
+
with self.assertRaises(DataFetchError) as ctx:
|
| 157 |
+
get_historical("NOPE-USD", "1m", lookback_days=30)
|
| 158 |
+
|
| 159 |
+
message = str(ctx.exception)
|
| 160 |
+
self.assertIn("NOPE-USD", message)
|
| 161 |
+
self.assertIn("1m", message)
|
| 162 |
+
self.assertIn(str(self.limits["max_days"]), message)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class TestTimeframeValidation(unittest.TestCase):
|
| 166 |
+
def test_unknown_timeframe_raises_before_any_request(self):
|
| 167 |
+
fetcher = _RecordingFetcher()
|
| 168 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 169 |
+
with self.assertRaises(DataFetchError):
|
| 170 |
+
get_historical("BTC-USD", "3y", lookback_days=5)
|
| 171 |
+
self.assertEqual(fetcher.calls, [])
|
| 172 |
+
|
| 173 |
+
def test_blank_symbol_raises_before_any_request(self):
|
| 174 |
+
fetcher = _RecordingFetcher()
|
| 175 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 176 |
+
with self.assertRaises(DataFetchError):
|
| 177 |
+
get_historical(" ", "1d", lookback_days=5)
|
| 178 |
+
self.assertEqual(fetcher.calls, [])
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class TestResampling(unittest.TestCase):
|
| 182 |
+
def test_custom_timeframe_resamples_from_its_source_interval(self):
|
| 183 |
+
fetcher = _RecordingFetcher(freq="1h")
|
| 184 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 185 |
+
df = get_historical("BTC-USD", "4h", lookback_days=5)
|
| 186 |
+
|
| 187 |
+
self.assertEqual([c["interval"] for c in fetcher.calls], ["60m"])
|
| 188 |
+
spacing = df.index.to_series().diff().dropna().unique()
|
| 189 |
+
self.assertEqual(list(spacing), [pd.Timedelta(hours=4)])
|
| 190 |
+
|
| 191 |
+
raw = fetcher.raw()
|
| 192 |
+
bar_time = df.index[len(df) // 2]
|
| 193 |
+
bucket = raw[(raw.index >= bar_time)
|
| 194 |
+
& (raw.index < bar_time + pd.Timedelta(hours=4))]
|
| 195 |
+
self.assertEqual(len(bucket), 4)
|
| 196 |
+
self.assertAlmostEqual(df.loc[bar_time, "Open"], float(bucket["Open"].iloc[0]))
|
| 197 |
+
self.assertAlmostEqual(df.loc[bar_time, "High"], float(bucket["High"].max()))
|
| 198 |
+
self.assertAlmostEqual(df.loc[bar_time, "Low"], float(bucket["Low"].min()))
|
| 199 |
+
self.assertAlmostEqual(df.loc[bar_time, "Close"], float(bucket["Close"].iloc[-1]))
|
| 200 |
+
self.assertAlmostEqual(df.loc[bar_time, "Volume"], float(bucket["Volume"].sum()))
|
| 201 |
+
|
| 202 |
+
def test_resample_ohlc_aggregates_each_field(self):
|
| 203 |
+
idx = pd.date_range("2024-01-01", periods=4, freq="1h")
|
| 204 |
+
df = pd.DataFrame(
|
| 205 |
+
{"Open": [10.0, 11.0, 12.0, 13.0], "High": [15.0, 11.5, 20.0, 13.5],
|
| 206 |
+
"Low": [9.0, 8.0, 11.0, 12.0], "Close": [11.0, 12.0, 13.0, 14.0],
|
| 207 |
+
"Volume": [1.0, 2.0, 3.0, 4.0]},
|
| 208 |
+
index=idx,
|
| 209 |
+
)
|
| 210 |
+
out = resample_ohlc(df, "4h")
|
| 211 |
+
self.assertEqual(len(out), 1)
|
| 212 |
+
row = out.iloc[0]
|
| 213 |
+
self.assertEqual(row["Open"], 10.0)
|
| 214 |
+
self.assertEqual(row["High"], 20.0)
|
| 215 |
+
self.assertEqual(row["Low"], 8.0)
|
| 216 |
+
self.assertEqual(row["Close"], 14.0)
|
| 217 |
+
self.assertEqual(row["Volume"], 10.0)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class TestGetHistoricalWithFeatures(unittest.TestCase):
|
| 221 |
+
def test_features_off_returns_none_and_requests_no_padding(self):
|
| 222 |
+
fetcher = _RecordingFetcher(freq="1h")
|
| 223 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 224 |
+
df, features = get_historical_with_features(
|
| 225 |
+
"BTC-USD", "1h", lookback_days=3, use_features=False)
|
| 226 |
+
|
| 227 |
+
self.assertIsNone(features)
|
| 228 |
+
self.assertEqual(fetcher.total_span, timedelta(days=3))
|
| 229 |
+
self.assertGreater(len(df), 0)
|
| 230 |
+
|
| 231 |
+
def test_features_on_pads_history_and_returns_aligned_clean_frames(self):
|
| 232 |
+
fetcher = _RecordingFetcher(freq="1h")
|
| 233 |
+
with mock.patch("data.historical._fetch_yf", fetcher):
|
| 234 |
+
df, features = get_historical_with_features(
|
| 235 |
+
"BTC-USD", "1h", lookback_days=3, use_features=True)
|
| 236 |
+
|
| 237 |
+
self.assertGreater(fetcher.total_span, timedelta(days=3))
|
| 238 |
+
self.assertEqual(list(features.columns), FEATURE_COLUMNS)
|
| 239 |
+
self.assertEqual(len(features), len(df))
|
| 240 |
+
self.assertFalse(features.isna().any().any())
|
| 241 |
+
self.assertLess(len(df), len(fetcher.raw()))
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
if __name__ == "__main__":
|
| 245 |
+
unittest.main()
|
tests/test_feature_pipeline.py
ADDED
|
@@ -0,0 +1,271 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Executable checks for features/feature_pipeline.py -- in particular an
|
| 3 |
+
actual, run-it-yourself proof of the "no lookahead" property, not just a
|
| 4 |
+
docstring claim.
|
| 5 |
+
|
| 6 |
+
Run with: python -m unittest tests.test_feature_pipeline -v
|
| 7 |
+
(from the project root; only needs pandas/numpy, same as indicators.py).
|
| 8 |
+
"""
|
| 9 |
+
import unittest
|
| 10 |
+
|
| 11 |
+
import numpy as np
|
| 12 |
+
import pandas as pd
|
| 13 |
+
|
| 14 |
+
from features.feature_pipeline import (
|
| 15 |
+
FEATURE_COLUMNS,
|
| 16 |
+
carry_forward_future,
|
| 17 |
+
compute_feature_frame,
|
| 18 |
+
compute_feature_frame_for_period,
|
| 19 |
+
slice_features,
|
| 20 |
+
validate_features,
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _synthetic_ohlcv(n: int, seed: int = 0) -> pd.DataFrame:
|
| 25 |
+
"""A plausible-looking random-walk OHLCV frame, positive prices,
|
| 26 |
+
strictly increasing DatetimeIndex -- enough to exercise every
|
| 27 |
+
indicator without needing real market data."""
|
| 28 |
+
rng = np.random.default_rng(seed)
|
| 29 |
+
steps = rng.normal(loc=0.0, scale=0.5, size=n)
|
| 30 |
+
close = 100 + np.cumsum(steps)
|
| 31 |
+
close = np.abs(close) + 1.0 # keep strictly positive
|
| 32 |
+
open_ = close + rng.normal(0, 0.1, n)
|
| 33 |
+
high = np.maximum(open_, close) + np.abs(rng.normal(0, 0.2, n))
|
| 34 |
+
low = np.minimum(open_, close) - np.abs(rng.normal(0, 0.2, n))
|
| 35 |
+
volume = rng.integers(100, 10000, n).astype(float)
|
| 36 |
+
idx = pd.date_range("2024-01-01", periods=n, freq="min")
|
| 37 |
+
return pd.DataFrame(
|
| 38 |
+
{"Open": open_, "High": high, "Low": low, "Close": close, "Volume": volume},
|
| 39 |
+
index=idx,
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class TestNoLookahead(unittest.TestCase):
|
| 44 |
+
"""The property the whole no-leakage requirement rests on: a feature
|
| 45 |
+
value at row t must be identical no matter how much (or little) data
|
| 46 |
+
after row t exists when it's computed."""
|
| 47 |
+
|
| 48 |
+
def test_truncation_invariance(self):
|
| 49 |
+
df = _synthetic_ohlcv(300, seed=1)
|
| 50 |
+
full = compute_feature_frame(df)
|
| 51 |
+
|
| 52 |
+
# Recompute using only data up to several different cutoffs, and
|
| 53 |
+
# check every row that exists in both versions matches EXACTLY.
|
| 54 |
+
for cutoff in (50, 100, 150, 250, 299):
|
| 55 |
+
truncated = compute_feature_frame(df.iloc[: cutoff + 1])
|
| 56 |
+
overlap = min(len(full), len(truncated))
|
| 57 |
+
pd.testing.assert_frame_equal(
|
| 58 |
+
full.iloc[:overlap].reset_index(drop=True),
|
| 59 |
+
truncated.iloc[:overlap].reset_index(drop=True),
|
| 60 |
+
check_exact=False,
|
| 61 |
+
atol=1e-10,
|
| 62 |
+
obj=f"feature frame truncated at row {cutoff}",
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
def test_single_row_extension_does_not_rewrite_history(self):
|
| 66 |
+
"""Appending ONE new candle must never change any prior row --
|
| 67 |
+
this is what the walk-forward backtest loop depends on candle to
|
| 68 |
+
candle."""
|
| 69 |
+
df = _synthetic_ohlcv(120, seed=2)
|
| 70 |
+
shorter = compute_feature_frame(df.iloc[:100])
|
| 71 |
+
longer = compute_feature_frame(df.iloc[:101])
|
| 72 |
+
pd.testing.assert_frame_equal(
|
| 73 |
+
shorter.reset_index(drop=True),
|
| 74 |
+
longer.iloc[:100].reset_index(drop=True),
|
| 75 |
+
check_exact=False,
|
| 76 |
+
atol=1e-10,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
class TestShapeAndColumns(unittest.TestCase):
|
| 81 |
+
def test_columns_are_exactly_the_expected_14(self):
|
| 82 |
+
df = _synthetic_ohlcv(200, seed=3)
|
| 83 |
+
feats = compute_feature_frame(df)
|
| 84 |
+
self.assertEqual(list(feats.columns), FEATURE_COLUMNS)
|
| 85 |
+
# 4 raw OHLCV (Open/High/Low/Volume) + 1 RSI + 3 MACD + 2 Bollinger
|
| 86 |
+
# + 2 SMA/EMA + 2 Stochastic, from 9 used categories (Close excluded).
|
| 87 |
+
self.assertEqual(len(FEATURE_COLUMNS), 14)
|
| 88 |
+
|
| 89 |
+
def test_close_is_not_a_feature_column(self):
|
| 90 |
+
self.assertNotIn("Close", FEATURE_COLUMNS)
|
| 91 |
+
|
| 92 |
+
def test_bb_mid_not_duplicated_as_sma20(self):
|
| 93 |
+
# BB_Mid == SMA_20 by construction (see module docstring) -- make
|
| 94 |
+
# sure we didn't accidentally keep both.
|
| 95 |
+
self.assertIn("SMA_20", FEATURE_COLUMNS)
|
| 96 |
+
self.assertNotIn("BB_Mid", FEATURE_COLUMNS)
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class TestNoNaN(unittest.TestCase):
|
| 100 |
+
def test_no_nan_once_past_warmup(self):
|
| 101 |
+
df = _synthetic_ohlcv(200, seed=4)
|
| 102 |
+
feats = compute_feature_frame(df)
|
| 103 |
+
# Row 60 has 60 real candles of history before it -- comfortably
|
| 104 |
+
# past every indicator's warm-up (the longest is Bollinger/SMA_20
|
| 105 |
+
# at 20 candles).
|
| 106 |
+
self.assertFalse(feats.iloc[60:].isna().any().any())
|
| 107 |
+
|
| 108 |
+
def test_first_19_rows_ARE_nan_without_padding(self):
|
| 109 |
+
"""The failure mode this project actually hit: compute_feature_frame
|
| 110 |
+
alone always leaves its own first ~19 rows NaN, no matter how large
|
| 111 |
+
the input is -- window size doesn't matter, row 0 never has warm-up
|
| 112 |
+
history *within this fetch*. This is the bug compute_feature_frame_
|
| 113 |
+
for_period (tested below) exists to work around."""
|
| 114 |
+
df = _synthetic_ohlcv(500, seed=99)
|
| 115 |
+
feats = compute_feature_frame(df)
|
| 116 |
+
self.assertTrue(feats.iloc[:19].isna().any().any())
|
| 117 |
+
self.assertFalse(feats.iloc[19:].isna().any().any())
|
| 118 |
+
|
| 119 |
+
def test_missing_ohlcv_column_raises(self):
|
| 120 |
+
bad = pd.DataFrame({"Open": [1, 2], "High": [1, 2], "Low": [1, 2]})
|
| 121 |
+
with self.assertRaises(ValueError):
|
| 122 |
+
compute_feature_frame(bad)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class TestComputeFeatureFrameForPeriod(unittest.TestCase):
|
| 126 |
+
"""The actual fix for the observed bug: a Backtest/Live run whose
|
| 127 |
+
requested period starts right at the edge of the fetched data always
|
| 128 |
+
had NaN in its first ~19 rows (see test_first_19_rows_ARE_nan_without_
|
| 129 |
+
padding above) -- this is what makes that go away."""
|
| 130 |
+
|
| 131 |
+
def test_no_nan_anywhere_in_the_trimmed_result(self):
|
| 132 |
+
# Simulate "fetch padding_days extra, then only want the last
|
| 133 |
+
# keep_days" -- e.g. window=60 on 1-minute BTC-USD candles, which
|
| 134 |
+
# is the exact case that surfaced this bug.
|
| 135 |
+
df_padded = _synthetic_ohlcv(60 * 24 * 3, seed=21) # 3 days of 1-min candles
|
| 136 |
+
df_trimmed, feats_trimmed = compute_feature_frame_for_period(df_padded, keep_days=2)
|
| 137 |
+
self.assertFalse(feats_trimmed.isna().any().any(),
|
| 138 |
+
"compute_feature_frame_for_period must never leave "
|
| 139 |
+
"leading NaN in the period actually requested")
|
| 140 |
+
|
| 141 |
+
def test_trimmed_period_is_the_requested_length_not_the_padded_one(self):
|
| 142 |
+
df_padded = _synthetic_ohlcv(60 * 24 * 3, seed=22)
|
| 143 |
+
keep_days = 1
|
| 144 |
+
df_trimmed, feats_trimmed = compute_feature_frame_for_period(df_padded, keep_days=keep_days)
|
| 145 |
+
expected_span = df_padded.index[-1] - df_trimmed.index[0]
|
| 146 |
+
self.assertLessEqual(expected_span, pd.Timedelta(days=keep_days) + pd.Timedelta(minutes=1))
|
| 147 |
+
self.assertEqual(len(df_trimmed), len(feats_trimmed))
|
| 148 |
+
|
| 149 |
+
def test_trimmed_values_match_computing_on_the_full_padded_series(self):
|
| 150 |
+
"""The trim must only DROP rows, never change the surviving ones --
|
| 151 |
+
same truncation-invariance property as compute_feature_frame itself,
|
| 152 |
+
just checked the other direction (padding in front, not truncating
|
| 153 |
+
the end)."""
|
| 154 |
+
df_padded = _synthetic_ohlcv(60 * 24 * 2, seed=23)
|
| 155 |
+
full_features = compute_feature_frame(df_padded)
|
| 156 |
+
df_trimmed, feats_trimmed = compute_feature_frame_for_period(df_padded, keep_days=1)
|
| 157 |
+
|
| 158 |
+
keep_mask = df_padded.index >= df_padded.index[-1] - pd.Timedelta(days=1)
|
| 159 |
+
expected = full_features.iloc[keep_mask].reset_index(drop=True)
|
| 160 |
+
pd.testing.assert_frame_equal(feats_trimmed, expected, atol=1e-10)
|
| 161 |
+
|
| 162 |
+
def test_reproduces_and_fixes_the_reported_btc_1m_window60_case(self):
|
| 163 |
+
"""Direct reproduction of the actual failure: BTC-USD, 1-minute
|
| 164 |
+
candles, 1 day lookback, window=60 -- the first backtest window is
|
| 165 |
+
rows [0:60] of whatever got fetched, which used to include the
|
| 166 |
+
always-NaN rows [0:19]. With padding, it no longer does."""
|
| 167 |
+
from utils.helpers import feature_warmup_days
|
| 168 |
+
keep_days = 1
|
| 169 |
+
padding_days = feature_warmup_days("1m", minimum_days=0)
|
| 170 |
+
df_padded = _synthetic_ohlcv(60 * 24 * (keep_days + padding_days) + 100, seed=24)
|
| 171 |
+
|
| 172 |
+
df_trimmed, feats_trimmed = compute_feature_frame_for_period(df_padded, keep_days=keep_days)
|
| 173 |
+
window = 60
|
| 174 |
+
first_window = slice_features(feats_trimmed, 0, window)
|
| 175 |
+
self.assertFalse(first_window.isna().any().any(),
|
| 176 |
+
"the FIRST walk-forward window must be NaN-free after padding")
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
class TestSliceFeatures(unittest.TestCase):
|
| 180 |
+
def test_slice_matches_close_slice_positionally(self):
|
| 181 |
+
df = _synthetic_ohlcv(200, seed=5)
|
| 182 |
+
feats = compute_feature_frame(df)
|
| 183 |
+
close = df["Close"].reset_index(drop=True)
|
| 184 |
+
|
| 185 |
+
window, i = 60, 130
|
| 186 |
+
close_window = close.iloc[i - window : i]
|
| 187 |
+
feat_window = slice_features(feats, i - window, i)
|
| 188 |
+
|
| 189 |
+
self.assertEqual(len(close_window), len(feat_window))
|
| 190 |
+
# Same positional slice, just re-indexed -- last row of the feature
|
| 191 |
+
# window must describe the SAME candle as the last row of the
|
| 192 |
+
# close window (spot check via Close reconstructed from OHLCV: the
|
| 193 |
+
# feature frame doesn't carry Close, so we check against the
|
| 194 |
+
# original df's own Close at that position instead).
|
| 195 |
+
self.assertAlmostEqual(
|
| 196 |
+
df["Close"].iloc[i - 1], close_window.iloc[-1], places=8
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class TestValidateFeatures(unittest.TestCase):
|
| 201 |
+
def test_length_mismatch_raises(self):
|
| 202 |
+
feats = pd.DataFrame({c: [1.0, 2.0] for c in FEATURE_COLUMNS})
|
| 203 |
+
with self.assertRaises(ValueError):
|
| 204 |
+
validate_features(feats, expected_len=3, model_name="Test")
|
| 205 |
+
|
| 206 |
+
def test_nan_raises(self):
|
| 207 |
+
feats = pd.DataFrame({c: [1.0, np.nan] for c in FEATURE_COLUMNS})
|
| 208 |
+
with self.assertRaises(ValueError):
|
| 209 |
+
validate_features(feats, expected_len=2, model_name="Test")
|
| 210 |
+
|
| 211 |
+
def test_check_nan_false_skips_nan_but_still_checks_length(self):
|
| 212 |
+
"""The Moirai/TimesFM pattern: a caller that only ever uses the
|
| 213 |
+
TAIL of `features` calls this once with check_nan=False against the
|
| 214 |
+
FULL history length (to still catch a genuinely misaligned caller
|
| 215 |
+
early), then again with the default check_nan=True against just
|
| 216 |
+
the truncated tail it actually uses."""
|
| 217 |
+
feats_with_nan = pd.DataFrame({c: [np.nan, 1.0, 2.0] for c in FEATURE_COLUMNS})
|
| 218 |
+
validate_features(feats_with_nan, expected_len=3, model_name="Test", check_nan=False) # no raise
|
| 219 |
+
|
| 220 |
+
with self.assertRaises(ValueError):
|
| 221 |
+
validate_features(feats_with_nan, expected_len=2, model_name="Test", check_nan=False)
|
| 222 |
+
|
| 223 |
+
def test_check_nan_false_then_true_on_truncated_tail_mirrors_model_usage(self):
|
| 224 |
+
# row 0 has NaN, rows 1-2 don't -- a model that only uses the last
|
| 225 |
+
# 2 rows should pass; one that (mistakenly) got handed the NaN row
|
| 226 |
+
# inside its own truncation should still fail.
|
| 227 |
+
feats = pd.DataFrame({c: [np.nan, 1.0, 2.0] for c in FEATURE_COLUMNS})
|
| 228 |
+
validate_features(feats, expected_len=3, model_name="Test", check_nan=False)
|
| 229 |
+
|
| 230 |
+
clean_tail = feats.iloc[-2:].reset_index(drop=True)
|
| 231 |
+
validate_features(clean_tail, expected_len=2, model_name="Test") # no raise -- no NaN in the tail
|
| 232 |
+
|
| 233 |
+
dirty_tail = feats.iloc[-3:].reset_index(drop=True)
|
| 234 |
+
with self.assertRaises(ValueError):
|
| 235 |
+
validate_features(dirty_tail, expected_len=3, model_name="Test") # NaN still inside this one
|
| 236 |
+
|
| 237 |
+
def test_clean_window_passes(self):
|
| 238 |
+
feats = pd.DataFrame({c: [1.0, 2.0, 3.0] for c in FEATURE_COLUMNS})
|
| 239 |
+
validate_features(feats, expected_len=3, model_name="Test") # no raise
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
class TestCarryForwardFuture(unittest.TestCase):
|
| 243 |
+
def test_repeats_last_row(self):
|
| 244 |
+
feats = pd.DataFrame({"a": [1.0, 2.0, 3.0], "b": [10.0, 20.0, 30.0]})
|
| 245 |
+
future = carry_forward_future(feats, horizon=4)
|
| 246 |
+
self.assertEqual(len(future), 4)
|
| 247 |
+
self.assertTrue((future["a"] == 3.0).all())
|
| 248 |
+
self.assertTrue((future["b"] == 30.0).all())
|
| 249 |
+
|
| 250 |
+
def test_uses_zero_future_information(self):
|
| 251 |
+
"""The defining property: carry-forward for a window ending at
|
| 252 |
+
cutoff `c` must be identical whether or not candles AFTER `c`
|
| 253 |
+
exist in the source data -- otherwise it would be leaking them."""
|
| 254 |
+
df = _synthetic_ohlcv(150, seed=6)
|
| 255 |
+
feats_short = compute_feature_frame(df.iloc[:80])
|
| 256 |
+
feats_long = compute_feature_frame(df) # 150 rows, i.e. real future data exists
|
| 257 |
+
|
| 258 |
+
future_from_short = carry_forward_future(feats_short.iloc[:80], horizon=5)
|
| 259 |
+
future_from_long = carry_forward_future(feats_long.iloc[:80], horizon=5)
|
| 260 |
+
pd.testing.assert_frame_equal(future_from_short, future_from_long, atol=1e-10)
|
| 261 |
+
|
| 262 |
+
def test_rejects_bad_input(self):
|
| 263 |
+
feats = pd.DataFrame({"a": [1.0]})
|
| 264 |
+
with self.assertRaises(ValueError):
|
| 265 |
+
carry_forward_future(feats, horizon=0)
|
| 266 |
+
with self.assertRaises(ValueError):
|
| 267 |
+
carry_forward_future(pd.DataFrame({"a": []}), horizon=1)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
if __name__ == "__main__":
|
| 271 |
+
unittest.main()
|
tests/test_helpers.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Unit tests for utils/helpers.py: history sizing, step inference and
|
| 2 |
+
candle hygiene.
|
| 3 |
+
|
| 4 |
+
Run with: python -m unittest tests.test_helpers -v
|
| 5 |
+
"""
|
| 6 |
+
import unittest
|
| 7 |
+
|
| 8 |
+
import pandas as pd
|
| 9 |
+
|
| 10 |
+
from config import CUSTOM_TIMEFRAMES, YF_NATIVE_INTERVALS
|
| 11 |
+
from utils.helpers import (INDICATOR_WARMUP_CANDLES, MINUTES_PER_CANDLE,
|
| 12 |
+
PREDICTION_HISTORY_CANDLES, drop_forming_candle,
|
| 13 |
+
feature_warmup_days, future_index,
|
| 14 |
+
history_days_for_candles, infer_step)
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def _frame(index) -> pd.DataFrame:
|
| 18 |
+
return pd.DataFrame({"Close": range(len(index))}, index=index)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class TestHistoryDaysForCandles(unittest.TestCase):
|
| 22 |
+
def test_window_covers_the_requested_candle_count(self):
|
| 23 |
+
for timeframe, minutes in MINUTES_PER_CANDLE.items():
|
| 24 |
+
days = history_days_for_candles(timeframe, 200)
|
| 25 |
+
self.assertGreaterEqual(days * 24 * 60, 200 * minutes, timeframe)
|
| 26 |
+
|
| 27 |
+
def test_known_sizes(self):
|
| 28 |
+
self.assertEqual(history_days_for_candles("1d", 200), 200)
|
| 29 |
+
self.assertEqual(history_days_for_candles("4h", 200), 34)
|
| 30 |
+
self.assertEqual(history_days_for_candles("5m", 200), 1)
|
| 31 |
+
|
| 32 |
+
def test_minimum_days_acts_as_a_floor_only(self):
|
| 33 |
+
self.assertEqual(history_days_for_candles("1m", 10, minimum_days=2), 2)
|
| 34 |
+
self.assertEqual(history_days_for_candles("1d", 10, minimum_days=2), 10)
|
| 35 |
+
|
| 36 |
+
def test_non_positive_candle_counts_still_request_a_real_window(self):
|
| 37 |
+
self.assertEqual(history_days_for_candles("1h", 0), 1)
|
| 38 |
+
self.assertEqual(history_days_for_candles("1h", -5), 1)
|
| 39 |
+
|
| 40 |
+
def test_unknown_timeframe_uses_the_hourly_fallback(self):
|
| 41 |
+
self.assertEqual(history_days_for_candles("7m", 200),
|
| 42 |
+
history_days_for_candles("1h", 200))
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class TestFeatureWarmupDays(unittest.TestCase):
|
| 46 |
+
def test_padding_covers_the_indicator_warmup(self):
|
| 47 |
+
for timeframe, minutes in MINUTES_PER_CANDLE.items():
|
| 48 |
+
days = feature_warmup_days(timeframe, minimum_days=0)
|
| 49 |
+
self.assertGreaterEqual(days * 24 * 60,
|
| 50 |
+
INDICATOR_WARMUP_CANDLES * minutes, timeframe)
|
| 51 |
+
|
| 52 |
+
def test_default_floor_is_two_days(self):
|
| 53 |
+
self.assertEqual(feature_warmup_days("1m"), 2)
|
| 54 |
+
|
| 55 |
+
def test_floor_can_be_dropped_for_padding_math(self):
|
| 56 |
+
self.assertEqual(feature_warmup_days("1m", minimum_days=0), 1)
|
| 57 |
+
self.assertEqual(feature_warmup_days("1d", minimum_days=0), 30)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class TestLiveSizingFitsSourceLimits(unittest.TestCase):
|
| 61 |
+
def test_prediction_history_is_servable_for_every_timeframe(self):
|
| 62 |
+
for timeframe in MINUTES_PER_CANDLE:
|
| 63 |
+
source = CUSTOM_TIMEFRAMES.get(timeframe, {}).get("source", timeframe)
|
| 64 |
+
limit = YF_NATIVE_INTERVALS.get(source, {}).get("max_days")
|
| 65 |
+
if limit is None:
|
| 66 |
+
continue
|
| 67 |
+
wanted = history_days_for_candles(timeframe, PREDICTION_HISTORY_CANDLES)
|
| 68 |
+
self.assertLessEqual(
|
| 69 |
+
wanted, limit,
|
| 70 |
+
f"{timeframe} wants {wanted}d but '{source}' serves {limit}d")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class TestInferStep(unittest.TestCase):
|
| 74 |
+
def test_uses_the_median_spacing(self):
|
| 75 |
+
idx = pd.date_range("2024-01-01", periods=5, freq="15min")
|
| 76 |
+
self.assertEqual(infer_step(idx), pd.Timedelta(minutes=15))
|
| 77 |
+
|
| 78 |
+
def test_market_closure_gap_does_not_dominate(self):
|
| 79 |
+
idx = pd.DatetimeIndex(["2024-01-05 20:00", "2024-01-05 21:00",
|
| 80 |
+
"2024-01-05 22:00", "2024-01-08 20:00",
|
| 81 |
+
"2024-01-08 21:00"])
|
| 82 |
+
self.assertEqual(infer_step(idx), pd.Timedelta(hours=1))
|
| 83 |
+
|
| 84 |
+
def test_single_candle_falls_back_to_one_minute(self):
|
| 85 |
+
idx = pd.date_range("2024-01-01", periods=1, freq="5min")
|
| 86 |
+
self.assertEqual(infer_step(idx), pd.Timedelta(minutes=1))
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
class TestFutureIndex(unittest.TestCase):
|
| 90 |
+
def test_projects_timestamps_after_the_last_candle(self):
|
| 91 |
+
last = pd.Timestamp("2024-01-01 00:00")
|
| 92 |
+
self.assertEqual(
|
| 93 |
+
future_index(last, pd.Timedelta(minutes=5), 3),
|
| 94 |
+
[pd.Timestamp("2024-01-01 00:05"), pd.Timestamp("2024-01-01 00:10"),
|
| 95 |
+
pd.Timestamp("2024-01-01 00:15")],
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
def test_zero_horizon_projects_nothing(self):
|
| 99 |
+
self.assertEqual(
|
| 100 |
+
future_index(pd.Timestamp("2024-01-01"), pd.Timedelta(minutes=1), 0), [])
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
class TestDropFormingCandle(unittest.TestCase):
|
| 104 |
+
def test_drops_the_still_forming_candle_and_its_feature_row(self):
|
| 105 |
+
now = pd.Timestamp.now(tz="UTC").floor("min")
|
| 106 |
+
idx = pd.DatetimeIndex([now - pd.Timedelta(minutes=10),
|
| 107 |
+
now - pd.Timedelta(minutes=5), now])
|
| 108 |
+
features = pd.DataFrame({"f": [1.0, 2.0, 3.0]})
|
| 109 |
+
|
| 110 |
+
df, trimmed_features = drop_forming_candle(_frame(idx), features)
|
| 111 |
+
|
| 112 |
+
self.assertEqual(len(df), 2)
|
| 113 |
+
self.assertEqual(df.index[-1], idx[-2])
|
| 114 |
+
self.assertEqual(len(trimmed_features), 2)
|
| 115 |
+
self.assertEqual(list(trimmed_features.index), [0, 1])
|
| 116 |
+
|
| 117 |
+
def test_keeps_a_closed_final_candle(self):
|
| 118 |
+
now = pd.Timestamp.now(tz="UTC").floor("min")
|
| 119 |
+
idx = pd.DatetimeIndex([now - pd.Timedelta(minutes=20),
|
| 120 |
+
now - pd.Timedelta(minutes=15),
|
| 121 |
+
now - pd.Timedelta(minutes=10)])
|
| 122 |
+
features = pd.DataFrame({"f": [1.0, 2.0, 3.0]})
|
| 123 |
+
|
| 124 |
+
df, kept_features = drop_forming_candle(_frame(idx), features)
|
| 125 |
+
|
| 126 |
+
self.assertEqual(len(df), 3)
|
| 127 |
+
self.assertEqual(len(kept_features), 3)
|
| 128 |
+
|
| 129 |
+
def test_handles_a_tz_naive_index(self):
|
| 130 |
+
now = pd.Timestamp.now(tz="UTC").tz_localize(None).floor("min")
|
| 131 |
+
idx = pd.DatetimeIndex([now - pd.Timedelta(minutes=10),
|
| 132 |
+
now - pd.Timedelta(minutes=5), now])
|
| 133 |
+
|
| 134 |
+
df, features = drop_forming_candle(_frame(idx), None)
|
| 135 |
+
|
| 136 |
+
self.assertEqual(len(df), 2)
|
| 137 |
+
self.assertIsNone(features)
|
| 138 |
+
|
| 139 |
+
def test_empty_frame_passes_through(self):
|
| 140 |
+
empty = pd.DataFrame({"Close": []}, index=pd.DatetimeIndex([]))
|
| 141 |
+
df, features = drop_forming_candle(empty, None)
|
| 142 |
+
self.assertEqual(len(df), 0)
|
| 143 |
+
self.assertIsNone(features)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
if __name__ == "__main__":
|
| 147 |
+
unittest.main()
|
tests/test_indicators.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Indicator tests: warm-up rows must stay NaN instead of being filled with
|
| 2 |
+
a neutral-looking value, the documented conventions (Wilder seeding,
|
| 3 |
+
population std, zero-range handling) must hold, and latest_signals must
|
| 4 |
+
report insufficient data rather than a fabricated reading.
|
| 5 |
+
|
| 6 |
+
Run with: python -m unittest tests.test_indicators -v
|
| 7 |
+
"""
|
| 8 |
+
import unittest
|
| 9 |
+
|
| 10 |
+
import numpy as np
|
| 11 |
+
import pandas as pd
|
| 12 |
+
|
| 13 |
+
from indicators.indicators import (_wilder_rma, add_all_indicators,
|
| 14 |
+
bollinger_bands, ema, latest_signals, macd,
|
| 15 |
+
rsi, sma, stochastic_oscillator)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _ohlcv(n: int, seed: int = 5) -> pd.DataFrame:
|
| 19 |
+
rng = np.random.default_rng(seed)
|
| 20 |
+
close = 100 + np.cumsum(rng.normal(0, 0.5, n))
|
| 21 |
+
open_ = close + rng.normal(0, 0.1, n)
|
| 22 |
+
high = np.maximum(open_, close) + np.abs(rng.normal(0, 0.3, n))
|
| 23 |
+
low = np.minimum(open_, close) - np.abs(rng.normal(0, 0.3, n))
|
| 24 |
+
volume = rng.integers(100, 5000, n).astype(float)
|
| 25 |
+
idx = pd.date_range("2024-01-01", periods=n, freq="5min")
|
| 26 |
+
return pd.DataFrame({"Open": open_, "High": high, "Low": low,
|
| 27 |
+
"Close": close, "Volume": volume}, index=idx)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TestWilderRma(unittest.TestCase):
|
| 31 |
+
def test_seeds_from_a_window_length_average_then_recurses(self):
|
| 32 |
+
values = pd.Series([1.0, 2.0, 3.0, 4.0, 5.0])
|
| 33 |
+
out = _wilder_rma(values, 3)
|
| 34 |
+
self.assertTrue(out.iloc[:2].isna().all())
|
| 35 |
+
self.assertAlmostEqual(out.iloc[2], 2.0)
|
| 36 |
+
self.assertAlmostEqual(out.iloc[3], (2.0 * 2 + 4.0) / 3)
|
| 37 |
+
self.assertAlmostEqual(out.iloc[4], (out.iloc[3] * 2 + 5.0) / 3)
|
| 38 |
+
|
| 39 |
+
def test_skips_a_leading_nan_before_seeding(self):
|
| 40 |
+
values = pd.Series([np.nan, 2.0, 4.0, 6.0])
|
| 41 |
+
out = _wilder_rma(values, 3)
|
| 42 |
+
self.assertTrue(out.iloc[:3].isna().all())
|
| 43 |
+
self.assertAlmostEqual(out.iloc[3], 4.0)
|
| 44 |
+
|
| 45 |
+
def test_series_shorter_than_the_window_is_all_nan(self):
|
| 46 |
+
out = _wilder_rma(pd.Series([1.0, 2.0]), 14)
|
| 47 |
+
self.assertTrue(out.isna().all())
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class TestRsi(unittest.TestCase):
|
| 51 |
+
def test_warmup_rows_are_nan_not_fifty(self):
|
| 52 |
+
out = rsi(_ohlcv(60)["Close"], 14)
|
| 53 |
+
self.assertTrue(out.iloc[:14].isna().all())
|
| 54 |
+
self.assertTrue(out.iloc[14:].notna().all())
|
| 55 |
+
self.assertEqual(int((out.iloc[:14] == 50.0).sum()), 0)
|
| 56 |
+
|
| 57 |
+
def test_only_gains_reads_one_hundred(self):
|
| 58 |
+
out = rsi(pd.Series(np.arange(40, dtype=float) + 100), 14)
|
| 59 |
+
self.assertTrue(out.iloc[:14].isna().all())
|
| 60 |
+
self.assertTrue((out.iloc[14:] == 100.0).all())
|
| 61 |
+
|
| 62 |
+
def test_flat_market_is_neutral_only_after_warmup(self):
|
| 63 |
+
out = rsi(pd.Series([100.0] * 40), 14)
|
| 64 |
+
self.assertTrue(out.iloc[:14].isna().all())
|
| 65 |
+
self.assertTrue((out.iloc[14:] == 50.0).all())
|
| 66 |
+
|
| 67 |
+
def test_stays_within_bounds(self):
|
| 68 |
+
out = rsi(_ohlcv(200, seed=9)["Close"], 14).dropna()
|
| 69 |
+
self.assertGreaterEqual(out.min(), 0.0)
|
| 70 |
+
self.assertLessEqual(out.max(), 100.0)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class TestMacdAndBollinger(unittest.TestCase):
|
| 74 |
+
def setUp(self):
|
| 75 |
+
self.close = _ohlcv(80, seed=3)["Close"]
|
| 76 |
+
|
| 77 |
+
def test_macd_is_the_fast_minus_slow_ema_with_its_own_signal_ema(self):
|
| 78 |
+
line, signal, hist = macd(self.close)
|
| 79 |
+
expected_line = ema(self.close, 12) - ema(self.close, 26)
|
| 80 |
+
pd.testing.assert_series_equal(line, expected_line, check_names=False)
|
| 81 |
+
pd.testing.assert_series_equal(signal, ema(expected_line, 9), check_names=False)
|
| 82 |
+
pd.testing.assert_series_equal(hist, expected_line - signal, check_names=False)
|
| 83 |
+
|
| 84 |
+
def test_bollinger_uses_population_std_around_the_sma(self):
|
| 85 |
+
upper, mid, lower = bollinger_bands(self.close, window=20, num_std=2.0)
|
| 86 |
+
pd.testing.assert_series_equal(mid, sma(self.close, 20), check_names=False)
|
| 87 |
+
self.assertTrue(upper.iloc[:19].isna().all())
|
| 88 |
+
|
| 89 |
+
window = self.close.iloc[-20:].to_numpy()
|
| 90 |
+
expected_std = float(np.std(window)) # ddof=0
|
| 91 |
+
self.assertAlmostEqual(float(upper.iloc[-1]),
|
| 92 |
+
float(window.mean()) + 2 * expected_std, places=9)
|
| 93 |
+
self.assertAlmostEqual(float(lower.iloc[-1]),
|
| 94 |
+
float(window.mean()) - 2 * expected_std, places=9)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class TestStochastic(unittest.TestCase):
|
| 98 |
+
def test_warmup_rows_are_nan_not_fifty(self):
|
| 99 |
+
df = _ohlcv(60, seed=4)
|
| 100 |
+
k, d = stochastic_oscillator(df["High"], df["Low"], df["Close"])
|
| 101 |
+
self.assertTrue(k.iloc[:13].isna().all())
|
| 102 |
+
self.assertTrue(k.iloc[13:].notna().all())
|
| 103 |
+
self.assertTrue(d.iloc[:15].isna().all())
|
| 104 |
+
self.assertEqual(int((k.iloc[:13] == 50.0).sum()), 0)
|
| 105 |
+
|
| 106 |
+
def test_percent_k_matches_the_definition(self):
|
| 107 |
+
df = _ohlcv(40, seed=6)
|
| 108 |
+
k, _ = stochastic_oscillator(df["High"], df["Low"], df["Close"])
|
| 109 |
+
lowest = float(df["Low"].iloc[-14:].min())
|
| 110 |
+
highest = float(df["High"].iloc[-14:].max())
|
| 111 |
+
expected = 100 * (float(df["Close"].iloc[-1]) - lowest) / (highest - lowest)
|
| 112 |
+
self.assertAlmostEqual(float(k.iloc[-1]), expected, places=9)
|
| 113 |
+
|
| 114 |
+
def test_zero_range_is_neutral_only_after_warmup(self):
|
| 115 |
+
flat = pd.Series([100.0] * 30)
|
| 116 |
+
k, d = stochastic_oscillator(flat, flat, flat)
|
| 117 |
+
self.assertTrue(k.iloc[:13].isna().all())
|
| 118 |
+
self.assertTrue((k.iloc[13:] == 50.0).all())
|
| 119 |
+
self.assertTrue((d.iloc[15:] == 50.0).all())
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
class TestAddAllIndicators(unittest.TestCase):
|
| 123 |
+
def setUp(self):
|
| 124 |
+
self.df = _ohlcv(60, seed=8)
|
| 125 |
+
self.out = add_all_indicators(self.df)
|
| 126 |
+
|
| 127 |
+
def test_adds_every_indicator_column_without_mutating_the_input(self):
|
| 128 |
+
expected = ["SMA_20", "EMA_20", "RSI_14", "MACD", "MACD_Signal",
|
| 129 |
+
"MACD_Hist", "BB_Upper", "BB_Mid", "BB_Lower",
|
| 130 |
+
"Stoch_%K", "Stoch_%D"]
|
| 131 |
+
for column in expected:
|
| 132 |
+
self.assertIn(column, self.out.columns)
|
| 133 |
+
self.assertNotIn(column, self.df.columns)
|
| 134 |
+
|
| 135 |
+
def test_warmup_nan_counts_are_the_real_indicator_periods(self):
|
| 136 |
+
self.assertEqual(int(self.out["RSI_14"].isna().sum()), 14)
|
| 137 |
+
self.assertEqual(int(self.out["Stoch_%K"].isna().sum()), 13)
|
| 138 |
+
self.assertEqual(int(self.out["Stoch_%D"].isna().sum()), 15)
|
| 139 |
+
self.assertEqual(int(self.out["SMA_20"].isna().sum()), 19)
|
| 140 |
+
self.assertEqual(int(self.out["BB_Upper"].isna().sum()), 19)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class TestLatestSignals(unittest.TestCase):
|
| 144 |
+
def test_reports_insufficient_data_instead_of_a_fabricated_reading(self):
|
| 145 |
+
out = add_all_indicators(_ohlcv(3, seed=2))
|
| 146 |
+
signals = latest_signals(out)
|
| 147 |
+
|
| 148 |
+
self.assertEqual(signals["RSI (14)"]["value"], "n/a")
|
| 149 |
+
self.assertEqual(signals["RSI (14)"]["signal"], "Insufficient data")
|
| 150 |
+
self.assertEqual(signals["Stochastic (14,3)"]["value"], "n/a")
|
| 151 |
+
self.assertEqual(signals["Stochastic (14,3)"]["signal"], "Insufficient data")
|
| 152 |
+
self.assertEqual(signals["Bollinger Bands"]["signal"], "Insufficient data")
|
| 153 |
+
self.assertEqual(signals["Moving Averages"]["signal"],
|
| 154 |
+
"Insufficient data for SMA")
|
| 155 |
+
self.assertIn("SMA20=n/a", signals["Moving Averages"]["value"])
|
| 156 |
+
|
| 157 |
+
def test_reports_real_readings_once_warmed_up(self):
|
| 158 |
+
signals = latest_signals(add_all_indicators(_ohlcv(80, seed=1)))
|
| 159 |
+
for name, entry in signals.items():
|
| 160 |
+
self.assertNotIn("Insufficient", entry["signal"], name)
|
| 161 |
+
self.assertIsInstance(signals["RSI (14)"]["value"], float)
|
| 162 |
+
self.assertIsInstance(signals["Stochastic (14,3)"]["value"], float)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
if __name__ == "__main__":
|
| 166 |
+
unittest.main()
|
tests/test_models_with_features.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""End-to-end checks that each model's `features=` covariate path runs and
|
| 2 |
+
produces a finite forecast, and that `features=None` still behaves as the
|
| 3 |
+
Close-only path always did.
|
| 4 |
+
|
| 5 |
+
Each per-model class skips (rather than fails) when its backend is not
|
| 6 |
+
importable, so the suite stays meaningful in a bare pandas/numpy
|
| 7 |
+
environment and exercises all five models once the requirements are
|
| 8 |
+
installed.
|
| 9 |
+
|
| 10 |
+
Run with: python -m unittest tests.test_models_with_features -v
|
| 11 |
+
"""
|
| 12 |
+
import importlib.util
|
| 13 |
+
import unittest
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
import pandas as pd
|
| 17 |
+
|
| 18 |
+
from features.feature_pipeline import compute_feature_frame, slice_features
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def _have(module_name: str) -> bool:
|
| 22 |
+
return importlib.util.find_spec(module_name) is not None
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
_HAVE_STATSMODELS = _have("statsmodels")
|
| 26 |
+
_HAVE_ARCH = _have("arch")
|
| 27 |
+
_HAVE_MOIRAI = _have("uni2ts") and _have("gluonts")
|
| 28 |
+
_HAVE_TIMESFM = _have("timesfm") and _have("torch")
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _synthetic_ohlcv(n: int, seed: int = 42) -> pd.DataFrame:
|
| 32 |
+
rng = np.random.default_rng(seed)
|
| 33 |
+
steps = rng.normal(loc=0.0, scale=0.4, size=n)
|
| 34 |
+
close = 100 + np.cumsum(steps)
|
| 35 |
+
close = np.abs(close) + 5.0
|
| 36 |
+
open_ = close + rng.normal(0, 0.1, n)
|
| 37 |
+
high = np.maximum(open_, close) + np.abs(rng.normal(0, 0.2, n))
|
| 38 |
+
low = np.minimum(open_, close) - np.abs(rng.normal(0, 0.2, n))
|
| 39 |
+
volume = rng.integers(100, 10000, n).astype(float)
|
| 40 |
+
idx = pd.date_range("2024-01-01", periods=n, freq="min")
|
| 41 |
+
return pd.DataFrame(
|
| 42 |
+
{"Open": open_, "High": high, "Low": low, "Close": close, "Volume": volume}, index=idx
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class TestArimaFamilyAlignment(unittest.TestCase):
|
| 47 |
+
"""Pure-logic regression check for the ARIMA-GARCH log-returns/features
|
| 48 |
+
alignment (see models/arima_garch_model.py's module docstring) -- does
|
| 49 |
+
NOT need statsmodels/arch, so this always runs regardless of environment."""
|
| 50 |
+
|
| 51 |
+
def test_returns_alignment_has_no_off_by_one(self):
|
| 52 |
+
n = 10
|
| 53 |
+
prices = pd.Series(100 + np.arange(n, dtype=float))
|
| 54 |
+
# label each feature row with the candle index it belongs to
|
| 55 |
+
features = pd.Series([float(i) for i in range(n)])
|
| 56 |
+
|
| 57 |
+
log_returns = np.log(prices / prices.shift(1)).dropna().reset_index(drop=True)
|
| 58 |
+
exog = features.iloc[1:].reset_index(drop=True)
|
| 59 |
+
|
| 60 |
+
self.assertEqual(len(exog), len(log_returns))
|
| 61 |
+
for k in range(len(log_returns)):
|
| 62 |
+
# log_returns[k] = log(p_{k+1}/p_k) -- realized at candle k+1,
|
| 63 |
+
# so it must pair with the feature row for candle k+1.
|
| 64 |
+
self.assertEqual(exog[k], float(k + 1))
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@unittest.skipUnless(_HAVE_STATSMODELS, "statsmodels not installed in this environment")
|
| 68 |
+
class TestArimaWithFeatures(unittest.TestCase):
|
| 69 |
+
def setUp(self):
|
| 70 |
+
self.df = _synthetic_ohlcv(120)
|
| 71 |
+
self.close = self.df["Close"].reset_index(drop=True)
|
| 72 |
+
self.feats = compute_feature_frame(self.df)
|
| 73 |
+
|
| 74 |
+
def test_baseline_unchanged_shape(self):
|
| 75 |
+
from models.arima_model import ArimaModel
|
| 76 |
+
m = ArimaModel(max_p=2, max_d=1, max_q=2)
|
| 77 |
+
out = m.predict(self.close, horizon=3)
|
| 78 |
+
self.assertEqual(len(out), 3)
|
| 79 |
+
self.assertTrue(all(np.isfinite(out)))
|
| 80 |
+
|
| 81 |
+
def test_with_features_runs_and_is_finite(self):
|
| 82 |
+
from models.arima_model import ArimaModel
|
| 83 |
+
m = ArimaModel(max_p=2, max_d=1, max_q=2)
|
| 84 |
+
window = slice_features(self.feats, 0, len(self.close))
|
| 85 |
+
out = m.predict(self.close, horizon=3, features=window)
|
| 86 |
+
self.assertEqual(len(out), 3)
|
| 87 |
+
self.assertTrue(all(np.isfinite(out)))
|
| 88 |
+
|
| 89 |
+
def test_mismatched_features_length_raises(self):
|
| 90 |
+
from models.arima_model import ArimaModel
|
| 91 |
+
m = ArimaModel(max_p=2, max_d=1, max_q=2)
|
| 92 |
+
short_window = slice_features(self.feats, 0, len(self.close) - 5)
|
| 93 |
+
with self.assertRaises(ValueError):
|
| 94 |
+
m.predict(self.close, horizon=3, features=short_window)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@unittest.skipUnless(_HAVE_STATSMODELS, "statsmodels not installed in this environment")
|
| 98 |
+
class TestAutoArimaWithFeatures(unittest.TestCase):
|
| 99 |
+
def setUp(self):
|
| 100 |
+
self.df = _synthetic_ohlcv(120)
|
| 101 |
+
self.close = self.df["Close"].reset_index(drop=True)
|
| 102 |
+
self.feats = compute_feature_frame(self.df)
|
| 103 |
+
|
| 104 |
+
def test_with_features_runs_and_is_finite(self):
|
| 105 |
+
from models.auto_arima_model import AutoArimaModel
|
| 106 |
+
m = AutoArimaModel(max_p=3, max_q=3, max_d=1)
|
| 107 |
+
window = slice_features(self.feats, 0, len(self.close))
|
| 108 |
+
out = m.predict(self.close, horizon=2, features=window)
|
| 109 |
+
self.assertEqual(len(out), 2)
|
| 110 |
+
self.assertTrue(all(np.isfinite(out)))
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@unittest.skipUnless(_HAVE_STATSMODELS and _HAVE_ARCH, "statsmodels+arch not installed in this environment")
|
| 114 |
+
class TestArimaGarchWithFeatures(unittest.TestCase):
|
| 115 |
+
def setUp(self):
|
| 116 |
+
self.df = _synthetic_ohlcv(150)
|
| 117 |
+
self.close = self.df["Close"].reset_index(drop=True)
|
| 118 |
+
self.feats = compute_feature_frame(self.df)
|
| 119 |
+
|
| 120 |
+
def test_with_features_runs_and_is_finite(self):
|
| 121 |
+
from models.arima_garch_model import ArimaGarchModel
|
| 122 |
+
m = ArimaGarchModel(max_p=2, max_q=2)
|
| 123 |
+
window = slice_features(self.feats, 0, len(self.close))
|
| 124 |
+
out = m.predict(self.close, horizon=2, features=window)
|
| 125 |
+
self.assertEqual(len(out), 2)
|
| 126 |
+
self.assertTrue(all(np.isfinite(out)))
|
| 127 |
+
self.assertIsNotNone(m.last_volatility_forecast)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@unittest.skipUnless(_HAVE_MOIRAI, "uni2ts/gluonts not installed in this environment")
|
| 131 |
+
class TestMoiraiWithFeatures(unittest.TestCase):
|
| 132 |
+
def test_with_features_runs_and_is_finite(self):
|
| 133 |
+
from models.moirai_model import MoiraiModel
|
| 134 |
+
df = _synthetic_ohlcv(60)
|
| 135 |
+
close = df["Close"].reset_index(drop=True)
|
| 136 |
+
feats = compute_feature_frame(df)
|
| 137 |
+
m = MoiraiModel(context_length=60, num_samples=10) # small for a fast test
|
| 138 |
+
out = m.predict(close, horizon=2, features=feats)
|
| 139 |
+
self.assertEqual(len(out), 2)
|
| 140 |
+
self.assertTrue(all(np.isfinite(out)))
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
@unittest.skipUnless(_HAVE_TIMESFM, "timesfm/torch not installed in this environment")
|
| 144 |
+
class TestTimesFMWithFeatures(unittest.TestCase):
|
| 145 |
+
def test_with_features_runs_and_is_finite(self):
|
| 146 |
+
from models.timesfm_model import TimesFMModel
|
| 147 |
+
df = _synthetic_ohlcv(64)
|
| 148 |
+
close = df["Close"].reset_index(drop=True)
|
| 149 |
+
feats = compute_feature_frame(df)
|
| 150 |
+
m = TimesFMModel(max_context=64)
|
| 151 |
+
out = m.predict(close, horizon=2, features=feats)
|
| 152 |
+
self.assertEqual(len(out), 2)
|
| 153 |
+
self.assertTrue(all(np.isfinite(out)))
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
if __name__ == "__main__":
|
| 157 |
+
unittest.main()
|
utils/__init__.py
ADDED
|
File without changes
|
utils/helpers.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared helpers used by the app, live_runner and the feature pipeline."""
|
| 2 |
+
import math
|
| 3 |
+
|
| 4 |
+
import pandas as pd
|
| 5 |
+
|
| 6 |
+
MINUTES_PER_CANDLE = {"1m": 1, "5m": 5, "10m": 10, "15m": 15, "30m": 30,
|
| 7 |
+
"1h": 60, "4h": 240, "1d": 1440}
|
| 8 |
+
|
| 9 |
+
# SMA_20/Bollinger need 20 candles; the rest is safety margin.
|
| 10 |
+
INDICATOR_WARMUP_CANDLES = 30
|
| 11 |
+
|
| 12 |
+
# History handed to a model for a single live prediction. Comfortably above
|
| 13 |
+
# every model's minimum (TimesFM's 32 is the largest) even on weekday-only
|
| 14 |
+
# forex calendars, where ~5/7 of the requested days carry candles.
|
| 15 |
+
PREDICTION_HISTORY_CANDLES = 200
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def infer_step(index: pd.DatetimeIndex):
|
| 19 |
+
"""Median candle spacing, used to project forecasts past the last candle."""
|
| 20 |
+
if len(index) < 2:
|
| 21 |
+
return pd.Timedelta(minutes=1)
|
| 22 |
+
diffs = index.to_series().diff().dropna()
|
| 23 |
+
if diffs.empty:
|
| 24 |
+
return pd.Timedelta(minutes=1)
|
| 25 |
+
return diffs.median()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def future_index(last_timestamp, step, n):
|
| 29 |
+
"""`n` timestamps spaced `step` apart, starting after last_timestamp."""
|
| 30 |
+
return [last_timestamp + step * (i + 1) for i in range(n)]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def history_days_for_candles(timeframe: str, candles: int, minimum_days: int = 1) -> int:
|
| 34 |
+
"""Calendar days that cover `candles` candles of this timeframe. Markets
|
| 35 |
+
that close (forex, weekends) yield fewer candles than this, so callers
|
| 36 |
+
should treat the result as a lower bound and clamp it against the data
|
| 37 |
+
source's own history limit."""
|
| 38 |
+
minutes = MINUTES_PER_CANDLE.get(timeframe, 60) * max(int(candles), 0)
|
| 39 |
+
return max(minimum_days, math.ceil(minutes / (24 * 60)))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def feature_warmup_days(timeframe: str, minimum_days: int = 2) -> int:
|
| 43 |
+
"""Extra days of history the indicators need before the tested period."""
|
| 44 |
+
return history_days_for_candles(timeframe, INDICATOR_WARMUP_CANDLES,
|
| 45 |
+
minimum_days=minimum_days)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def drop_forming_candle(df: pd.DataFrame, features_df: pd.DataFrame = None):
|
| 49 |
+
"""Drop the newest candle while it is still forming. Yahoo returns the
|
| 50 |
+
in-progress candle, whose Close keeps moving, so grading a prediction
|
| 51 |
+
against it compares against an unsettled value. features_df is trimmed
|
| 52 |
+
with it to keep the two positionally aligned."""
|
| 53 |
+
if df is None or len(df) == 0:
|
| 54 |
+
return df, features_df
|
| 55 |
+
last = df.index[-1]
|
| 56 |
+
now = pd.Timestamp.now(tz="UTC")
|
| 57 |
+
if last.tzinfo is None:
|
| 58 |
+
now = now.tz_localize(None)
|
| 59 |
+
if now - last >= infer_step(df.index):
|
| 60 |
+
return df, features_df
|
| 61 |
+
df = df.iloc[:-1]
|
| 62 |
+
if features_df is not None:
|
| 63 |
+
features_df = features_df.iloc[:-1].reset_index(drop=True)
|
| 64 |
+
return df, features_df
|