-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathstockbot.py
More file actions
318 lines (237 loc) · 9.65 KB
/
stockbot.py
File metadata and controls
318 lines (237 loc) · 9.65 KB
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
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
import yfinance as yf
import pandas as _pd
import numpy as np
import enum
import matplotlib.pyplot as plt
"""
Author: Ryan Cullen
"""
class Decisions(enum.Enum):
sell = -1
hold = 0
buy = 1
class Portfolio:
""" Stock portfolio
Holds information about current buying power, equity, and overall value
Attributes:
capital: starting cash
shares: starting number of shares
portfolio value: the overall value of the stock portfolio in $USD if the owner were to liquidate all assets
Funtions:
Decide(): This is where the logic of when to buy, sell, or hold should go
Order(): Used to execute a buy or sell order
"""
def __init__(self, capital, shares):
""" Inits a Portfolio object """
self.capital = capital
self.shares = shares
self.portfolio_value = self.capital + self.shares*price
def Decide(self, f1, f2, f3, window):
""" This is where the script decides to Buy, Sell, or Hold; Desgin your algorithm logic here """
def Order(self, decision, n = -1):
""" Executes a buy/sell order of n shares, or a buy/sell max order if no input for n
decision: an element from the Decisions class
n: number of shares to order
"""
# plot a dot for buy or sell
if decision.value > 0:
plt.plot([i], [price], marker='o', markersize=4, color="limegreen")
elif decision.value < 0:
plt.plot([i], [price], marker='o', markersize=4, color="red")
# buy n
if decision == Decisions.buy:
counter = 0
while self.capital >= price:
self.capital -= price
self.shares += 1
counter += 1
if counter == n:
break
# sell n
elif decision == Decisions.sell:
counter = 0
while self.shares > 0:
self.capital += price
self.shares -= 1
counter += 1
if counter == n:
break
def OptimalPosition(expected_return, prob_win, modifier):
""" Uses the Kelly Criterion to calculate the optimal position size for a given play
expected return: the expected value of the shares at the end of the play minus the value today
prob_win: the fractional probability that we will get our expected return
modifier: a value between 0 and 1; higher values make for a more aggressive bet
"""
prob_lose = 1 - prob_win
fraction = ((expected_return * prob_win) - prob_lose) / expected_return
optimal_position = (self.capital * fraction) * modifier
return optimal_position
def PortfolioValue(self):
""" Returns the current total monetary value of the portfolio """
self.portfolio_value = self.capital + (self.shares*price)
return self.portfolio_value
class MovingAverage:
""" Moving Average
An object used to represent a moving average function
Attributes:
averages: the list of average values at each point
percent_difference: the percent difference between the price and the current point
slope: the slope at the current point
slope_sum: the sum of the slopes over the interval (window)
avg_slope: the average slope over the interval (window)
slopes: a list to hold the slopes
concavity: the value for the concavity (2nd derivative) at the current point
concavity_sum: the sum of the concavities over the interval (window)
avg_concavity: the average concavity over the interval (window)
concavities: a list to hold the concavities
above: a bool to tell whether the proce is above or below the current point
flipped: a bool that is True for one day after the price flips over the function
edge: variable to account for the beginning of the dataset
"""
def __init__(self):
""" Inits a MovingAverage object """
self.averages = []
self.percent_difference = 0
self.slope = 0
self.slope_sum = 0
self.avg_slope = 0
self.slopes = []
self.concavity = 0
self.concavity_sum = 0
self.avg_concavity = 0
self.concavities = []
self.above = False
self.flipped = False
self.edge = 0
def CalculateAverage(self, value_list, window):
""" Calculates the value for the moving average over the last (window) days
Attributes:
value_list: the list of values of which the average will be calculated
window: the interval over which to calculate the average value
"""
# account for the beginning of the dataset
if i < (window - 1):
self.edge = window - (i + 1)
else: self.edge = 0
# calculate the average value over the interval
if i == 0:
value_sum = price
else:
value_sum = 0
for n in range(window - self.edge):
value_sum += value_list[i - n]
return value_sum/(window - self.edge)
def Update(self, window):
""" Updates the indicators used for building the algorithm
Attributes:
window: the interval over which to calculate the indicators
"""
# percent deviation from the mean
difference = price - self.averages[i]
self.percent_difference = difference/self.averages[i]
# calculate slope
if i > 1:
self.slope = self.averages[i] - self.averages[i - 1]
# calculate average slope and concavity
self.slopes.append(self.slope)
self.slope_sum += abs(self.slope)
if i < window:
self.avg_slope = self.slope_sum/(i+1)
self.concavity = self.slopes[i] - self.slopes[0]
else:
self.slope_sum -= abs(self.slopes[0])
self.slopes.pop(0)
self.avg_slope = self.slope_sum/window
self.concavity = self.slopes[window - 1] - self.slopes[0]
# calculate average concavity
self.concavities.append(self.concavity)
self.concavity_sum += self.concavity
if i < window:
self.avg_concavity = self.concavity_sum/(i+1)
else:
self.concavity_sum -= self.concavities[0]
self.concavities.pop(0)
self.avg_concavity = self.concavity_sum/window
# check if we flip over average line
if price > self.averages[i]:
if self.above == False:
self.above = True
self.flipped = True
else: self.flipped = False
else:
if self.above:
self.above = False
self.flipped = True
else: self.flipped = False
"""
Main Loop
"""
while True:
# input a ticker to track
ticker = input("Enter ticker: ")
if ticker == 'exit':
break
# get ticker information and price history
ticker_info = yf.Ticker(ticker)
price_history = ticker_info.history(start="2017-01-01", end="2020-12-20")
# assign lists for the open/close prices, the moving-average values,
# and the daily average prices.
opens = price_history['Open']
closes = price_history['Close']
prices = []
# calculates the inital price of the stock, and
# the number of days we are looking back in history
price = closes[0]
days = opens.size
# initialize figure for plottingexit
fig, ax = plt.subplots()
# initialize the portfolio and moving average objects
starting_capital = 0
starting_shares = 100
entry_price = starting_shares * price
portfolio = Portfolio(starting_capital, starting_shares)
# objects to track moving averages
f1 = MovingAverage()
f2 = MovingAverage()
f3 = MovingAverage()
# iterate over the history of the stock
for i in range(days):
# create a list of the closing prices
price = closes[i]
prices.append(price)
# calculate the current moving averages
window = 40
f1.averages.append(f1.CalculateAverage(prices, window))
f2.averages.append(f2.CalculateAverage(f1.averages, window))
f3.averages.append(f3.CalculateAverage(f2.averages, window))
# update the functions
small_window = int(window/2)
f1.Update(small_window)
f2.Update(small_window)
f3.Update(small_window)
# decide if we buy, sell, or hold
portfolio.Decide(f1, f2, f3, window)
# did we win?
control_value = starting_capital + (prices[days - 1] * starting_shares)
algo_value = portfolio.PortfolioValue()
print(" ")
print(f"Capital: {portfolio.capital:,.2f}")
print(f"Shares: {portfolio.shares:,.2f}")
print(f"Buy and Hold portfolio value: {control_value:,.2f}")
print(f"Returns: {(control_value - entry_price):,.2f}")
print(f"Algorithm portfolio value: {algo_value:,.2f}")
print(f"Returns: {(algo_value - entry_price):,.2f}")
print(" ")
plt.plot([0], [prices[0]], marker='o', markersize=4, color="red", label="Sell Point")
plt.plot([0], [prices[0]], marker='o', markersize=4, color="limegreen", label="Buy Point")
# plot the price history and moving average history
x = list(range(0, days))
plt.plot(x, prices)
plt.title(ticker)
plt.xlabel("Days")
plt.ylabel("Price")
plt.legend()
plt.plot(x, f1.averages)
plt.plot(x, f2.averages)
plt.plot(x, f3.averages)
plt.show()