Here’s a step‐by‐step Python example that:
- Simulates an AR(1) process
- Plots the time series
- Fits an OLS regression to estimate the AR coefficient
- Visualizes the fit
Feel free to tweak the parameters (φ, sample size, noise level) as you like! 😎
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
# 1. SIMULATE AN AR(1) PROCESS
np.random.seed(42)
T = 200 # number of time points
phi = 0.7 # autoregressive coefficient
sigma = 1.0 # noise standard deviation
# initialize
y = np.zeros(T)
eps = np.random.normal(scale=sigma, size=T)
# generate data: y[t] = phi * y[t-1] + eps[t]
for t in range(1, T):
y[t] = phi * y[t-1] + eps[t]
# 2. PLOT THE TIME SERIES
plt.figure(figsize=(10,3))
plt.plot(y, color='C0')
plt.title("Simulated AR(1) Process (φ = {:.2f})".format(phi))
plt.xlabel("Time")
plt.ylabel("y_t")
plt.tight_layout()
plt.show()
# 3. PREPARE DATA FOR OLS: y_t ~ α + β y_{t-1}
# Drop the first observation since y_{t-1} starts at t=1
y2 = y[1:]
X = y[:-1]
Xc = sm.add_constant(X) # adds intercept term
# fit OLS
model = sm.OLS(y2, Xc)
results = model.fit()
print(results.summary())
# 4. VISUALIZE THE REGRESSION
beta_hat = results.params[1]
alpha_hat = results.params[0]
print(f"Estimated α = {alpha_hat:.3f}, β = {beta_hat:.3f}")
# Scatter + fitted line
plt.figure(figsize=(6,6))
plt.scatter(X, y2, alpha=0.5, label="Data")
x_line = np.linspace(X.min(), X.max(), 100)
y_line = alpha_hat + beta_hat * x_line
plt.plot(x_line, y_line, color='C3', lw=2, label="OLS fit")
plt.title("OLS Regression of y_t on y_{t-1}")
plt.xlabel("y_{t-1}")
plt.ylabel("y_t")
plt.legend()
plt.tight_layout()
plt.show()
# OPTIONAL: Plot the fitted series vs. actual
y_pred = results.predict(Xc)
plt.figure(figsize=(10,3))
plt.plot(range(1, T), y2, label="Actual y_t", alpha=0.7)
plt.plot(range(1, T), y_pred, label="Fitted ŷ_t", lw=2)
plt.title("Actual vs. Fitted Values")
plt.xlabel("Time")
plt.legend()
plt.tight_layout()
plt.show()
Explanation:
- We simulate an AR(1):
yₜ = φ · yₜ₋₁ + εₜ, εₜ ∼ N(0,σ²).
- We then regress yₜ on yₜ₋₁ (plus intercept) via Ordinary Least Squares.
- Finally, we plot:
- The raw time series
- The scatter of (yₜ₋₁, yₜ) with the fitted regression line
- (Optionally) Actual vs. fitted yₜ to check how well the model tracks the data
Let me know if you’d like to extend to higher‐order AR(p), include diagnostic plots, or estimate via maximum likelihood! 😊