Basic Data Exploration Model seasonal patterns
stata Create interaction terms for differential effects
* View first 10 observations CREATING DUMMY VARIABLES
list in 1/10 Method 1: Manual Creation
stata
* View dataset structure * Binary dummy (Female = 1, Male = 0)
describe gen female = (gender == "F" | gender == 2)
* Summary statistics * Multiple categories
summarize gen north = (region == 1)
sum var1 var2 var3, detail gen south = (region == 2)
gen east = (region == 3) // west is base (region == 4)
* Check for missing values
misstable summarize * Time-based dummies
gen post2008 = (year > 2008)
* Frequency tables gen recession = (year >= 2008 & year <= 2009)
tabulate category_var
tabulate var1 var2 * Seasonal dummies
Creating and Modifying Variables gen Q2 = (quarter == 2)
stata gen Q3 = (quarter == 3)
* Create new variables gen Q4 = (quarter == 4) // Q1 is base
gen ln_gdp = log(gdp)
gen gdp_sq = gdp^2 * Interaction dummies
gen growth = (gdp - [Link])/[Link] * 100 gen fem_edu = female * education
Method 2: Using Factor Variables (Recommended)
* Generate time variables stata
gen year = year(datevar) * i. prefix automatically creates dummies
gen month = month(datevar) regress wage [Link] education
gen quarter = quarter(datevar)
* Multiple categories
* Label variables regress wage [Link] education
label variable ln_gdp "Log of GDP"
label variable growth "GDP Growth Rate (%)" * Interactions
regress wage [Link]##[Link] // includes
* Create value labels female, education, and interaction
label define gender 1 "Male" 2 "Female"
label values gender gender * Time dummies
regress sales [Link] [Link]
2. DUMMY VARIABLES: CREATION, USAGE, Method 3: Using xi Prefix (Legacy)
INTERPRETATION stata
WHEN and WHY Create Dummy Variables xi: regress wage [Link] i.educ_level
When to use: DUMMY VARIABLE MODELS & INTERPRETATION
1. Categorical variables with no inherent ordering Model 1: ANOVA (All Dummies)
(gender, region, race) stata
2. Time periods (pre/post policy, seasons, quarters) * Test if region affects income
3. Group comparisons (treatment vs control) regress income [Link]
4. Structural breaks (regime changes, crises) Interpretation:
5. Interaction effects (different slopes for different _cons: Mean income for base region (region 1)
groups) [Link]: Difference between region 2 and region 1
Why use them: [Link]: Difference between region 3 and region 1
Allow different intercepts for different groups t-test for each coefficient tests if that region differs
Test for structural differences from base
Control for unobserved heterogeneity (in panel data) Model 2: ANCOVA (Mixed Variables)
stata ARCH (Autoregressive Conditional
* Wage with gender dummy and continuous Heteroscedasticity): Volatility depends on past
education squared errors
regress wage female education GARCH: Volatility depends on past volatility and past
Interpretation: squared errors
_cons: Predicted wage for male with 0 education Used for: Financial time series, volatility clustering,
female: Wage difference between female and male risk modeling
(same education) Testing for ARCH Effects
education: Effect of one more year of education (for stata
both genders) * Step 1: Run OLS regression
Model 3: Interaction Model (Slope Dummy) regress returns market_returns
stata
* Different returns to education by gender * Step 2: Save residuals
regress wage female education fem_edu predict resid, residuals
* OR using factor notation:
regress wage [Link]##[Link] * Step 3: Test for ARCH effects
Interpretation: * Engle's ARCH test
For males (female=0): wage = β₀ + β₂*education estat archlm, lags(1/5)
For females (female=1): wage = (β₀+β₁) +
(β₂+β₃)*education * LM test for ARCH
β₁: Difference in intercepts regress resid2 L.resid2 L2.resid2 L3.resid2
β₃: Difference in slopes (returns to education) test L.resid2 L2.resid2 L3.resid2
Model 4: Chow Test via Dummies ARCH(1) Model
stata stata
* Test if 2008 financial crisis changed relationship arch returns market_returns, arch(1)
gen crisis = (year >= 2008) Interpretation:
gen crisis_edu = crisis * education Equation 1: Mean equation (returns = α +
regress wage education crisis crisis_edu β*market_returns)
Equation 2: Variance equation (σ²ₜ = ω + α₁*ε²ₜ₋₁)
* Test joint significance α₁ significant → ARCH effects present
test crisis crisis_edu α₁ > 0 → volatility clustering
Chow Test Result: GARCH(1,1) Model (Most Common)
F-statistic > critical value → reject H₀ (structural stata
change) arch returns market_returns, arch(1) garch(1)
p-value < 0.05 → significant structural break * OR simply:
arch returns market_returns, garch(1,1)
3. TIME SERIES ANALYSIS: ARCH/GARCH MODELS Interpretation:
Setting Time Series Data Mean equation: returns = α + β*market_returns
stata Variance equation: σ²ₜ = ω + α₁ε²ₜ₋₁ + β₁σ²ₜ₋₁
* Declare time series α₁ + β₁ measures persistence of volatility shocks
tsset datevar // for daily If α₁ + β₁ ≈ 1 → volatility shocks persistent
tsset year // for annual If α₁ + β₁ > 1 → IGARCH (integrated GARCH)
tsset year quarter // for quarterly GARCH with Different Distributions
stata
* Generate time variables * Normal distribution (default)
gen time = _n // sequence number arch returns market_returns, garch(1,1)
tsset time
* Student's t-distribution (fatter tails)
* Check for gaps arch returns market_returns, garch(1,1)
tsset, noquery distribution(t)
tsreport, report
ARCH/GARCH Models * Generalized error distribution (GED)
What are ARCH/GARCH?
arch returns market_returns, garch(1,1)
distribution(ged) * Save results
EGARCH Model (Exponential GARCH) estimates store model1
stata
arch returns market_returns, earch(1) egarch(1) * Goodness of fit
Advantages: estat ic // AIC, BIC
Captures asymmetric effects (bad news increases
volatility more than good news) * Residual analysis
No parameter restrictions (variance always positive) predict res1, residuals
TGARCH Model (Threshold GARCH) predict yhat1, xb
stata
arch returns market_returns, arch(1) garch(1) * Plot residuals vs fitted
tarch(1) rvfplot, yline(0)
Captures: Leverage effect (negative shocks increase STEP 3: Multiple Regression (Chapter 7)
volatility more) stata
Forecasting with GARCH * Multiple regression
stata regress income education experience age [Link]
* Estimate model
arch returns market_returns, garch(1,1) * Check multicollinearity
vif
* Static forecast (in-sample) estat vif
predict yhat, xb // conditional mean
predict variance, variance // conditional variance * Test joint significance
predict residuals, residuals test education experience age
* Dynamic forecast (out-of-sample) * Test linear restriction
tsappend, add(12) // add 12 periods test education + experience = 0.5
arch returns market_returns, garch(1,1) STEP 4: Dummy Variables (Chapter 9)
predict yhat_dynamic, xb dynamic(tm(1)) stata
* Create and use dummies
4. COMPLETE WORKFLOW: CHAPTER 3 TO 22 gen female = (gender == 2)
Step-by-Step Analysis Pipeline gen manager = (position == "Manager")
STEP 1: Data Preparation
stata * Model with dummies
* Load data regress income female education experience
use "C:/econometrics/[Link]", clear [Link]
* Check and clean * Interaction effects
describe regress income [Link]##[Link] experience
summarize
misstable summarize * Marginal effects
margins female, at(education=(10 12 16))
* Handle missing values marginsplot
mvdecode _all, mv(-999) STEP 5: Diagnostics (Chapters 10-13)
drop if missing(income, education) stata
* Heteroscedasticity tests
* Create necessary variables estat hettest // Breusch-Pagan
gen ln_income = log(income) estat imtest, white // White test
gen exp_sq = experience^2
STEP 2: Basic Regression (Chapter 3) * Autocorrelation tests
stata dwstat // Durbin-Watson
* Simple regression estat bgodfrey, lags(1/4) // Breusch-Godfrey
regress income education
* Normality test stata
predict res, residuals * Declare panel data
sktest res // Skewness-kurtosis xtset id year
histogram res, normal // Visual check
* Fixed effects
* Specification tests xtreg income education experience, fe
estat ovtest // RESET test estimates store fe
linktest // Link test
* Random effects
* Outlier detection xtreg income education experience, re
predict rstu, rstudent estimates store re
list if abs(rstu) > 2.5
* Hausman test
* Influence statistics hausman fe re
predict cooksd, cooksd
dfbeta * Test for time effects
STEP 6: Remedies for Problems xtreg income education experience [Link], fe
stata testparm [Link]
* For heteroscedasticity STEP 9: Time Series (Chapters 21-22)
regress income education experience, robust // stata
Robust SEs * Stationarity tests
dfuller gdp // ADF test
* For autocorrelation pperron gdp // Phillips-Perron
newey income education experience, lag(1) //
Newey-West * If non-stationary, difference
prais income education experience // Prais-Winsten gen d_gdp = [Link]
dfuller d_gdp
* For multicollinearity
* Option 1: Drop correlated variable * Cointegration test (Engle-Granger)
* Option 2: Use PCA regress consumption gdp
pca education experience age predict e, residuals
predict pc1 pc2 pc3 dfuller e // Test residuals
regress income pc1 pc2
* VAR model
* For outliers var consumption gdp investment, lag(1/4)
* Winsorize extreme values vargranger // Granger causality
winsor2 income, cuts(1 99) replace irf create myirf, step(20) // Impulse response
STEP 7: Qualitative Models (Chapter 15) irf graph irf
stata
* Logistic regression * Forecasting
logit employed education experience age [Link] arima gdp, arima(1,1,1)
predict gdp_forecast, dynamic(tm(1))
* Marginal effects STEP 10: ARCH/GARCH (Chapter 22)
margins, dydx(*) // average marginal effects stata
margins, at(education=12) // at specific values * Test for ARCH effects
regress returns
* Predicted probabilities estat archlm, lags(1/5)
predict prob, pr
list prob in 1/10 * Estimate GARCH
arch returns, arch(1) garch(1)
* ROC curve
lroc * Forecast volatility
STEP 8: Panel Data (Chapter 16) predict condvar, variance
tsline condvar // Plot conditional variance
5. INTERPRETATION GUIDE FOR OUTPUT
Regression Output Interpretation
stata
regress wage education experience female
Output Example:
text
Interpretation:
1. Mean equation: Average daily return = 0.1%
2. Variance equation: σ²ₜ = 0.0001 + 0.15*ε²ₜ₋₁ +
0.80*σ²ₜ₋₁
3. ARCH(1) effect: Past squared shocks increase
volatility (α₁=0.15)
4. GARCH(1) effect: Volatility persists (β₁=0.80)
Interpretation:
5. Persistence: α₁+β₁=0.95 → shocks die out slowly
1. education: Each additional year of education
6. Long-run variance: ω/(1-α₁-β₁) = 0.0001/0.05 = 0.002
increases wage by $2.50/hour, holding experience
and gender constant (t=12.5, p<0.001, significant)
6. COMMON PITFALLS AND SOLUTIONS
2. experience: Each additional year of experience
Dummy Variable Trap
increases wage by $1.20/hour
Problem: Including all categories + constant
3. female: Females earn $0.80/hour less than males
Solution: Omit one category or drop constant
with same education and experience
stata
4. _cons: Male with 0 education and 0 experience
* WRONG:
earns $10/hour
reg y [Link] // includes constant AND all regions
5. R-squared: 65% of wage variation explained by
model
* RIGHT:
Logit/Probit Output Interpretation
reg y [Link], noconstant // no constant, all
stata
dummies
logit employed education experience
* OR:
margins, dydx(*)
reg y [Link] // set region 2 as base
Interpretation:
Interaction Terms Interpretation
Logit coefficients are log-odds ratios
Problem: Interpreting main effects when interaction
Marginal effects show change in probability for unit
present
change in X
Solution: Main effects are effects when other
e^coefficient = odds ratio (if coefficient=0.7, odds
variable = 0
ratio=2.01 → doubling of odds)
stata
reg y female education fem_edu
GARCH Output Interpretation
* education effect is for males only (female=0)
stata
* Use margins command for correct interpretation
arch returns, garch(1,1)
GARCH Convergence Issues
Problem: Model won't converge
Solution:
stata
* Provide starting values
arch returns, arch(1) garch(1) from(0.1 0.1 0.8)
Interpretation:
text
* Try different algorithms
arch returns, arch(1) garch(1) technique(nr)
arch returns, arch(1) garch(1) technique(bfgs)
* Simplify model
arch returns, arch(1) // ARCH only first * 5. BASIC REGRESSION
Missing Standard Errors in Logit/Probit regress ln_y x female post
Problem: Perfect prediction estimates store baseline
Solution:
stata * 6. DIAGNOSTICS
* Check for separation * Heteroscedasticity
logit y x1 x2 x3, asis estat hettest
estat imtest, white
* Use penalized logit
firthlogit y x1 x2 x3 // if installed * Autocorrelation
dwstat
7. AUTOMATION SCRIPTS estat bgodfrey, lags(1/4)
Complete Analysis Do-File
stata * Multicollinearity
* vif
===========================================
= * 7. ROBUST REGRESSION
* COMPLETE ECONOMETRICS ANALYSIS regress ln_y x female post, robust
* estimates store robust
===========================================
= * 8. MODEL COMPARISON
estimates table baseline robust, star stats(N r2 r2_a)
version 17
clear all * 9. MARGINAL EFFECTS
set more off margins, dydx(*) atmeans
capture log close margins female, at(x=(1(1)10))
log using "[Link]", replace marginsplot
* 1. LOAD DATA * 10. FORECASTING
use "[Link]", clear predict yhat, xb
predict se, stdp
* 2. DATA CLEANING gen ub = yhat + 1.96*se
describe gen lb = yhat - 1.96*se
summarize
misstable summarize * 11. SAVE RESULTS
estimates save "[Link]", replace
* Handle missing save "analysis_data.dta", replace
mvdecode _all, mv(-999 -888 .a .b .c)
drop if missing(keyvar1, keyvar2) * 12. CREATE TABLE
esttab baseline robust using "[Link]", ///
* 3. CREATE VARIABLES replace b(3) se(3) star(* 0.10 ** 0.05 *** 0.01) ///
gen ln_y = log(y) stats(N r2 r2_a, fmt(0 3 3))
gen x_sq = x^2
gen time = _n log close
* Dummies 8. QUICK REFERENCE: MOST USED COMMANDS
gen post = (year > 2010) Top 20 Essential Commands
gen female = (gender == 2) 1. regress - OLS regression
2. logit/probit - Binary choice models
* 4. DESCRIPTIVE STATISTICS 3. xtreg - Panel data models
summarize ln_y x female post, detail 4. arch - ARCH/GARCH models
tabstat ln_y x, by(female) stat(mean sd n) 5. predict - Predictions after estimation
6. test - Hypothesis tests
7. margins - Marginal effects
8. vif - Multicollinearity check
9. estat hettest - Heteroscedasticity test
10. dwstat - Durbin-Watson test
11. dfuller - Unit root test
12. var - VAR models
13. arima - ARIMA models
14. summarize - Descriptive stats
15. tabulate - Frequency tables
16. correlate - Correlation matrix
17. graph - Create graphs
18. save - Save data
19. use - Load data
20. do - Run do-file
Key Shortcuts
Ctrl+D - Execute selection
Ctrl+9 - Open do-file editor
Ctrl+1 - Command window
Ctrl+4 - Results window
Ctrl+8 - Variables window
Page Up - Previous command
Tab - Auto-complete