Added forex_10 contents
Browse files- README.md +14 -7
- app.py +26 -13
- backtest/backtester.py +2 -0
- config.py +23 -6
- data/historical.py +1 -1
- indicators/indicators.py +65 -6
- live_runner.py +1 -1
- models/arima_garch_model.py +3 -0
- models/arima_model.py +4 -2
- models/auto_arima_model.py +96 -62
- models/moirai_model.py +8 -2
- models/registry.py +56 -34
- models/timesfm_model.py +9 -1
- requirements.txt +0 -1
README.md
CHANGED
|
@@ -36,9 +36,12 @@ recommendation to trade.
|
|
| 36 |
- **5 forecasting models**, one shared interface (`models/base_model.py`):
|
| 37 |
- **ARIMA** (`statsmodels`) β fast, classical, always available. Order
|
| 38 |
(p,d,q) is found with a brute-force AIC grid search.
|
| 39 |
-
- **Auto-ARIMA** (`
|
| 40 |
-
with
|
| 41 |
-
`auto.arima()`) instead of a brute-force grid.
|
|
|
|
|
|
|
|
|
|
| 42 |
- **ARIMA-GARCH** (`statsmodels` + `arch`) β ARIMA models the conditional
|
| 43 |
mean of returns, GARCH(1,1) models the conditional variance (volatility
|
| 44 |
clustering) on top of it. Forecasted volatility is kept on the model
|
|
@@ -74,7 +77,7 @@ indicators/
|
|
| 74 |
models/
|
| 75 |
base_model.py shared interface all 5 models implement
|
| 76 |
arima_model.py ARIMA (statsmodels), cached order search
|
| 77 |
-
auto_arima_model.py Auto-ARIMA (
|
| 78 |
arima_garch_model.py ARIMA-GARCH (statsmodels + arch), mean + volatility
|
| 79 |
moirai_model.py Moirai (uni2ts + GluonTS)
|
| 80 |
timesfm_model.py TimesFM 2.5 (timesfm[torch])
|
|
@@ -117,7 +120,7 @@ Open the local URL Gradio prints (usually `http://127.0.0.1:7860`).
|
|
| 117 |
| Model | Package | Approx. size | Notes |
|
| 118 |
|---|---|---|---|
|
| 119 |
| ARIMA | `statsmodels` | tiny | Fastest by far. Order (p,d,q) is searched once per backtest run (brute-force AIC grid) and reused, not re-searched every candle. |
|
| 120 |
-
| Auto-ARIMA | `
|
| 121 |
| ARIMA-GARCH | `statsmodels` + `arch` | tiny | Two fits per prediction (ARIMA for the mean, GARCH for the volatility), so a little slower than plain ARIMA β still fast next to the foundation models. |
|
| 122 |
| Moirai (`moirai-1.1-R-small`) | `uni2ts` | small (~14M params) | Zero-shot foundation model, no training needed. |
|
| 123 |
| TimesFM 2.5 (`timesfm-2.5-200m`) | `timesfm[torch]` | ~800MB download, ~4GB RAM | Zero-shot foundation model, no training needed. |
|
|
@@ -161,8 +164,12 @@ secondary, continuous-error view.
|
|
| 161 |
current documentation but not executed end-to-end here. Test on your own
|
| 162 |
machine or Space before trusting it, and check each library's docs/repo if
|
| 163 |
an API has moved since (`uni2ts` and `timesfm` are active research
|
| 164 |
-
projects that occasionally make breaking changes; `
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
## Disclaimer
|
| 168 |
|
|
|
|
| 36 |
- **5 forecasting models**, one shared interface (`models/base_model.py`):
|
| 37 |
- **ARIMA** (`statsmodels`) β fast, classical, always available. Order
|
| 38 |
(p,d,q) is found with a brute-force AIC grid search.
|
| 39 |
+
- **Auto-ARIMA** (`statsmodels`) β same idea as ARIMA, but the order is
|
| 40 |
+
found with a Hyndman-Khandakar-style stepwise search (the same
|
| 41 |
+
algorithm behind R's `auto.arima()`) instead of a brute-force grid.
|
| 42 |
+
Implemented directly on statsmodels rather than depending on
|
| 43 |
+
`pmdarima` β that package's compiled Cython extensions are a known
|
| 44 |
+
source of numpy-version install breakage on fresh environments.
|
| 45 |
- **ARIMA-GARCH** (`statsmodels` + `arch`) β ARIMA models the conditional
|
| 46 |
mean of returns, GARCH(1,1) models the conditional variance (volatility
|
| 47 |
clustering) on top of it. Forecasted volatility is kept on the model
|
|
|
|
| 77 |
models/
|
| 78 |
base_model.py shared interface all 5 models implement
|
| 79 |
arima_model.py ARIMA (statsmodels), cached order search
|
| 80 |
+
auto_arima_model.py Auto-ARIMA (statsmodels only), cached stepwise search
|
| 81 |
arima_garch_model.py ARIMA-GARCH (statsmodels + arch), mean + volatility
|
| 82 |
moirai_model.py Moirai (uni2ts + GluonTS)
|
| 83 |
timesfm_model.py TimesFM 2.5 (timesfm[torch])
|
|
|
|
| 120 |
| Model | Package | Approx. size | Notes |
|
| 121 |
|---|---|---|---|
|
| 122 |
| ARIMA | `statsmodels` | tiny | Fastest by far. Order (p,d,q) is searched once per backtest run (brute-force AIC grid) and reused, not re-searched every candle. |
|
| 123 |
+
| Auto-ARIMA | `statsmodels` | tiny | Same dependency as plain ARIMA β no extra package. Stepwise order search runs once and is reused; usually visits fewer candidate models than ARIMA's brute-force grid. |
|
| 124 |
| ARIMA-GARCH | `statsmodels` + `arch` | tiny | Two fits per prediction (ARIMA for the mean, GARCH for the volatility), so a little slower than plain ARIMA β still fast next to the foundation models. |
|
| 125 |
| Moirai (`moirai-1.1-R-small`) | `uni2ts` | small (~14M params) | Zero-shot foundation model, no training needed. |
|
| 126 |
| TimesFM 2.5 (`timesfm-2.5-200m`) | `timesfm[torch]` | ~800MB download, ~4GB RAM | Zero-shot foundation model, no training needed. |
|
|
|
|
| 164 |
current documentation but not executed end-to-end here. Test on your own
|
| 165 |
machine or Space before trusting it, and check each library's docs/repo if
|
| 166 |
an API has moved since (`uni2ts` and `timesfm` are active research
|
| 167 |
+
projects that occasionally make breaking changes; `arch` is more stable
|
| 168 |
+
but worth a version check too). Every model also validates its own
|
| 169 |
+
forecast is finite (no NaN/inf) before returning it, and raises a clear
|
| 170 |
+
error instead if it isn't β this surfaces as a "failed" row in a backtest
|
| 171 |
+
rather than silently corrupting the accuracy/MAE numbers, which is how an
|
| 172 |
+
earlier version of this project let a bad TimesFM forecast slip through.
|
| 173 |
|
| 174 |
## Disclaimer
|
| 175 |
|
app.py
CHANGED
|
@@ -94,7 +94,7 @@ def run_prediction(symbol, timeframe, selected_models, horizon, lookback_days):
|
|
| 94 |
summary_lines = []
|
| 95 |
for name in selected_models:
|
| 96 |
try:
|
| 97 |
-
model = get_model(name)
|
| 98 |
forecast = model.predict(close, horizon=horizon)
|
| 99 |
fc_index = future_index(df.index[-1], step, len(forecast))
|
| 100 |
fig.add_trace(go.Scatter(x=fc_index, y=forecast, name=f"{name} forecast",
|
|
@@ -176,17 +176,29 @@ def _check_live_impl(symbol, timeframe, model_name, log_df):
|
|
| 176 |
|
| 177 |
# 2) make a fresh prediction for the next candle, unless one is already
|
| 178 |
# pending for this exact latest candle
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
have_pending_for_latest = False
|
| 180 |
if len(log_df):
|
| 181 |
last_row = log_df.iloc[-1]
|
| 182 |
have_pending_for_latest = (
|
| 183 |
-
pd.isna(last_row["actual_close"]) and last_row["
|
| 184 |
)
|
| 185 |
|
| 186 |
status_extra = ""
|
| 187 |
if not have_pending_for_latest:
|
| 188 |
try:
|
| 189 |
-
model = get_model(model_name)
|
| 190 |
forecast = model.predict(df["Close"], horizon=1)
|
| 191 |
predicted_close = float(forecast[-1])
|
| 192 |
predicted_direction = "up" if predicted_close > latest_close else "down"
|
|
@@ -288,16 +300,17 @@ with gr.Blocks(title="Forex & Crypto Prediction Dashboard") as demo:
|
|
| 288 |
label="Per-model accuracy β kept separate, never mixed",
|
| 289 |
)
|
| 290 |
status_out3 = gr.Markdown()
|
| 291 |
-
with gr.
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
|
|
|
| 301 |
|
| 302 |
backtest_btn.click(
|
| 303 |
run_backtest_ui,
|
|
|
|
| 94 |
summary_lines = []
|
| 95 |
for name in selected_models:
|
| 96 |
try:
|
| 97 |
+
model = get_model(name, symbol, timeframe)
|
| 98 |
forecast = model.predict(close, horizon=horizon)
|
| 99 |
fc_index = future_index(df.index[-1], step, len(forecast))
|
| 100 |
fig.add_trace(go.Scatter(x=fc_index, y=forecast, name=f"{name} forecast",
|
|
|
|
| 176 |
|
| 177 |
# 2) make a fresh prediction for the next candle, unless one is already
|
| 178 |
# pending for this exact latest candle
|
| 179 |
+
#
|
| 180 |
+
# Dedup by TIMESTAMP (predicted_at == latest_time), not by close price.
|
| 181 |
+
# Price equality is the wrong proxy in both directions: an intraday
|
| 182 |
+
# "latest" candle from yfinance is often still forming, so its close
|
| 183 |
+
# can drift between polls even though it's still the SAME candle
|
| 184 |
+
# (price-equality would wrongly log a second, duplicate pending row
|
| 185 |
+
# for it before it even closes) -- and a genuinely NEW candle can by
|
| 186 |
+
# coincidence close at the exact same price as the previous one,
|
| 187 |
+
# especially in a quiet/ranging market (price-equality would then
|
| 188 |
+
# wrongly skip predicting it entirely). Either way corrupts the
|
| 189 |
+
# running-accuracy count this tab reports. Timestamp equality has
|
| 190 |
+
# neither failure mode.
|
| 191 |
have_pending_for_latest = False
|
| 192 |
if len(log_df):
|
| 193 |
last_row = log_df.iloc[-1]
|
| 194 |
have_pending_for_latest = (
|
| 195 |
+
pd.isna(last_row["actual_close"]) and last_row["predicted_at"] == latest_time
|
| 196 |
)
|
| 197 |
|
| 198 |
status_extra = ""
|
| 199 |
if not have_pending_for_latest:
|
| 200 |
try:
|
| 201 |
+
model = get_model(model_name, symbol, timeframe)
|
| 202 |
forecast = model.predict(df["Close"], horizon=1)
|
| 203 |
predicted_close = float(forecast[-1])
|
| 204 |
predicted_direction = "up" if predicted_close > latest_close else "down"
|
|
|
|
| 300 |
label="Per-model accuracy β kept separate, never mixed",
|
| 301 |
)
|
| 302 |
status_out3 = gr.Markdown()
|
| 303 |
+
with gr.Tabs():
|
| 304 |
+
with gr.Tab("ARIMA β verify log"):
|
| 305 |
+
arima_detail = gr.Dataframe(label="Per-candle: predicted vs actual, correct/incorrect")
|
| 306 |
+
with gr.Tab("Auto-ARIMA β verify log"):
|
| 307 |
+
autoarima_detail = gr.Dataframe(label="Per-candle: predicted vs actual, correct/incorrect")
|
| 308 |
+
with gr.Tab("ARIMA-GARCH β verify log"):
|
| 309 |
+
arimagarch_detail = gr.Dataframe(label="Per-candle: predicted vs actual, correct/incorrect")
|
| 310 |
+
with gr.Tab("Moirai β verify log"):
|
| 311 |
+
moirai_detail = gr.Dataframe(label="Per-candle: predicted vs actual, correct/incorrect")
|
| 312 |
+
with gr.Tab("TimesFM β verify log"):
|
| 313 |
+
timesfm_detail = gr.Dataframe(label="Per-candle: predicted vs actual, correct/incorrect")
|
| 314 |
|
| 315 |
backtest_btn.click(
|
| 316 |
run_backtest_ui,
|
backtest/backtester.py
CHANGED
|
@@ -38,6 +38,8 @@ def backtest_model(df: pd.DataFrame, model, window: int = 100, horizon: int = 1,
|
|
| 38 |
try:
|
| 39 |
forecast = model.predict(history, horizon=horizon)
|
| 40 |
predicted_next_close = float(forecast[-1])
|
|
|
|
|
|
|
| 41 |
except Exception as e:
|
| 42 |
rows.append({
|
| 43 |
"datetime": timestamps[target_idx],
|
|
|
|
| 38 |
try:
|
| 39 |
forecast = model.predict(history, horizon=horizon)
|
| 40 |
predicted_next_close = float(forecast[-1])
|
| 41 |
+
if not np.isfinite(predicted_next_close):
|
| 42 |
+
raise ValueError(f"non-finite forecast value: {predicted_next_close!r}")
|
| 43 |
except Exception as e:
|
| 44 |
rows.append({
|
| 45 |
"datetime": timestamps[target_idx],
|
config.py
CHANGED
|
@@ -58,15 +58,32 @@ YF_NATIVE_INTERVALS = {
|
|
| 58 |
# Timeframes offered in the app UI. Ones that aren't native Yahoo intervals
|
| 59 |
# (e.g. "10m") are built by resampling a smaller native interval, so you can
|
| 60 |
# ask for basically any custom candle size, not just what Yahoo natively has.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
CUSTOM_TIMEFRAMES = {
|
| 62 |
-
"1m": {"source": "1m", "rule":
|
| 63 |
-
"5m": {"source": "5m", "rule":
|
| 64 |
"10m": {"source": "5m", "rule": "10min"},
|
| 65 |
-
"15m": {"source": "15m", "rule":
|
| 66 |
-
"30m": {"source": "30m", "rule":
|
| 67 |
-
"1h": {"source": "60m", "rule":
|
| 68 |
"4h": {"source": "60m", "rule": "4h"},
|
| 69 |
-
"1d": {"source": "1d", "rule":
|
| 70 |
}
|
| 71 |
|
| 72 |
# ---------------------------------------------------------------------------
|
|
|
|
| 58 |
# Timeframes offered in the app UI. Ones that aren't native Yahoo intervals
|
| 59 |
# (e.g. "10m") are built by resampling a smaller native interval, so you can
|
| 60 |
# ask for basically any custom candle size, not just what Yahoo natively has.
|
| 61 |
+
#
|
| 62 |
+
# `rule: None` means this timeframe IS a native Yahoo interval already (just
|
| 63 |
+
# under a friendlier display name) -- return it as-is, no resampling.
|
| 64 |
+
# `rule: "<pandas rule>"` means genuine upsampling from a smaller native
|
| 65 |
+
# interval is needed.
|
| 66 |
+
#
|
| 67 |
+
# "1h" -> source "60m" is the one case where the display name and yfinance's
|
| 68 |
+
# native interval name differ ("1h" vs "60m") even though they're the same
|
| 69 |
+
# candle size. That mismatch used to make get_historical()'s
|
| 70 |
+
# `source_interval != timeframe` check misfire and re-resample already-hourly
|
| 71 |
+
# candles through rule="1h" -- a harmless-looking no-op when Yahoo's 60m
|
| 72 |
+
# candles happen to fall on clean UTC hour boundaries, but not otherwise: it
|
| 73 |
+
# silently re-labels each candle's timestamp to the bucket start (observed
|
| 74 |
+
# shifting real candle times by up to 59 minutes in testing) and, for
|
| 75 |
+
# irregularly-spaced candles (weekend gaps, DST), can merge two distinct
|
| 76 |
+
# candles into one bucket or drop one to a dropna(how="any"). Native
|
| 77 |
+
# passthrough (`rule: None`) sidesteps all of that.
|
| 78 |
CUSTOM_TIMEFRAMES = {
|
| 79 |
+
"1m": {"source": "1m", "rule": None},
|
| 80 |
+
"5m": {"source": "5m", "rule": None},
|
| 81 |
"10m": {"source": "5m", "rule": "10min"},
|
| 82 |
+
"15m": {"source": "15m", "rule": None},
|
| 83 |
+
"30m": {"source": "30m", "rule": None},
|
| 84 |
+
"1h": {"source": "60m", "rule": None},
|
| 85 |
"4h": {"source": "60m", "rule": "4h"},
|
| 86 |
+
"1d": {"source": "1d", "rule": None},
|
| 87 |
}
|
| 88 |
|
| 89 |
# ---------------------------------------------------------------------------
|
data/historical.py
CHANGED
|
@@ -127,7 +127,7 @@ def get_historical(symbol: str, timeframe: str, lookback_days: int = None) -> pd
|
|
| 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(
|
|
|
|
| 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(
|
indicators/indicators.py
CHANGED
|
@@ -27,14 +27,59 @@ def ema(series: pd.Series, window: int) -> pd.Series:
|
|
| 27 |
return series.ewm(span=window, adjust=False).mean()
|
| 28 |
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
def rsi(series: pd.Series, window: int = 14) -> pd.Series:
|
| 31 |
delta = series.diff()
|
| 32 |
gain = delta.clip(lower=0)
|
| 33 |
loss = -delta.clip(upper=0)
|
| 34 |
-
avg_gain =
|
| 35 |
-
avg_loss =
|
| 36 |
rs = avg_gain / avg_loss.replace(0, np.nan)
|
| 37 |
out = 100 - (100 / (1 + rs))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
return out.fillna(50)
|
| 39 |
|
| 40 |
|
|
@@ -49,7 +94,13 @@ def macd(series: pd.Series, fast: int = 12, slow: int = 26, signal: int = 9):
|
|
| 49 |
|
| 50 |
def bollinger_bands(series: pd.Series, window: int = 20, num_std: float = 2.0):
|
| 51 |
mid = sma(series, window)
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
upper = mid + num_std * std
|
| 54 |
lower = mid - num_std * std
|
| 55 |
return upper, mid, lower
|
|
@@ -102,17 +153,25 @@ def latest_signals(df_with_indicators: pd.DataFrame) -> dict:
|
|
| 102 |
"value": round(float(last["MACD"]), 5),
|
| 103 |
"signal": "Bullish (above signal)" if last["MACD"] > last["MACD_Signal"] else "Bearish (below signal)",
|
| 104 |
}
|
|
|
|
| 105 |
signals["Bollinger Bands"] = {
|
| 106 |
"value": round(float(last["Close"]), 5),
|
| 107 |
"signal": (
|
| 108 |
-
"
|
|
|
|
| 109 |
else "Below Lower Band" if last["Close"] < last["BB_Lower"]
|
| 110 |
else "Inside Bands"
|
| 111 |
),
|
| 112 |
}
|
|
|
|
| 113 |
signals["Moving Averages"] = {
|
| 114 |
-
"value": f"SMA20={round(float(last['SMA_20']), 5)
|
| 115 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
}
|
| 117 |
signals["Stochastic (14,3)"] = {
|
| 118 |
"value": round(float(last["Stoch_%K"]), 2),
|
|
|
|
| 27 |
return series.ewm(span=window, adjust=False).mean()
|
| 28 |
|
| 29 |
|
| 30 |
+
def _wilder_rma(values: pd.Series, window: int) -> pd.Series:
|
| 31 |
+
"""
|
| 32 |
+
Wilder's exact smoothed moving average (the "RMA" his RSI/ATR/ADX are
|
| 33 |
+
all defined with): the FIRST output is a plain SIMPLE average of the
|
| 34 |
+
first `window` values, and every value after that is
|
| 35 |
+
`prev*(window-1)/window + current/window`.
|
| 36 |
+
|
| 37 |
+
`series.ewm(alpha=1/window, adjust=False).mean()` looks equivalent but
|
| 38 |
+
is NOT: `adjust=False` seeds the recursion from the very first raw
|
| 39 |
+
observation instead of a `window`-length simple-average, so for window
|
| 40 |
+
periods it takes roughly 6-7x `window` more bars to converge to what
|
| 41 |
+
the simple-average seed gives immediately. Verified against the
|
| 42 |
+
classic 14-period Wilder RSI reference example (StockCharts'
|
| 43 |
+
44.34/44.09/.../46.28 series): the seeded version reproduces the
|
| 44 |
+
textbook 70.46 exactly; plain `ewm(adjust=False)` gives 50.66 at that
|
| 45 |
+
same point -- a ~20-point error right at the point a short lookback
|
| 46 |
+
would actually display. The two converge (difference < 0.05) only
|
| 47 |
+
after roughly 100 bars, so this only silently matters on short
|
| 48 |
+
lookbacks -- which the Chart tab's lookback slider allows down to 1 day.
|
| 49 |
+
"""
|
| 50 |
+
arr = values.to_numpy(dtype=float)
|
| 51 |
+
n = len(arr)
|
| 52 |
+
out = np.full(n, np.nan)
|
| 53 |
+
first_valid_pos = 0
|
| 54 |
+
while first_valid_pos < n and np.isnan(arr[first_valid_pos]):
|
| 55 |
+
first_valid_pos += 1
|
| 56 |
+
seed_end = first_valid_pos + window
|
| 57 |
+
if seed_end > n:
|
| 58 |
+
return pd.Series(out, index=values.index)
|
| 59 |
+
prev = arr[first_valid_pos:seed_end].mean()
|
| 60 |
+
out[seed_end - 1] = prev
|
| 61 |
+
for i in range(seed_end, n):
|
| 62 |
+
prev = (prev * (window - 1) + arr[i]) / window
|
| 63 |
+
out[i] = prev
|
| 64 |
+
return pd.Series(out, index=values.index)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
def rsi(series: pd.Series, window: int = 14) -> pd.Series:
|
| 68 |
delta = series.diff()
|
| 69 |
gain = delta.clip(lower=0)
|
| 70 |
loss = -delta.clip(upper=0)
|
| 71 |
+
avg_gain = _wilder_rma(gain, window)
|
| 72 |
+
avg_loss = _wilder_rma(loss, window)
|
| 73 |
rs = avg_gain / avg_loss.replace(0, np.nan)
|
| 74 |
out = 100 - (100 / (1 + rs))
|
| 75 |
+
# Wilder's defined edge case (see StockCharts/Wilder RSI reference): a
|
| 76 |
+
# window with gains but zero losses is a divide-by-zero for RS, and RSI
|
| 77 |
+
# is defined as 100 by convention -- NOT neutral. Without this, an
|
| 78 |
+
# all-gains window (the exact moment RSI should scream "overbought")
|
| 79 |
+
# was silently reported as a neutral 50. A genuinely flat window (zero
|
| 80 |
+
# gain AND zero loss) has no such convention and still falls through to
|
| 81 |
+
# the neutral fillna(50) below, same as the warm-up NaN period.
|
| 82 |
+
out = out.mask((avg_loss == 0) & (avg_gain > 0), 100.0)
|
| 83 |
return out.fillna(50)
|
| 84 |
|
| 85 |
|
|
|
|
| 94 |
|
| 95 |
def bollinger_bands(series: pd.Series, window: int = 20, num_std: float = 2.0):
|
| 96 |
mid = sma(series, window)
|
| 97 |
+
# ddof=0 (population std): traditional Bollinger Bands, as defined by
|
| 98 |
+
# John Bollinger, use the population standard deviation of the SAME
|
| 99 |
+
# `window` closes as the SMA -- not pandas' default sample std
|
| 100 |
+
# (ddof=1), which divides by (window-1) and makes the bands ~2-3%
|
| 101 |
+
# too wide at the default window=20, shifting the "above/below/inside
|
| 102 |
+
# the band" reading right at the margin.
|
| 103 |
+
std = series.rolling(window=window).std(ddof=0)
|
| 104 |
upper = mid + num_std * std
|
| 105 |
lower = mid - num_std * std
|
| 106 |
return upper, mid, lower
|
|
|
|
| 153 |
"value": round(float(last["MACD"]), 5),
|
| 154 |
"signal": "Bullish (above signal)" if last["MACD"] > last["MACD_Signal"] else "Bearish (below signal)",
|
| 155 |
}
|
| 156 |
+
bb_ready = pd.notna(last["BB_Upper"]) and pd.notna(last["BB_Lower"])
|
| 157 |
signals["Bollinger Bands"] = {
|
| 158 |
"value": round(float(last["Close"]), 5),
|
| 159 |
"signal": (
|
| 160 |
+
"Insufficient data" if not bb_ready
|
| 161 |
+
else "Above Upper Band" if last["Close"] > last["BB_Upper"]
|
| 162 |
else "Below Lower Band" if last["Close"] < last["BB_Lower"]
|
| 163 |
else "Inside Bands"
|
| 164 |
),
|
| 165 |
}
|
| 166 |
+
sma_ready = pd.notna(last["SMA_20"])
|
| 167 |
signals["Moving Averages"] = {
|
| 168 |
+
"value": f"SMA20={round(float(last['SMA_20']), 5) if sma_ready else 'n/a'}, "
|
| 169 |
+
f"EMA20={round(float(last['EMA_20']), 5)}",
|
| 170 |
+
"signal": (
|
| 171 |
+
"Insufficient data for SMA" if not sma_ready
|
| 172 |
+
else "Price Above MA (Uptrend)" if last["Close"] > last["SMA_20"]
|
| 173 |
+
else "Price Below MA (Downtrend)"
|
| 174 |
+
),
|
| 175 |
}
|
| 176 |
signals["Stochastic (14,3)"] = {
|
| 177 |
"value": round(float(last["Stoch_%K"]), 2),
|
live_runner.py
CHANGED
|
@@ -34,7 +34,7 @@ def main():
|
|
| 34 |
|
| 35 |
safe_symbol = args.symbol.replace("=", "_").replace("/", "_")
|
| 36 |
log_path = os.path.join(OUTPUT_DIR, f"live_{safe_symbol}_{args.timeframe}_{args.model}.csv")
|
| 37 |
-
model = get_model(args.model)
|
| 38 |
|
| 39 |
pending = None # dict: target_time, current_close, predicted_close, predicted_direction
|
| 40 |
correct_count = 0
|
|
|
|
| 34 |
|
| 35 |
safe_symbol = args.symbol.replace("=", "_").replace("/", "_")
|
| 36 |
log_path = os.path.join(OUTPUT_DIR, f"live_{safe_symbol}_{args.timeframe}_{args.model}.csv")
|
| 37 |
+
model = get_model(args.model, args.symbol, args.timeframe)
|
| 38 |
|
| 39 |
pending = None # dict: target_time, current_close, predicted_close, predicted_direction
|
| 40 |
correct_count = 0
|
models/arima_garch_model.py
CHANGED
|
@@ -133,4 +133,7 @@ class ArimaGarchModel(BaseForecastModel):
|
|
| 133 |
cum_log_return += float(r)
|
| 134 |
prices_out.append(last_price * float(np.exp(cum_log_return)))
|
| 135 |
|
|
|
|
|
|
|
|
|
|
| 136 |
return prices_out
|
|
|
|
| 133 |
cum_log_return += float(r)
|
| 134 |
prices_out.append(last_price * float(np.exp(cum_log_return)))
|
| 135 |
|
| 136 |
+
if not all(np.isfinite(x) for x in prices_out):
|
| 137 |
+
raise ValueError(f"ARIMA-GARCH produced a non-finite forecast for order {self._cached_order}.")
|
| 138 |
+
|
| 139 |
return prices_out
|
models/arima_model.py
CHANGED
|
@@ -67,5 +67,7 @@ class ArimaModel(BaseForecastModel):
|
|
| 67 |
self._calls_since_search += 1
|
| 68 |
|
| 69 |
fit = ARIMA(series, order=self._cached_order).fit()
|
| 70 |
-
forecast = fit.forecast(steps=horizon)
|
| 71 |
-
|
|
|
|
|
|
|
|
|
| 67 |
self._calls_since_search += 1
|
| 68 |
|
| 69 |
fit = ARIMA(series, order=self._cached_order).fit()
|
| 70 |
+
forecast = np.asarray(fit.forecast(steps=horizon), dtype=float)
|
| 71 |
+
if not np.all(np.isfinite(forecast)):
|
| 72 |
+
raise ValueError(f"ARIMA produced a non-finite forecast for order {self._cached_order}.")
|
| 73 |
+
return [float(x) for x in forecast]
|
models/auto_arima_model.py
CHANGED
|
@@ -1,28 +1,46 @@
|
|
| 1 |
"""
|
| 2 |
-
Auto-ARIMA β automatic (p, d, q) order selection for ARIMA
|
| 3 |
-
`
|
| 4 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
How this differs from the plain `ARIMA` model in `arima_model.py`:
|
| 7 |
- `arima_model.py` picks (p, d, q) with a brute-force grid search over
|
| 8 |
every combination up to max_p/max_d/max_q, scored by AIC.
|
| 9 |
-
- This model
|
| 10 |
-
|
| 11 |
-
`
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
"""
|
| 22 |
import warnings
|
| 23 |
|
| 24 |
import numpy as np
|
| 25 |
import pandas as pd
|
|
|
|
|
|
|
| 26 |
|
| 27 |
from models.base_model import BaseForecastModel
|
| 28 |
|
|
@@ -32,39 +50,71 @@ warnings.filterwarnings("ignore")
|
|
| 32 |
class AutoArimaModel(BaseForecastModel):
|
| 33 |
name = "Auto-ARIMA"
|
| 34 |
|
| 35 |
-
def __init__(self,
|
| 36 |
-
order=None, seasonal_order=None, refit_order_every=None):
|
| 37 |
-
# Forex/crypto candles at the timeframes this app trades (1m-1d)
|
| 38 |
-
# rarely have clean calendar seasonality, so seasonal search is OFF
|
| 39 |
-
# by default. Set seasonal=True and m=<period> (e.g. m=24 for hourly
|
| 40 |
-
# candles with a suspected daily cycle) if you want it.
|
| 41 |
-
self.seasonal = seasonal
|
| 42 |
-
self.m = m
|
| 43 |
self.max_p = max_p
|
| 44 |
self.max_q = max_q
|
| 45 |
self.max_d = max_d
|
| 46 |
self._cached_order = order
|
| 47 |
-
self._cached_seasonal_order = seasonal_order
|
| 48 |
self.refit_order_every = refit_order_every # None = search once, then always reuse
|
| 49 |
self._calls_since_search = 0
|
| 50 |
|
| 51 |
def _check_dependencies(self):
|
| 52 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
def
|
| 55 |
try:
|
| 56 |
-
|
| 57 |
-
except
|
| 58 |
-
|
| 59 |
-
"Auto-ARIMA needs the 'pmdarima' package. Install with:\n"
|
| 60 |
-
" pip install pmdarima\n"
|
| 61 |
-
f"(original error: {e})"
|
| 62 |
-
)
|
| 63 |
-
return pm
|
| 64 |
|
| 65 |
-
def
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
series = pd.Series(history).astype(float).reset_index(drop=True)
|
| 69 |
if len(series) < 20:
|
| 70 |
raise ValueError("Auto-ARIMA needs at least 20 candles of history.")
|
|
@@ -74,32 +124,16 @@ class AutoArimaModel(BaseForecastModel):
|
|
| 74 |
need_search = True
|
| 75 |
|
| 76 |
if need_search:
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
# forecast straight from it instead of re-fitting a second time.
|
| 80 |
-
auto_fit = pm.auto_arima(
|
| 81 |
-
series,
|
| 82 |
-
start_p=0, start_q=0,
|
| 83 |
-
max_p=self.max_p, max_q=self.max_q, max_d=self.max_d,
|
| 84 |
-
seasonal=self.seasonal, m=self.m if self.seasonal else 1,
|
| 85 |
-
stepwise=True, suppress_warnings=True, error_action="ignore",
|
| 86 |
-
trace=False,
|
| 87 |
-
)
|
| 88 |
-
self._cached_order = auto_fit.order
|
| 89 |
-
self._cached_seasonal_order = auto_fit.seasonal_order if self.seasonal else None
|
| 90 |
self._calls_since_search = 0
|
| 91 |
-
forecast = auto_fit.predict(n_periods=horizon)
|
| 92 |
-
else:
|
| 93 |
-
# Reuse the previously-found order, refit only its parameters on
|
| 94 |
-
# the current window β this is what keeps repeated calls (e.g.
|
| 95 |
-
# one per candle in a backtest) fast.
|
| 96 |
-
fixed = pm.ARIMA(
|
| 97 |
-
order=self._cached_order,
|
| 98 |
-
seasonal_order=self._cached_seasonal_order or (0, 0, 0, 0),
|
| 99 |
-
suppress_warnings=True,
|
| 100 |
-
)
|
| 101 |
-
fixed.fit(series)
|
| 102 |
-
forecast = fixed.predict(n_periods=horizon)
|
| 103 |
|
| 104 |
self._calls_since_search += 1
|
| 105 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
Auto-ARIMA β automatic (p, d, q) order selection for ARIMA, implemented
|
| 3 |
+
directly on top of `statsmodels` (no extra dependency beyond what plain
|
| 4 |
+
`arima_model.py` already needs).
|
| 5 |
+
|
| 6 |
+
An earlier version of this file used the `pmdarima` package. It's been
|
| 7 |
+
removed: pmdarima ships compiled Cython extensions that are notorious for
|
| 8 |
+
breaking on environments where its build-time numpy version doesn't match
|
| 9 |
+
the runtime one ("binary incompatibility" / import errors) β exactly the
|
| 10 |
+
kind of thing that silently fails every single prediction on a fresh
|
| 11 |
+
Space/container without touching any of your actual code. Since
|
| 12 |
+
`statsmodels` was already confirmed working (plain ARIMA and ARIMA-GARCH
|
| 13 |
+
both depend on it), doing the search ourselves with statsmodels removes
|
| 14 |
+
that whole failure class.
|
| 15 |
|
| 16 |
How this differs from the plain `ARIMA` model in `arima_model.py`:
|
| 17 |
- `arima_model.py` picks (p, d, q) with a brute-force grid search over
|
| 18 |
every combination up to max_p/max_d/max_q, scored by AIC.
|
| 19 |
+
- This model instead follows the Hyndman-Khandakar (2008) stepwise
|
| 20 |
+
procedure β the same algorithm R's `forecast::auto.arima()` and
|
| 21 |
+
`pmdarima.auto_arima()` are built on:
|
| 22 |
+
1. pick the differencing order `d` with a KPSS unit-root test
|
| 23 |
+
(difference until the series looks stationary, up to max_d times)
|
| 24 |
+
instead of trying every `d` blindly,
|
| 25 |
+
2. fit a handful of starting (p, q) candidates at that `d`,
|
| 26 |
+
3. greedily step to whichever neighbouring (p, q) improves AIC,
|
| 27 |
+
repeating until no neighbour improves on the current best.
|
| 28 |
+
This visits far fewer models than the brute-force grid, and tends to
|
| 29 |
+
land on the same or a better order.
|
| 30 |
+
|
| 31 |
+
Speed note: same reasoning as arima_model.py β running the full search on
|
| 32 |
+
every single `.predict()` call would make backtesting painfully slow
|
| 33 |
+
(hundreds of candles x a search each time). So the order is searched ONCE
|
| 34 |
+
(on the first call) and reused for every later call on this instance β pass
|
| 35 |
+
`refit_order_every=N` to re-search every N calls, or pass `order=(p, d, q)`
|
| 36 |
+
yourself to skip the search entirely.
|
| 37 |
"""
|
| 38 |
import warnings
|
| 39 |
|
| 40 |
import numpy as np
|
| 41 |
import pandas as pd
|
| 42 |
+
from statsmodels.tsa.arima.model import ARIMA
|
| 43 |
+
from statsmodels.tsa.stattools import kpss
|
| 44 |
|
| 45 |
from models.base_model import BaseForecastModel
|
| 46 |
|
|
|
|
| 50 |
class AutoArimaModel(BaseForecastModel):
|
| 51 |
name = "Auto-ARIMA"
|
| 52 |
|
| 53 |
+
def __init__(self, max_p=5, max_q=5, max_d=2, order=None, refit_order_every=None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 54 |
self.max_p = max_p
|
| 55 |
self.max_q = max_q
|
| 56 |
self.max_d = max_d
|
| 57 |
self._cached_order = order
|
|
|
|
| 58 |
self.refit_order_every = refit_order_every # None = search once, then always reuse
|
| 59 |
self._calls_since_search = 0
|
| 60 |
|
| 61 |
def _check_dependencies(self):
|
| 62 |
+
import statsmodels # noqa
|
| 63 |
+
|
| 64 |
+
def _find_d(self, series: pd.Series) -> int:
|
| 65 |
+
"""KPSS-based differencing order, capped at max_d."""
|
| 66 |
+
s = series.copy()
|
| 67 |
+
d = 0
|
| 68 |
+
while d < self.max_d:
|
| 69 |
+
try:
|
| 70 |
+
_, p_value, _, _ = kpss(s, regression="c", nlags="auto")
|
| 71 |
+
except Exception:
|
| 72 |
+
break
|
| 73 |
+
if p_value < 0.05: # KPSS null = stationary -> low p-value = reject -> difference again
|
| 74 |
+
s = s.diff().dropna()
|
| 75 |
+
d += 1
|
| 76 |
+
else:
|
| 77 |
+
break
|
| 78 |
+
return d
|
| 79 |
|
| 80 |
+
def _aic(self, series: pd.Series, order) -> float:
|
| 81 |
try:
|
| 82 |
+
return ARIMA(series, order=order).fit().aic
|
| 83 |
+
except Exception:
|
| 84 |
+
return np.inf
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 85 |
|
| 86 |
+
def _stepwise_search(self, series: pd.Series, d: int):
|
| 87 |
+
"""Hyndman-Khandakar-style stepwise search: a few starting points,
|
| 88 |
+
then greedy steps to the best-AIC neighbour until nothing improves."""
|
| 89 |
+
starting_points = [(0, 0), (1, 0), (0, 1), (2, 2)]
|
| 90 |
+
best_order, best_aic = None, np.inf
|
| 91 |
+
for p, q in starting_points:
|
| 92 |
+
if p > self.max_p or q > self.max_q:
|
| 93 |
+
continue
|
| 94 |
+
aic = self._aic(series, (p, d, q))
|
| 95 |
+
if aic < best_aic:
|
| 96 |
+
best_aic, best_order = aic, (p, q)
|
| 97 |
+
|
| 98 |
+
if best_order is None:
|
| 99 |
+
best_order, best_aic = (0, 0), self._aic(series, (0, d, 0))
|
| 100 |
+
|
| 101 |
+
improved = True
|
| 102 |
+
while improved:
|
| 103 |
+
improved = False
|
| 104 |
+
p0, q0 = best_order
|
| 105 |
+
for p, q in [(p0 + 1, q0), (p0 - 1, q0), (p0, q0 + 1), (p0, q0 - 1),
|
| 106 |
+
(p0 + 1, q0 + 1), (p0 - 1, q0 - 1)]:
|
| 107 |
+
if p < 0 or q < 0 or p > self.max_p or q > self.max_q:
|
| 108 |
+
continue
|
| 109 |
+
aic = self._aic(series, (p, d, q))
|
| 110 |
+
if aic < best_aic - 1e-6:
|
| 111 |
+
best_aic, best_order = aic, (p, q)
|
| 112 |
+
improved = True
|
| 113 |
|
| 114 |
+
p, q = best_order
|
| 115 |
+
return (p, d, q)
|
| 116 |
+
|
| 117 |
+
def predict(self, history: pd.Series, horizon: int = 1) -> list:
|
| 118 |
series = pd.Series(history).astype(float).reset_index(drop=True)
|
| 119 |
if len(series) < 20:
|
| 120 |
raise ValueError("Auto-ARIMA needs at least 20 candles of history.")
|
|
|
|
| 124 |
need_search = True
|
| 125 |
|
| 126 |
if need_search:
|
| 127 |
+
d = self._find_d(series)
|
| 128 |
+
self._cached_order = self._stepwise_search(series, d)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
self._calls_since_search = 0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
self._calls_since_search += 1
|
| 132 |
+
|
| 133 |
+
fit = ARIMA(series, order=self._cached_order).fit()
|
| 134 |
+
forecast = np.asarray(fit.forecast(steps=horizon), dtype=float)
|
| 135 |
+
|
| 136 |
+
if not np.all(np.isfinite(forecast)):
|
| 137 |
+
raise ValueError(f"Auto-ARIMA produced a non-finite forecast for order {self._cached_order}.")
|
| 138 |
+
|
| 139 |
+
return [float(x) for x in forecast]
|
models/moirai_model.py
CHANGED
|
@@ -58,7 +58,10 @@ class MoiraiModel(BaseForecastModel):
|
|
| 58 |
# Moirai/GluonTS need a DatetimeIndex but only the VALUES matter for a
|
| 59 |
# point forecast β the real candle timestamps are re-attached in
|
| 60 |
# app.py, so a clean synthetic per-minute index is fine here.
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
| 62 |
series_df = pd.DataFrame({"target": context}, index=idx)
|
| 63 |
dataset = PandasDataset(series_df, target="target")
|
| 64 |
|
|
@@ -79,4 +82,7 @@ class MoiraiModel(BaseForecastModel):
|
|
| 79 |
# forecast.samples has shape (num_samples, horizon) β take the
|
| 80 |
# per-step median across samples as the point forecast.
|
| 81 |
point_forecast = np.median(forecast.samples, axis=0)
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
# Moirai/GluonTS need a DatetimeIndex but only the VALUES matter for a
|
| 59 |
# point forecast β the real candle timestamps are re-attached in
|
| 60 |
# app.py, so a clean synthetic per-minute index is fine here.
|
| 61 |
+
# (Timestamp.now("UTC"), not the deprecated Timestamp.utcnow() β
|
| 62 |
+
# pandas already warns that utcnow() will be removed in a future
|
| 63 |
+
# release.)
|
| 64 |
+
idx = pd.date_range(end=pd.Timestamp.now("UTC").floor("min"), periods=len(context), freq="min")
|
| 65 |
series_df = pd.DataFrame({"target": context}, index=idx)
|
| 66 |
dataset = PandasDataset(series_df, target="target")
|
| 67 |
|
|
|
|
| 82 |
# forecast.samples has shape (num_samples, horizon) β take the
|
| 83 |
# per-step median across samples as the point forecast.
|
| 84 |
point_forecast = np.median(forecast.samples, axis=0)
|
| 85 |
+
out = [float(x) for x in point_forecast]
|
| 86 |
+
if not all(np.isfinite(x) for x in out):
|
| 87 |
+
raise ValueError("Moirai produced a non-finite forecast (NaN/inf) for this window.")
|
| 88 |
+
return out
|
models/registry.py
CHANGED
|
@@ -4,38 +4,78 @@ module does NOT import torch/uni2ts/timesfm, and calling get_model("ARIMA")
|
|
| 4 |
never touches the (heavier) Moirai/TimesFM code paths. This matters on a
|
| 5 |
shared 2 vCPU / 16GB Space: a session that only ever uses ARIMA should never
|
| 6 |
pay the cost of loading foundation-model weights.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 7 |
"""
|
| 8 |
from models.base_model import BaseForecastModel
|
| 9 |
|
| 10 |
-
|
|
|
|
|
|
|
| 11 |
|
|
|
|
| 12 |
|
| 13 |
-
def get_model(name: str) -> BaseForecastModel:
|
| 14 |
-
if name in _CACHE:
|
| 15 |
-
return _CACHE[name]
|
| 16 |
|
|
|
|
| 17 |
if name == "ARIMA":
|
| 18 |
from models.arima_model import ArimaModel
|
| 19 |
-
|
| 20 |
elif name == "Auto-ARIMA":
|
| 21 |
from models.auto_arima_model import AutoArimaModel
|
| 22 |
-
|
| 23 |
elif name == "ARIMA-GARCH":
|
| 24 |
from models.arima_garch_model import ArimaGarchModel
|
| 25 |
-
|
| 26 |
elif name == "Moirai":
|
| 27 |
from models.moirai_model import MoiraiModel
|
| 28 |
-
|
| 29 |
elif name == "TimesFM":
|
| 30 |
from models.timesfm_model import TimesFMModel
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
|
| 38 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 39 |
return model
|
| 40 |
|
| 41 |
|
|
@@ -45,22 +85,4 @@ def fresh_model(name: str) -> BaseForecastModel:
|
|
| 45 |
cache β useful for ARIMA in a backtest, where you want a fresh order
|
| 46 |
search rather than reusing whatever order a previous run settled on.
|
| 47 |
"""
|
| 48 |
-
|
| 49 |
-
from models.arima_model import ArimaModel
|
| 50 |
-
return ArimaModel()
|
| 51 |
-
elif name == "Auto-ARIMA":
|
| 52 |
-
from models.auto_arima_model import AutoArimaModel
|
| 53 |
-
return AutoArimaModel()
|
| 54 |
-
elif name == "ARIMA-GARCH":
|
| 55 |
-
from models.arima_garch_model import ArimaGarchModel
|
| 56 |
-
return ArimaGarchModel()
|
| 57 |
-
elif name == "Moirai":
|
| 58 |
-
from models.moirai_model import MoiraiModel
|
| 59 |
-
return MoiraiModel()
|
| 60 |
-
elif name == "TimesFM":
|
| 61 |
-
from models.timesfm_model import TimesFMModel
|
| 62 |
-
return TimesFMModel()
|
| 63 |
-
raise ValueError(
|
| 64 |
-
f"Unknown model '{name}'. Expected one of: "
|
| 65 |
-
"ARIMA, Auto-ARIMA, ARIMA-GARCH, Moirai, TimesFM."
|
| 66 |
-
)
|
|
|
|
| 4 |
never touches the (heavier) Moirai/TimesFM code paths. This matters on a
|
| 5 |
shared 2 vCPU / 16GB Space: a session that only ever uses ARIMA should never
|
| 6 |
pay the cost of loading foundation-model weights.
|
| 7 |
+
|
| 8 |
+
Caching strategy differs by model type, because "cached" means something
|
| 9 |
+
different for each:
|
| 10 |
+
|
| 11 |
+
- ARIMA / Auto-ARIMA / ARIMA-GARCH search and cache a (p, d, q) order on
|
| 12 |
+
their first `.predict()` call, then reuse it for every later call (see
|
| 13 |
+
each model's own docstring) β that order is fit to whichever
|
| 14 |
+
symbol/timeframe supplied the FIRST window of history it ever saw. A
|
| 15 |
+
cache keyed only on model name would keep reusing e.g. EURUSD's order
|
| 16 |
+
after switching to BTC-USD, silently fitting the wrong symbol's dynamics
|
| 17 |
+
with no error or obviously-bad output β just a quietly worse forecast.
|
| 18 |
+
So these three are cached per (name, symbol, timeframe): switching
|
| 19 |
+
either gets its own fresh order search, same symbol+timeframe keeps
|
| 20 |
+
reusing the cached order (the whole reason this cache exists).
|
| 21 |
+
- Moirai / TimesFM are zero-shot foundation models: `.predict()` takes the
|
| 22 |
+
history fresh every call and never caches anything symbol-specific β the
|
| 23 |
+
only thing cached on the instance is the pretrained weights themselves
|
| 24 |
+
(large, symbol-agnostic, and expensive to reload β TimesFM alone is a
|
| 25 |
+
~800MB/compile-step load). There's no staleness to fix here, so these
|
| 26 |
+
stay cached by name only and are always shared/reused across symbols.
|
| 27 |
"""
|
| 28 |
from models.base_model import BaseForecastModel
|
| 29 |
|
| 30 |
+
# Model names that internally cache a fitted (p, d, q) order β see module
|
| 31 |
+
# docstring above for why these need a (name, symbol, timeframe) cache key.
|
| 32 |
+
_ORDER_SEARCH_MODELS = {"ARIMA", "Auto-ARIMA", "ARIMA-GARCH"}
|
| 33 |
|
| 34 |
+
_CACHE: dict = {}
|
| 35 |
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
def _build_model(name: str) -> BaseForecastModel:
|
| 38 |
if name == "ARIMA":
|
| 39 |
from models.arima_model import ArimaModel
|
| 40 |
+
return ArimaModel()
|
| 41 |
elif name == "Auto-ARIMA":
|
| 42 |
from models.auto_arima_model import AutoArimaModel
|
| 43 |
+
return AutoArimaModel()
|
| 44 |
elif name == "ARIMA-GARCH":
|
| 45 |
from models.arima_garch_model import ArimaGarchModel
|
| 46 |
+
return ArimaGarchModel()
|
| 47 |
elif name == "Moirai":
|
| 48 |
from models.moirai_model import MoiraiModel
|
| 49 |
+
return MoiraiModel()
|
| 50 |
elif name == "TimesFM":
|
| 51 |
from models.timesfm_model import TimesFMModel
|
| 52 |
+
return TimesFMModel()
|
| 53 |
+
raise ValueError(
|
| 54 |
+
f"Unknown model '{name}'. Expected one of: "
|
| 55 |
+
"ARIMA, Auto-ARIMA, ARIMA-GARCH, Moirai, TimesFM."
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def get_model(name: str, symbol: str = None, timeframe: str = None) -> BaseForecastModel:
|
| 60 |
+
"""
|
| 61 |
+
Cached model factory.
|
| 62 |
|
| 63 |
+
Pass the symbol/timeframe you're about to predict on β for ARIMA,
|
| 64 |
+
Auto-ARIMA and ARIMA-GARCH this keys the cache so a symbol or
|
| 65 |
+
timeframe switch gets its own fresh instance (and therefore its own
|
| 66 |
+
fresh order search) instead of silently reusing another symbol's
|
| 67 |
+
cached order. Moirai/TimesFM ignore symbol/timeframe for caching
|
| 68 |
+
purposes and are always shared by name only (see module docstring).
|
| 69 |
+
|
| 70 |
+
Calling with just `name` (no symbol/timeframe) still works and behaves
|
| 71 |
+
like before β fine for scripts that only ever handle one symbol.
|
| 72 |
+
"""
|
| 73 |
+
key = (name, symbol, timeframe) if name in _ORDER_SEARCH_MODELS else name
|
| 74 |
+
if key in _CACHE:
|
| 75 |
+
return _CACHE[key]
|
| 76 |
+
|
| 77 |
+
model = _build_model(name)
|
| 78 |
+
_CACHE[key] = model
|
| 79 |
return model
|
| 80 |
|
| 81 |
|
|
|
|
| 85 |
cache β useful for ARIMA in a backtest, where you want a fresh order
|
| 86 |
search rather than reusing whatever order a previous run settled on.
|
| 87 |
"""
|
| 88 |
+
return _build_model(name)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
models/timesfm_model.py
CHANGED
|
@@ -67,4 +67,12 @@ class TimesFMModel(BaseForecastModel):
|
|
| 67 |
context = values[-self.max_context:] if len(values) > self.max_context else values
|
| 68 |
model = self._load()
|
| 69 |
point_forecast, _quantiles = model.forecast(horizon=horizon, inputs=[context])
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
context = values[-self.max_context:] if len(values) > self.max_context else values
|
| 68 |
model = self._load()
|
| 69 |
point_forecast, _quantiles = model.forecast(horizon=horizon, inputs=[context])
|
| 70 |
+
out = [float(x) for x in point_forecast[0]]
|
| 71 |
+
|
| 72 |
+
if not all(np.isfinite(x) for x in out):
|
| 73 |
+
raise ValueError(
|
| 74 |
+
"TimesFM returned a non-finite forecast (NaN/inf) for this window. "
|
| 75 |
+
"This is usually a sign the input window is degenerate (e.g. a flat "
|
| 76 |
+
"or near-constant price run) β try a different window size or symbol."
|
| 77 |
+
)
|
| 78 |
+
return out
|
requirements.txt
CHANGED
|
@@ -13,7 +13,6 @@ plotly>=5.20
|
|
| 13 |
|
| 14 |
# --- ARIMA / Auto-ARIMA / ARIMA-GARCH ---
|
| 15 |
statsmodels>=0.14
|
| 16 |
-
pmdarima>=2.0
|
| 17 |
arch>=6.3
|
| 18 |
|
| 19 |
# --- Moirai (Salesforce) β https://github.com/SalesforceAIResearch/uni2ts ---
|
|
|
|
| 13 |
|
| 14 |
# --- ARIMA / Auto-ARIMA / ARIMA-GARCH ---
|
| 15 |
statsmodels>=0.14
|
|
|
|
| 16 |
arch>=6.3
|
| 17 |
|
| 18 |
# --- Moirai (Salesforce) β https://github.com/SalesforceAIResearch/uni2ts ---
|