# -*- coding: utf-8 -*-
"""180123048_lab05.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1Q_QDHaZCQ0Y1fut5kKFxXLgKIa69Masq
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize

def get_ret(w):
    return np.dot(w, mu)

def get_risk(w):
    return (np.matmul(np.matmul(w, cov), np.transpose(w)))**0.5

def efficient_frontier(M):
    R = []
    W = []
    w = []
    x = 0
    y = 0
    r = 0
    for i in range(len(M)):
        cons = (
            {'type': 'eq', 'fun': lambda w: np.sum(w)-1},
            {'type': 'eq', 'fun': lambda w: get_ret(w)-M[i]}
        )
        res = minimize(get_risk, np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]), method='SLSQP', constraints=cons)
        R.append(res.fun)
        W.append(res.x)
        if abs((M[i]-rf)/R[i]) > r:
            r = abs((M[i]-rf)/R[i])
            x = R[i]
            y = M[i]
            w = W[i]
    return W, R

from google.colab import files
files.upload()

dataset = pd.read_csv('nsedata1.csv')
dataset.head()

dataset1 = pd.read_csv('bsedata1.csv')
dataset1.head()

stock_name = dataset.iloc[:, :].columns
asset_prices = dataset.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365*(asset_prices[j][i]-asset_prices[j-1][i])/asset_prices[j-1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='green', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of NSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()

stock_name = dataset1.iloc[:, :].columns
asset_prices = dataset1.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365*(asset_prices[j][i]-asset_prices[j-1][i])/asset_prices[j-1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='red', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of non NSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()

stock_name = dataset1.iloc[:, :].columns
asset_prices = dataset1.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365*(asset_prices[j][i]-asset_prices[j-1][i])/asset_prices[j-1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='green', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of BSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()

stock_name = dataset.iloc[:, :].columns
asset_prices = dataset.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365*(asset_prices[j][i]-asset_prices[j-1][i])/asset_prices[j-1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='red', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of non BSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()

df1 = pd.read_csv('nsedata1.csv')
df2 = pd.read_csv('bsedata1.csv')
data_nse = df1.iloc[:, :].to_numpy()
data_bse = df2.iloc[:,:].to_numpy()

df3 = pd.read_csv('NSE.csv')
df4 = pd.read_csv('BSE.csv')
nse_index = df3.iloc[:,4:5].to_numpy()
bse_index = df4.iloc[:1233,4:5].to_numpy()

bse_index[1:] = (bse_index[1:]-bse_index[:-1])/bse_index[:-1]
nse_index[1:] = (nse_index[1:]-nse_index[:-1])/nse_index[:-1]

data1 = np.array([data_nse,data_bse])
data1[2:] = (data1[2:]-data1[1:-1])/data1[1:-1]
data1[0] = 0

bse_index[0] = 0
nse_index[0] = 0

sigma_m_nse = (np.var(nse_index))**0.5
mu_m_nse = np.mean(nse_index)
mu_m_bse = np.mean(bse_index)
sigma_m_bse = (np.var(bse_index))**0.5

r_f = 0.05
M = np.mean(data1)
beta_nse = (M-r_f)/(mu_m_nse - r_f)
beta_bse = (M - r_f)/(mu_m_bse - r_f)

beta = np.linspace(-1,1.5,251)

mu_v_nse = r_f + (mu_m_nse-r_f)*beta
plt.plot(beta,mu_v_nse,label='NSE',color = 'r')
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market line for NSE')
plt.legend()
plt.grid()
plt.show()

stock_name = df2.iloc[:, :].columns
stock_name

beta = np.linspace(-1,1.5,251)
mu_v_bse = r_f + (mu_m_bse-r_f)*beta

plt.plot(beta,mu_v_bse,label = 'BSE',color = 'g')
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market line for BSE')
plt.legend()
plt.grid()
plt.show()

beta = np.linspace(-1,1.5,251)
mu_v_nse = r_f + (mu_m_nse-r_f)*beta
mu_v_bse = r_f + (mu_m_bse-r_f)*beta
plt.plot(beta,mu_v_nse,label='NSE',color = 'r')
plt.plot(beta,mu_v_bse,label = 'BSE',color = 'g')
plt.scatter(1,mu_m_nse,label='NSE INDEX',s=80, marker=(5, 2));
plt.scatter(1,mu_m_bse,label='BSE INDEX',s=80, marker=(5, 2));
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market lines for both BSE and NSE')
plt.legend()
plt.grid()
plt.show()

plt.plot(beta,mu_v_bse-mu_v_nse)
plt.xlabel('β ')
plt.ylabel('β₈ₛₑ-βₙₛₑ')
plt.title('Difference in SMLs')
plt.grid()
plt.show()
6481e438c935460355aad8865b171294b2f375b8
<mask token>


def get_ret(w):
    return np.dot(w, mu)


def get_risk(w):
    return np.matmul(np.matmul(w, cov), np.transpose(w)) ** 0.5


def efficient_frontier(M):
    R = []
    W = []
    w = []
    x = 0
    y = 0
    r = 0
    for i in range(len(M)):
        cons = {'type': 'eq', 'fun': lambda w: np.sum(w) - 1}, {'type':
            'eq', 'fun': lambda w: get_ret(w) - M[i]}
        res = minimize(get_risk, np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 
            0.1, 0.1, 0.1, 0.1]), method='SLSQP', constraints=cons)
        R.append(res.fun)
        W.append(res.x)
        if abs((M[i] - rf) / R[i]) > r:
            r = abs((M[i] - rf) / R[i])
            x = R[i]
            y = M[i]
            w = W[i]
    return W, R


<mask token>

<mask token>


def get_ret(w):
    return np.dot(w, mu)


def get_risk(w):
    return np.matmul(np.matmul(w, cov), np.transpose(w)) ** 0.5


def efficient_frontier(M):
    R = []
    W = []
    w = []
    x = 0
    y = 0
    r = 0
    for i in range(len(M)):
        cons = {'type': 'eq', 'fun': lambda w: np.sum(w) - 1}, {'type':
            'eq', 'fun': lambda w: get_ret(w) - M[i]}
        res = minimize(get_risk, np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 
            0.1, 0.1, 0.1, 0.1]), method='SLSQP', constraints=cons)
        R.append(res.fun)
        W.append(res.x)
        if abs((M[i] - rf) / R[i]) > r:
            r = abs((M[i] - rf) / R[i])
            x = R[i]
            y = M[i]
            w = W[i]
    return W, R


<mask token>
files.upload()
<mask token>
dataset.head()
<mask token>
dataset1.head()
<mask token>
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365 * (asset_prices[j][i] - asset_prices[j - 1][i]) /
            asset_prices[j - 1][i])
    ret.append(temp)
<mask token>
for r in ret:
    mean_ret.append(np.mean(r))
<mask token>
plt.plot(R, M, color='green', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of NSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()
<mask token>
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365 * (asset_prices[j][i] - asset_prices[j - 1][i]) /
            asset_prices[j - 1][i])
    ret.append(temp)
<mask token>
for r in ret:
    mean_ret.append(np.mean(r))
<mask token>
plt.plot(R, M, color='red', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of non NSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()
<mask token>
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365 * (asset_prices[j][i] - asset_prices[j - 1][i]) /
            asset_prices[j - 1][i])
    ret.append(temp)
<mask token>
for r in ret:
    mean_ret.append(np.mean(r))
<mask token>
plt.plot(R, M, color='green', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of BSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()
<mask token>
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365 * (asset_prices[j][i] - asset_prices[j - 1][i]) /
            asset_prices[j - 1][i])
    ret.append(temp)
<mask token>
for r in ret:
    mean_ret.append(np.mean(r))
<mask token>
plt.plot(R, M, color='red', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of non BSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()
<mask token>
plt.plot(beta, mu_v_nse, label='NSE', color='r')
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market line for NSE')
plt.legend()
plt.grid()
plt.show()
<mask token>
stock_name
<mask token>
plt.plot(beta, mu_v_bse, label='BSE', color='g')
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market line for BSE')
plt.legend()
plt.grid()
plt.show()
<mask token>
plt.plot(beta, mu_v_nse, label='NSE', color='r')
plt.plot(beta, mu_v_bse, label='BSE', color='g')
plt.scatter(1, mu_m_nse, label='NSE INDEX', s=80, marker=(5, 2))
plt.scatter(1, mu_m_bse, label='BSE INDEX', s=80, marker=(5, 2))
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market lines for both BSE and NSE')
plt.legend()
plt.grid()
plt.show()
plt.plot(beta, mu_v_bse - mu_v_nse)
plt.xlabel('β ')
plt.ylabel('β₈ₛₑ-βₙₛₑ')
plt.title('Difference in SMLs')
plt.grid()
plt.show()

<mask token>


def get_ret(w):
    return np.dot(w, mu)


def get_risk(w):
    return np.matmul(np.matmul(w, cov), np.transpose(w)) ** 0.5


def efficient_frontier(M):
    R = []
    W = []
    w = []
    x = 0
    y = 0
    r = 0
    for i in range(len(M)):
        cons = {'type': 'eq', 'fun': lambda w: np.sum(w) - 1}, {'type':
            'eq', 'fun': lambda w: get_ret(w) - M[i]}
        res = minimize(get_risk, np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 
            0.1, 0.1, 0.1, 0.1]), method='SLSQP', constraints=cons)
        R.append(res.fun)
        W.append(res.x)
        if abs((M[i] - rf) / R[i]) > r:
            r = abs((M[i] - rf) / R[i])
            x = R[i]
            y = M[i]
            w = W[i]
    return W, R


<mask token>
files.upload()
dataset = pd.read_csv('nsedata1.csv')
dataset.head()
dataset1 = pd.read_csv('bsedata1.csv')
dataset1.head()
stock_name = dataset.iloc[:, :].columns
asset_prices = dataset.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365 * (asset_prices[j][i] - asset_prices[j - 1][i]) /
            asset_prices[j - 1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='green', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of NSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()
stock_name = dataset1.iloc[:, :].columns
asset_prices = dataset1.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365 * (asset_prices[j][i] - asset_prices[j - 1][i]) /
            asset_prices[j - 1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='red', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of non NSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()
stock_name = dataset1.iloc[:, :].columns
asset_prices = dataset1.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365 * (asset_prices[j][i] - asset_prices[j - 1][i]) /
            asset_prices[j - 1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='green', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of BSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()
stock_name = dataset.iloc[:, :].columns
asset_prices = dataset.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365 * (asset_prices[j][i] - asset_prices[j - 1][i]) /
            asset_prices[j - 1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='red', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of non BSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()
df1 = pd.read_csv('nsedata1.csv')
df2 = pd.read_csv('bsedata1.csv')
data_nse = df1.iloc[:, :].to_numpy()
data_bse = df2.iloc[:, :].to_numpy()
df3 = pd.read_csv('NSE.csv')
df4 = pd.read_csv('BSE.csv')
nse_index = df3.iloc[:, 4:5].to_numpy()
bse_index = df4.iloc[:1233, 4:5].to_numpy()
bse_index[1:] = (bse_index[1:] - bse_index[:-1]) / bse_index[:-1]
nse_index[1:] = (nse_index[1:] - nse_index[:-1]) / nse_index[:-1]
data1 = np.array([data_nse, data_bse])
data1[2:] = (data1[2:] - data1[1:-1]) / data1[1:-1]
data1[0] = 0
bse_index[0] = 0
nse_index[0] = 0
sigma_m_nse = np.var(nse_index) ** 0.5
mu_m_nse = np.mean(nse_index)
mu_m_bse = np.mean(bse_index)
sigma_m_bse = np.var(bse_index) ** 0.5
r_f = 0.05
M = np.mean(data1)
beta_nse = (M - r_f) / (mu_m_nse - r_f)
beta_bse = (M - r_f) / (mu_m_bse - r_f)
beta = np.linspace(-1, 1.5, 251)
mu_v_nse = r_f + (mu_m_nse - r_f) * beta
plt.plot(beta, mu_v_nse, label='NSE', color='r')
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market line for NSE')
plt.legend()
plt.grid()
plt.show()
stock_name = df2.iloc[:, :].columns
stock_name
beta = np.linspace(-1, 1.5, 251)
mu_v_bse = r_f + (mu_m_bse - r_f) * beta
plt.plot(beta, mu_v_bse, label='BSE', color='g')
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market line for BSE')
plt.legend()
plt.grid()
plt.show()
beta = np.linspace(-1, 1.5, 251)
mu_v_nse = r_f + (mu_m_nse - r_f) * beta
mu_v_bse = r_f + (mu_m_bse - r_f) * beta
plt.plot(beta, mu_v_nse, label='NSE', color='r')
plt.plot(beta, mu_v_bse, label='BSE', color='g')
plt.scatter(1, mu_m_nse, label='NSE INDEX', s=80, marker=(5, 2))
plt.scatter(1, mu_m_bse, label='BSE INDEX', s=80, marker=(5, 2))
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market lines for both BSE and NSE')
plt.legend()
plt.grid()
plt.show()
plt.plot(beta, mu_v_bse - mu_v_nse)
plt.xlabel('β ')
plt.ylabel('β₈ₛₑ-βₙₛₑ')
plt.title('Difference in SMLs')
plt.grid()
plt.show()

<mask token>
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize


def get_ret(w):
    return np.dot(w, mu)


def get_risk(w):
    return np.matmul(np.matmul(w, cov), np.transpose(w)) ** 0.5


def efficient_frontier(M):
    R = []
    W = []
    w = []
    x = 0
    y = 0
    r = 0
    for i in range(len(M)):
        cons = {'type': 'eq', 'fun': lambda w: np.sum(w) - 1}, {'type':
            'eq', 'fun': lambda w: get_ret(w) - M[i]}
        res = minimize(get_risk, np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 
            0.1, 0.1, 0.1, 0.1]), method='SLSQP', constraints=cons)
        R.append(res.fun)
        W.append(res.x)
        if abs((M[i] - rf) / R[i]) > r:
            r = abs((M[i] - rf) / R[i])
            x = R[i]
            y = M[i]
            w = W[i]
    return W, R


from google.colab import files
files.upload()
dataset = pd.read_csv('nsedata1.csv')
dataset.head()
dataset1 = pd.read_csv('bsedata1.csv')
dataset1.head()
stock_name = dataset.iloc[:, :].columns
asset_prices = dataset.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365 * (asset_prices[j][i] - asset_prices[j - 1][i]) /
            asset_prices[j - 1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='green', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of NSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()
stock_name = dataset1.iloc[:, :].columns
asset_prices = dataset1.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365 * (asset_prices[j][i] - asset_prices[j - 1][i]) /
            asset_prices[j - 1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='red', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of non NSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()
stock_name = dataset1.iloc[:, :].columns
asset_prices = dataset1.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365 * (asset_prices[j][i] - asset_prices[j - 1][i]) /
            asset_prices[j - 1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='green', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of BSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()
stock_name = dataset.iloc[:, :].columns
asset_prices = dataset.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365 * (asset_prices[j][i] - asset_prices[j - 1][i]) /
            asset_prices[j - 1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='red', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of non BSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()
df1 = pd.read_csv('nsedata1.csv')
df2 = pd.read_csv('bsedata1.csv')
data_nse = df1.iloc[:, :].to_numpy()
data_bse = df2.iloc[:, :].to_numpy()
df3 = pd.read_csv('NSE.csv')
df4 = pd.read_csv('BSE.csv')
nse_index = df3.iloc[:, 4:5].to_numpy()
bse_index = df4.iloc[:1233, 4:5].to_numpy()
bse_index[1:] = (bse_index[1:] - bse_index[:-1]) / bse_index[:-1]
nse_index[1:] = (nse_index[1:] - nse_index[:-1]) / nse_index[:-1]
data1 = np.array([data_nse, data_bse])
data1[2:] = (data1[2:] - data1[1:-1]) / data1[1:-1]
data1[0] = 0
bse_index[0] = 0
nse_index[0] = 0
sigma_m_nse = np.var(nse_index) ** 0.5
mu_m_nse = np.mean(nse_index)
mu_m_bse = np.mean(bse_index)
sigma_m_bse = np.var(bse_index) ** 0.5
r_f = 0.05
M = np.mean(data1)
beta_nse = (M - r_f) / (mu_m_nse - r_f)
beta_bse = (M - r_f) / (mu_m_bse - r_f)
beta = np.linspace(-1, 1.5, 251)
mu_v_nse = r_f + (mu_m_nse - r_f) * beta
plt.plot(beta, mu_v_nse, label='NSE', color='r')
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market line for NSE')
plt.legend()
plt.grid()
plt.show()
stock_name = df2.iloc[:, :].columns
stock_name
beta = np.linspace(-1, 1.5, 251)
mu_v_bse = r_f + (mu_m_bse - r_f) * beta
plt.plot(beta, mu_v_bse, label='BSE', color='g')
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market line for BSE')
plt.legend()
plt.grid()
plt.show()
beta = np.linspace(-1, 1.5, 251)
mu_v_nse = r_f + (mu_m_nse - r_f) * beta
mu_v_bse = r_f + (mu_m_bse - r_f) * beta
plt.plot(beta, mu_v_nse, label='NSE', color='r')
plt.plot(beta, mu_v_bse, label='BSE', color='g')
plt.scatter(1, mu_m_nse, label='NSE INDEX', s=80, marker=(5, 2))
plt.scatter(1, mu_m_bse, label='BSE INDEX', s=80, marker=(5, 2))
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market lines for both BSE and NSE')
plt.legend()
plt.grid()
plt.show()
plt.plot(beta, mu_v_bse - mu_v_nse)
plt.xlabel('β ')
plt.ylabel('β₈ₛₑ-βₙₛₑ')
plt.title('Difference in SMLs')
plt.grid()
plt.show()

# -*- coding: utf-8 -*-
"""180123048_lab05.ipynb

