Postby **Maverick** » Mon Aug 11, 2014 2:04 pm

Hi, I have modified the fmb code to become rolling and with adjusted r square but I need to get the residuals. I have specified an equation(retvec-yhat) and added it into a matrix in the same way I did with r square but for the residual equation I get the error message " non numeric value added to matrix". The matrix is specified in the same way as the r square matrix which is 1 row and 612 columns. I have 30 stock portfolios as dependent variables and five factors as undependent variables. The time series is from january 1960 to december 2010. Can you help me to solve the problem? Below you find the whole code.

I would also appreciate if someone could confirm that the code is correct since I have not been able to replicate the gammas after the first roll.

!doGUI = 1 ' default is GUI dialog

subroutine local fmb(scalar n_p, scalar n_f, matrix rm, matrix b, scalar j, matrix g, matrix rs,matrix ls,matrix e)

' cs fama-macbeth regression

' ex: goes into a loop indexed by j

vector retvec = @transpose(@rowextract(rm, j))

matrix(n_p, n_f + 1) design = 1

matplace(design, b, 1, 2)

rowplace(g, @transpose(@inverse(@transpose(design) * design) * @transpose(design) * retvec), j)

'R-square calculations

vector yhat = (design*(@inverse(@transpose(design) * design) * @transpose(design) * retvec))

'Residuals calculation

vector e1=(retvec-yhat)

e(1,j)= e1

'R-square calculations

scalar f2 = @cor(yhat, retvec)

scalar R2 = f2*f2

Adjusted r square

scalar R2adj = (R2 - ((5/24)*(1-R2)))

rs(1,j)= R2

ls(1,j)=R2adj

endsub

subroutine checkExistence(string r, string f)

' check that returns and factors exist

if @len(@wlookup(r)) = 0 then

%error = "Error: returns '" + r + "' not in workfile"

@uiprompt(%error)

stop

endif

if @len(@wlookup(f)) = 0 then

%error = "Error: factors '" + f + "' not in workfile"

@uiprompt(%error)

stop

endif

endsub

' temp variable substitutions

%sube= @getnextname("residuals")

%subr = @getnextname("adjusted r square")

%subrsqure = @getnextname("r square")

%subrets = @getnextname("rets")

%subfacs = @getnextname("facs")

%subbhat = @getnextname("bhat")

%subbetaeq = @getnextname("betaeq")

%subretsm = @getnextname("retsm")

%subgammag = @getnextname("gammag")

%subavgretv = @getnextname("avgretv")

%subcsavg = @getnextname("csavg")

%subtemp = @getnextname("temp")

' remaining var substitutions

%subgamma = "gamma"

%subgamma = @getnextname(%subgamma) ' so gamma begins with gamma01, gamma02, etc

if @isobject(%subgamma) then

%subgamma = @getnextname(%subgamma)

endif

%subgamma_summary = "gamma_summary"

if @isobject(%subgamma_summary) then

%subgamma_summary = @getnextname(%subgamma_summary)

endif

%subcsavg = "csavg"

if @isobject(%subcsavg) then

%subcsavg = @getnextname(%subcsavg)

endif

'default options

%subresults = "results"

%action = "append"

' user options

' user has chosen to use the command line

if @len(%args) > 0 then

!doGUI = 0

endif

if !doGUI = 0 then

%retnames = %0

%factors = @wdrop(%args, %0)

' check that returns and factors exist

call checkExistence(%retnames, %factors)

' put the first argument into a group (it must be either a group or a series wildcard)

group {%subrets} {%retnames}

' put the second argument into a group (it must be a group, a series wildcard,

' or a list of series

group {%subfacs} {%factors}

if @len(@option(1)) then

!doGUI = @hasoption("prompt")

%temp = @equaloption("action")

if @len(%temp) then

%action = %temp

endif

%temp = @equaloption("spoolname")

if @len(%temp) then

%subresults = %temp

endif

'process command-line options

if %action = "REPLACE" then

if @isobject(%subresults) then

delete {%subresults}

endif

else

if %action = "NEW" then

if @isobject(%subresults) then

%subresults = @getnextname(%subresults)

endif

else

if %action <> "APPEND" then

%error = "Error: unknown action"

@uiprompt(%error)

stop

endif

endif

endif

endif

endif

' user has chosen to use the GUI

if !doGUI = 1 then

!result = @uidialog("caption", "Fama-MacBeth regression", "edit", %retnames, "List of portfolio/asset returns", "edit", %factors, "List of factor names", "edit", %subresults, "Put results into")

if !result = -1 then

stop

endif

' check that returns and factors exist

call checkExistence(%retnames, %factors)

group {%subrets} {%retnames}

group {%subfacs} {%factors}

while @isobject(%subresults)

!sel = 1

