I'll help you generate an AR process, visualize it, and perform OLS regression. Here's a complete Python implementation:
python
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from statsmodels.regression.linear_model import OLS
import statsmodels.api as sm
# Set random seed for reproducibility
np.random.seed(42)
# Generate AR(1) process
def generate_ar_process(n, phi, sigma=1, y0=0):
"""
Generate AR(1) process: y_t = phi * y_{t-1} + epsilon_t
Parameters:
n: number of observations
phi: AR coefficient
sigma: standard deviation of error term
y0: initial value
"""
y = np.zeros(n)
y[0] = y0
epsilon = np.random.normal(0, sigma, n)
for t in range(1, n):
y[t] = phi * y[t-1] + epsilon[t]
return y
# Generate time series
n = 200
phi_true = 0.7 # True AR coefficient
y = generate_ar_process(n, phi_true)
# Create time index
time_index = np.arange(n)
# Visualize the time series
plt.figure(figsize=(12, 5))
plt.plot(time_index, y, 'b-', linewidth=1)
plt.title(f'AR(1) Process with φ = {phi_true}')
plt.xlabel('Time')
plt.ylabel('Value')
plt.grid(True, alpha=0.3)
plt.show()
# Prepare data for OLS regression
# For AR(1): y_t = c + phi * y_{t-1} + epsilon_t
X = y[:-1] # Lagged values (y_{t-1})
y_reg = y[1:] # Current values (y_t)
# Add constant term
X_with_const = sm.add_constant(X)
# Perform OLS regression
model = OLS(y_reg, X_with_const)
results = model.fit()
# Print regression results
print(results.summary())
# Extract coefficients
intercept = results.params[0]
phi_estimated = results.params[1]
print(f"\nTrue AR coefficient: {phi_true}")
print(f"Estimated AR coefficient: {phi_estimated:.4f}")
# Visualize regression results
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))
# Scatter plot with regression line
ax1.scatter(X, y_reg, alpha=0.5, label='Actual data')
ax1.plot(X, results.predict(X_with_const), 'r-', linewidth=2, label='OLS fit')
ax1.set_xlabel('$y_{t-1}$')
ax1.set_ylabel('$y_t$')
ax1.set_title('OLS Regression: $y_t$ vs $y_{t-1}$')
ax1.legend()
ax1.grid(True, alpha=0.3)
# Residuals plot
residuals = results.resid
ax2.scatter(time_index[1:], residuals, alpha=0.5)
ax2.axhline(y=0, color='r', linestyle='--')
ax2.set_xlabel('Time')
ax2.set_ylabel('Residuals')
ax2.set_title('Residual Plot')
ax2.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
# Additional diagnostics
# ACF plot of residuals
from statsmodels.graphics.tsaplots import plot_acf
fig, ax = plt.subplots(figsize=(10, 5))
plot_acf(residuals, lags=20, ax=ax)
ax.set_title('Autocorrelation Function of Residuals')
plt.show()
# Generate predictions
n_pred = 20
y_pred = np.zeros(n_pred)
y_pred[0] = y[-1] # Start from last observed value
for t in range(1, n_pred):
y_pred[t] = intercept + phi_estimated * y_pred[t-1]
# Plot original series with predictions
plt.figure(figsize=(12, 5))
plt.plot(time_index, y, 'b-', label='Original series')
plt.plot(np.arange(n, n + n_pred), y_pred, 'r--', linewidth=2, label='Predictions')
plt.axvline(x=n-1, color='gray', linestyle=':', alpha=0.7)
plt.title('AR(1) Process with Out-of-Sample Predictions')
plt.xlabel('Time')
plt.ylabel('Value')
plt.legend()
plt.grid(True, alpha=0.3)
plt.show()
This code performs the following tasks:
Generates an AR(1) process: The generate_ar_process function creates a time series following the equation y_t = φ * y_{t-1} + ε_t, where φ is the AR coefficient and ε_t is white noise.
Visualizes the time series: Shows the generated AR process over time.
Implements OLS regression: Uses statsmodels to estimate the AR coefficient by regressing y_t on y_{t-1}.
Visualizes the results:
Scatter plot showing the relationship between y_t and y_{t-1} with the fitted regression line
Residual plot to check for patterns
ACF plot of residuals to verify they behave like white noise
Original series with out-of-sample predictions
The code also prints a detailed regression summary including the estimated coefficients, standard errors, t-statistics, and R-squared value. You can modify the AR coefficient (phi_true) or extend this to higher-order AR processes (AR(p)) by including more lags in the regression.