10.12.2019 Views

Python for Finance

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Portfolio Theory

output=pd.DataFrame(ret,index=ddate[1:])

output.columns=[ticker]

return output

ret=ret_f('IBM')

print(ret.head())

IBM

DATE

19620228 -0.008475

19620330 -0.008547

19620430 -0.146552

19620531 -0.136364

19620629 -0.134503

Finally, we could construct an n-stock return matrix from yanMonthly.pkl:

import scipy as sp

import pandas as pd

import numpy as np

n_stocks=10

x=pd.read_pickle('c:/temp/yanMonthly.pkl')

x2=sp.unique(np.array(x.index))

x3=x2[x2<'ZZZZ']

# remove all indices

sp.random.seed(1234567)

nonStocks=['GOLDPRICE','HML','SMB','Mkt_Rf','Rf','Russ3000E_D','US_

DEBT','Russ3000E_X','US_GDP2009dollar','US_GDP2013dollar']

x4=list(x3)

for i in range(len(nonStocks)):

x4.remove(nonStocks[i])

k=sp.random.uniform(low=1,high=len(x4),size=n_stocks)

y,s=[],[]

for i in range(n_stocks):

index=int(k[i])

y.append(index)

s.append(x4[index])

final=sp.unique(y)

print(s)

def ret_f(ticker):

a=x[x.index==ticker]

p=sp.array(a['VALUE'])

ddate=a['DATE']

ret=p[1:]/p[:-1]-1

output=pd.DataFrame(ret,index=ddate[1:])

[ 304 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!