Historical forecast

Our time series model offers a powerful feature that allows users to retrieve historical forecasts alongside the prospective predictions. This functionality is accessible through the forecast method by setting the add_history=True argument.


import pandas as pd
from nixtla import NixtlaClient


nixtla_client = NixtlaClient(
    # defaults to os.environ.get("NIXTLA_API_KEY")
    api_key = 'my_api_key_provided_by_nixtla'
)

Now you can start to make forecasts! Let’s import an example:


df = pd.read_csv('https://raw.githubusercontent.com/Nixtla/transfer-learning-time-series/main/datasets/air_passengers.csv')
df.head()

timestampvalue
01949-01-01112
11949-02-01118
21949-03-01132
31949-04-01129
41949-05-01121

nixtla_client.plot(df, time_col='timestamp', target_col='value')


Let’s add fitted values. When add_history is set to True, the output DataFrame will include not only the future forecasts determined by the h argument, but also the historical predictions. Currently, the historical forecasts are not affected by h, and have a fix horizon depending on the frequency of the data. The historical forecasts are produced in a rolling window fashion, and concatenated. This means that the model is applied sequentially at each time step using only the most recent information available up to that point.


timegpt_fcst_with_history_df = nixtla_client.forecast(
    df=df, h=12, time_col='timestamp', target_col='value',
    add_history=True,
)

INFO:nixtla.nixtla_client:Validating inputs...
INFO:nixtla.nixtla_client:Preprocessing dataframes...
INFO:nixtla.nixtla_client:Inferred freq: MS
INFO:nixtla.nixtla_client:Calling Forecast Endpoint...
INFO:nixtla.nixtla_client:Calling Historical Forecast Endpoint...

timegpt_fcst_with_history_df.head()

timestampTimeGPT
01951-01-01135.483673
11951-02-01144.442398
21951-03-01157.191910
31951-04-01148.769363
41951-05-01140.472946
Let’s plot the results. This consolidated view of past and future predictions can be invaluable for understanding the model’s behavior and for evaluating its performance over time.

nixtla_client.plot(df, timegpt_fcst_with_history_df, time_col='timestamp', target_col='value')


Please note, however, that the initial values of the series are not included in these historical forecasts. This is because TimeGPT requires a certain number of initial observations to generate reliable forecasts. Therefore, while interpreting the output, it’s important to be aware that the first few observations serve as the basis for the model’s predictions and are not themselves predicted values.