# Approximation of a non linear problem with python

I need your help to solve a problem I'm working on for school. My goal is to approximate the coefficients of a weight matrix so that they check particular properties. So I have $W$ the weight matrix of my assets and $\Omega$ the covariance matrix of these assets. The global risk of my portfolio, $\sigma$, is defined by : $\sigma = \sqrt{^tW.\Omega.W}$ and the marginal risk of the asset number $j$ by : $\sigma_j = (W_j*(\Omega.W)_j)/\sigma^{2}$.

I need to find a way to approximate the weights so that if $N$ is the number of assets, for each $j$, $\sigma_j=1/N$ and $\sum_{j=1}^{N}W_j=1$, the covariance matrix being known.

I tried to use the fsolve function from scipy.optimize package in python, but the answers I get don't matches my criteria as I need the coefficients of $W$ to be between 0 and 1 and their sum to be 1

My program:

def CalcPoids(A,t):
n=len(A)
W=MatriceCov(A,t-30,30)
C=[(1/n) for i in range(n)]
def g(x,i):
M=np.dot(W,x)
d=np.dot((x.T),np.dot(W,x))
return(x[i]*M[i])/d - (1/n)
def f(x):
return [g(x,i) for i in range(n)]
return op.fsolve(f,C)


where MatriceCov is just calculating the covariance matrix of my assets for the previous 30 values.

def MatriceCov(A,j,t):
n=len(A)
M=np.zeros((n,n))
for i in range(n):
M[i][i]=Variancet(A[i],j,t)
for j in range(n):
i=0
while i<j:
M[i][j]=M[j][i]=Covt(A[i],A[j],j,t)
i+=1
return M


If you have any ideas about how solving this problem, any help would be appreciated.

• I am having a hard time to make a correspondence between your formulas and the code: $\sigma$ is totally missing, $g(x,i)$ appear from nowhere. It would be nice if the code actually reflect your formulas. I also want to clarigy the notation of $t$ superscript inside the root (does it mean $1/t$ power)? and $*$ and . notation (do they mean regular and Hadamard products?) Jun 6 '18 at 13:01
• I apologize for not being clear. I used different notations in the code I put here : g(x,i) is a fonction I implemented to use fsolve, it calculates the marginal risk as in my code, W=$\Omega$ and d= $\sigma^{2}$. Moreover the t in the root stands for the transposed matrix of the weights (it is the way we represent transposed matrix in France). Finally * is the regular products as $W_j$ and $(\Omega.W)_j$ are scalars. Jun 6 '18 at 13:31

A very common reason that iteration can fail to converge is that you've given it an invalid system of equation because of a coding error. I suspect that's what happened here: in op.fsolve(f,C), the parameter C is the starting guess, so you end up solving $f(x)=0$ starting with $x_0=C$ instead of solving $f(x)=C$.