!result = @uidialog("caption", "Fama-MacBeth regression", "radio", !sel, "This object already exists. Do you want to", """Append to it"" ""Replace it"" ""Make a new object""")

if !result = -1 then

stop

endif

if !sel = 1 then

exitloop

endif

if !sel = 2 then

delete {%subresults}

endif

if !sel = 3 then

%subresults = @getnextname(%subresults)

!result = @uidialog("caption", "Fama-MacBeth regression", "edit", %subresults, "New results object")

endif

wend

endif

' set up variables

%startpage = @pagename

!num_p = @columns({%subrets})

'!len_ts = @obsrange ' changed 20131028 RE

!len_ts = @obssmpl

!num_f = @columns({%subfacs})

!window = 60

!step = 12

!length = @obsrange

' set up matrices and vectors for cs regressions

stom({%subrets}, {%subretsm})

matrix(!len_ts, !num_f + 1) {%subgamma}

'Matrix specification for r square, adjusted r square and residuals

matrix(1,612) {%subrsqure}

matrix(1,612) {%subr}

matrix(1,612) {%sube}

for !i= 1 to !length-!window+1-!step step !step

smpl @first+!i-1 @first+!i+!window-2

' calculate betas from ts regressions of portfolio/asset returns on market returns

matrix(!num_p, !num_f) {%subbhat}

matrix(1,!num_p) rs

for !k=1 to !num_p

equation {%subbetaeq}.ls {%subrets}(!k) c {%subfacs}

for !m=1 to !num_f

{%subbhat}(!k, !m) = @coefs(!m + 1)

next

close {%subbetaeq}

next

delete {%subbetaeq}

' loop through each time unit and store the results in gamma

for !h=!i+!window-1 to !i+!window-1+12

call fmb(!num_p, !num_f, {%subretsm}, {%subbhat}, !h, {%subgamma},{%subrsqure},{%subr},{%sube})

next

next

smpl @first @last

' fill in the summary table for gamma

mtos({%subgamma}, {%subgammag})

freeze({%subgamma_summary}) {%subgammag}.stats

{%subgamma_summary}.insertrow(21, 2)

setcell({%subgamma_summary}, 22, 1, " t-stat", "l")

for !i=1 to !num_f+1

{%subgamma_summary}(22, !i+1) = @val({%subgamma_summary}(6, !i+1)) _

/ (@val({%subgamma_summary}(10, !i+1)) / @sqrt(@val({%subgamma_summary}(20, !i+1))))

setcell({%subgamma_summary}, 4, !i+1, "gamma_" + @str(!i-1), "c")

next

setline({%subgamma_summary}, 23)

' what are the coefficients using average returns (for comparison)?

vector(!num_p) {%subavgretv} = @cmeans({%subretsm})

pagecreate(page={%subtemp}) u !num_p

copy {%startpage}\{%subavgretv} {%subavgretv}

mtos({%subavgretv}, avgrets)

copy {%startpage}\{%subbhat} {%subbhat}

mtos({%subbhat}, bhatg)

rename ser* beta*

group betag beta*

equation {%subcsavg}.ls(cov=hac) avgrets c betag

copy {%subcsavg} {%startpage}\{%subcsavg}

pageselect {%startpage}

' put everything together

spool {%subresults}

{%subresults}.append {%subgamma_summary}

{%subresults}.append {%subcsavg}

!sp_num = {%subresults}.@count

!run_num = !sp_num / 2

%last_unt = {%subresults}.@objname(!sp_num)

%penl_unt = {%subresults}.@objname(!sp_num - 1)

%last_nme = "csavg_" + @str(!run_num)

%penl_nme = "gamma_summary_" + @str(!run_num)

%last_dsp = "CS Average Regression " + @str(!run_num)

%penl_dsp = "Gamma Summary " + @str(!run_num)

%last_cmt = " Returns: " + %retnames + "\n Factors: " + %factors

%penl_cmt = " Returns: " + %retnames + "\n Factors: " + %factors

{%subresults}.name %penl_unt %penl_nme

{%subresults}.name %last_unt %last_nme

{%subresults}.displayname %penl_nme %penl_dsp

{%subresults}.displayname %last_nme %last_dsp

{%subresults}.comment %penl_nme %penl_cmt

{%subresults}.comment %last_nme %last_cmt

{%subresults}.options titles displaynames comments

{%subresults}.display

' display the matrix of betas from ts regressions (added 20141630 RE)

{%subbhat}.displayname Betas from timeseries regressions

' clean up the wf

pagedelete {%subtemp}

delete {%subretsm}

'delete {%subbhat}

%ggser = {%subgammag}.@members

delete {%ggser}

delete {%subgammag}

delete {%subrets}

delete {%subfacs}

delete {%subavgretv}

delete {%subcsavg}

delete {%subgamma_summary}