0% found this document useful (0 votes)
100 views

Python For Finance

This document discusses methods for calculating the single and multiple security rate of return from stock market data. It extracts daily adjusted closing prices for several stocks from Yahoo Finance and calculates their daily, annualized, and portfolio returns over time. It also analyzes the mean, standard deviation, covariance, and correlation of returns. Finally, it generates an efficient frontier by plotting the expected returns and volatility of random portfolio combinations.

Uploaded by

Piyush Purohit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
100 views

Python For Finance

This document discusses methods for calculating the single and multiple security rate of return from stock market data. It extracts daily adjusted closing prices for several stocks from Yahoo Finance and calculates their daily, annualized, and portfolio returns over time. It also analyzes the mean, standard deviation, covariance, and correlation of returns. Finally, it generates an efficient frontier by plotting the expected returns and volatility of random portfolio combinations.

Uploaded by

Piyush Purohit
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

For Single Security Rate of Return

import numpy as np

import pandas as pd

from pandas_datareader import data as wb

import matplotlib.pyplot as plt

BSES = wb.DataReader('^BSESN', data_source='yahoo',start='1990-1-1') -----Data extraction

BSES["Returns”] =BSES ["Adj Close"].pct_change() ---------% Change

BSES.head()

BSES.tail()

plt.hist(BSES["Returns"].dropna(),bins=70, density=False) ------for histogram

plt.show()

OR

BSES["Returns"]. plot (figsize= (8,5))

MEAN

mean_return_daily= np.mean(BSES["Returns"]) ----------Daily Returns

print(mean_return_daily)

mean_return_annualized= ((1+mean_return_daily)**252)-1 ---------Annual Returns

print(mean_return_annualized)

print (str(round(mean_return_annualized,4)*100) + '%') -------In % terms


For Multiple Securities Rate of Return

import numpy as np

import pandas as pd

from pandas_datareader import data as wb

import matplotlib.pyplot as plt

assets = ['RELIANCE.BO','HDFCBANK.BO','ALOKTEXT.BO']

Mydata= pd.DataFrame()

for a in assets:

Mydata[t] = wb.DataReader(a, data_source='yahoo',start='2015-1-1')['Adj Close']

Mydata.info()

Mydata.head()

Mydata.tail()

(Mydata/Mydata.iloc[0]*100).plot(figsize=(15,6)); -----Normalisation to 100

plt.show()

Returns = Mydata.pct_change() ------% Change

print (Returns)
Date
2015-01-01 NaN NaN NaN
2015-01-02 -0.002759 0.014349 0.002874
2015-01-05 -0.009598 -0.008602 0.001910
2015-01-06 -0.046745 -0.014634 -0.044805
2015-01-07 0.023083 0.002864 -0.003992
2015-01-08 -0.014672 0.020257 0.009018
2015-01-09 0.020882 0.010576 -0.009930
2015-01-12 -0.011506 -0.006771 0.130391
2015-01-13 -0.008818 -0.004700 -0.042591
2015-01-14 -0.009489 -0.000208 0.005561
2015-01-15 0.035387 0.030363 0.003687
2015-01-16 0.005089 0.008966 -0.022039
2015-01-19 0.012486 0.002996 -0.018779
2015-01-20 0.024209 0.017621 -0.001914
2015-01-21 0.003884 -0.002299 -0.003835
2015-01-22 -0.022716 0.001275 -0.029836
2015-01-23 0.003224 0.021300 -0.007937
2015-01-27 0.002029 0.029821 -0.017000
2015-01-28 0.019240 -0.014805 0.003052
2015-01-29 0.024342 0.034212 0.000000
2015-01-30 -0.013525 -0.016723 0.019270
2015-02-02 -0.008139 0.005855 0.001990
2015-02-03 0.032548 -0.017601 -0.010924
2015-02-04 -0.009334 0.003762 0.006024
2015-02-05 -0.006838 0.009370 -0.012974
2015-02-06 -0.012902 -0.019216 -0.013145
2015-02-09 -0.014443 -0.015427 -0.027664
2015-02-10 -0.016271 0.014756 -0.009484
2015-02-11 0.020675 0.002747 0.032979
2015-02-12 0.010544 0.018044 -0.046344
... ... ... ...
2019-06-17 -0.026918 -0.006013 0.048518
2019-06-18 0.000819 -0.002065 0.000000
2019-06-19 -0.003938 0.005234 -0.002571
2019-06-20 0.015186 0.004804 -0.048969
2019-06-21 -0.013648 -0.004410 -0.027100
2019-06-24 -0.012938 0.000580 0.008357
2019-06-25 0.026254 0.004924 -0.035912
2019-06-26 -0.000965 0.015832 -0.028653
2019-06-27 -0.015218 -0.000264 0.011799
2019-06-28 -0.017924 -0.008129 0.005831
2019-07-01 0.013179 0.016044 0.000000
2019-07-02 0.007529 0.003500 -0.008696
2019-07-03 0.003286 -0.001944 0.014620
2019-07-04 0.000585 -0.002350 -0.011527
2019-07-05 -0.015900 -0.003322 -0.029155
2019-07-08 -0.008475 -0.027288 -0.015015
2019-07-09 0.022006 -0.011982 -0.006098
2019-07-10 -0.000860 0.003047 -0.027607
2019-07-11 0.002308 0.009031 0.009464
2019-07-12 -0.000546 -0.005960 -0.034375
2019-07-15 -0.003670 0.001107 -0.009709
2019-07-16 0.013481 -0.001649 -0.003268
2019-07-17 -0.008932 0.002320 -0.022951
2019-07-18 -0.015411 0.002586 0.003356
2019-07-19 -0.010144 -0.011627 0.003344
2019-07-22 0.025220 -0.033208 -0.033333
2019-07-23 -0.005974 -0.014410 -0.044828
2019-07-24 -0.011038 0.007001 0.046931
2019-07-25 -0.021052 0.002632 0.048276
2019-07-26 -0.014769 -0.004156 0.049342

[1126 rows x 3 columns]

Weights = np.array([0.25,0.35,0.4])

np.dot(Returns, Weights)

Annual_Returns = Returns.mean()*252 ---------Annual Returns

print (Annual_Returns)

RELIANCE.BO 0.271463
HDFCBANK.BO 0.216001
ALOKTEXT.BO -0.091436
dtype: float64

np.dot(Annual_Returns, Weights)

0.10689172240625852

Portfolio_1= print (str(round(np.dot(Annual_Returns,Weights),3)*100) + '%')

10.7%

Mean_Returns= print(Returns[['RELIANCE.BO','HDFCBANK.BO','ALOKTEXT.BO']]. mean ()) ----Mean


RELIANCE.BO 0.001077
HDFCBANK.BO 0.000857
ALOKTEXT.BO -0.000361
dtype: float64

Annual_Mean_Returns =
print(Returns[['RELIANCE.BO','HDFCBANK.BO','ALOKTEXT.BO']].mean()*252)

RELIANCE.BO 0.271463s
HDFCBANK.BO 0.216001
ALOKTEXT.BO -0.090900
dtype: float64

Std_Returns=
print(Returns[['RELIANCE.BO','HDFCBANK.BO','ALOKTEXT.BO']].std()) ----------Std. Deviation

RELIANCE.BO 0.015838
HDFCBANK.BO 0.010042
ALOKTEXT.BO 0.037674

Annual_Std_Returns = print(Returns[['RELIANCE.BO','HDFCBANK.BO','ALOKTEXT.BO']].
std()*252**0.5)

RELIANCE.BO 0.251414
HDFCBANK.BO 0.159417
ALOKTEXT.BO 0.598058

Cov_Matrix= Returns.cov()*252 -------------------Annualised Covariance

print(Cov_Matrix)

RELIANCE.BO HDFCBANK.BO ALOKTEXT.BO


RELIANCE.BO 0.063209 0.013816 0.016118
HDFCBANK.BO 0.013816 0.025414 0.013255
ALOKTEXT.BO 0.016118 0.013255 0.357673

Corr_Matrix = Returns.corr() -----Never annualize Coorelation


print(Corr_Matrix)

RELIANCE.BO HDFCBANK.BO ALOKTEXT.BO


RELIANCE.BO 1.000000 0.34471 0.107195
HDFCBANK.BO 0.344710 1.00000 0.139030
ALOKTEXT.BO 0.107195 0.13903 1.000000

MARKOWITZ EFFICIENT FRONTIER

import numpy as np

import pandas as pd

from pandas_datareader import data as wb

import matplotlib.pyplot as plt

%matplotlib inline
assets = ['RELIANCE.BO','HDFCBANK.BO','ALOKTEXT.BO']

Mydata= pd.DataFrame()

for a in assets:

Mydata[a] = wb.DataReader(a, data_source='yahoo',start='2015-1-1')['Adj Close']

Mydata.info()

Mydata.tail()

RELIANCE.BO HDFCBANK.BO LT.BO

Date

2019-07-22 1280.500000 2297.050049 1385.879272

2019-07-23 1272.849976 2263.949951 1392.000000

2019-07-24 1258.800049 2279.800049 1387.150024

2019-07-25 1232.300049 2285.800049 1372.949951

2019-07-26 1214.099976 2276.300049 1391.849976

Returns = Mydata.pct_change()

print(Returns)

Mydata/Mydata.iloc[0]*100).plot(figsize=(15,6));

