library(dynlm);library(lmtest)data(barium, package='wooldridge')# Define monthly time series beginning in Feb. 1978tsdata <-ts(barium, start=c(1978,2), frequency=12)res <-dynlm(log(chnimp) ~log(chempi)+log(gas)+log(rtwex)+befile6+ affile6+afdec6+season(tsdata) , data=tsdata )coeftest(res)
Example-10-2.R
data(intdef, package='wooldridge')# Linear regression of static model:summary( lm(i3~inf+def,data=intdef) )
Example-10-4-contd.R
# Calculating the LRPb<-coef(res)b["pe"]+b["L(pe)"]+b["L(pe, 2)"]# F test. H0: LRP=0linearHypothesis(res,"pe + L(pe) + L(pe, 2) = 0")
Example-10-4.R
# Libraries for dynamic lm, regression table and F testslibrary(dynlm);library(lmtest);library(car)data(fertil3, package='wooldridge')# Define Yearly time series beginning in 1913tsdata <-ts(fertil3, start=1913)# Linear regression of model with lags:res <-dynlm(gfr ~ pe +L(pe) +L(pe,2) + ww2 + pill, data=tsdata)coeftest(res)# F test. H0: all pe coefficients are=0linearHypothesis(res, matchCoefs(res,"pe"))
Example-10-7.R
library(dynlm);library(stargazer)data(hseinv, package='wooldridge')# Define Yearly time series beginning in 1947tsdata <-ts(hseinv, start=1947)# Linear regression of model with lags:res1 <-dynlm(log(invpc) ~log(price) , data=tsdata)res2 <-dynlm(log(invpc) ~log(price) +trend(tsdata), data=tsdata)# Pretty regression tablestargazer(res1,res2, type="text")
Example-Barium.R
data(barium, package='wooldridge')# Imports from China: Variable "chnimp" from data frame "data"# Monthly time series starting Feb. 1978impts <-ts(barium$chnimp, start=c(1978,2), frequency=12)# plot time seriesplot(impts)
Example-quantmod.R
library(quantmod)# Which Yahoo Finance symbols? # See http://finance.yahoo.com/lookup:# "F" = Ford Motor Company# Download datagetSymbols("F", auto.assign=TRUE)# first and last 6 rows of resulting data frame:head(F)tail(F)# Time series plot of adjusted closing prices:plot(F$F.Adjusted, las=2)
Example-zoo.R
data(intdef, package='wooldridge')# Variable "year" as the time measure:intdef$year# define "zoo" object containing all data, time measure=year:library(zoo)zoodata <-zoo(intdef, order.by=intdef$year)# Time series plot of inflationplot(zoodata$i3)
Example-10-11.py
import wooldridge as wooimport numpy as npimport pandas as pdimport statsmodels.formula.api as smfbarium = woo.dataWoo('barium')# linear regression with seasonal effects:reg = smf.ols(formula='np.log(chnimp) ~ np.log(chempi) + np.log(gas) +''np.log(rtwex) + befile6 + affile6 + afdec6 +''feb + mar + apr + may + jun + jul +''aug + sep + oct + nov + dec', data=barium)results = reg.fit()# print regression table:table = pd.DataFrame({'b': round(results.params, 4),'se': round(results.bse, 4),'t': round(results.tvalues, 4),'pval': round(results.pvalues, 4)})print(f'table: \n{table}\n')
Example-10-2.py
import wooldridge as wooimport pandas as pdimport statsmodels.formula.api as smfintdef = woo.dataWoo('intdef')# linear regression of static model (Q function avoids conflicts with keywords):reg = smf.ols(formula='i3 ~ Q("inf") + Q("def")', data=intdef)results = reg.fit()# print regression table:table = pd.DataFrame({'b': round(results.params, 4),'se': round(results.bse, 4),'t': round(results.tvalues, 4),'pval': round(results.pvalues, 4)})print(f'table: \n{table}\n')
Example-10-4-cont.py
import wooldridge as wooimport pandas as pdimport statsmodels.formula.api as smffertil3 = woo.dataWoo('fertil3')T =len(fertil3)# define yearly time series beginning in 1913:fertil3.index = pd.date_range(start='1913', periods=T, freq='Y').year# add all lags of 'pe' up to order 2:fertil3['pe_lag1'] = fertil3['pe'].shift(1)fertil3['pe_lag2'] = fertil3['pe'].shift(2)# linear regression of model with lags:reg = smf.ols(formula='gfr ~ pe + pe_lag1 + pe_lag2 + ww2 + pill', data=fertil3)results = reg.fit()# F test (H0: all pe coefficients are=0):hypotheses1 = ['pe = 0', 'pe_lag1 = 0', 'pe_lag2 = 0']ftest1 = results.f_test(hypotheses1)fstat1 = ftest1.statistic[0][0]fpval1 = ftest1.pvalueprint(f'fstat1: {fstat1}\n')print(f'fpval1: {fpval1}\n')# calculating the LRP:b = results.paramsb_pe_tot = b['pe'] + b['pe_lag1'] + b['pe_lag2']print(f'b_pe_tot: {b_pe_tot}\n')# F test (H0: LRP=0):hypotheses2 = ['pe + pe_lag1 + pe_lag2 = 0']ftest2 = results.f_test(hypotheses2)fstat2 = ftest2.statistic[0][0]fpval2 = ftest2.pvalueprint(f'fstat2: {fstat2}\n')print(f'fpval2: {fpval2}\n')
Example-10-4.py
import wooldridge as wooimport pandas as pdimport statsmodels.formula.api as smffertil3 = woo.dataWoo('fertil3')T =len(fertil3)# define yearly time series beginning in 1913:fertil3.index = pd.date_range(start='1913', periods=T, freq='Y').year# add all lags of 'pe' up to order 2:fertil3['pe_lag1'] = fertil3['pe'].shift(1)fertil3['pe_lag2'] = fertil3['pe'].shift(2)# linear regression of model with lags:reg = smf.ols(formula='gfr ~ pe + pe_lag1 + pe_lag2 + ww2 + pill', data=fertil3)results = reg.fit()# print regression table:table = pd.DataFrame({'b': round(results.params, 4),'se': round(results.bse, 4),'t': round(results.tvalues, 4),'pval': round(results.pvalues, 4)})print(f'table: \n{table}\n')
Example-10-7.py
import wooldridge as wooimport numpy as npimport pandas as pdimport statsmodels.formula.api as smfhseinv = woo.dataWoo('hseinv')# linear regression without time trend:reg_wot = smf.ols(formula='np.log(invpc) ~ np.log(price)', data=hseinv)results_wot = reg_wot.fit()# print regression table:table_wot = pd.DataFrame({'b': round(results_wot.params, 4),'se': round(results_wot.bse, 4),'t': round(results_wot.tvalues, 4),'pval': round(results_wot.pvalues, 4)})print(f'table_wot: \n{table_wot}\n')# linear regression with time trend (data set includes a time variable t):reg_wt = smf.ols(formula='np.log(invpc) ~ np.log(price) + t', data=hseinv)results_wt = reg_wt.fit()# print regression table:table_wt = pd.DataFrame({'b': round(results_wt.params, 4),'se': round(results_wt.bse, 4),'t': round(results_wt.tvalues, 4),'pval': round(results_wt.pvalues, 4)})print(f'table_wt: \n{table_wt}\n')
Example-Barium.py
import wooldridge as wooimport pandas as pdimport matplotlib.pyplot as pltbarium = woo.dataWoo('barium')T =len(barium)# monthly time series starting Feb. 1978:barium.index = pd.date_range(start='1978-02', periods=T, freq='M')print(f'barium["chnimp"].head(): \n{barium["chnimp"].head()}\n')# plot chnimp (default: index on the x-axis):plt.plot('chnimp', data=barium, color='black', linestyle='-')plt.ylabel('chnimp')plt.xlabel('time')plt.savefig('PyGraphs/Example-Barium.pdf')
Example-StockData.py
import pandas_datareader as pdrimport matplotlib.pyplot as plt# download data for 'F' (= Ford Motor Company) and define start and end:tickers = ['F']start_date ='2014-01-01'end_date ='2015-12-31'# use pandas_datareader for the import:F_data = pdr.data.DataReader(tickers, 'yahoo', start_date, end_date)# look at imported data:print(f'F_data.head(): \n{F_data.head()}\n')print(f'F_data.tail(): \n{F_data.tail()}\n')# time series plot of adjusted closing prices:plt.plot('Close', data=F_data, color='black', linestyle='-')plt.ylabel('Ford Close Price')plt.xlabel('time')plt.savefig('PyGraphs/Example-StockData.pdf')
Example-10-11.jl
usingWooldridgeDatasets, GLM, DataFramesbarium =DataFrame(wooldridge("barium"))# linear regression with seasonal effects:reg =lm(@formula(log(chnimp) ~log(chempi) +log(gas) +log(rtwex) + befile6 + affile6 + afdec6 + feb + mar + apr + may + jun + jul + aug + sep + oct + nov + dec), barium)table_reg =coeftable(reg)println("table_reg: \n$table_reg")
Example-10-2.jl
usingWooldridgeDatasets, GLM, DataFramesintdef =DataFrame(wooldridge("intdef"))# linear regression of static model:reg =lm(@formula(i3 ~ inf + def), intdef)table_reg =coeftable(reg)println("table_reg: \n$table_reg")
Example-10-4-cont.jl
usingWooldridgeDatasets, GLM, DataFrames, Distributionsfertil3 =DataFrame(wooldridge("fertil3"))# add all lags of pe up to order 2:fertil3.pe_lag1 =lag(fertil3.pe, 1)fertil3.pe_lag2 =lag(fertil3.pe, 2)# handle missings due to lagged data manually (important for ftest):fertil3 = fertil3[Not([1, 2]), :]# linear regression of model with lags:reg_ur =lm(@formula(gfr ~ pe + pe_lag1 + pe_lag2 + ww2 + pill), fertil3)# F test (H0: all pe coefficients are zero):reg_r =lm(@formula(gfr ~ ww2 + pill), fertil3)ftest_res =ftest(reg_r.model, reg_ur.model)fstat = ftest_res.fstat[2]fpval = ftest_res.pval[2]println("fstat = $fstat\n")println("fpval = $fpval\n")# calculating the LRP:b_pe_tot =sum(coef(reg_ur)[[2, 3, 4]])println("b_pe_tot = $b_pe_tot\n")# testing LRP=0:fertil3.ptm1pt = fertil3.pe_lag1 - fertil3.pefertil3.ptm2pt = fertil3.pe_lag2 - fertil3.pereg_LRP =lm(@formula(gfr ~ pe + ptm1pt + ptm2pt + ww2 + pill), fertil3)table_res_LRP =coeftable(reg_LRP)println("table_res_LRP: \n$table_res_LRP")
Example-10-4.jl
usingWooldridgeDatasets, GLM, DataFramesfertil3 =DataFrame(wooldridge("fertil3"))# add all lags of pe up to order 2:fertil3.pe_lag1 =lag(fertil3.pe, 1)fertil3.pe_lag2 =lag(fertil3.pe, 2)# linear regression of model with lags:reg =lm(@formula(gfr ~ pe + pe_lag1 + pe_lag2 + ww2 + pill), fertil3)table_reg =coeftable(reg)println("table_reg: \n$table_reg")
Example-10-7.jl
usingWooldridgeDatasets, GLM, DataFrameshseinv =DataFrame(wooldridge("hseinv"))# linear regression without time trend:reg_wot =lm(@formula(log(invpc) ~log(price)), hseinv)table_reg_wot =coeftable(reg_wot)println("table_reg_wot: \n$table_reg_wot\n")# linear regression with time trend (data set includes a time variable t):reg_wt =lm(@formula(log(invpc) ~log(price) + t), hseinv)table_reg_wt =coeftable(reg_wt)println("table_reg_wt: \n$table_reg_wt")
usingDataFrames, Dates, MarketData, Plots# download data for "F" (= Ford Motor Company) and define start and end:ticker ="F"start_date =DateTime(2014, 1, 1)end_date =DateTime(2016, 1, 1)# import data:F_data =yahoo(ticker, YahooOpt(period1=start_date, period2=end_date))# look at imported data:F_data_head =first(DataFrame(F_data), 5)println("F_data_head: \n$F_data_head\n")F_data_tail =last(DataFrame(F_data), 5)println("F_data_tail: \n$F_data_tail")# time series plot of adjusted closing prices:plot(F_data.AdjClose, legend=false, color="grey")ylabel!("AdjClose")savefig("JlGraphs/Example-StockData.pdf")