-
Notifications
You must be signed in to change notification settings - Fork 0
/
simulate.py
162 lines (120 loc) · 4.41 KB
/
simulate.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#function for the first quizz:
import sys
# QSTK Imports
import QSTK.qstkutil.qsdateutil as du
import QSTK.qstkutil.tsutil as tsu
import QSTK.qstkutil.DataAccess as da
# Third Party Imports
import datetime as dt
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
def Compute(close_norm,allocations):
#normalized value of portfolio
np_alloc=np.array(allocations)
valuePortfolio=np.dot(close_norm,np_alloc)
print 'valuePortolio = ',valuePortfolio
#print 'normalized valuePortfolio ',valuePortfolio
#daily returns of the PF
daily_Portfolio=valuePortfolio.copy()
tsu.returnize0(daily_Portfolio)
print 'valuePortolio afer returnize= ',valuePortfolio
#calculate the quantities
avg_P=np.average(daily_Portfolio)
sigma_P=np.std(daily_Portfolio)
sharpe_P=np.sqrt(252)*avg_P/sigma_P
cum_P=valuePortfolio[valuePortfolio.size -1]
return sigma_P,avg_P,sharpe_P,cum_P
def GetNormalizedReturn(dt_start,dt_end, symbols,c_dataobj):
#
#
#
# Keys to be read from the data, it is good to read everything in one go.
ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']
# We need closing prices so the timestamp should be hours=16.
dt_timeofday = dt.timedelta(hours=16)
# Get a list of trading days between the start and the end.
ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)
# Timestamps and symbols are the ones that were specified before.
ldf_data = c_dataobj.get_data(ldt_timestamps, symbols, ls_keys)
d_data = dict(zip(ls_keys, ldf_data))
#normalized returns data frame
df_rets=d_data['close'].copy()
close=df_rets.values
#normalized returns
close_norm=close/close[0,:]
#print 'close norm = ',close_norm.shape
return close_norm
def simulate(dt_start,dt_end, symbols, allocations):
#==========check allocations:
sum_alloc=0
for all in allocations:
sum_alloc+=all
#
if sum_alloc != 1.0:
print 'the allocations are wrong!'
sys.exit(1)
if len(allocations)!=len(symbols):
print 'the sizes are different!'
sys.exit(1)
#=========construct the portfolio
portfolio=zip(symbols,allocations)
print 'portfolio = ',portfolio
#check for bad symbols
#
c_dataobj=da.DataAccess('Yahoo')
ls_all_syms = c_dataobj.get_all_symbols()
# Bad symbols are symbols present in portfolio but not in all syms
ls_bad_syms = list(set(symbols) - set(ls_all_syms))
if len(ls_bad_syms) != 0:
print "Portfolio contains bad symbols : ", ls_bad_syms
sys.exit(1)
#
#
close_norm=GetNormalizedReturn(dt_start,dt_end, symbols,c_dataobj)
#optimize!
sharpe_max=-1
step=0.1
for a in range(0,11):
for b in range (0,11-a):
for c in range(0,11-a-b):
d=10-a-b-c
alloc_a=a*step
alloc_b=b*step
alloc_c=c*step
alloc_d=d*step
allocations=[alloc_a,alloc_b,alloc_c,alloc_d]
vol,daily,sharpe,cumul=Compute(close_norm,allocations)
#print 'sharpe =',sharpe
if sharpe>sharpe_max:
sharpe_max=sharpe
best_alloc=allocations
#print alloc_a,alloc_b,alloc_c,alloc_d
#raw_input('hey')
#
#
#
#
print 'the best sharpe is = ',sharpe_max
print 'with the allocation =',best_alloc
# vol,daily,sharpe,cumul=Compute(close_norm,allocations)
#return vol,daily,sharpe,cumul
if __name__=='__main__':
# List of symbols
ls_symbols=['BRCM', 'TXN', 'IBM', 'HNZ']
#ls_symbols=['C', 'GS', 'IBM', 'HNZ']
#ls_symbols=['BRCM', 'TXN', 'IBM', 'HNZ']
#ls_symbols=['GOOG', 'AAPL', 'GLD', 'XOM']
#ls_symbols=['AXP', 'HPQ', 'IBM', 'HNZ']
#ls_symbols=['AAPL', 'GLD', 'GOOG', 'XOM']
#ls_symbols = ["AAPL", "GLD", "GOOG", "$SPX", "XOM"]
# Start and End date of the charts
dt_start = dt.datetime(2010, 1, 1)
dt_end = dt.datetime(2010, 12, 31)
ls_allocations=(0.4,0.4,0.0,0.2)
#vol,daily,sharpe,cumul=simulate(dt_start,dt_end,ls_symbols,ls_allocations)
simulate(dt_start,dt_end,ls_symbols,ls_allocations)
#print 'volatility= ',vol
#print 'avg daily ret =',daily
#print 'sharpe ratio = ',sharpe
#print 'cumulative return =',cumul