You are on page 1of 3

def generate_weigths(n):

k = np.random.rand(n)
return k / sum(k)

def portfolio (returns, weights=""):

opt_mean = np.asmatrix(np.mean(returns, axis=1))

if (weights == ""):
opt_weight = np.asmatrix(generate_weigths(returns.shape[0]))
else:
z=weights
we = []
for x in range(0,len(df_opt)):
we.append(z)
opt_weight = np.asmatrix(we)

opt_cov = np.asmatrix(np.cov(returns))

mu = opt_weight * opt_mean.T
sigma = np.sqrt(opt_weight * opt_cov * opt_weight.T)

if sigma > 2:
return portfolio(returns, weights)
return mu, sigma

def optimizate_portfolio(returns):

n = len(returns)
returns = np.asmatrix(returns)

N = 100
mus = [10**(5.0 * t/N - 1.0) for t in range(N)]

# Convert to cvxopt matrices


S = opt.matrix(np.cov(returns))
pbar = opt.matrix(np.mean(returns, axis=1))

# Create constraint matrices


G = -opt.matrix(np.eye(n)) # negative n x n identity matrix
h = opt.matrix(0.0, (n ,1))
A = opt.matrix(1.0, (1, n))
b = opt.matrix(1.0)

# Calculate efficient frontier weights using quadratic programming


portfolios = [solvers.qp(mu*S, -pbar, G, h, A, b)['x']
for mu in mus]

## CALCULATE RISKS AND RETURNS FOR FRONTIER


returns = [blas.dot(pbar, x) for x in portfolios]
risks = [np.sqrt(blas.dot(x, S*x)) for x in portfolios]

## CALCULATE THE 2ND DEGREE POLYNOMIAL OF THE FRONTIER CURVE


m1 = np.polyfit(returns, risks, 2)
x1 = np.sqrt(m1[2] / m1[0])
# CALCULATE THE OPTIMAL PORTFOLIO
wt = solvers.qp(opt.matrix(x1 * S), -pbar, G, h, A, b)['x']
return np.asarray(wt), returns, risks

weights, returns, risks = optimizate_portfolio(df_opt)

fig = plt.figure (figsize=(15,7))

plt.scatter(results_df.Std,results_df.Return,c=results_df.Sharpe,cmap='afmhot')
plt.xlabel('Volatility')
plt.ylabel('Returns')
plt.colorbar()
#plot red star to highlight position of portfolio with highest Sharpe Ratio

plt.scatter(max_sharpe.iloc[:,1],max_sharpe.iloc[:,0],marker=(5,1,0),color='r',s=10
00)
#plot green star to highlight position of minimum variance portfolio

plt.scatter(min_sharpe.iloc[:,1],min_sharpe.iloc[:,0],marker=(5,1,0),color='g',s=10
00)
plt.show()

days = (df_opt.index[-1] - df_opt.index[0]).days; days


cagr = ((((google['Adj Close'][-1]) / google['Adj Close'][1])) ** (365.0/days)) - 1
#compound annual growth rate (CAGR)
vol = std_monte['Google']
vol
S = apple['Adj Close'][-1]
T = 252 #Number of trading days
mu = cagr
vol = vol
result = []

for i in range(100):

custom_returns=np.random.normal(mu/T,vol/sqrt(T),T)+1

price_list = [S]

for x in custom_returns:
price_list.append(price_list[-1]*x)

plt.plot(price_list)
plt.yticks(np.arange(0, 500, 50))
plt.title("Random Walk")

result.append(price_list[-1])
plt.show()
plt.hist(result,bins=50)
plt.show()

plt.hist(result,bins=50, color="orange")
plt.axvline(np.percentile(result,5), color='r', linestyle='dotted', linewidth=2)
plt.axvline(np.percentile(result,95), color='r', linestyle='dotted', linewidth=2)
plt.title("Monte Carlo with Random Walk")
plt.show()

You might also like