forked from Rarlegend/cs182
-
Notifications
You must be signed in to change notification settings - Fork 0
/
myownq.py
260 lines (232 loc) · 6.88 KB
/
myownq.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
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
import random, util, time
import copy
import gradientParser
#bucket ranges for different metrics
buckets = dict()
for i in range(55):
#buckets[i] = [0,-50,-40,-30,-20,-10,10,20,30,40,50,10000000]
# buckets[i] = [0,10000000]
buckets[i] = [0,-10,-6,-3,-2,-1,-0.5,0,0.5,1,1.5,2,2.5,3,6,10,10000000]
#take data and put it into buckets defined somewhere else
class state():
def __init__(self, values):
data = values[0]
newPrice = values[2]
self.data = data
self.curPrice = values[1]
self.newPrice = newPrice
stateDef = []
#print data
#print values
#place values into buckets
for i in range(0, len(data)):
bucketRanges = buckets[i]
dataVal = data[i]
if (dataVal == None):
stateDef += [0]
else:
for j in range(1,len(bucketRanges)):
if (data[i] < bucketRanges[j]):
stateDef += [j]
break
self.stateDef = tuple(stateDef)
#print (self.stateDef)
def getScore(self):
if (self.newPrice == None or self.curPrice == None):
return 0.0
priceChange = float(self.newPrice - self.curPrice)
return priceChange
#-1 = predict lower price, 1 = predict higher price
def getLegalActions(self):
return [-1,1]
def getDef(self):
return self.stateDef
class qAgent():
def __init__ (self, actionFn = None, numTraining=100000, epsilon=0.1, alpha=0.5, gamma=1):
if (actionFn == None):
actionFn = lambda state: state.getLegalActions()
self.actionFn = actionFn
self.totalRewards = 0
self.numCorrect = 0
self.numWrong = 0
self.numTraining = int(numTraining)
self.epsilon = epsilon
self.alpha = alpha
self.discount = gamma
self.qValues = util.Counter()
self.inTesting = False
self.testRewards = 0
self.testCorrect = 0
self.testWrong = 0
def getQValue(self, state, action):
value = self.qValues[(state.getDef(), action)]
# print action
# if (value == 0):
# print "new state"
# print action
# print state.getDef()
# else:
# print "old state"
return value
def computeActionFromQValues(self, state):
maxAction = None
maxVal = 0
actions = state.getLegalActions()
for action in actions:
# print action
qVal = self.getQValue(state, action)
if qVal > maxVal or maxAction is None:
maxVal = qVal
maxAction = action
if (maxVal == 0):
return random.choice(actions)
else:
return maxAction
def getAction(self, state):
legalActions = state.getLegalActions()
if util.flipCoin(self.epsilon):
return random.choice(legalActions)
else:
return self.computeActionFromQValues(state)
def update(self, reward, state, action):
sample = reward
self.totalRewards += reward
if (reward < 0):
self.numWrong += 1
# self.totalRewards -= 1
else:
self.numCorrect += 1
# self.totalRewards += 1
self.alpha = float(1 - (float(self.numCorrect + self.numWrong) / float(self.numTraining)))
addVal = (1 - self.alpha) * self.getQValue(state, action) + self.alpha * sample
# print "add"
# print addVal
self.qValues[(state.getDef(), action)] = addVal
def getPercentCorrect(self):
if (self.inTesting):
return float(self.testCorrect) / float(self.test + self.testWrong)
else:
return float(self.numCorrect) / float(self.numCorrect + self.numWrong)
def getTotalRewards(self):
if (self.inTesting):
return self.testRewards
else:
return self.totalRewards
def finish(self):
print ("DONE")
print (self.totalRewards)
def setTestingOn(self):
self.epsilon = 0.0
self.alpha = 0.0
# def runInnerLoop(selectedKeys):
# agent = qAgent()
# reward = 0
# correct = 0
# # open data row by row to avoid memory overflow
# fname = 'data_cleaned.csv'
# with open(fname, 'r+') as f:
# # this reads in one line at a time from stdin
# date_previous = None
# ticker_previous = None
# observation = {}
# observationPrevious = {}
# isFirstObservation = True
# lineo = 0
# for i, line in enumerate(f):
# #print line
# fList = line.split(",")
# date = fList[0]
# value = float(fList[1])
# ticker = str(fList[2])
# fundamental = str(fList[3])
# lineo += 1
# if (lineo == 10000):
# break
# if (date_previous == None):
# date_previous = date
# elif (date_previous != date):
# if (not isFirstObservation):
# #break
# observedData = gradientParser.getObservation(observationPrevious, observation, selectedKeys)
# curState = state(observedData)
# action = agent.getAction(curState)
# priceChange = curState.getScore()
# reward = action * priceChange
# agent.update(reward, curState, action)
# reward = agent.getTotalRewards()
# correct = agent.getPercentCorrect()
# else:
# isFirstObservation = False
# observationPrevious = copy.deepcopy(observation)
# observation = {}
# date_previous = date
# if (ticker_previous == None):
# ticker_previous = ticker
# elif (ticker_previous != ticker):
# isFirstObservation = True
# ticker_previous = ticker
# observation[fundamental] = value
# return [reward, correct]
def runInnerLoop(selectedKeys):
agent = qAgent()
reward = 0
correct = 0
# open data row by row to avoid memory overflow
fname = 'data_ARQ_price.csv'
with open(fname, 'r+') as f:
# this reads in one line at a time from stdin
date_previous = None
ticker_previous = None
observation = {}
observationPrevious = {}
isFirstObservation = True
lineo = 0
currentPriceDict = dict()
currentDateList = []
for i, line in enumerate(f):
lineo += 1
if (lineo == 10000):
break
fList = line.split(",")
date = fList[0]
value = float(fList[1])
ticker = str(fList[2])
#add the -1 thing to get rid of newline character
fundamental = str(fList[3])[:-1]
if (ticker_previous == None):
ticker_previous = ticker
elif (ticker_previous != ticker):
isFirstObservation = True
ticker_previous = ticker
if (fundamental == '"PRICE"'):
currentDateList.append(date)
currentPriceDict[hash(date)] = value
else:
if (date_previous != date):
if (not isFirstObservation):
try:
index = currentDateList.index(date)
except:
index = None
if (index):
observation['"PRICE"'] = currentPriceDict[hash(currentDateList[index])]
if (index + 3 >= len(currentDateList)):
index = len(currentDateList) - 1
else:
index = index + 3
observation['"PRICENEXT"'] = currentPriceDict[hash(currentDateList[index])]
observedData = gradientParser.getObservation(observationPrevious, observation, selectedKeys)
curState = state(observedData)
action = agent.getAction(curState)
priceChange = curState.getScore()
reward = action * priceChange
agent.update(reward, curState, action)
reward = agent.getTotalRewards()
correct = agent.getPercentCorrect()
else:
isFirstObservation = False
observationPrevious = copy.deepcopy(observation)
observation = {}
date_previous = date
observation[fundamental] = value
return [reward, correct, agent]