> ## Documentation Index
> Fetch the complete documentation index at: https://nixtla.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Prediction Intervals

> Learn how to create prediction intervals with TimeGPT

## What Are Prediction Intervals?

A prediction interval provides a range where a future observation of a time series is expected to fall, with a specific level of probability.
For example, a 95% prediction interval means that the true future value is expected to lie within this range 95 times out of 100.
Wider intervals reflect greater uncertainty, while narrower intervals indicate higher confidence in the forecast.

With TimeGPT, you can easily generate prediction intervals for any confidence level between 0% and 100%.
These intervals are constructed using **[conformal prediction](https://en.wikipedia.org/wiki/Conformal_prediction)**, a distribution-free framework for uncertainty quantification.

Prediction intervals differ from confidence intervals:

* **Prediction Intervals**: Capture the uncertainty in future observations.

* **Confidence Intervals**:  Quantify the uncertainty in the estimated model parameters (e.g., the mean).

As a result, prediction intervals are typically wider, as they account for both model and data variability.

## How to Generate Prediction Intervals

[![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/Nixtla/nixtla/blob/main/nbs/docs/capabilities/forecast/10_prediction_intervals.ipynb)

### Step 1: Import Packages

Import the required packages and initialize the Nixtla client.

```python theme={null}
import pandas as pd
from nixtla import NixtlaClient

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

### Step 2: Load Data

In this tutorial, we will use the Air Passengers dataset.

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

|   | timestamp  | value |
| - | ---------- | ----- |
| 0 | 1949-01-01 | 112   |
| 1 | 1949-02-01 | 118   |
| 2 | 1949-03-01 | 132   |
| 3 | 1949-04-01 | 129   |
| 4 | 1949-05-01 | 121   |

### Step 3: Forecast with Prediction Intervals

To generate prediction intervals with TimeGPT, provide a list of desired confidence levels using the `level` argument.

Note that accepted values are between 0 and 100.

* Higher confidence levels provide more certainty that the true value will be captured, but result in wider, less precise intervals.

* Lower confidence levels provide less certainty that the true value will be captured, but result in narrower, more precise intervals.

```python theme={null}
timegpt_fcst_pred_int_df = nixtla_client.forecast(
    df=df,
    h=12,
    level=[80, 90, 99],
    time_col='timestamp',
    target_col='value',
)

timegpt_fcst_pred_int_df.head()
```

| timestamp  | TimeGPT | TimeGPT-hi-80 | TimeGPT-hi-90 | TimeGPT-hi-99 | TimeGPT-lo-80 | TimeGPT-lo-90 | TimeGPT-lo-99 |
| ---------- | ------- | ------------- | ------------- | ------------- | ------------- | ------------- | ------------- |
| 1961-01-01 | 437.84  | 443.69        | 451.89        | 459.28        | 431.99        | 423.78        | 416.40        |
| 1961-02-01 | 426.06  | 439.42        | 444.43        | 448.94        | 412.70        | 407.70        | 403.19        |
| 1961-03-01 | 463.12  | 488.83        | 495.92        | 502.31        | 437.41        | 430.31        | 423.93        |
| 1961-04-01 | 478.24  | 507.77        | 509.72        | 511.47        | 448.72        | 446.77        | 445.02        |
| 1961-05-01 | 505.65  | 532.89        | 539.32        | 545.12        | 478.41        | 471.97        | 466.18        |

You can visualize the prediction intervals using the `plot` method. To do so, specify the confidence levels to display using the `level` argument.

```python theme={null}
nixtla_client.plot(
  df, 
  timegpt_fcst_pred_int_df, 
  time_col='timestamp', 
  target_col='value',
  level=[80, 90, 99]
)
```

<img src="https://mintcdn.com/nixtla-enterprise/2mYHtm59xC8HB7vL/images/docs/tutorials-uncertainty/prediction_intervals_fc.png?fit=max&auto=format&n=2mYHtm59xC8HB7vL&q=85&s=0fec62f76b152567b5a4f3162537f953" width="1592" height="315" data-path="images/docs/tutorials-uncertainty/prediction_intervals_fc.png" />

### Step 4: Historical Forecast

You can also generate prediction intervals for historical forecasts by setting `add_history=True`.

```python theme={null}
timegpt_fcst_pred_int_historical_df = nixtla_client.forecast(
      df=df,
      h=12,
      level=[80, 90],
      time_col='timestamp',
      target_col='value',
      add_history=True,
  )

timegpt_fcst_pred_int_historical_df.head()
```

Plot the prediction intervals for the historical forecasts.

```python theme={null}
nixtla_client.plot(
  df, 
  timegpt_fcst_pred_int_historical_df, 
  time_col='timestamp', 
  target_col='value', 
  level=[80,90,99]
)
```

<img src="https://mintcdn.com/nixtla-enterprise/2mYHtm59xC8HB7vL/images/docs/tutorials-uncertainty/prediction_intervals_historical.png?fit=max&auto=format&n=2mYHtm59xC8HB7vL&q=85&s=23b08b0036550e61efa70c89acfdf157" width="1591" height="314" data-path="images/docs/tutorials-uncertainty/prediction_intervals_historical.png" />

### Step 5. Cross-Validation

You can use the `cross_validation` method to generate prediction intervals for each time window.

```python theme={null}
cv_df = nixtla_client.cross_validation(
    df=df,
    h=12,
    n_windows=4,
    level=[80, 90, 99],
    time_col='timestamp',
    target_col='value'
)
cv_df.head()
```

After computing the forecasts, you can visualize the results for each cross-validation cutoff to better understand model performance over time.

```python theme={null}
cutoffs = cv_df['cutoff'].unique()

for cutoff in cutoffs:
    fig = nixtla_client.plot(
        df.tail(100),
        cv_df.query('cutoff == @cutoff').drop(columns=['cutoff', 'value']),
        level=[80,90,99],
        time_col='timestamp',
        target_col='value', 
    )
    display(fig)
```

<img src="https://mintcdn.com/nixtla-enterprise/2mYHtm59xC8HB7vL/images/docs/tutorials-uncertainty/prediction_intervals_cv1.png?fit=max&auto=format&n=2mYHtm59xC8HB7vL&q=85&s=3f7f67d6dfcbc8a0d2a65412aec11f3f" width="1592" height="653" data-path="images/docs/tutorials-uncertainty/prediction_intervals_cv1.png" />

<img src="https://mintcdn.com/nixtla-enterprise/2mYHtm59xC8HB7vL/images/docs/tutorials-uncertainty/prediction_intervals_cv2.png?fit=max&auto=format&n=2mYHtm59xC8HB7vL&q=85&s=76956e218ff96d59cc10eba7fe04dcc3" width="1602" height="644" data-path="images/docs/tutorials-uncertainty/prediction_intervals_cv2.png" />

<Check>
  Congratulations! You have successfully generated prediction intervals using TimeGPT.
  You also visualized historical forecasts with intervals and evaluated their coverage across multiple time windows using cross-validation.
</Check>
