Portfolio Standard Deviation with Matrix in Stata



Finding portfolio standard deviation under the Modern Portfolio theory using matrix algebra requires three matrices
1. Weights of the assets in portfolio, in row format = W
2. Variance-Covariance matrix of assets returns = S
3. Weights of the assets in portfolio, in column format = W'

Portfolio SD = W * S * W'

NOTE: In order to find the variance-covariance matrix, you can install varrets program from ssc with: 

ssc install mvport

I have written the following code to:
(1) make dummy data for 4 stocks with returns ri1 ri2 ri3 ri4
(2) assign each stock equal weight of .25 with names w1 w2 w3 w4 and assign them to matrix W
(3) Find port standard deviation in each year and write the results to file SD.dta in the user current directory

Copy and paste the following code in Stata do editor and run

Note: You need Stata 12.1 or above for using varrets program

//Create Dummy Data
clear
set obs 1000
gen date=_n
format %td date
expand 10
bys date: gen id=_n
gen year = year(date)
gen ri1 = uniform()
gen ri2 = uniform()
gen ri3 = uniform()
gen ri4 = uniform()
gen W1 = .25
gen W2 = .25
gen W3 = .25
gen W4 = .25

//Now Portfolio SD
qui sum year
loc MAX = r(max)
loc MIN = r(min)
forval i = `MIN' / `MAX' {

        //To make variance-covariance matrix from stock returns
varrets ri1 ri2 ri3 ri4 if year==`i'

      //To write covariance matrix to matrix S
mat S = r(cov)
      
      //To make matrix W from variable W1 W2 W3 W4
mkmat W1 W2 W3 W4 in 1, matrix (W)

      //Write portfolio variance to matrix VAR
mat VAR = W*S*W'

      //Write VAR matrix to variable VAR
svmat double VAR, name(VAR)
preserve
keep year VAR1
drop if VAR1==.
replace year = `i'
if year==`MIN' {
save SD, replace
}

      else {
    append using SD.dta
    save SD.dta, replace
      }
restore
cap drop VAR1
}