Mean Variance Optimal Portfolio

Hello, I have n risky assets and no risk free asset and risk aversion parameter is 4(gamma). I want to use mean-variance criteria to compute optimal portfolio weights. From historical data, I have expected return data or data matrix on n risky assets, r = […] (r is a two dimensional Python array where each row represents an asset and column represents net returns). I also estimated mu and variance-co-variance matrix sigma from historical data. I would like to convert my python code to Julia code to compute the mean, variance and optimal portfolio weights. Can anyone please suggest me how can I write it on Julia. Here I have Python code.

gamma=4
n=r.shape[1]
mu=r[:,0:n].mean
sigma=cov[r:,0:n]
onematrix=ones(n)
numer1=dot(onematrix.transpose(),inv(sigma))
numer2=dot(numer1,mu)-gamma
denominator=dot(numer1,onematrix)
numer3=dot(numer2,inv(denominator))
result=mu-numer3
weight=(1.0/gamma)*dot(inv(sigma),result)
return weight

I you are a new user, you should probably make an effort to learn the language. The example about should be very straightforward to translate to Julia. See, in particular, algebra and arrays.

(is this homework?)

No, its not homework. Just have been trying to practice few of my R and Python work into Julia. So here what I have tried on Julia:
gamma=4,
n=length[:,1:end]
mu=mean(r[:,1:end])
sigma=r[:,1:end]
onematrix=ones(n)
numer1=transpose(onematrix).*inv(sigma))
numer2=numer1.*mu-gamma
denominator=numer1.*onematrix
numer3=numer2.*inv(denominator))
result=mu-numer3
weight=(1.0/gamma)*inv(sigma)*result
println( weight)

You may get better help if you post a self-contained minimal working example that highlights where you got stuck. The above code is not that, but a couple of comments:

  1. length may denote a variable, but it is also a function in Julia, use something like lengths or len (cf c(...) in R). Or did you mean length(...)?
  2. You can use ' for transpose.
  3. You can use Greek letters (try typing \mu and press TAB), your code will be much more compact.
  4. If n is an integer, ones(n) will give you a vector of 1.0s. Use I for the identity matrix.

Also, please delimit your code with ```julia … ```.

I can’t run that example because I do not know what any of the variables are. Please give a full example otherwise we can’t help. One thing I do see is that mu=mean(r[:,1:end] had a syntax error because it’s missing a ). Since you didn’t describe what your error is, I assume that might be it?

Hi,

“chapter” 3 of these (fairly easy) tutorials shows one way of doing these calculations:

https://github.com/PaulSoderlind/FinancialTheoryMSc

/Paul S

5 Likes

Prof. Soderlind, thank you so much. Your web site is a great resource for Macro-finance and for Julia. My humble appreciation and respect to you.