0

I'm coding a markowitz efficient frontier with a group of 10 stocks. Until now, a get almost everything right, but, when i printed the weights gived for each stock, the sum was bigger than 1, and i cant resolve this.

#normalization of returns
log_ret = np.log(carteira/carteira.shift(1))
log_ret.head()
log_ret.cov()
np.random.seed(42)


num_ports = 6000
all_weights = np.zeros((num_ports, len(carteira.columns)))
ret_arr = np.zeros(num_ports)
vol_arr = np.zeros(num_ports)
sharpe_arr = np.zeros(num_ports)


for x in range(num_ports):
weights = np.array(np.random.random(10))
weighs = weights/np.sum(weights)

all_weights[x,:] = weights

#expected return
ret_arr [x] = np.sum( (log_ret.mean() *weights * 264))

#expected volatility
vol_arr[x] = np.sqrt(np.dot(weights.T, np.dot(log_ret.cov()*264, weights )))

 #sharpe ration
sharpe_arr[x] = ret_arr[x]/vol_arr[x]




 print('Max sharpe ration: {}'.format(sharpe_arr.max()))
print(' location  array: {}'.format(sharpe_arr.argmax()))
print(all_weights[1506,:])

with this specific stocks, my weight is almost 4 but i need that return sum = 1.

Someone can help me ?

martineau
  • 119,623
  • 25
  • 170
  • 301
  • Does this answer your question? [Generating a list of random numbers, summing to 1](https://stackoverflow.com/questions/18659858/generating-a-list-of-random-numbers-summing-to-1) – Michael Ruth Jun 17 '21 at 20:29
  • but i did it, weighs = "weights/np.sum(weights)" – Gustavo Lima Jun 17 '21 at 20:32
  • I did it too and `np.sum(weights)` is `0.9999999999999998`. This value is not `1` due to floating point error but the solution is mathematically correct. Is your actual question "How do I account for floating point error?" – Michael Ruth Jun 17 '21 at 20:37
  • i cant post images, but here i got 3.6516451833591126 – Gustavo Lima Jun 17 '21 at 20:39
  • I generated weights and normalized them 100 times and never had their sum differ from 1 by more than 0.0000000000000002. Please provide an example of how you reached a sum of 3.6516451833591126. – Michael Ruth Jun 17 '21 at 20:45
  • i put more portfolios for simulation, and now i got these weights '''[0.40543753 0.99814663 0.3575673 0.27739949 0.84617137 0.867938 0.33886915 0.29867314 0.64728148 0.20517848]'''. I cant see any error, my code is exactly what i posted here with ctrl c /crtl v – Gustavo Lima Jun 17 '21 at 20:45
  • These weights sum to 0.9999999999999999 after normalization. What's the problem? – Michael Ruth Jun 17 '21 at 20:51
  • they already dont should be normalized ? Like, i really dont was expecting need normalize again. The code that i saw how guide dont did it. Sorry for the inconvenience, I didn't expect this – Gustavo Lima Jun 17 '21 at 20:56
  • Oh, I see it. The code doesn't use the normalized weights (`weighs`), it uses the raw weights (`weights`). Try changing `weighs` to `normalized_weights` and this sort of typo will be much less likely to happen. – Michael Ruth Jun 17 '21 at 20:58

0 Answers0