gwp1 Code
gwp1 Code
Problem 1
1d) Using simulation, create a known regression
model
parameters containing
of the two predictors.
model are In
known. this
Now case,
omit the
one
ofthetheestimates
predictors
of and
the estimate
coefficientthe
of model.
the Compare
non-omitted
predictor in both cases. What do you notice? If you
increase the
results change? sample size of the simulation, do the
In [1]: import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
import [Link] as plt
import seaborn as sns
Parameters:
n_samples: Number of samples per simulation
n_simulations: Number of simulation runs
true_params: Dictionary of true model parameters
sigma_e: Standard deviation of error term
correlation: Correlation coefficient between X and Z
"""
# Store results
results = []
for _ in range(n_simulations):
# Generate X
X = [Link](0, 1, n_samples)
[Link] 1/30
6/17/25, 6:31 PM gwp1_code
# Full model (Y ~ X + Z)
full_model = LinearRegression()
X_full = np.column_stack((X, Z))
full_model.fit(X_full, Y)
b_full = full_model.coef_[0]
# Omitted model (Y ~ X)
omitted_model = LinearRegression()
omitted_model.fit([Link](-1, 1), Y)
b_omitted = omitted_model.coef_[0]
[Link]({
'b_full': b_full,
'b_omitted': b_omitted,
'sample_size': n_samples
})
return [Link](results)
[Link] 2/30
6/17/25, 6:31 PM gwp1_code
[Link] 3/30
6/17/25, 6:31 PM gwp1_code
Problem 2
2b) Illustrating the Impact of Outliers
Parameters with a Simulated Instance on Regression
In [2]: # Import necessary libraries
import numpy as np
import pandas as pd
import [Link] as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
from [Link] import mean_squared_error, r2_score
[Link] 4/30
6/17/25, 6:31 PM gwp1_code
[Link](42)
Summary Statistics:
X y
count 100.000000 100.000000
mean 5.046199 15.053810
std 2.758270 6.027335
min 0.335324 4.783092
25% 2.539303 10.169822
50% 5.051654 14.465658
75% 7.507640 20.206754
max 9.899602 25.801202
[Link] 5/30
6/17/25, 6:31 PM gwp1_code
# Create X outliers (values that are far from the main data cloud)
outlier_X = [Link](9, 10, n_outliers)
[Link] 6/30
6/17/25, 6:31 PM gwp1_code
[Link] 7/30
6/17/25, 6:31 PM gwp1_code
f"{outlier_model.intercept_:.4f}",
f"{outlier_model.coef_[0]:.4f}",
f"{r2_score(data_with_outliers['y'], outlier_model.predict(data_w
f"{mean_squared_error(data_with_outliers['y'], outlier_model.pred
],
'Percent Change': [
f"{intercept_change:.2f}%",
f"{slope_change:.2f}%",
'N/A',
'N/A'
]
})
[Link] 8/30
6/17/25, 6:31 PM gwp1_code
plt.tight_layout()
[Link]()
# Let's also create a combined plot to better compare the regression line
[Link](figsize=(12, 10))
[Link] 9/30
6/17/25, 6:31 PM gwp1_code
Residual Analysis
Let's examine the residuals to further understand the impact of outliers.
In [11]: # Calculate residuals for both models
clean_residuals = clean_data['y'] - clean_model.predict(clean_data[['X']]
outlier_residuals = data_with_outliers['y'] - outlier_model.predict(data_
[Link] 10/30
6/17/25, 6:31 PM gwp1_code
ax2.set_ylabel('Residuals', fontsize=14)
[Link](True)
plt.tight_layout()
[Link]()
plt.tight_layout()
[Link]()
Simulation
Insights) Methodology (with Residual and Parameter
[Link] 11/30
6/17/25, 6:31 PM gwp1_code
1. Data Generation:
A synthetic dataset with 100 samples was generated to simulate a simple
linear relationship.
The ground-truth model was: , where
y = 5 + 2x + ϵ . 2
ϵ ∼ N (0, 1.5 )
both.
The presence of outliers caused:
Intercept to increase by +24.75% (from 4.6161 → 5.7584).
Slope to drop by –17.54% (from 2.1097 → 1.7396).
R to fall significantly (from 0.9462 to 0.6962), indicating reduced
2
explanatory power.
MSE to spike (from 2.15 to 12.08), showing much higher average error.
4. Visualization:
Residual plots were used to assess model fit and error patterns.
In the clean model, residuals are roughly homoscedastic and symmetrically
distributed around zero—consistent with OLS assumptions.
In the outlier model, residuals show heavy downward deviations for outliers
(highlighted in red), indicating non-constant variance and model misfit.
These red points (bottom-right) show extreme negative residuals, which
dominate the regression fit and pull the line downward, flattening the slope
and misrepresenting the bulk of the data.
The residual pattern becomes non-random, suggesting model assumptions
are violated when outliers are present.
Problem 3
Overview
[Link] 12/30
6/17/25, 6:31 PM gwp1_code
Finding the best regression model for y in terms of x1, x2, x3, x4 and x5
In [28]: import pandas as pd
import numpy as np
import [Link] as plt
import seaborn as sns
import [Link] as sm
import [Link] as smf
from itertools import combinations
from sklearn.linear_model import Lasso, LassoCV
from [Link] import StandardScaler
from [Link] import mean_squared_error, r2_score
from sklearn.model_selection import train_test_split
# Basic statistics
print("\nBasic Statistics:")
print([Link]())
# Correlation matrix
print("\nCorrelation Matrix:")
correlation_matrix = [Link]()
print(correlation_matrix)
[Link] 13/30
6/17/25, 6:31 PM gwp1_code
Dataset Preview:
Y X1 X2 X3 X4 X5
0 3.388410 0.017954 -0.800583 -0.352454 2.187210 1.014887
1 0.287191 0.083057 -0.597947 -0.357639 -1.630284 0.221841
2 3.989645 -0.923437 -1.386575 1.180202 0.632606 -1.576638
3 -2.959602 -0.313775 2.955133 -1.798692 -2.117621 0.159291
4 0.529773 0.388996 1.019611 0.472062 0.590497 0.877048
Basic Statistics:
Y X1 X2 X3 X4
X5
count 100.000000 100.000000 100.000000 100.000000 100.000000 100.000
000
mean 1.257388 0.026830 0.084613 -0.016037 0.122374 -0.201
661
std 1.436655 0.481708 0.962145 0.976559 1.076935 1.073
358
min -2.959602 -1.275230 -2.041959 -2.228483 -2.697316 -3.526
357
25% 0.349470 -0.316585 -0.676951 -0.572893 -0.431023 -0.960
214
50% 1.278526 0.040237 0.040447 0.056879 0.279594 -0.185
795
75% 2.152954 0.373899 0.748166 0.636408 0.747868 0.506
592
max 5.176803 1.083062 2.955133 1.816825 3.167298 2.499
820
Missing Values:
Y 0
X1 0
X2 0
X3 0
X4 0
X5 0
dtype: int64
Correlation Matrix:
Y X1 X2 X3 X4 X5
Y 1.000000 -0.061400 -0.419326 0.411351 0.538308 -0.279807
X1 -0.061400 1.000000 0.103063 0.062876 -0.050210 0.061230
X2 -0.419326 0.103063 1.000000 -0.065582 -0.004993 -0.005223
X3 0.411351 0.062876 -0.065582 1.000000 -0.038886 -0.178590
X4 0.538308 -0.050210 -0.004993 -0.038886 1.000000 -0.125909
X5 -0.279807 0.061230 -0.005223 -0.178590 -0.125909 1.000000
[Link] 14/30
6/17/25, 6:31 PM gwp1_code
[Link] 15/30
6/17/25, 6:31 PM gwp1_code
all_models_results = []
[Link] 16/30
6/17/25, 6:31 PM gwp1_code
# Model summary for the best BIC model (if different from AIC)
if best_aic_model_name != best_bic_model_name:
print("\nSummary for Best Model by BIC:")
print(best_bic_model.summary())
[Link] 17/30
6/17/25, 6:31 PM gwp1_code
'AIC': m['AIC'],
'BIC': m['BIC'],
'Adj. R-squared': m['Adjusted R-squared']
} for m in all_models_results])
# Sort by AIC
model_comparison_df = model_comparison_df.sort_values('AIC')
print("\nAll Models Comparison (Sorted by AIC):")
print(model_comparison_df.to_string(index=False))
[Link](1, 2, 2)
[Link](model_comparison_df['Parameters'], model_comparison_df['BIC']
[Link](model_comparison_df['Parameters'], model_comparison_df['BIC'], '
[Link]('Number of Parameters')
[Link]('BIC')
[Link]('BIC vs Model Complexity')
plt.tight_layout()
[Link]()
[Link] 18/30
6/17/25, 6:31 PM gwp1_code
==================================================
METHOD 1: MODEL SELECTION USING INFORMATION CRITERIA (AIC/BIC)
==================================================
Best Model by AIC: Model with X2, X3, X4, X5 (AIC: 260.617)
Best Model by BIC: Model with X2, X3, X4, X5 (BIC: 273.643)
[Link] 19/30
6/17/25, 6:31 PM gwp1_code
0.873
X5 -0.1966 0.083 -2.355 0.021 -0.362 -
0.031
==========================================================================
====
Omnibus: 4.462 Durbin-Watson:
1.974
Prob(Omnibus): 0.107 Jarque-Bera (JB):
3.920
Skew: 0.473 Prob(JB):
0.141
Kurtosis: 3.215 Cond. No.
1.39
==========================================================================
====
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is cor
rectly specified.
[Link] 20/30
6/17/25, 6:31 PM gwp1_code
82529
Model with X1, X4 3 326.861789 334.677299 0.2
76341
Model with X2, X5 3 331.760939 339.576449 0.2
40005
Model with X1, X2, X5 4 333.760859 344.181540 0.2
32089
Model with X3, X5 3 337.269269 345.084780 0.1
96967
Model with X1, X3, X5 4 338.605294 349.025975 0.1
93972
Model with X2 2 339.907807 345.118147 0.1
67424
Model with X3 2 340.708322 345.918663 0.1
60732
Model with X1, X3 3 341.783826 349.599337 0.1
59883
Model with X1, X2 3 341.867252 349.682762 0.1
59182
Model with X5 2 351.093485 356.303825 0.0
68886
Model with X1, X5 3 352.879853 360.695364 0.0
61295
Model with X1 2 358.868424 364.078765 -0.0
06396
# Standardize features
scaler = StandardScaler()
[Link] 21/30
6/17/25, 6:31 PM gwp1_code
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = [Link](X_test)
# Fit LASSO with different alpha values to see how coefficients change
alphas = [Link](-4, 1, 100)
coefs = []
[Link] 22/30
6/17/25, 6:31 PM gwp1_code
[Link](lasso.coef_)
[Link]('log')
[Link]('Alpha (Regularization Strength)')
[Link]('Coefficient Value')
[Link]('LASSO Coefficient Paths')
[Link](x=best_alpha, color='k', linestyle='--', label=f'Best Alpha:
[Link](y=0, color='gray', linestyle='--')
[Link]()
[Link](True, alpha=0.3)
plt.tight_layout()
[Link]()
==================================================
METHOD 2: MODEL SELECTION USING LASSO REGRESSION
==================================================
Best Alpha Value: 0.000829
[Link] 23/30
6/17/25, 6:31 PM gwp1_code
Comparison
Key Findings
Information Criteria (AIC/BIC) Approach
Best Model:
Both AIC and BIC selected the same optimal model: Y ~ X2 + X3 + X4 + X5.
Performance Metrics:
Adjusted R²: 0.634 (63.4% of variance explained, highest among candidates).
AIC: 260.617 (lowest, indicating better fit with parsimony).
BIC: 273.643 (lowest, favoring simpler models).
Interpretation:
X1 was excluded as it added negligible explanatory power while increasing
complexity (higher AIC/BIC when included).
The selected model balances goodness-of-fit and parsimony, aligning with CFA
best practices for model selection.
Performance Metrics:
R²: 0.349 (weaker than AIC/BIC model).
MSE: 0.6833.
Interpretation:
X1’s coefficient was near zero (-0.082), suggesting minimal impact.
Feature Importance:
X4: Strongest positive effect.
X2: Strongest negative effect.
LASSO’s inclusion of all features (despite shrinkage) hints at potential
multicollinearity or overfitting risks.
Problem 5
5c)
are Why do you
concerned think
about ain Economics
unit root and and
not,Finance
say a we
root
of 1.5?
Simulations to Illustrate the Differences:
Let's simulate both an AR(1) process with a unit root ( ) and an AR(1) process
ϕ = 1
with an explosive root ( ) to visualize their behavior. We'll use standard normal
ϕ = 1.5
white noise ( ).
Wt ∼ N (0, 1)
[Link](figsize=(12, 6))
[Link](rw_series, label='Random Walk (Unit Root, $\\phi=1$)')
[Link](explosive_series, label='Explosive Process ($\\phi=1.5$)')
[Link]('Simulated Time Series: Unit Root vs. Explosive Process')
[Link]('Time')
[Link]('Value')
[Link]()
[Link] 25/30
6/17/25, 6:31 PM gwp1_code
[Link](True)
[Link]()
Problem 6
In [32]: import numpy as np
import pandas as pd
import [Link] as sm
import [Link] as plt
from scipy import stats
[Link] 26/30
6/17/25, 6:31 PM gwp1_code
X_D = X * D
print(f"\nEstimated parameters:")
print(f"Alpha: {[Link][0]:.4f}")
print(f"Beta1 (t ≤ 10): {beta1_est:.4f}")
print(f"Beta2 (t > 10): {beta2_est:.4f}")
print(f"Change in Beta (Beta2 - Beta1): {[Link][2]:.4f}")
[Link] 27/30
6/17/25, 6:31 PM gwp1_code
plt.tight_layout()
[Link]()
[Link] 28/30
6/17/25, 6:31 PM gwp1_code
Regression Results:
OLS Regression Results
==========================================================================
====
Dep. Variable: y R-squared:
0.889
Model: OLS Adj. R-squared:
0.876
Method: Least Squares F-statistic: 6
8.26
Date: Tue, 17 Jun 2025 Prob (F-statistic): 7.52
e-09
Time: 18:28:40 Log-Likelihood: -1
3.083
No. Observations: 20 AIC: 3
2.17
Df Residuals: 17 BIC: 3
5.15
Df Model: 2
Covariance Type: nonrobust
==========================================================================
====
coef std err t P>|t| [0.025 0.
975]
--------------------------------------------------------------------------
----
const 1.8708 0.149 12.577 0.000 1.557
2.185
X 0.3873 0.219 1.771 0.094 -0.074
0.849
X_D 1.5583 0.318 4.894 0.000 0.886
2.230
==========================================================================
====
Omnibus: 1.143 Durbin-Watson:
2.142
Prob(Omnibus): 0.565 Jarque-Bera (JB):
0.678
Skew: 0.445 Prob(JB):
0.713
Kurtosis: 2.854 Cond. No.
4.28
==========================================================================
====
[Link] 29/30
6/17/25, 6:31 PM gwp1_code
Notes:
[1] Standard Errors assume that the covariance matrix of the errors is cor
rectly specified.
Estimated parameters:
Alpha: 1.8708
Beta1 (t ≤ 10): 0.3873
Beta2 (t > 10): 1.9456
Change in Beta (Beta2 - Beta1): 1.5583
[Link] 30/30