plt.show()

Log_Returns= np.log(Mydata/Mydata.shift(1))
Log_Returns.mean()*252
RELIANCE.BO 0.239846
HDFCBANK.BO 0.203241
LT.BO 0.095831

Log_Returns.cov()*252

RELIANCE.BO HDFCBANK.BO LT.BO

RELIANCE.BO 0.062976 0.013904 0.020069

HDFCBANK.BO 0.013904 0.025352 0.015831

LT.BO 0.020069 0.015831 0.059797

Log_Returns.corr()

RELIANCE.BO HDFCBANK.BO LT.BO

RELIANCE.BO 1.000000 0.347972 0.327046

HDFCBANK.BO 0.347972 1.000000 0.406591

LT.BO 0.327046 0.406591 1.000000

num_assets = len(assets)

num_assets
3

weights = np.random.random(num_assets)

weights /= np.sum(weights)

weights
array([0.07582801, 0.78392948, 0.14024251])

weights[0] + weights[1] + weights[2]

1.0

np.sum(weights + Log_Returns.mean())*252 -------------Expected Pfolio Return

252.53891832986932
np.dot(weights.T,np.dot(Log_Returns.cov()*252, weights)) ----------Expected Pfolio Variance

0.022678552059398352

np.sqrt(np.dot(weights.T,np.dot(Log_Returns.cov()*252, weights))) ----Expected Pfolio Volatility

0.15059399742153853

Port_Returns = []

Port_Volatility = []

#populating the empty lists with each portfolios returns,risk and weights

for single_portfolio in range(1000):


weights = np.random.random(num_assets)
weights /= np.sum(weights)
Port_Returns.append(np.sum(weights * Log_Returns.mean())*252)
Port_Volatility.append(np.sqrt(np.dot(weights.T,np.dot(Log_Returns.cov()*252, weights))))

Port_Returns = np.array(Port_Returns)
Port_Volatility = np.array(Port_Volatility)

Port_Returns, Port_Volatility

#dictionary for Returns and Risk values of each pfolio

Portfolio = {'Returns': Port_Returns,'Volatility': Port_Volatility

df = pd.DataFrame(Portfolio)
df.head()

Returns Volatility

0 0.210084 0.179371

1 0.127285 0.197943

2 0.219485 0.194872

3 0.160627 0.163101

4 0.210797 0.152278
#plot the efficient frontier with a scatter plot

plt.style.use('seaborn')
df.plot.scatter(x='Volatility', y='Returns', figsize=(15, 7), grid=True)
plt.xlabel('Volatility (Std. Deviation)')
plt.ylabel('Expected Returns')
plt.title('Efficient Frontier')
plt.show()

You might also like