-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
74 lines (55 loc) · 2.98 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import numpy as np
import pandas as pd
import pandas_datareader.data as web
import matplotlib.pyplot as plt
# list of stocks in portfolio
stocks = ['AAPL', 'AMZN', 'MSFT', 'MOIL', 'GOOG', 'VEDL','TSLA' ,'SBI','ITC','MRF','IDEA','BSE','PNB','CSV','OIL','SPY','QQQ','IWM','FB','GDX','INDA','TCS','V','VOD','JPM']
# download daily price data for each of the stocks in the portfolio
data = web.DataReader(stocks, data_source='yahoo', start='1/01/2010')['Adj Close']
data.sort_index(inplace=True)
# convert daily stock prices into daily returns
returns = data.pct_change()
# calculate mean daily return and covariance of daily returns
mean_daily_returns = returns.mean()
cov_matrix = returns.cov()
# set number of runs of random portfolio weights
num_portfolios = 250000
# set up array to hold results
# We have increased the size of the array to hold the weight values for each stock
results = np.zeros((4 + len(stocks) - 1, num_portfolios))
for i in xrange(num_portfolios):
# select random weights for portfolio holdings
weights = np.array(np.random.random(25))
# rebalance weights to sum to 1
weights /= np.sum(weights)
# calculate portfolio return and volatility
portfolio_return = np.sum(mean_daily_returns * weights) * 252
portfolio_std_dev = np.sqrt(np.dot(weights.T, np.dot(cov_matrix, weights))) * np.sqrt(252)
# store results in results array
results[0, i] = portfolio_return
results[1, i] = portfolio_std_dev
# store Sharpe Ratio (return / volatility) - risk free rate element excluded for simplicity
results[2, i] = results[0, i] / results[1, i]
# iterate through the weight vector and add data to results array
for j in range(len(weights)):
results[j + 3, i] = weights[j]
# convert results array to Pandas DataFrame
results_frame = pd.DataFrame(results.T, columns=['ret', 'stdev', 'sharpe', stocks[0], stocks[1], stocks[2], stocks[3],
stocks[4], stocks[5], stocks[6], stocks[7], stocks[8],stocks[9],stocks[10],stocks[11],stocks[12],stocks[13],stocks[14],stocks[15],stocks[16],stocks[17],stocks[18],stocks[19],stocks[20],stocks[21],stocks[22],stocks[23],stocks[24]])
# locate position of portfolio with highest Sharpe Ratio
max_sharpe_port = results_frame.iloc[results_frame['sharpe'].idxmax()]
# locate positon of portfolio with minimum standard deviation
min_vol_port = results_frame.iloc[results_frame['stdev'].idxmin()]
print(min_vol_port)
# create scatter plot coloured by Sharpe Ratio
plt.scatter(results_frame.stdev, results_frame.ret, c=results_frame.sharpe, cmap='RdYlBu')
plt.xlabel('Volatility')
plt.ylabel('Returns')
plt.colorbar()
# plot red star to highlight position of portfolio with highest Sharpe Ratio
# plt.scatter(max_sharpe_port[1], max_sharpe_port[0], marker=(5, 1, 0), color='r', s=1000)
# plot green star to highlight position of minimum variance portfolio
plt.scatter(min_vol_port[1], min_vol_port[0], marker=(5, 1, 0), color='g', s=1000)
plt.plot()
plt.show()
#print(max_sharpe_port)