--- title: Core keywords: fastai sidebar: home_sidebar nb_path: "nbs/core.ipynb" ---
from fastcore.test import test_eq
from statsforecast.models import (
adida,
croston_classic,
historic_average,
naive,
seasonal_naive,
seasonal_window_average,
ses,
auto_arima
)
from statsforecast.utils import generate_series
fcst = StatsForecast(
series,
[adida, (ses, 0.1), historic_average, croston_classic],
freq='D',
)
res = fcst.forecast(14)
res
monthly_series = generate_series(10_000, freq='M', min_length=10, max_length=20, equal_ends=True)
monthly_series
fcst = StatsForecast(
monthly_series,
[adida, (ses, 0.1), historic_average, croston_classic],
freq='M',
)
%time monthly_res = fcst.forecast(4)
monthly_res
from statsforecast.utils import AirPassengers as ap
int_ds_df = pd.DataFrame({'ds': np.arange(1, len(ap) + 1), 'y': ap})
int_ds_df.insert(0, 'unique_id', 'AirPassengers')
int_ds_df.set_index('unique_id', inplace=True)
int_ds_df.head()
int_ds_df.tail()
fcst = StatsForecast(int_ds_df, models=[historic_average], freq='D')
horizon = 7
forecast = fcst.forecast(horizon)
forecast.head()
last_date = int_ds_df['ds'].max()
test_eq(forecast['ds'].values, np.arange(last_date + 1, last_date + 1 + horizon))
Every column after y is considered an external regressor and will be passed to the models that allow them. If you use them you must supply the future values to the forecast
method.
def linear_regression(X, h, future_xreg):
y = X[:, 0]
xreg = X[:, 1:]
coefs, *_ = np.linalg.lstsq(xreg, y, rcond=None)
return future_xreg @ coefs
series_xreg = series = generate_series(10_000, equal_ends=True)
series_xreg['intercept'] = 1
series_xreg['dayofweek'] = series_xreg['ds'].dt.dayofweek
series_xreg = pd.get_dummies(series_xreg, columns=['dayofweek'], drop_first=True)
series_xreg
dates = sorted(series_xreg['ds'].unique())
valid_start = dates[-14]
train_mask = series_xreg['ds'] < valid_start
series_train = series_xreg[train_mask]
series_valid = series_xreg[~train_mask]
X_valid = series_valid.drop(columns=['y'])
fcst = StatsForecast(
series_train,
[linear_regression],
freq='D',
)
%time xreg_res = fcst.forecast(14, xreg=X_valid)
xreg_res['y'] = series_valid['y'].values
xreg_res.groupby('ds').mean().plot();
ap_df = pd.DataFrame({'ds': np.arange(ap.size), 'y': ap}, index=pd.Index([0] * ap.size, name='unique_id'))
fcst = StatsForecast(
ap_df,
[(seasonal_naive, 12), (auto_arima, 12)],
freq='M',
)
ap_ci = fcst.forecast(12, level=(80, 95))
ap_ci.set_index('ds').plot(marker='.', figsize=(10, 6));