Automatically generated by Colaboratory.

Original file is located at
    https://colab.research.google.com/drive/1Q_QDHaZCQ0Y1fut5kKFxXLgKIa69Masq
"""

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import minimize

def get_ret(w):
    return np.dot(w, mu)

def get_risk(w):
    return (np.matmul(np.matmul(w, cov), np.transpose(w)))**0.5

def efficient_frontier(M):
    R = []
    W = []
    w = []
    x = 0
    y = 0
    r = 0
    for i in range(len(M)):
        cons = (
            {'type': 'eq', 'fun': lambda w: np.sum(w)-1},
            {'type': 'eq', 'fun': lambda w: get_ret(w)-M[i]}
        )
        res = minimize(get_risk, np.array([0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]), method='SLSQP', constraints=cons)
        R.append(res.fun)
        W.append(res.x)
        if abs((M[i]-rf)/R[i]) > r:
            r = abs((M[i]-rf)/R[i])
            x = R[i]
            y = M[i]
            w = W[i]
    return W, R

from google.colab import files
files.upload()

dataset = pd.read_csv('nsedata1.csv')
dataset.head()

dataset1 = pd.read_csv('bsedata1.csv')
dataset1.head()

stock_name = dataset.iloc[:, :].columns
asset_prices = dataset.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365*(asset_prices[j][i]-asset_prices[j-1][i])/asset_prices[j-1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='green', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of NSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()

stock_name = dataset1.iloc[:, :].columns
asset_prices = dataset1.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365*(asset_prices[j][i]-asset_prices[j-1][i])/asset_prices[j-1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='red', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of non NSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()

stock_name = dataset1.iloc[:, :].columns
asset_prices = dataset1.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365*(asset_prices[j][i]-asset_prices[j-1][i])/asset_prices[j-1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='green', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of BSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()

stock_name = dataset.iloc[:, :].columns
asset_prices = dataset.iloc[:, :].to_numpy()
ret = []
for i in range(len(asset_prices[0])):
    temp = []
    for j in range(1, len(asset_prices)):
        temp.append(365*(asset_prices[j][i]-asset_prices[j-1][i])/asset_prices[j-1][i])
    ret.append(temp)
mean_ret = []
for r in ret:
    mean_ret.append(np.mean(r))
cov = np.cov(ret)
mu = mean_ret
u = np.ones((1, len(mu)))
M = np.linspace(-2, 2, 1000)
rf = 0.05
W, R = efficient_frontier(M)
plt.plot(R, M, color='red', label='Markowitz Efficient Frontier')
plt.title('Markowitz Efficient Frontier of non BSE stocks')
plt.xlabel('Volatility')
plt.ylabel('Return')
plt.grid()
plt.legend()
plt.show()

df1 = pd.read_csv('nsedata1.csv')
df2 = pd.read_csv('bsedata1.csv')
data_nse = df1.iloc[:, :].to_numpy()
data_bse = df2.iloc[:,:].to_numpy()

df3 = pd.read_csv('NSE.csv')
df4 = pd.read_csv('BSE.csv')
nse_index = df3.iloc[:,4:5].to_numpy()
bse_index = df4.iloc[:1233,4:5].to_numpy()

bse_index[1:] = (bse_index[1:]-bse_index[:-1])/bse_index[:-1]
nse_index[1:] = (nse_index[1:]-nse_index[:-1])/nse_index[:-1]

data1 = np.array([data_nse,data_bse])
data1[2:] = (data1[2:]-data1[1:-1])/data1[1:-1]
data1[0] = 0

bse_index[0] = 0
nse_index[0] = 0

sigma_m_nse = (np.var(nse_index))**0.5
mu_m_nse = np.mean(nse_index)
mu_m_bse = np.mean(bse_index)
sigma_m_bse = (np.var(bse_index))**0.5

r_f = 0.05
M = np.mean(data1)
beta_nse = (M-r_f)/(mu_m_nse - r_f)
beta_bse = (M - r_f)/(mu_m_bse - r_f)

beta = np.linspace(-1,1.5,251)

mu_v_nse = r_f + (mu_m_nse-r_f)*beta
plt.plot(beta,mu_v_nse,label='NSE',color = 'r')
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market line for NSE')
plt.legend()
plt.grid()
plt.show()

stock_name = df2.iloc[:, :].columns
stock_name

beta = np.linspace(-1,1.5,251)
mu_v_bse = r_f + (mu_m_bse-r_f)*beta

plt.plot(beta,mu_v_bse,label = 'BSE',color = 'g')
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market line for BSE')
plt.legend()
plt.grid()
plt.show()

beta = np.linspace(-1,1.5,251)
mu_v_nse = r_f + (mu_m_nse-r_f)*beta
mu_v_bse = r_f + (mu_m_bse-r_f)*beta
plt.plot(beta,mu_v_nse,label='NSE',color = 'r')
plt.plot(beta,mu_v_bse,label = 'BSE',color = 'g')
plt.scatter(1,mu_m_nse,label='NSE INDEX',s=80, marker=(5, 2));
plt.scatter(1,mu_m_bse,label='BSE INDEX',s=80, marker=(5, 2));
plt.xlabel('β')
plt.ylabel('μᵥ')
plt.title('Security Market lines for both BSE and NSE')
plt.legend()
plt.grid()
plt.show()

plt.plot(beta,mu_v_bse-mu_v_nse)
plt.xlabel('β ')
plt.ylabel('β₈ₛₑ-βₙₛₑ')
plt.title('Difference in SMLs')
plt.grid()
plt.show()