statsmodels.api.tsa.get_forcast参数、样本外预测问题及示例请求
statsmodels.tsa.get_forecast(): Parameter Details & 20-Day Prediction Example Hey there! Let's break down how to use get_forecast() properly—including key parameter details and a working example for 20-day out-of-sample predictions—to fix your code issues.
First, a quick note: get_forecast() is a method attached to fitted time series models (like ARIMA, SARIMAX, etc.) in statsmodels, so you’ll always call it after training a model on your data.
Key Parameter Breakdown
Here are the most critical parameters you’ll work with:
steps: (int, required) Number of periods to forecast ahead. This is where you’ll set20for your 20-day prediction.exog: (array-like, optional) If your model was trained with exogenous variables (e.g., external factors like temperature affecting sales), you need to provide future values of these variables here. Omit this if your model doesn’t use external inputs.alpha: (float, optional) Significance level for confidence intervals. Defaults to0.05, which generates 95% confidence bands.start: (int/str/datetime, optional) The starting point of the forecast. Rarely needed if you want to predict immediately after your training data—stepshandles the forward prediction length.method: (str, optional) Prediction method (e.g., 'ols', 'mle'). Defaults to the method used to fit the model, so you usually don’t need to tweak this.
Full Working Example: 20-Day Out-of-Sample Prediction
Let’s walk through a complete workflow using the classic AirPassengers dataset (monthly airline passenger numbers) to demonstrate correct usage:
Step 1: Import Libraries & Prepare Data
import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt # Load sample time series data data = sm.datasets.get_rdataset("AirPassengers").data # Convert to a properly indexed time series data['date'] = pd.date_range(start='1949-01', periods=len(data), freq='M') data.set_index('date', inplace=True) ts = data['value']
Step 2: Fit a Time Series Model
We’ll use a SARIMAX model (ideal for seasonal data), but get_forecast() works the same way for other statsmodels time series models:
# Fit a SARIMAX model (adjust order/seasonal_order based on your own data!) model = sm.tsa.SARIMAX(ts, order=(1,1,1), seasonal_order=(1,1,1,12)) fitted_model = model.fit()
Step 3: Generate the 20-Day Forecast
# Get forecast for 20 periods ahead forecast_results = fitted_model.get_forecast(steps=20) # Extract key forecast components predicted_values = forecast_results.predicted_mean confidence_intervals = forecast_results.conf_int() lower_band = confidence_intervals.iloc[:, 0] upper_band = confidence_intervals.iloc[:, 1]
Step 4: Visualize the Results
# Plot historical data + forecast plt.figure(figsize=(12,6)) plt.plot(ts, label='Historical Data') plt.plot(predicted_values.index, predicted_values, label='20-Day Forecast', color='crimson') plt.fill_between(confidence_intervals.index, lower_band, upper_band, color='pink', alpha=0.3, label='95% Confidence Interval') plt.legend() plt.title('AirPassengers: Historical Data + 20-Day Forecast') plt.xlabel('Date') plt.ylabel('Number of Passengers') plt.show()
Troubleshooting Common Code Issues
If your original code was throwing errors, here are the most likely fixes:
- Forgot to fit the model first: You can’t call
get_forecast()on an unfitted model—always runmodel.fit()and use the returned results object to call the method. - Missing exogenous variables: If your model used
exogduring training, you must pass future exog values toget_forecast(exog=future_exog). - Invalid
stepsvalue: Double-check thatstepsis an integer (e.g.,20, not a string or float). - Poorly formatted time series: Ensure your data has a datetime index—statsmodels relies on this to align forecast dates correctly.
内容的提问来源于stack exchange,提问作者taylor

