Forecasting stock prices with hyp.predict¶
Stock forecasting is the classic playground for timeseries models – and the classic cautionary tale. In this tutorial we’ll:
Download real daily closing prices for a handful of stocks with
hyp.load('yahoo:<TICKER>', start=..., end=...).Fit several
hyp.predictmodels ('Kalman','ARIMA','Laplace','GaussianProcess','AutoRegressor', and the pretrained'Chronos'foundation model) on all but the last 30 trading days.Backtest those last 30 days with
hyp.predict(..., holdout=HOLD)and score the forecasts against what actually happened, using mean absolute error (MAE) and mean absolute percentage error (MAPE) – alongside a naive “tomorrow = today” baselinehyp.predictreports automatically.Visualize the forecasts, both in HyperTools’ reduced plotting space and directly in price space.
Demonstrate
return_model=True: fit once, reuse the fitted forecaster on a stock it has never seen.
A word of honesty up front: daily equity closing prices are close to a random walk. Under the efficient-market hypothesis, the best predictor of tomorrow’s price is roughly today’s price, and no simple timeseries model should be expected to reliably beat that. The point of this tutorial is not to hand you a money machine – it’s to demonstrate the hyp.predict API and an honest evaluation methodology. We report whatever numbers come out below, including if (when) the naive baseline wins.
[ ]:
# HyperTools setup: use 1.1 or newer; retain a current local checkout.
import importlib.util
from importlib.metadata import version, PackageNotFoundError
from packaging.version import Version
from pathlib import Path
try:
_hypertools_version = Version(version('hypertools'))
except PackageNotFoundError:
_hypertools_version = Version('0')
if _hypertools_version < Version('1.1.0'):
_spec = importlib.util.find_spec('hypertools')
if _spec and _spec.origin and (Path(_spec.origin).resolve().parents[1] / '.git').exists():
raise RuntimeError('Select a HyperTools 1.1 checkout/kernel before running this tutorial; the installer will not replace your checkout.')
%pip install -q "hypertools[interactive]>=1.1.0"
else:
print('Keeping HyperTools', _hypertools_version, 'in this kernel. Optional extras are loaded when requested.')
Downloading real price data¶
We’ll grab about two years of daily closing prices (Yahoo’s close: split-adjusted, with dividends not reinvested) for four large, liquid, very different stocks: Apple (AAPL), Microsoft (MSFT), Nvidia (NVDA), and JPMorgan (JPM), via hyp.load('yahoo:<TICKER>', start=..., end=...).
We work in log prices rather than raw dollar prices for two standard reasons: (1) daily log-price differences are approximately the daily percentage return, so a model that is well-behaved in log space corresponds to sensible multiplicative (percentage) behavior in price space, and (2) forecasting models that assume roughly constant noise variance (Kalman, ARIMA, GaussianProcess) fit much more naturally to log prices than to raw prices, whose absolute volatility grows with the price level.
We convert forecasts back to dollar prices (via exp) for the price-space plots later in this tutorial; the honest backtest below scores directly in log-price space, where every model is fit.
If the live hyp.load('yahoo:...') download is unavailable (offline, rate-limited, or the API is having a bad day), the notebook falls back to a real-data snapshot (stock_closes_cached.csv / stock_volumes_cached.csv) shipped alongside this notebook, and prints a notice – so the tutorial always runs on real market data.
[1]:
%matplotlib inline
import time
import numpy as np
import pandas as pd
import hypertools as hyp
tickers = ['AAPL', 'MSFT', 'NVDA', 'JPM']
CACHE = {'close': 'stock_closes_cached.csv',
'volume': 'stock_volumes_cached.csv'}
def fetch_prices(tickers, attempts=3):
"""Daily closes/volumes via hyp.load('yahoo:<TICKER>', ...), retrying
transient failures; falls back to the CSV snapshot shipped next to
this notebook (real data saved by a previous successful run)."""
end = pd.Timestamp.now().normalize()
start = end - pd.Timedelta(days=365 * 2)
for attempt in range(attempts):
try:
close_cols, volume_cols = {}, {}
for tk in tickers:
bars = hyp.load(f'yahoo:{tk}', start=start, end=end)
close_cols[tk] = bars['close']
volume_cols[tk] = bars['volume']
closes = pd.DataFrame(close_cols)
volumes = pd.DataFrame(volume_cols)
if closes.dropna(how='all').empty:
raise ValueError('hyp.load returned an empty frame')
closes.to_csv(CACHE['close']) # refresh the on-disk snapshot
volumes.to_csv(CACHE['volume']) # for offline runs
print(f"data source: hyp.load('yahoo:...') (live, "
f'{closes.index[0].date()} to {closes.index[-1].date()})')
return closes, volumes
except Exception as e:
print(f'yahoo load attempt {attempt + 1}/{attempts} failed: '
f'{type(e).__name__}: {e}')
time.sleep(2)
closes = pd.read_csv(CACHE['close'], index_col=0, parse_dates=True)
volumes = pd.read_csv(CACHE['volume'], index_col=0, parse_dates=True)
print(f'NOTE: live download unavailable -- using the bundled snapshot '
f'({closes.index[0].date()} to {closes.index[-1].date()}).')
return closes, volumes
closes, volumes = fetch_prices(tickers)
closes.tail()
data source: hyp.load('yahoo:...') (live, 2024-10-09 to 2026-10-08)
[1]:
| AAPL | MSFT | NVDA | JPM | |
|---|---|---|---|---|
| date | ||||
| 2026-10-02 | 333.690002 | 517.530029 | 233.949997 | 332.380005 |
| 2026-10-05 | 332.890015 | 525.179993 | 238.899994 | 332.380005 |
| 2026-10-06 | 333.630005 | 529.299988 | 239.240005 | 331.279999 |
| 2026-10-07 | 336.670013 | 529.760010 | 237.470001 | 329.579987 |
| 2026-10-08 | 340.420013 | 522.609985 | 230.479996 | 331.420013 |
[2]:
# One DataFrame per ticker, in log-price space. We index by trading-day
# position (0, 1, 2, ...): one step is one observed trading day. This
# deliberately gives weekends and holidays no extra model time. Keeping
# the original dates instead models elapsed calendar time; see below.
HOLD = 30 # trading days held out for backtesting
datasets = {}
for tk in tickers:
log_close = np.log(closes[tk].dropna())
datasets[tk] = pd.DataFrame({'log_close': log_close.values})
{tk: df.shape for tk, df in datasets.items()}
[2]:
{'AAPL': (501, 1), 'MSFT': (501, 1), 'NVDA': (501, 1), 'JPM': (501, 1)}
Honest backtesting: hold out the last 30 trading days¶
hyp.predict(datasets, model=model_specs, holdout=HOLD, return_forecasts=True) runs the whole honest backtest in one call: for each ticker it fits every model on everything except the last HOLD trading days, forecasts those days, and scores every model – plus an always-present 'naive' last-value-carried-forward baseline (tomorrow’s forecast = today’s last known price, the textbook random-walk benchmark) – against the real closing prices that actually occurred. The models differ in
what they assume: Kalman assumes a linear-Gaussian state space; ARIMA and AutoRegressor assume linear dependence on recent lags (an ARIMA(1, 1, 1) fit per column, and a Ridge regression on the last 10 observations, respectively); GaussianProcess assumes a smooth kernel over the time index; Laplace assumes no single structure, mixing a likelihood-weighted ensemble of candidate models under a uniform prior; Chronos is Amazon’s pretrained time-series foundation model
(Ansari et al., 2024), which tokenizes the series and samples continuations from a T5-style language model – there is no fitting at all, only a forward pass of a checkpoint downloaded from the Hugging Face Hub. We use the smallest checkpoint, amazon/chronos-t5-tiny (8M parameters), named through the model_name keyword; hyp.predict installs the chronos-forecasting package on first use.
Every model here is fit directly on the log-price series built above, so the MAE/MAPE hyp.predict reports are in log-price units, not dollars, unlike the plots later in this tutorial (which convert forecasts back with exp for display). scores.attrs carries the verdict directly: scores.attrs['best'] is the model with the lowest average MAPE among the real forecasters that forecast every held-out value (never the naive baseline, and never a model listed in
scores.attrs['incomplete']), and scores.attrs['beats_baseline'] says whether it actually beat that baseline. We report whatever comes out below, with no cherry-picking. (Depending on the data, GaussianProcess can print scikit-learn’s ConvergenceWarning – “lbfgs failed to converge” – while it optimizes its kernel; the fitted model is still used and scored. Chronos samples its forecasts, so the cell seeds torch first to make its rows reproducible.)
[3]:
# Chronos SAMPLES its forecasts (the only hypertools forecaster that does), so
# seed torch's generator to make its rows reproducible. torch arrives with the
# chronos-forecasting package hyp.predict installs on first use; if it is not
# installed yet, this run's Chronos rows are simply unseeded.
try:
import torch
torch.manual_seed(0)
except ImportError:
pass
# model name -> the spec handed to hyp.predict(model=...). A plain string
# names a model with its defaults; a dict carries keyword arguments.
model_specs = {
'Kalman': 'Kalman',
'ARIMA': 'ARIMA',
'Laplace': 'Laplace',
'GaussianProcess': 'GaussianProcess',
'AutoRegressor': 'AutoRegressor',
'Chronos': {'model': 'Chronos', 'kwargs': {'model_name': 'amazon/chronos-t5-tiny'}},
}
models = list(model_specs)
# hyp.predict(holdout=HOLD) IS the honest backtest: for each ticker it holds
# out the last HOLD rows, fits every model in `model_specs` on the rest,
# forecasts those HOLD rows, and scores every model AND an always-present
# 'naive' last-value-carried-forward baseline against what actually
# happened. `metrics=['mape', 'mae', 'rmse']` makes MAPE (the metric this
# tutorial ranks models by) the RANKING metric behind `scores.attrs['best']`.
# `per_column=True` keeps one scored row per (model, ticker) instead of
# averaging over tickers; `return_forecasts=True` also hands back the
# forecasts themselves, reused (with no refitting) in the plots below.
scores, backtest = hyp.predict(
[datasets[tk] for tk in tickers], model=model_specs, holdout=HOLD,
metrics=['mape', 'mae', 'rmse'], per_column=True, return_forecasts=True)
scores = scores.rename(index=dict(enumerate(tickers)), level='dataset')
# forecasts[(ticker, model)] -- the 30-row forecast, reused below (the
# 'naive' baseline is keyed the same way)
forecasts = {(tk, model): backtest[model][i]
for i, tk in enumerate(tickers) for model in list(models) + ['naive']}
scores.round(2)
~/hypertools/.venv/lib/python3.12/site-packages/sklearn/gaussian_process/_gpr.py:670: ConvergenceWarning: lbfgs failed to converge after 17 iteration(s) (status=2):
ABNORMAL:
You might also want to scale the data as shown in:
https://scikit-learn.org/stable/modules/preprocessing.html
_check_optimize_result("lbfgs", opt_res)
[3]:
| MAPE | MAE | RMSE | n | unscored | horizon | |||
|---|---|---|---|---|---|---|---|---|
| model | dataset | column | ||||||
| Kalman | AAPL | log_close | 0.79 | 0.05 | 0.05 | 30 | 0 | 30 |
| MSFT | log_close | 0.33 | 0.02 | 0.03 | 30 | 0 | 30 | |
| NVDA | log_close | 0.85 | 0.05 | 0.05 | 30 | 0 | 30 | |
| JPM | log_close | 0.82 | 0.05 | 0.06 | 30 | 0 | 30 | |
| ARIMA | AAPL | log_close | 0.88 | 0.05 | 0.06 | 30 | 0 | 30 |
| MSFT | log_close | 0.32 | 0.02 | 0.03 | 30 | 0 | 30 | |
| NVDA | log_close | 1.28 | 0.07 | 0.08 | 30 | 0 | 30 | |
| JPM | log_close | 0.56 | 0.03 | 0.04 | 30 | 0 | 30 | |
| Laplace | AAPL | log_close | 0.86 | 0.05 | 0.05 | 30 | 0 | 30 |
| MSFT | log_close | 0.24 | 0.02 | 0.02 | 30 | 0 | 30 | |
| NVDA | log_close | 1.33 | 0.07 | 0.08 | 30 | 0 | 30 | |
| JPM | log_close | 0.65 | 0.04 | 0.05 | 30 | 0 | 30 | |
| GaussianProcess | AAPL | log_close | 1.53 | 0.09 | 0.10 | 30 | 0 | 30 |
| MSFT | log_close | 1.70 | 0.11 | 0.12 | 30 | 0 | 30 | |
| NVDA | log_close | 0.49 | 0.03 | 0.03 | 30 | 0 | 30 | |
| JPM | log_close | 0.83 | 0.05 | 0.05 | 30 | 0 | 30 | |
| AutoRegressor | AAPL | log_close | 1.21 | 0.07 | 0.08 | 30 | 0 | 30 |
| MSFT | log_close | 0.82 | 0.05 | 0.06 | 30 | 0 | 30 | |
| NVDA | log_close | 1.10 | 0.06 | 0.07 | 30 | 0 | 30 | |
| JPM | log_close | 0.35 | 0.02 | 0.03 | 30 | 0 | 30 | |
| Chronos | AAPL | log_close | 1.21 | 0.07 | 0.08 | 30 | 0 | 30 |
| MSFT | log_close | 0.36 | 0.02 | 0.03 | 30 | 0 | 30 | |
| NVDA | log_close | 1.28 | 0.07 | 0.08 | 30 | 0 | 30 | |
| JPM | log_close | 0.84 | 0.05 | 0.06 | 30 | 0 | 30 | |
| naive | AAPL | log_close | 0.90 | 0.05 | 0.06 | 30 | 0 | 30 |
| MSFT | log_close | 0.34 | 0.02 | 0.03 | 30 | 0 | 30 | |
| NVDA | log_close | 1.31 | 0.07 | 0.08 | 30 | 0 | 30 | |
| JPM | log_close | 0.56 | 0.03 | 0.04 | 30 | 0 | 30 |
[4]:
mape_by_ticker = scores['MAPE'].droplevel('column').unstack('dataset')
mape_by_ticker['mean'] = mape_by_ticker.mean(axis=1)
mape_by_ticker = mape_by_ticker.sort_values('mean')
print('MAPE (log-price %) per model x ticker, sorted by average:')
mape_by_ticker.round(2)
MAPE (log-price %) per model x ticker, sorted by average:
[4]:
| dataset | AAPL | JPM | MSFT | NVDA | mean |
|---|---|---|---|---|---|
| model | |||||
| Kalman | 0.79 | 0.82 | 0.33 | 0.85 | 0.70 |
| ARIMA | 0.88 | 0.56 | 0.32 | 1.28 | 0.76 |
| Laplace | 0.86 | 0.65 | 0.24 | 1.33 | 0.77 |
| naive | 0.90 | 0.56 | 0.34 | 1.31 | 0.78 |
| AutoRegressor | 1.21 | 0.35 | 0.82 | 1.10 | 0.87 |
| Chronos | 1.21 | 0.84 | 0.36 | 1.28 | 0.92 |
| GaussianProcess | 1.53 | 0.83 | 1.70 | 0.49 | 1.14 |
[5]:
mae_by_ticker = scores['MAE'].droplevel('column').unstack('dataset')
mae_by_ticker['mean'] = mae_by_ticker.mean(axis=1)
mae_by_ticker = mae_by_ticker.loc[mape_by_ticker.index]
print('MAE (log-price units) per model x ticker (same row order as the MAPE table above):')
mae_by_ticker.round(2)
MAE (log-price units) per model x ticker (same row order as the MAPE table above):
[5]:
| dataset | AAPL | JPM | MSFT | NVDA | mean |
|---|---|---|---|---|---|
| model | |||||
| Kalman | 0.05 | 0.05 | 0.02 | 0.05 | 0.04 |
| ARIMA | 0.05 | 0.03 | 0.02 | 0.07 | 0.04 |
| Laplace | 0.05 | 0.04 | 0.02 | 0.07 | 0.04 |
| naive | 0.05 | 0.03 | 0.02 | 0.07 | 0.04 |
| AutoRegressor | 0.07 | 0.02 | 0.05 | 0.06 | 0.05 |
| Chronos | 0.07 | 0.05 | 0.02 | 0.07 | 0.05 |
| GaussianProcess | 0.09 | 0.05 | 0.11 | 0.03 | 0.07 |
[6]:
# "Best" is chosen only among the real forecasting models (not the naive
# baseline), so it's always something we can hand back to hyp.predict below.
best_model = scores.attrs['best']
best_mape = scores.attrs['best_score']
naive_mape = scores.attrs['baseline_score']
beat_naive = scores.attrs['beats_baseline']
print(f"Best model by average MAPE: {best_model} ({best_mape:.2f}%)")
print(f"Naive last-value baseline: {naive_mape:.2f}%")
if beat_naive is None:
# no verdict: no model forecast every held-out value (they are
# listed in scores.attrs['incomplete']), or the baseline did not
print("-> No verdict: models that left held-out values missing "
f"({scores.attrs['incomplete']}) are not ranked.")
elif beat_naive:
print(f"-> {best_model} beat the naive baseline by "
f"{naive_mape - best_mape:.2f} percentage points of MAPE, on "
f"average across these {len(tickers)} tickers.")
else:
print("-> Nothing meaningfully beat the naive last-value baseline on "
"average. This is exactly what an efficient, close-to-random-walk "
"market predicts: recent price is the best simple summary of the "
"immediate future, and no model here reliably extracts more "
"signal than that over a 30-day horizon.")
Best model by average MAPE: Kalman (0.70%)
Naive last-value baseline: 0.78%
-> Kalman beat the naive baseline by 0.08 percentage points of MAPE, on average across these 4 tickers.
The honest takeaway, whichever way the numbers above landed: 30-day-ahead daily stock price forecasting is hard, and a naive random-walk baseline is a tough competitor. That’s expected, and it’s useful to see it quantified rather than assumed – it’s exactly the kind of sanity check a real forecasting pipeline should run before trusting a model’s predictions.
Calendar time versus trading-day position¶
The comparison above deliberately uses trading-day positions: Friday to Monday is one step, just like Monday to Tuesday. HyperTools also accepts actual calendar timestamps. The following backtest keeps the original dates for one ticker and holds out its last 30 observations.
HyperTools recognizes these dates as business-day trading sessions, so the model interval is one business day (step='B'), inferred from the training timestamps only. Kalman fits the training closes on that business-day calendar; market holidays are the only gaps, and they are filled by linear interpolation before fitting (the warning below says so). GaussianProcess evaluates the actual held-out timestamps. No held-out price enters fitting or interpolation. All returned predictions carry
the same index as the held-out truth, so the scores compare matching times, and the reported horizon is the 30 held-out observations.
The filled holiday values are synthetic, not observed market closes. Choose the time axis that matches the question you want to model; changing it can change the fit and the scores.
[7]:
calendar_data = np.log(closes['NVDA'].dropna()).tail(60 + HOLD).to_frame('log_close')
calendar_scores, calendar_backtest = hyp.predict(
calendar_data, model=['Kalman', 'GaussianProcess'], holdout=HOLD,
return_forecasts=True)
for name, prediction in calendar_backtest.items():
assert prediction.index.equals(calendar_backtest['truth'].index), name
print('First held-out time:', calendar_backtest['truth'].index[0])
print('Last held-out time:', calendar_backtest['truth'].index[-1])
calendar_scores.round(4)
First held-out time: 2026-08-27 00:00:00
Last held-out time: 2026-10-08 00:00:00
<cell>:2: UserWarning: Irregular observation times were linearly interpolated onto a regular grid with step='B' before fitting this discrete-time forecaster. Pass step= to choose the grid interval; GaussianProcess uses the actual observation times without interpolation.
calendar_scores, calendar_backtest = hyp.predict(
[7]:
| MAE | RMSE | MAPE | n | unscored | horizon | |
|---|---|---|---|---|---|---|
| model | ||||||
| Kalman | 0.0602 | 0.0676 | 1.1084 | 30 | 0 | 30 |
| GaussianProcess | 0.0653 | 0.0722 | 1.2018 | 30 | 0 | 30 |
| naive | 0.0714 | 0.0781 | 1.3138 | 30 | 0 | 30 |
A closer look at the foundation model¶
Chronos forecasts by sampling: it draws num_samples plausible continuations (20 by default) and reports their median, so its forecast is a distribution summary rather than a fitted curve. Because it needs no fitting, the same call works with at least two observations and any column count. Below we forecast one ticker directly in price space – the trailing 60 training days as an ndims=1 series (a real DataFrame, its own index the trading day, so the x-axis is in actual
trading-day units rather than a hand-built (day, price) column stack) – and let hyp.plot’s own predict=/truth= draw the Chronos forecast next to what actually happened, in one call instead of three hand-assembled datasets.
[8]:
tk = 'NVDA'
df = datasets[tk]
price = np.exp(df['log_close'].values)
day = np.arange(len(df))
context = 60
train_tail = pd.DataFrame({'price': price[-HOLD - context:-HOLD]},
index=day[-HOLD - context:-HOLD])
held_out = pd.DataFrame({'price': price[-HOLD:]}, index=day[-HOLD:])
fig = hyp.plot(train_tail, ndims=1, reduce=None,
predict={'model': 'Chronos', 'kwargs': {'model_name': 'amazon/chronos-t5-tiny'}},
t=HOLD, truth=held_out,
names=['observed (train)'], legend=True,
xlabel='trading day', ylabel='price ($)',
title=f'{tk}: Chronos zero-shot forecast, {HOLD} trading days ahead')
Visualizing forecasts in reduced space¶
hyp.plot(..., predict=..., t=...) overlays a forecast tail (in the same, plotted space – after HyperTools’ normalize / reduce / align pipeline) on top of each input dataset, styled exactly like the trace it continues – same color, linestyle and linewidth – at half its opacity, so it reads as the same series projected forward. We add log trading volume as a second feature per ticker purely so there’s more than one dimension to reduce and plot.
We fit and plot the trailing 60 trading days per ticker, smoothed at the canonical first pipeline stage with manip={'model': 'Smooth', 'kwargs': {'kernel': 'boxcar', 'kernel_width': 11}} – an 11-day boxcar over both features (a boxcar width must be odd, which is why it is 11 and not 10), applied by HyperTools before normalize/reduce rather than in pandas so the 30-step forecast tails are visible at the plotted scale – fitting on the full 2-year history makes the tails microscopic next to
the cloud of training points. Tickers whose recent prices were flat produce short, nearly stationary tails; that is the honest shape of the Kalman forecast, not a rendering artifact.
ndims=2 reduces the (log price, log volume) pair to a 2-D plot rather than hypertools’ default 3-D: with only two input features, a third component would carry no information.
[9]:
context = 60 # trailing trading days to fit/plot per ticker
train_2col = []
for tk in tickers:
log_close = np.log(closes[tk].dropna())
log_volume = np.log(volumes[tk].reindex(log_close.index)
.replace(0, np.nan)).ffill()
df = pd.DataFrame({'log_close': log_close.values,
'log_volume': log_volume.values})
train_2col.append(df.iloc[:-HOLD].tail(context).reset_index(drop=True))
fig = hyp.plot(train_2col, predict='Kalman', t=HOLD, legend=tickers,
manip={'model': 'Smooth', 'kwargs': {'kernel': 'boxcar', 'kernel_width': 11}},
ndims=2, linewidth=2,
title='Kalman forecasts (faded tails) in reduced (price, volume) space')
Best model vs. actual, in price space¶
Rather than the abstract reduced space above, let’s look at the best model (by average MAPE, chosen above – not cherry-picked per ticker) directly in dollar terms for each ticker: an ndims=1 panel per ticker (the real trading day as its index, so hyp.plot draws the x-axis itself) whose predict=/truth= overlay the model’s forecast and the real held-out prices in one call – the model is refit directly on each panel’s own trailing dollar-price series, rather than reusing the
log-price backtest forecast computed above.
[10]:
# backend='matplotlib' on the grid and on each call: suptitle/tight_layout are matplotlib's,
# and on Colab the default backend would be plotly
fig, axes = hyp.subplots(2, 2, ndims=1, size=(12, 8), backend='matplotlib')
context = 60 # trailing days of history to show for context
for ax, tk in zip(axes, tickers):
df = datasets[tk]
price = np.exp(df['log_close'].values)
day = np.arange(len(df))
train_tail = pd.DataFrame({'price': price[-HOLD - context:-HOLD]},
index=day[-HOLD - context:-HOLD])
held_out = pd.DataFrame({'price': price[-HOLD:]}, index=day[-HOLD:])
# predict=/truth= fit and forecast directly on this panel's own
# trailing dollar-price series -- no refitting from the log-price
# backtest above, so the drawn forecast is the model applied fresh
# to exactly what's plotted.
hyp.plot(train_tail, reduce=None, ndims=1, predict=best_model, t=HOLD,
truth=held_out, ax=ax, title=tk, backend='matplotlib',
# names= draws a legend by itself, so it goes on the first panel only
names=[f'observed (train + {best_model} forecast)'] if ax is axes[0] else None,
legend=(ax is axes[0]),
xlabel='trading day', ylabel='price ($)',
show=False)
fig.suptitle(f'{best_model} forecast vs. actual, last {HOLD} trading days '
'(held out)')
fig.tight_layout()
Reusing a fitted forecaster with return_model=True¶
hyp.predict(..., return_model=True) also returns the fitted forecaster object. That fitted instance can be passed back in as model= on brand new data, and it will apply its already-learned parameters directly – no re-fitting/re-estimation – via Forecaster.predict_new under the hood.
To demonstrate: we pool the (log-price) training data from three tickers (AAPL, MSFT, NVDA) into one combined series and fit a single AutoRegressor forecaster on it. Then we hand that already-fitted forecaster the fourth ticker’s (JPM) training tail – a stock it has never seen – and ask it to forecast forward. The learned lag-regression weights are reused as-is; only JPM’s own recent values seed the recursion.
[11]:
pool_tickers = ['AAPL', 'MSFT', 'NVDA']
reuse_ticker = 'JPM'
pooled_train = pd.concat(
[datasets[tk].iloc[:-HOLD] for tk in pool_tickers], ignore_index=True)
_, fitted_forecaster = hyp.predict(pooled_train, model='AutoRegressor',
t=HOLD, return_model=True)
print('Fitted on pooled', pool_tickers, '-- is_fitted:',
fitted_forecaster.is_fitted)
jpm_train = datasets[reuse_ticker].iloc[:-HOLD].reset_index(drop=True)
reused_forecast = hyp.predict(jpm_train, model=fitted_forecaster, t=HOLD)
jpm_actual_price = np.exp(datasets[reuse_ticker].iloc[-HOLD:]['log_close'].values)
reused_price = np.exp(reused_forecast['log_close'].values)
reused_mape = np.mean(np.abs((reused_price - jpm_actual_price) / jpm_actual_price)) * 100
# the backtest above already fit a per-ticker AutoRegressor on JPM -- reuse
# that forecast (no refitting) for an apples-to-apples, dollar-space MAPE.
jpm_own_price = np.exp(forecasts[(reuse_ticker, 'AutoRegressor')]['log_close'].values)
jpm_own_mape = np.mean(np.abs((jpm_own_price - jpm_actual_price) / jpm_actual_price)) * 100
print(f"Reused-forecaster MAPE on {reuse_ticker}: {reused_mape:.2f}%")
print(f"(for comparison, {reuse_ticker}'s own freshly-fit AutoRegressor MAPE: "
f"{jpm_own_mape:.2f}%)")
Fitted on pooled ['AAPL', 'MSFT', 'NVDA'] -- is_fitted: True
Reused-forecaster MAPE on JPM: 1.81%
(for comparison, JPM's own freshly-fit AutoRegressor MAPE: 2.08%)
Whether the pooled fit lands above or below JPM’s own fit on a given run (compare the two MAPEs printed above) says little on its own: it is one 30-day window, and a lag regression fit on other stocks’ price dynamics is not in general a substitute for fitting on the ticker you care about. What the cell demonstrates is the mechanics of return_model=True: the forecaster’s learned parameters were reused as-is, with no re-estimation, on data it had never seen.
Next steps¶
`hyp.predictAPI reference <../api.rst>`__ – full parameter docs for every model ('Kalman','GaussianProcess','AutoRegressor','ARIMA','Laplace','Chronos').hyp.plot(..., predict=..., t=...)overlays forecasts directly on any plot – see theplot_predictgallery example.hyp.impute(a sibling module) fills in missing observations rather than forecasting future ones – see theprojectile_kalmantutorial and theplot_imputegallery example.Try a larger Chronos checkpoint (
model_name='amazon/chronos-t5-small'and up – see the Chronos model cards) or pass your own scikit-learn regressor toAutoRegressor(model=...).