-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
521 lines (397 loc) · 19.8 KB
/
main.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
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
import tkinter as tk
from tkinter import messagebox, simpledialog
import warnings
import pickle
import yfinance as yf
import statistics
import pandas as pd
import os
import concurrent.futures
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
from scipy.stats import linregress
import numpy as np
from datetime import date
from data.database import DBManager, Update, open_file, close_file
from data.analysis import CIManager, RSIManager, AnalysisManager
from data.day_trade import DTViewer
from settings.settings_manager import SettingsManager
from data.winrate import WinrateManager
from data.shortrate import ShortrateManager
from applications.scraper import scraper
from applications.converter import convert
# Suppress warning
warnings.simplefilter(action='ignore', category=FutureWarning)
class GlobalInit:
def __init__(self):
self.settings_manager = SettingsManager()
self.winrate_manager = WinrateManager()
self.shortrate_manager = ShortrateManager()
self.update_manager = Update()
self.rsi_manager = RSIManager()
self.db_manager = DBManager()
class StockTracker:
def __init__(self, root):
self.root = root
self.root.title("Stock Tracker")
self.settings_manager = SettingsManager()
self.winrate_manager = WinrateManager()
self.shortrate_manager = ShortrateManager()
tk.Label(root, text="Main Menu", font=("Arial", 25)).pack(pady=20)
tk.Button(root, text="Run", command=self.run, height = 2, width = 15).pack(pady=20)
tk.Label(root, text="Day Trading Module.", font=("Arial", 10)).pack(pady=0)
tk.Button(root, text="Commands", command=self.commands, height = 2, width = 15).pack(pady=20)
tk.Label(root, text="Run individual tasks.", font=("Arial", 10)).pack(pady=0)
tk.Button(root, text="Manage Databases", command=self.manage_databases, height = 2, width = 15).pack(pady=20)
tk.Label(root, text="Database related settings.", font=("Arial", 10)).pack(pady=0)
tk.Button(root, text="Portfolio", command=self.portfolio, height = 2, width = 15).pack(pady=20) #make this more suitable for tkinter
tk.Label(root, text="Manage running portfolios.", font=("Arial", 10)).pack(pady=0)
tk.Button(root, text="Applications", command=self.application, height = 2, width = 15).pack(pady=20)
tk.Label(root, text="External applications.", font=("Arial", 10)).pack(pady=0)
tk.Button(root, text="Settings", command=self.settings, height = 2, width = 15).pack(pady=20)
tk.Label(root, text="Edit Settings File.", font=("Arial", 10)).pack(pady=0)
tk.Button(root, text="Quit", command=self.quit, height = 2, width = 15).pack(pady=20)
def run(self):
dt = DTViewer(self.root)
dt.run()
def commands(self):
commands_window = CommandsWindow(self.root)
commands_window.run()
def manage_databases(self):
edit_window = ManageDatabases(self.root)
edit_window.run()
def portfolio(self):
port_window = PortWindow(self.root)
port_window.run()
def application(self):
app_window = AppWindow(self.root)
app_window.run()
def settings(self):
settings_window = SettingsWindow(self.root)
settings_window.run()
def quit(self):
self.root.quit()
class CommandsWindow(GlobalInit):
def __init__(self, root):
super().__init__()
self.root = tk.Tk()
self.root.title = "Commands"
self.root.geometry("800x600+200+100")
tk.Button(self.root, text="Run (old)", command = self.run).pack(pady=5)
tk.Label(self.root, text="Check settings, update portfolios, update databases, run short and winrate experiments.", font = ("Arial", 10)).pack(pady=0)
tk.Button(self.root, text="Update", command=self.update).pack(pady=5)
tk.Label(self.root, text="Choose a database to update.", font = ("Arial", 10)).pack(pady=0)
tk.Button(self.root, text="Update W/S", command=self.winshort).pack(pady=5)
tk.Label(self.root, text="Update winrate/shortrate experiment.", font = ("Arial", 10)).pack(pady=0)
tk.Button(self.root, text="RSI", command=self.rsi).pack(pady=5)
tk.Label(self.root, text="Find historical/current RSI of any ticker.", font = ("Arial", 10)).pack(pady=0)
tk.Button(self.root, text="RSI Accuracy", command=self.rsi_acc).pack(pady=5)
tk.Label(self.root, text="Check how well RSI fits with stock trend (not proven to be effective for analysis).", font = ("Arial", 10)).pack(pady=0)
tk.Button(self.root, text="RSI Turnover", command=self.rsi_turn).pack(pady=5)
tk.Label(self.root, text="Find average turnover rate (time from 30 rsi to 70 rsi).", font = ("Arial", 10)).pack(pady=0)
tk.Button(self.root, text="Moving Average", command = self.MovingAverage).pack(pady=5)
tk.Label(self.root, text="Show moving averages of stock (20 day / 50 day).", font = ("Arial", 10)).pack(pady=0)
tk.Button(self.root, text="Machine Learning Prediction", command = self.MachineLearning).pack(pady=5)
tk.Label(root, text="Not currently working.", font = ("Arial", 10)).pack(pady=0)
tk.Button(self.root, text="Back", command=self.back).pack(pady=10)
def run(self):
#Run settings/winrate/shortrate
print("pressed")
self.settings_manager.checkSettings()
self.winrate_manager.checkWinrate()
self.shortrate_manager.checkShortrate()
self.winrate_manager.winrate()
self.winrate_manager.scanWinrate()
self.winrate_manager.winratePotential()
#self.shortrate_manager.shortrate()
#self.shortrate_manager.scanShortrate()
#self.shortrate_manager.shortratePotential()
winshort_window = WinShortWindow(self.root)
winshort_window.run()
def update(self):
dbname = simpledialog.askstring("Input", "Name of database:")
self.update_manager.updateData(dbname)
def winshort(self):
self.winrate_manager.checkWinrate()
self.winrate_manager.winrate()
self.winrate_manager.scanWinrate()
self.winrate_manager.winratePotential()
self.shortrate_manager.checkShortrate()
self.shortrate_manager.shortrate()
self.shortrate_manager.scanShortrate()
self.shortrate_manager.shortratePotential()
winshort_window = WinShortWindow(self.root)
winshort_window.run()
def rsi(self):
ticker = simpledialog.askstring("Input", "Name of ticker:").upper()
graph = messagebox.askyesno("Y/N","Would you like a graph?")
if graph == False:
date_q = messagebox.askyesno("Y/N", "Would you like to input a specific date?")
if date_q == False:
rsi_value = self.rsi_manager.rsi_calc(ticker, graph, date = None)
messagebox.showinfo(title = "RSI", message = f"RSI for {ticker}: {rsi_value}")
else:
date_q = simpledialog.askstring("Input", "Date in Y-M-D Format:")
rsi_value = self.rsi_manager.rsi_calc(ticker, graph = False, date = date_q)
messagebox.showinfo(title = "RSI", message = f"RSI for {ticker} on {date_q}: {rsi_value}")
else:
self.rsi_manager.rsi_calc(ticker, graph, date = None)
def rsi_acc(self):
ticker = simpledialog.askstring("Input", "Name of ticker:").upper()
cos_accuracy, msd_accuracy = self.rsi_manager.rsi_accuracy(ticker)
messagebox.showinfo(title = "RSI Accuracy", message = f"RSI Cosine, MSD Accuracy for {ticker}: {round(cos_accuracy,2)}, {round(msd_accuracy,2)}")
def rsi_turn(self):
ticker = simpledialog.askstring("Input", "Name of ticker:").upper()
turnover = self.rsi_manager.rsi_turnover(ticker)
messagebox.showinfo(title = "RSI Turnover", message = f"The average RSI turnover for {ticker} is {round(turnover,0)} days.")
def MovingAverage(self):
ticker = simpledialog.askstring("Input", "Name of ticker:").upper()
self.rsi_manager.MA(ticker, graph = True)
#def MachineLearning(self):
# ticker = simpledialog.askstring("Input", "Name of ticker:").upper()
# ml(ticker)
def back(self):
self.root.destroy()
class ManageDatabases(GlobalInit):
def __init__(self, root):
super().__init__()
self.root = tk.Tk()
self.root.title("Database Manager")
self.root.geometry("800x600+200+100")
tk.Button(self.root, text="Store", command=self.store).pack(pady=5)
tk.Button(self.root, text="Load", command=self.load).pack(pady=5)
tk.Button(self.root, text="Load WinShort", command=self.loadWinShort).pack(pady=5)
tk.Button(self.root, text="Add Ticker", command=self.add).pack(pady=5)
tk.Button(self.root, text="Remove Ticker", command=self.remove).pack(pady=5)
tk.Button(self.root, text="Reset Database", command=self.reset).pack(pady=5)
tk.Button(self.root, text="Back", command=self.back).pack(pady=50)
def store(self):
input_file = simpledialog.askstring("Input", "File containing tickers:")
dbname = simpledialog.askstring("Input", "Name of database:")
try:
with open(f'./storage/ticker_lists/{input_file}.txt', 'r') as txt:
data_txt = txt.read()
data_txt = data_txt.split('\n')
stock_list = list(data_txt)
self.db_manager.storeData(dbname, stock_list)
messagebox.showinfo("Info", "Tickers stored successfully.")
except:
messagebox.showinfo("Info", "We ran into a problem, please check names of files and resubmit.")
def load(self):
#try:
load_window = LoadWindow(self.root)
load_window.run()
#except:
# messagebox.showinfo("Sort", "There has been a typo.")
def loadWinShort(self):
winshort_window = WinShortWindow(self.root)
winshort_window.run()
def add(self):
dbname = simpledialog.askstring("Input", "Name of database:")
ticker = simpledialog.askstring("Input", "Name of ticker:").upper()
self.db_manager.addData(ticker, dbname)
def remove(self):
dbname = simpledialog.askstring("Input", "Name of database:")
ticker = simpledialog.askstring("Input", "Name of ticker:").upper()
self.db_manager.remData(ticker, dbname)
def reset(self):
dbname = simpledialog.askstring("Input", "Name of database:")
self.db_manager.resetData(dbname)
def back(self):
self.root.destroy()
def run(self):
self.root.mainloop()
#WIP
class PortWindow(GlobalInit):
def __init__(self, root):
self.root = tk.Tk()
self.root.title = "Portfolio Manager"
self.root.geometry("800x600+200+100")
tk.Button(self.root, text = "Portfolio", command = self.portfolio).pack(pady=5)
tk.Button(self.root, text = "Portfolio Update", command = self.updatePortfolio).pack(pady=5)
tk.Button(self.root, text="Back", command=self.back).pack(pady=50)
def portfolio(self):
dbname = simpledialog.askstring("Input", "Name of database:")
self.update_manager.mainPortfolio(dbname)
def back(self):
self.root.destroy()
def updatePortfolio(self):
dbname = simpledialog.askstring("Input", "Name of database:")
self.update_manager.updatePortfolio(dbname)
def run(self):
self.root.mainloop()
class AppWindow(GlobalInit):
def __init__(self, root):
super().__init__()
self.root = tk.Tk()
self.root.title = "Application Manager"
self.root.geometry("800x600+200+100")
tk.Button(self.root, text = "Converter", command = self.converter).pack(pady=5)
tk.Button(self.root, text = "Scraper", command = self.scraper).pack(pady=5)
tk.Button(self.root, text = "Back", command = self.back).pack(pady=5)
def scraper(self):
index = simpledialog.askstring("Input", "Name of index (eg. dowjones, sp500, nasdaq100):")
filename = simpledialog.askstring("Input", "Output file:")
choice = simpledialog.askstring("Input", "Add or Overwrite to file?")
scraper(index, choice, filename)
def converter(self):
convert()
def back(self):
self.root.destroy()
def run(self):
self.root.mainloop()
class SettingsWindow(GlobalInit): ##should make this resemble a settings screen - auto popup choices of database then switches etc
def __init__(self,root):
super().__init__()
self.root = tk.Tk()
self.root.title("Settings")
self.root.geometry("800x600+200+100")
tk.Button(self.root, text="Startup", command = self.startup).pack(pady=5)
tk.Button(self.root, text="Back", command = self.startup).pack(pady=5)
def startup(self):
self.settings_manager.loadSettings()
database = simpledialog.askstring("Input", "Name of database:").strip()
choice = messagebox.askyesno("Y/N", "Would you like this database to update on startup?")
self.settings_manager.adjustSettings(database, choice)
def back(self):
self.root.destroy()
def run(self):
self.root.mainloop()
class WinShortWindow: #paused shortrate() project, not interested in data.
def __init__(self, root):
self.root = tk.Tk()
self.root.title("Winrate Results/Shorting Results")
self.root.geometry("1500x800+200+100")
def WinFrame(self):
win_frame = tk.Frame(self.root)
win_frame.pack(fill = tk.X, expand = True)
win_canvas = tk.Canvas(win_frame, width=1480, height=380, highlightthickness = 1, highlightbackground = 'black')
win_canvas.pack(side=tk.LEFT)
y_scrollbar = tk.Scrollbar(win_frame, orient=tk.VERTICAL, command=win_canvas.yview)
y_scrollbar.pack(side=tk.LEFT, fill=tk.Y)
y_pos = 20
win_canvas.create_text(750, y_pos, text="Potential Sell", font=("Arial", 16), anchor = "center")
y_pos += 20
db, dbfile = open_file('winrate_potential')
for key, value in db.items():
label_text = f"{key}: {value} \n"
y_pos +=15
win_canvas.create_text(750, y_pos, text=label_text, anchor = "center")
y_pos += 20
win_canvas.create_text(750, y_pos, text="Sold", font=("Arial", 16), anchor = "center")
y_pos += 20
db, dbfile = open_file('winrate')
for key, value in db.items():
label_text = f"{key}: {value} \n"
y_pos +=15
win_canvas.create_text(750, y_pos, text=label_text, anchor = "center")
y_pos += 20
win_canvas.create_text(750, y_pos, text="Holding", font=("Arial", 16), anchor = "center")
y_pos += 20
db, dbfile = open_file('winrate_storage')
db_sorted = dict(sorted(db.items(), key=lambda x: x[1]["Date"]))
for key, value in db_sorted.items():
label_text = f"{key}: {value}\n"
y_pos +=15
win_canvas.create_text(750, y_pos, text=label_text, anchor = "center")
actual_height= y_pos
win_canvas.configure(yscrollcommand=y_scrollbar.set, scrollregion=(0,0,750, actual_height))
def ShortFrame(self):
short_frame = tk.Frame(self.root)
short_frame.pack(fill = tk.X, expand = True)
short_canvas = tk.Canvas(short_frame, width=1480, height=380, highlightthickness = 1, highlightbackground = 'black')
short_canvas.pack(side=tk.LEFT)
y_scrollbar = tk.Scrollbar(short_frame, orient=tk.VERTICAL, command=short_canvas.yview)
y_scrollbar.pack(side=tk.LEFT, fill=tk.Y)
y_pos = 20
short_canvas.create_text(750, y_pos, text="Potential Sell", font=("Arial", 16), anchor = "center")
y_pos += 20
db, dbfile = open_file('shortrate_potential')
for key, value in db.items():
label_text = f"{key}: {value} \n"
y_pos +=15
short_canvas.create_text(750, y_pos, text=label_text, anchor = "center")
y_pos += 20
short_canvas.create_text(750, y_pos, text="Sold", font=("Arial", 16), anchor = "center")
y_pos += 20
db, dbfile = open_file('shortrate')
for key, value in db.items():
label_text = f"{key}: {value}\n"
y_pos +=15
short_canvas.create_text(750, y_pos, text=label_text, anchor = "center")
print(f"{key}: {value}\n")
short_canvas.create_text(750, y_pos, text="Holding", font=("Arial", 16), anchor = "center")
y_pos += 20
db, dbfile = open_file('shortrate_storage')
db_sorted = dict(sorted(db.items(), key=lambda x: x[1]["Date"]))
for key, value in db_sorted.items():
label_text = f"{key}: {value}\n"
y_pos +=15
short_canvas.create_text(750, y_pos, text=label_text, anchor = "center")
actual_height= y_pos
short_canvas.configure(yscrollcommand=y_scrollbar.set, scrollregion=(0,0,750, actual_height))
def run(self):
self.WinFrame()
#self.ShortFrame()
self.root.mainloop()
class LoadWindow(GlobalInit): #fix bug related to multiple windows appearing
def __init__(self, root):
super().__init__()
self.root = tk.Tk()
self.root.title = "Loaded Results"
self.root.geometry("1400x1000+400+200")
def load(self):
dbname = simpledialog.askstring("Input", "Name of database:")
sort_choice = simpledialog.askstring("Sort", "Sort by over 95% (short), under 95% (normal), RSI (RSI), RSI accuracy (MSD), or RSI turnover (turn)? ('short ', 'normal', 'MSD', 'RSI', 'turn) ").lower().strip()
sorted_data = self.db_manager.loadData(dbname, sort_choice)
load_frame = tk.Frame(self.root)
load_frame.pack(fill = tk.X, expand = True)
load_canvas = tk.Canvas(load_frame, width=1380, height=900)
load_canvas.pack(side=tk.LEFT)
y_scrollbar = tk.Scrollbar(load_frame, orient=tk.VERTICAL, command=load_canvas.yview)
y_scrollbar.pack(side=tk.LEFT, fill=tk.Y)
y_pos = 10
for ticker in sorted_data:
load_canvas.create_text(750, y_pos, text=ticker, anchor = "center")
y_pos +=15
actual_height= y_pos
load_canvas.configure(yscrollcommand=y_scrollbar.set, scrollregion=(0,0,750, actual_height))
def run(self):
load_window = LoadWindow(self.root)
load_window.load()
self.root.mainloop()
root = tk.Tk()
app = StockTracker(root)
root.geometry("500x800+50+100")
root.mainloop()
"""
def update_all():
db_w_s, dbfile_w_s = open_file('winrate_storage') #holds
db_w, dbfile_w = open_file('winrate') #sold
db_w_p, dbfile_w_p = open_file('winrate_potential')
db_s, dbfile_s = open_file('shortrate') #sold
db_s_s, dbfile_s_s = open_file('shortrate_storage') #holds
db_s_p, dbfile_s_p = open_file('shortrate_potential')
db_ticker, dbfile_ticker = open_file('t_safe')
for ticker, ticker_data in db_ticker.items():
if ticker in db_w_s:
db_w_s[ticker]['MA Converging'] = ticker_data['MA Converging']
print(f'Updated {ticker}')
close_file(db_w_s, 'winrate_storage')
for ticker, ticker_data in db_ticker.items():
if ticker in db_w:
db_w[ticker]['MA Converging'] = ticker_data['MA Converging']
print(f'Updated {ticker}')
close_file(db_w, 'winrate')
for ticker, ticker_data in db_ticker.items():
if ticker in db_w_p:
db_w_p[ticker]['MA Converging'] = ticker_data['MA Converging']
print(f'Updated {ticker}')
close_file(db_w_p, 'winrate_potential')
for ticker, ticker_data in db_ticker.items():
if ticker in db_s_s:
db_s_s[ticker]['MA Converging'] = ticker_data['MA Converging']
print(f'Updated {ticker}')
close_file(db_s_s, 'shortrate_storage')
update_all()
"""