Ad

Getting ValueError When Performing Np.dot

- 1 answer

I have to find annual returns and volatility of a portfolio. I have a dataframe with 5 columns, each containing the closing price of a stock

    ABC FINE    GAYA    RITES   LEMON
0   98.00   1203.70 1.00    260.30  69.00
1   98.25   1200.45 1.00    263.10  69.55
2   99.25   1202.55 1.05    267.50  71.15
3   100.10  1212.05 1.05    271.35  74.30
4   100.00  1188.00 1.00    274.00  73.60

To calculate returns and volatility, I had to calculate daily returns and covariance matrix.

daily_return = port.pct_change().dropna()
port_cov = daily_return.cov()

When I am calculating the volatility and returns using

pf_returns, pf_volatility, pf_sharpe_ratio, pf_port_weights=([] for i in range(4))
num_portfolios = 10000
for portfolio in range(num_portfolios):
    weights = np.full((332,5),0.2)
    returns = np.array(np.dot(weights,daily_return))
    volatility = np.sqrt(np.dot(weights.T,np.dot(port_cov,weights)))
    sharpe = returns / volatility
    pf_port_weights.append(weights)
    pf_returns.append(returns)
    pf_volatility.append(volatility)
    pf_sharpe_ratio.append(sharpe)

I am getting the error

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-666-31789f69fbed> in <module>()
      3 for portfolio in range(num_portfolios):
      4     weights = np.full((332,5),0.2)
----> 5     returns = np.array(np.dot(weights,daily_return))
      6     volatility = np.sqrt(np.dot(weights.T,np.dot(port_cov,weights)))
      7     sharpe = returns / volatility

ValueError: shapes (332,5) and (332,5) not aligned: 5 (dim 1) != 332 (dim 0)

The shapes are

daily_return.shape

(332,5)
port_cov.shape
(5,5)
weights.shape
(332,5)

I have tried to convert the shape of port_cov, using

cov = np.asarray(port_cov)
cov.reshape(332,5)

I am getting the error

ValueError: cannot reshape array of size 25 into shape (332,5)
Ad

Answer

  1. In dot product, inner dimensions of the two structures have to conform, e.g., consider the row vector v`1x5, to be able to dot product it, the other structure has to be S5xX (where X is any dimension). So, your line:
weights = np.full((332,5),0.2)

Has to be:

weights = np.full((5,332),0.2)

Or transpose it beforehand the dot operation using .T property as in:

returns = np.array(np.dot(weights.T,daily_return))

  1. The following two lines are erroneous because it's clear that port_conv only has 25 elements (as you illustrated in port_cov.shape). How would you transform those elements into 332x5, i.e., 1660 element!
cov = np.asarray(port_cov)
cov.reshape(332,5)

There are two possible ways to multiply weights by port_cov:

np.dot(weights, port_cov)

Or

np.dot(port_cov, weights.T)
Ad
source: stackoverflow.com
Ad