title: Python - Marginal contribution to risk
body: <p>Can somebody help with the below as i have been struggling for sometime.</p>
  
  <p>Marginal contribution to risk= To find the marginal contribution of each asset, take the cross-product of the weights vector and the covariance matrix divided by the portfolio standard deviation.</p>
  
  <p>Now multiply the marginal contribution of each asset by the weights vector to get total contribution. We can then sum the asset contributions and make sure it’s equal to the total portfolio standard deviation.</p>
  
  <pre><code>Relativeweights = np.array([0.02, -0.025, -0.015, 0.0, 0.02,0,0,0])
  cov_matrix_a= 8x8 matrix
  Port_volatility= 0.05882615906289199
  </code></pre>
  
  <p>So i have tried the following code;</p>
  
  <pre><code>MCTAR=(np.dot(Relativeweights,cov_matrix_a))/Port_volatility
  TCTPR=MCTAR*Relativeweights
  np.sum(TCTPR, axis=0)
  </code></pre>
  
  <p>This doesn't sum to the portfolio volatility so not sure what is wrong?</p>
  
  <p>Any help appreciated.
  Thanks</p>
  
  <hr>
  
  <p>Full code below;</p>
  
  <h1>Pull in returns from csv file</h1>
  
  <pre><code>import numpy as np
  import ST as STPL
  Assetreturns = STPL.get_Asset_returns()
  </code></pre>
  
  <h1>Construct a covariance matrix for the portfolio's daily returns with the .cov() method</h1>
  
  <pre><code>cov_matrix_Assetreturns = Assetreturns.cov()
  cov_matrix_Assetreturns
  </code></pre>
  
  <h1>Annualise the daily covariance matrix with the standard 252 trading days</h1>
  
  <pre><code>cov_matrix_a = cov_matrix_Assetreturns * 252
  cov_matrix_a
  </code></pre>
  
  <h1>Assign relative weights</h1>
  
  <pre><code>Relativeweights = np.array([0.02, -0.025, -0.015, 0.0, 0.02,0,0,0])
  Relativeweights
  </code></pre>
  
  <h1>Assign portfolio weights</h1>
  
  <pre><code>Portweights = np.array([0.49, 0.15, 0.125, 0.215, 0.02, 0, 0,0])
  Portweights
  </code></pre>
  
  <h1>The standard deviation of a portfolio is just a square root of its variance</h1>
  
  <pre><code>Port_volatility = np.sqrt(np.dot(Portweights.T, np.dot(cov_matrix_a, Portweights)))
  Port_volatility
  </code></pre>
  
  <h1>Marginal contribution of each asset, take the cross-product of the weights vector and the covariance matrix divided by the portfolio standard deviation.</h1>
  
  <pre><code>MCTAR=(np.dot(Relativeweights,cov_matrix_a))/Port_volatility
  </code></pre>
  
  <h1>Now multiply the marginal contribution of each asset by the weights vector to get total contribution. We can then sum the asset contributions and make sure it’s equal to the total portfolio standard deviation.</h1>
  
  <pre><code>TCTPR=MCTAR*Relativeweights
  
  np.sum(TCTPR, axis=0)
  </code></pre>