Great idea to compare different ϕ values and fix the plot ranges for better comparison!
Here's the updated Python script that does exactly that:
It defines a list of phi values to test.
It uses matplotlib.pyplot.subplots to create a grid of plots.
For each phi value:
It simulates the AR(1) process.
It plots the time series with a fixed Y-axis range to make the visual scale consistent across different series.
It performs OLS regression.
It plots the (yₜ₋₁, yₜ) scatter with the fitted line, also with fixed X and Y axis ranges.
It prints and collects the estimated ϕ and α values.
Finally, it prints a summary table of the estimated coefficients.
python
import numpy as np
import matplotlib.pyplot as plt
import statsmodels.api as sm
import pandas as pd # For a nice summary table
# --- Simulation Parameters ---
T = 200 # Number of time points
sigma = 1.0 # Noise standard deviation (standard deviation of epsilon_t)
# Different AR coefficients to test
phi_values_to_test = [0.2, 0.7, 0.95]
# --- Plotting Setup ---
# Determine a fixed y-axis range for time series and scatter plots.
# For a stationary AR(1) process y_t = phi * y_{t-1} + epsilon_t,
# the variance of y_t is sigma^2 / (1 - phi^2).
# For phi=0.95 and sigma=1, variance = 1 / (1 - 0.95^2) = 1 / (1 - 0.9025) = 1 / 0.0975 approx 10.25
# Standard deviation approx sqrt(10.25) = 3.2.
# A range of +/- 3-4 standard deviations should cover most values. Let's use [-12, 12].
FIXED_PLOT_LIMITS = [-12, 12]
# --- Store Results for Summary ---
results_summary = []
# --- Create a figure with subplots for comparison ---
num_phi = len(phi_values_to_test)
# Each phi will have 2 plots: Time Series + OLS Scatter
fig, axes = plt.subplots(num_phi, 2, figsize=(12, 4.5 * num_phi), sharex=False, sharey=False)
# Ensure axes is always 2D, even if num_phi = 1
if num_phi == 1:
axes = np.array([axes]) # Make it a 2D array if there's only one row
# Add a main title for the entire figure
fig.suptitle("Comparison of AR(1) Processes and OLS Regression", y=1.02, fontsize=16)
# --- Loop through different phi values ---
for i, phi in enumerate(phi_values_to_test):
print(f"\n--- Processing for True phi = {phi:.2f} ---")
np.random.seed(42 + i) # Use a different seed for each run for variety
# 1. SIMULATE AN AR(1) PROCESS
y = np.zeros(T)
# Generate noise terms
eps = np.random.normal(loc=0, scale=sigma, size=T)
# Generate data: y[t] = phi * y[t-1] + eps[t]
# We start y[0] at 0. For large T, the initial condition's effect fades.
for t in range(1, T):
y[t] = phi * y[t-1] + eps[t]
# 2. PLOT THE TIME SERIES
ax_ts = axes[i, 0] # Get the specific subplot for the time series
ax_ts.plot(y, color='C0', alpha=0.8)
ax_ts.set_title(f"AR(1) Series (True φ = {phi:.2f})")
ax_ts.set_xlabel("Time")
ax_ts.set_ylabel("y_t")
ax_ts.set_ylim(FIXED_PLOT_LIMITS) # Apply fixed y-axis limit
ax_ts.grid(True, linestyle='--', alpha=0.6)
# 3. IMPLEMENT OLS REGRESSION
# Prepare data: y_t as dependent, y_{t-1} as independent
# We predict y_t using y_{t-1}, so we need to align them.
# y_reg is y[1] to y[T-1]
# X_reg is y[0] to y[T-2]
y_reg = y[1:]
X_reg = y[:-1]
# Add a constant (intercept term) to the independent variable matrix
X_reg_const = sm.add_constant(X_reg)
# Fit the OLS model
model = sm.OLS(y_reg, X_reg_const)
results = model.fit()
# Extract estimated parameters
alpha_hat = results.params[0] # Estimated intercept
beta_hat = results.params[1] # Estimated AR coefficient (phi_hat)
print(f" Estimated α = {alpha_hat:.3f}")
print(f" Estimated φ = {beta_hat:.3f}")
# print(results.summary()) # Uncomment to see full summary for each run
# Store results for the final summary table
results_summary.append({
'True_phi': phi,
'Estimated_phi': beta_hat,
'Estimated_alpha': alpha_hat,
'R-squared': results.rsquared,
'P-value_phi': results.pvalues[1] # p-value for the phi coefficient
})
# 4. VISUALIZE THE OLS REGRESSION RESULTS
ax_ols = axes[i, 1] # Get the specific subplot for the OLS scatter plot
ax_ols.scatter(X_reg, y_reg, alpha=0.5, s=10, label="Data Points")
# Create points for the fitted line, spanning the fixed plot limits
x_line = np.linspace(FIXED_PLOT_LIMITS[0], FIXED_PLOT_LIMITS[1], 100)
y_line = alpha_hat + beta_hat * x_line
ax_ols.plot(x_line, y_line, color='C3', lw=2, label="OLS Fit")
ax_ols.set_title(f"OLS: y_t vs y_{{t-1}} (Est. φ = {beta_hat:.2f})")
ax_ols.set_xlabel("y_{t-1}")
ax_ols.set_ylabel("y_t")
ax_ols.set_xlim(FIXED_PLOT_LIMITS) # Apply fixed x-axis limit
ax_ols.set_ylim(FIXED_PLOT_LIMITS) # Apply fixed y-axis limit
ax_ols.legend(loc='upper left')
ax_ols.grid(True, linestyle='--', alpha=0.6)
plt.tight_layout(rect=[0, 0, 1, 0.98]) # Adjust layout to prevent title overlap
plt.show()
# --- Print Summary of Results ---
print("\n--- Summary of Estimated Coefficients ---")
df_results = pd.DataFrame(results_summary)
print(df_results.round(3))
Key Changes and Explanations:
phi_values_to_test: A list [0.2, 0.7, 0.95] is defined to iterate through different autoregressive coefficients.
ϕ=0.2: A weak autoregressive component.
ϕ=0.7: A moderate autoregressive component.
ϕ=0.95: A strong autoregressive component, where the series has a lot of memory and looks "smoother" or trends more persistently.
FIXED_PLOT_LIMITS:
This constant [-12, 12] is introduced to ensure all time series and scatter plots have the same y-axis (and x-axis for scatter) range.
This enhanced script provides a much clearer visual and numerical comparison of how the AR(1) process behaves with different ϕ values and how OLS effectively estimates these underlying parameters.
This range is chosen based on the theoretical standard deviation of an AR(1) process: σy=σϵ/1−ϕ2. For ϕ=0.95 and σϵ=1, σy≈3.2. A range of ±3−4 standard deviations usually covers most observations. This allows for a meaningful comparison of the series' volatility across different ϕ values.
plt.subplots(num_phi, 2, ...):
This creates a grid of plots, where num_phi is the number of rows (one for each ϕ value) and 2 is the number of columns (one for the time series, one for the OLS scatter plot).
sharex=False, sharey=False is used to allow individual axis limits where desired, although we manually set them to FIXED_PLOT_LIMITS.
Looping and Indexing:
The core logic is wrapped in a for loop that iterates through phi_values_to_test.
axes[i, 0] and axes[i, 1] are used to select the correct subplot for the current ϕ value.
np.random.seed(42 + i): By adding i to the seed, each simulation for a different ϕ value will use a different random sequence, making the generated series unique but still reproducible if you run the script again.
x_line for OLS plot: The x_line for the fitted regression line now spans the FIXED_PLOT_LIMITS to show the complete linear relationship across the chosen range, even if data points don't occupy the entire range.
Summary Table: A pandas.DataFrame is used to nicely print the true ϕ values alongside their estimated counterparts, the estimated intercepts (α), and R-squared values for each run, making the comparison very clear.