Announcement

Collapse
No announcement yet.
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Portfolio variance calculations using mata

    Dear Users,

    I am using STATA 17.0. I am trying to calculate firm portfolio variance based on the demand growth (return) in the set of countries where these firms have affiliates weighted by sales share (weights). I have data for share of sales for each destination as weight of that destination (w_DEST), and growth rate demand of that destination (g_DEST). My data looks as follow:
    Code:
    * Example generated by -dataex-. For more info, type help dataex
    clear
    input long tk_code float(year w_CHN w_IND w_USA g_CHN g_IND g_USA)
    10000016 2017          . . .18852627         . . .027771465
    10000016 2018          . .  .2161741         . . .030423343
    10000065 2010 .010309427 .         . .12010965 .          .
    10000065 2011  .01036901 .         . .07751633 .          .
    10000065 2012  .01096339 .         . .07946409 .          .
    end
    where tk_code is my firm_id.
    I found a mata code written by Abraham Wolde-Tsadick as an answer for a similar questions. Link to that thread (https://www.statalist.org/forums/for...folio-variance).
    The code I implement is as follow:
    Code:
     
    
    . egen fy = group(tk_code year)
    
    . 
    . gen VAR = .
    . 
    . mata
    ------------------------------------------------- mata (type end to exit) -----------------
    : 
    : mata clear
    
    : 
    : st_view(wt=.,.,tokens("w_ARE - w_ZWE"))
    
    : 
    : st_view(ex=.,.,tokens("g_ARE - g_ZWE"))
    
    : 
    : st_view(year=.,.,"year")
    
    : 
    : st_view(VAR=.,.,"VAR")
    
    : 
    : st_view(fy=.,.,"fy")
    
    : 
    : p = panelsetup(fy, 1)
    
    : 
    :
    : 
    : for (i=1; i<=rows(p); i++) {
    > 
    >     r1 = p[i,1]
    > 
    >     r2 = p[i,2]
    > 
    >     w = select(wt[r1..r2,.],  colsum(wt[r1..r2,.]:!=.) :== rows(wt[r1..r2,.])   )
    > 
    >     w = mean(w)
    > 
    >     s = select(ex[r1..r2,.],  colsum(ex[r1..r2,.]:!=.) :== rows(ex[r1..r2,.])   )
    > 
    >     s = (s :- mean(s))'(s :- mean(s)) :/ ( rows(s) - 1)
    > 
    >     VAR[r1..r2,1] = (w*s*w') * J(r2-r1+1,1,1)
    > 
    > }
    
    : 
    : end
    The code executes without any errors, but the VAR variable does not change. It still retains all the missing values.
    I have two questions:
    1) What is wrong with my mata code?
    2) In addition to calculation variance, I would like to calculate covariance matrix for a form portfolio depending on the set of countries for each year. How would that be possible?

    Thank you very much for your support and guidance in advance.
    I am relatively new to Statalist so apologies in advance, and your support is very much appreciated.
Working...
X