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.

2. Code for defining two functions:

Chapter 9

def ret_monthly(ticker): # function 1

x = getData(ticker,(begYear,1,1),(endYear,12,31),asobject=True

,adjusted=True)

logret=np.log(x.aclose[1:]/x.aclose[:-1])

date=[]

d0=x.date

for i in range(0,np.size(logret)):

date.append(''.join([d0[i].strftime("%Y"),d0[i].

strftime("%m")]))

y=pd.DataFrame(logret,date,columns=[ticker])

return y.groupby(y.index).sum()

# function 2: objective function

def objFunction(W, R, target_ret):

stock_mean=np.mean(R,axis=0)

port_mean=np.dot(W,stock_mean)

# portfolio mean

cov=np.cov(R.T)

# var-cov matrix

port_var=np.dot(np.dot(W,cov),W.T) # portfolio variance

penalty = 2000*abs(port_mean-target_ret)# penalty 4 deviation

return np.sqrt(port_var) + penalty # objective function

3. Code for generating a return matrix R:

R0=ret_monthly(stocks[0])

# starting from 1st

stock

n_stock=len(stocks)

# number of stocks

for i in xrange(1,n_stock):

# merge with other

stocks

x=ret_monthly(stocks[i])

R0=pd.merge(R0,x,left_index=True,right_index=True)

R=np.array(R0)

4. Code for estimating optimal portfolios for a given return:

out_mean,out_std,out_weight=[],[],[]

stockMean=np.mean(R,axis=0)

for r in np.linspace(np.min(stockMean),np.max(stockMean),num=100):

W = np.ones([n_stock])/n_stock # starting from equal

weights

b_ = [(0,1)

for i in range(n_stock)]

# bounds, here no short

c_ = ({'type':'eq', 'fun': lambda W: sum(W)-1. })#constraint

result=sp.optimize.minimize(objFunction,W,(R,r),method='SLSQP'

,constraints=c_, bounds=b_)

if not result.success:

# handle error raise

[ 311 ]

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

Saved successfully!

Ooh no, something went wrong!