# Chapter 34: Causal Machine Learning and Double Machine Learning
# Fundamentals of Python for Financial Econometrics - Causal Machine Learning and Double Machine Learning
# Dataset: Ceteris Lab teaching sample

# Chapter 34: Causal Machine Learning and Double Machine Learning
# **Economic question:** How can flexible prediction tools help estimate causal parameters without replacing identification assumptions?
#
# Double machine learning uses prediction to remove nuisance structure while protecting a low-dimensional causal target through orthogonalization.

# %% Cell 2
import numpy as np, statsmodels.api as sm
from sklearn.ensemble import RandomForestRegressor
rng=np.random.default_rng(34); Z=rng.normal(size=(1000,6)); d=Z[:,0]-Z[:,1]+rng.normal(size=1000); y=2*d+Z[:,0]+.5*Z[:,2]+rng.normal(size=1000)
md=RandomForestRegressor(n_estimators=200,random_state=1,min_samples_leaf=10).fit(Z,d); my=RandomForestRegressor(n_estimators=200,random_state=2,min_samples_leaf=10).fit(Z,y)
rd=d-md.predict(Z); ry=y-my.predict(Z); print(sm.OLS(ry,sm.add_constant(rd)).fit().params[1])

# Interpretation checklist
# - State the unit of observation and units of every variable.
# - Separate association, prediction, and causation.
# - Report magnitude and uncertainty.
# - Identify the most important threat to validity.
