-
Notifications
You must be signed in to change notification settings - Fork 1
/
PortfolioMgr.py
1485 lines (1309 loc) · 77.4 KB
/
PortfolioMgr.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
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#v1.0
#v0.9 - All research graph via menu & mouse click
#v0.8 - Candlestick graphs
#v0.7 - Base version with all graphs and bug fixes, added code to github desktop
#v0.6
#v0.5
#v0.4 - Features as below
# 1. File->Save current scripts in tree as portfolio to a file
# 2. File->Open existing portfolio file and render data in tree
# 3. Manage Portfolio->Add script to tree via menu
# 4. Manage Portfolio->Refresh selected script from tree.
# This takes current market price and updates the current value for that script
# 5. Manage portfolio->Delete selected script from portfolio.
# Entire data is deleted from Tree, but the file is not updated
# 6. Analyze script->Get Quote. Search script (type first few chars
# & enter or click search button). Click Get Quote to get current price.
# You can select specific indicator to see the performance graph of current script
# You can use Add script button to add the script in Tree
# 7. Analyze Script->Show historical proce series of selected script. Shows close price graph
# Note: this should be move to right click menu
# 8. Analyze Script->Compare Price Vs SMA. Currently shows popup graph
# Note: 7 & 8 needs to be merged and the graph needs to be shown in main window on
# right click menu
# 9. Help-> Test Mode (On/Off). Toggle the test mode. In Test mode we use file to
# load specific script data
# 10.Mouse right click->Delete. Deletes the currently selected portfolio entry from tree only.
# The data is not saved to file
# 11. Mouse right click->Modify selected script from tree. You can change the quantity,
# rate, commission etc. Based on the values the cost of investment will be updated
# This will also take current market price and update all current value field in Tree
# 5. Mouse right click->Performance. Shows current value for total holding, shows other
# comparison graph and return graph as well
# Note: this needs to be moved in main window
from tkinter import *
from tkinter import ttk
from tkinter import scrolledtext as tkst
from tkinter import messagebox as msgbx
from tkinter.filedialog import *
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
import pandas as pd
from pandas import DataFrame
from matplotlib.pyplot import Figure
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import interactive
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import warnings
from datetime import date
import os.path as ospath
from scripttree import *
from addnewmodifyscript import *
from backtestsma import *
from getquote import *
from testdata import *
from graphresearch import *
from downloaddata import *
from portfoliovaluation import *
from addaccesskey import *
class PortfolioManager:
def __init__(self):
super().__init__()
self.bool_test = False
self.output_counter = 0
self.currentScript = ''
#graph related variables
self.LookbackYears = 1 #we will analyze last one year date from today
self.graphctr = 1
# Now set the stretch options so that the widget are seen properly when window is resized
self.tickmark = '√' #Alt+251
self.dictgraphmenu = ({'m1':(3, 3, 0)}, {'m2':(3, 3, 0)}, {'m3':(3, 3, 0)},
{'m4':(3, 3, 0)}, {'m5':(3, 3, 0)}, {'m6':(3, 3, 0)},
{'m7':(3, 3, 0)}, {'m8':(3, 3, 0)}, {'m9':(3, 3, 0)})
#array to hold axes
self.ax = [None, None, None, None, None, None, None, None, None]
self.annotate_state = [None, None, None, None, None, None, None, None, None]
#DF for current script
self.dfDaily = DataFrame()
self.dfSMA = DataFrame()
self.dfIntra = DataFrame()
self.dfVWMP = DataFrame()
self.dfRSI = DataFrame()
self.dfStoch = DataFrame()
self.dfMACD = DataFrame()
self.dfAROON = DataFrame()
self.dfBBANDS = DataFrame()
self.dfADX = DataFrame()
self.event = None
self.annotate_visible = False
# Set Alpha Vantage key and create timeseriese and time indicator objects
#self.key = 'XXXX'
if(ospath.isfile('key_folder.txt')):
with open('key_folder.txt', 'r') as f:
d = f.read().split(',')
f.close()
self.key = d[0]
self.datafolderpath = d[1]
else:
self.key = 'UV6KQA6735QZKBTV'
self.datafolderpath = './scriptdata'
# get your key from https://www.alphavantage.co/support/#api-key
# ts = TimeSeries(key, output_format='json')
self.ts = TimeSeries(self.key, output_format='pandas')
self.ti = TechIndicators(self.key, output_format='pandas')
# Now create tkinter root object and the frame object on which we will place the other widgets
self.root = Tk()
#self.root.state('zoomed') #this maximizes the app window
self.root.state('normal') #this maximizes the app window
self.root.title('Stock Analytics - Online mode')
self.content = ttk.Frame(self.root, padding=(5, 5, 12, 0))
self.content.grid(column=0, row=0, sticky=(N, S, E, W))
self.root.wm_protocol("WM_DELETE_WINDOW", self.OnClose)
# add main menu object
self.menu= Menu(master=self.root)
self.root.config(menu=self.menu)
# add file menu
self.file_menu=Menu(self.menu, tearoff=0)
self.file_menu.add_command(label="New Portfolio", underline = 0, command=self.menuNewPortfolio)
self.file_menu.add_command(label="Open Portfolio", underline = 0, command=self.menuOpenPortfolio)
self.file_menu.add_command(label="Save Portfolio", underline = 0, command=self.menuSavePortfolio)
self.file_menu.add_separator()
self.file_menu.add_command(label="Exit", underline = 1, command=self.OnClose)
self.menu.add_cascade(label='File', underline = 0, menu=self.file_menu)
# add manage script menu
self.script_menu=Menu(self.menu, tearoff=0)
self.script_menu.add_command(label="Add New Script", underline = 0, command=self.menuAddScript)
self.script_menu.add_command(label="Delete Selected Script from Portfolio", underline = 0, command=self.menuDeleteSelectedScriptFromPortfolio)
self.script_menu.add_separator()
self.script_menu.add_command(label="Get Quote", underline = 0, command=self.menuGetStockQuote)
self.script_menu.add_separator()
self.script_menu.add_command(label="Refresh Selected Script with Market Price", underline = 0, command=self.menuRefreshScriptData)
self.script_menu.add_separator()
self.script_menu.add_command(label="Portfolio performance", underline = 0, command=self.menuPortfolioPerformance)
self.menu.add_cascade(label='Manage Portfolio', underline = 0, menu=self.script_menu)
# research script menu
self.research_menu=Menu(self.menu, tearoff=0)
self.research_menu.add_command(label="Graphs", underline = 0, command=self.menuResearchGraphs)
self.menu.add_cascade(label='Research', underline = 0, menu=self.research_menu)
# add help menu
self.help_menu=Menu(self.menu, tearoff=0)
self.help_menu.add_command(label="Add Key & Data Folder", underline = 0, command=self.menuKeyDataFolder)
self.help_menu.add_separator()
self.help_menu.add_command(label="Mode (Online/Offline)", underline = 0, command=self.menuSetTestMode)
self.help_menu.add_command(label="Download Data", underline = 0, command=self.menuDownloadData)
self.help_menu.add_separator()
self.menu.add_cascade(label='Help', underline = 0, menu=self.help_menu)
# plot variable used to plot 9 standard graphs, enabled via right click menu
self.f = Figure(figsize=(15,7), dpi=100, facecolor='w', edgecolor='k', tight_layout=True, linewidth=0.5)
self.output_canvas=FigureCanvasTkAgg(self.f, master=self.content)
self.toolbar_frame=Frame(master=self.root)
self.toolbar = NavigationToolbar2Tk(self.output_canvas, self.toolbar_frame)
self.output_canvas.mpl_connect('pick_event', self.OnPicker)
self.xmouseposition = None
self.ymouseposition = None
self.output_tree = ScriptTreeView(self.content, self.ts, self.ti, self.f, self.bool_test, self.output_canvas, self.toolbar, self.datafolderpath, selectmode='browse')
#self.output_tree.bind('<<TreeviewSelect>>', self.TreeViewSelectionChanged)
self.popup_menu_righclick = Menu(self.menu, tearoff=0)
"""self.popup_menu_righclick.add_command(label="Delete", underline = 0, command=self.menuDeleteSelectedScript)
self.popup_menu_righclick.add_command(label="Modify", underline = 0, command=self.menuModifySelectedScript)
self.popup_menu_righclick.add_separator()"""
self.popup_menu_rightclick_performance = Menu(self.popup_menu_righclick, tearoff=0)
self.popup_menu_rightclick_performance.add_command(label="Script-Show All", underline = 12, command=self.menuShowScriptPerformanceAllGraphs)
self.popup_menu_rightclick_performance.add_command(label="Script-Show Performance", underline = 12, command=self.menuShowScriptPerformance)
self.popup_menu_rightclick_performance.add_command(label="Script-Show Candle stick OHLC", underline = 12, command=self.menuShowScriptCandlestick)
self.popup_menu_rightclick_performance.add_command(label="Script-Show Buy & Sell prediction", underline = 12, command=self.menuShowScriptBuySell)
self.popup_menu_rightclick_performance.add_command(label="Script-Show Returns", underline = 12, command=self.menuShowScriptReturns)
self.popup_menu_righclick.add_cascade(label='Script Performance Graphs', menu=self.popup_menu_rightclick_performance, underline=0)
self.popup_menu_righclick.add_separator()
self.POSrightclickmenuDailyVsSMA = BooleanVar(False)
self.popup_menu_righclick.add_checkbutton(label="Daily closing Vs 20 SMA", onvalue=True, offvalue=False, variable=self.POSrightclickmenuDailyVsSMA, command=self.rightclickmenuDailyVsSMA)
#self.POSrightclickmenuDailyVsSMA = 5
self.POSrightclickmenuIntraDay = BooleanVar(False)
self.popup_menu_righclick.add_checkbutton(label="Intra-day", onvalue=True, offvalue=False, variable=self.POSrightclickmenuIntraDay, command=self.rightclickmenuIntraDay)
#self.POSrightclickmenuIntraDay = 6
self.POSrightclickmenuVWAP=BooleanVar(False)
self.popup_menu_righclick.add_checkbutton(label="Volume Weighted Avg Price", onvalue=True, offvalue=False, variable=self.POSrightclickmenuVWAP, command=self.rightclickmenuVWAP)
#self.POSrightclickmenuVWAP=7
self.POSrightclickmenuRSI= BooleanVar(False)
self.popup_menu_righclick.add_checkbutton(label="RSI", onvalue=True, offvalue=False, variable=self.POSrightclickmenuRSI, command=self.rightclickmenuRSI)
#self.POSrightclickmenuRSI=8
self.POSrightclickmenuADX= BooleanVar(False)
self.popup_menu_righclick.add_checkbutton(label="ADX", onvalue=True, offvalue=False, variable=self.POSrightclickmenuADX, command=self.rightclickmenuADX)
#self.POSrightclickmenuADX=9
self.POSrightclickmenuStochasticOscillator= BooleanVar(False)
self.popup_menu_righclick.add_checkbutton(label="Stochastic Oscillator", onvalue=True, offvalue=False, variable=self.POSrightclickmenuStochasticOscillator, command=self.rightclickmenuStochasticOscillator)
#self.POSrightclickmenuStochasticOscillator=10
self.POSrightclickmenuMACD= BooleanVar(False)
self.popup_menu_righclick.add_checkbutton(label="Moving Avg convergence/divergence", onvalue=True, offvalue=False, variable=self.POSrightclickmenuMACD, command=self.rightclickmenuMACD)
#self.POSrightclickmenuMACD=11
self.POSrightclickmenuAROON= BooleanVar(False)
self.popup_menu_righclick.add_checkbutton(label="AROON", onvalue=True, offvalue=False, variable=self.POSrightclickmenuAROON, command=self.rightclickmenuAROON)
#self.POSrightclickmenuAROON=12
self.POSrightclickmenuBBands= BooleanVar(False)
self.bbandmenu = self.popup_menu_righclick.add_checkbutton(label="Bollinger Bands", onvalue=True, offvalue=False, variable=self.POSrightclickmenuBBands, command=self.rightclickmenuBBands)
#self.POSrightclickmenuBBands=13
self.popup_menu_righclick.add_separator()
self.popup_menu_righclick.add_command(label="Clear All Graphs", underline = 0, command=self.menuClearAllGraphs)
#self.POSrightclickmenuBBands=13
self.popup_menu_righclick.add_separator()
self.popup_menu_righclick.add_command(label="Delete selected transaction", underline = 0, command=self.menuDeleteSelectedScript)
self.popup_menu_righclick.add_command(label="Modify selected transaction", underline = 0, command=self.menuModifySelectedScript)
self.popup_ongraph = Menu(self.menu, tearoff=0)
self.popup_ongraph.add_command(label="Detail Graph", command=self.OnDetailGraph)
self.popup_ongraph.add_command(label="Analysis", command=self.OnAnalysis)
self.popup_ongraph.add_command(label="Clear Graph", command=self.OnClearGraph)
self.output_tree.bind('<Button-3>', self.OnRightClick)
self.output_tree.grid(row=0, column=0, rowspan=1, columnspan=11, sticky=(N,E, W, S))
self.output_tree.vert_scroll.grid(row=0, column=11, sticky=(N, E, S))
self.output_tree.horiz_scroll.grid(row=1, column=0, columnspan=11, sticky=(N, E, W, S))
self.output_canvas.get_tk_widget().grid(row=2, column=0, columnspan=11, sticky=(N, E, W))
self.toolbar_frame.grid(row=3, column=0, columnspan=11, sticky=(N, E, W))
self.toolbar.grid(row=0, column=0, sticky=(N, W))
#initialize the 9 plot areas and set the visibility to false
for i in range(9):
self.ax[i] = self.f.add_subplot(3,3,i+1, visible=False)
# handles returned by the mouse move and mouse click event on plot areas
self.cid_leftclick = None
self.cid_leftrelease = None
self.cid_mouse_move = None
self.root.columnconfigure(0, weight=1)
self.root.rowconfigure(0, weight=1)
self.content.columnconfigure(0, weight=1)
mainloop()
def OnClose(self):
self.root.destroy()
def resetExisting(self):
#global output_counter
# delete existing tree items
self.currentScript = ''
self.output_tree.delete(*self.output_tree.get_children())
bShouldRestMenu = self.TreeViewSelectionChanged()
if( bShouldRestMenu):
self.resetMenuticktoFalse()
self.f.clf()
if(self.output_tree.output_counter > 0):
self.output_tree.output_counter = 1
"""Method - menuAddScript
Adds a new script to the tree view """
def menuAddScript(self):
dnewscript = dict()
dnewscript = classAddNewModifyScript(master=self.root, argkey=self.key).show()
# returns dictionary - {'Symbol': 'LT.BSE', 'Price': '1000', 'Date': '2020-02-22', 'Quantity': '10', 'Commission': '1', 'Cost': '10001.0'}
if((dnewscript != None) and (len(dnewscript['Symbol']) >0)):
stock_name = dnewscript['Symbol']
listnewscript = list(dnewscript.items())
#argHoldingIID="", argStockName=stock_name, argPriceDf=DataFrame()
self.output_tree.get_stock_quote("", stock_name, DataFrame(), listnewscript[1][0] + '=' +listnewscript[1][1],
listnewscript[2][0] + '=' + listnewscript[2][1],
listnewscript[3][0] + '=' + listnewscript[3][1],
listnewscript[4][0] + '=' + listnewscript[4][1],
listnewscript[5][0] + '=' + listnewscript[5][1])
#dnewscript['Price'], dnewscript['Date'],
# dnewscript['Quantity'], dnewscript['Commission'], dnewscript['Cost'])
""" menuDeleteSelectedScriptFromPortfolio """
def menuDeleteSelectedScriptFromPortfolio(self):
item = self.output_tree.get_parent_item()
if(len(item) > 0):
try:
if(msgbx.askyesno('Delete script from portfolio', 'Are you sure you want to delete entire script data?: '+ item + '?')):
self.output_tree.delete(item)
self.output_tree.update()
msgbx.showinfo('Delete Script from portfolio', "Selected script deleted successfully from portfolio. Please make sure to save portfolio!")
except Exception as e:
msgbx.showerror('Delete Error', "Selected entry could not be deleted due to error:-" + str(e))
return
""" Method - menuRefreshScriptData
Looks up the market data and refreshes the same along with updating existing holding records"""
def menuRefreshScriptData(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
return
self.output_tree.get_stock_quote("", script_name, DataFrame(),"Purchase Price="+'', "Purchase Date="+'',
"Purchase Qty="+'', "Commission Paid="+'', "Cost of Investment="+'')
"""menuModifySelectedScript"""
def menuModifySelectedScript(self):
rowid = self.output_tree.is_market_holding_col_row()
if(len(rowid) <= 0):
msgbx.showwarning("Modify Script", "Please select valid script row to modify")
return
else:
script_name = self.output_tree.get_parent_item(rowid)
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
return
row_val = self.output_tree.item(rowid, 'values')
dmodifyscript = dict()
dmodifyscript = classAddNewModifyScript(master=self.root, argisadd=False, argscript=script_name,
argPurchasePrice=row_val[0], argPurchaseDate=row_val[1], argPurchaseQty=row_val[2], argCommissionPaid=row_val[3], argCostofInvestment=row_val[4]).show()
# returns dictionary - {'Symbol': 'LT.BSE', 'Price': '1000', 'Date': '2020-02-22', 'Quantity': '10', 'Commission': '1', 'Cost': '10001.0'}
if((dmodifyscript != None) and (len(dmodifyscript['Symbol']) >0)):
stock_name = dmodifyscript['Symbol']
listnewscript = list(dmodifyscript.items())
self.output_tree.get_stock_quote(rowid, stock_name, DataFrame(), listnewscript[1][0] + '=' +listnewscript[1][1],
listnewscript[2][0] + '=' + listnewscript[2][1],
listnewscript[3][0] + '=' + listnewscript[3][1],
listnewscript[4][0] + '=' + listnewscript[4][1],
listnewscript[5][0] + '=' + listnewscript[5][1])
""" Method - menuDeleteSelectedScript
Deletes selection. If parent script is selected everything is deleted
else individual row under parent is selected
if selection is MARKETCOL or HOLDINGCOL then nothing will be deleted"""
def menuDeleteSelectedScript(self):
item = self.output_tree.is_market_holding_col_row()
if(len(item) > 0):
try:
if(msgbx.askyesno('Delete script', 'Are you sure you want to delete: '+ item + '?')):
self.output_tree.delete(item)
self.output_tree.update()
msgbx.showinfo('Delete Script', "Selected entry deleted successfully. Please make sure to save updated portfolio!")
except Exception as e:
msgbx.showerror('Delete Error', "Selected entry could not be deleted due to error:-" + str(e))
return
def menuPortfolioPerformance(self):
obj = PortfolioValuation(master=self.root, argkey=self.key,
argscripttree=self.output_tree,argIsTest=self.bool_test, argDataFolder=self.datafolderpath)
obj.ShowPortfolioPerformance()
""" called on right click menu selection """
def menuShowScriptPerformanceAllGraphs(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
return
# Now get the purchase price if available
holdinvalobj = BackTestSMA(master=self.root, argkey=self.key, argscript=script_name,
argscripttree=self.output_tree, argavgsmall=10, argavglarge=20, arglookbackyears=1,
argIsTest=self.bool_test, argDataFolder=self.datafolderpath)
holdinvalobj.findScriptPerformance(argShowPerformance=True, argShowCandlestick=True,
argShowMarketData=True, argShowReturns=True)
holdinvalobj.show()
return
""" called on right click menu selection """
def menuShowScriptPerformance(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
return
# Now get the purchase price if available
holdinvalobj = BackTestSMA(master=self.root, argkey=self.key, argscript=script_name,
argscripttree=self.output_tree, argavgsmall=10, argavglarge=20, arglookbackyears=1,
argIsTest=self.bool_test, argDataFolder=self.datafolderpath)
holdinvalobj.findScriptPerformance(argShowPerformance=True, argShowCandlestick=False,
argShowMarketData=False, argShowReturns=False)
holdinvalobj.show()
return
""" called on right click menu selection """
def menuShowScriptCandlestick(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
return
# Now get the purchase price if available
holdinvalobj = BackTestSMA(master=self.root, argkey=self.key, argscript=script_name,
argscripttree=self.output_tree, argavgsmall=10, argavglarge=20, arglookbackyears=1,
argIsTest=self.bool_test, argDataFolder=self.datafolderpath)
holdinvalobj.findScriptPerformance(argShowPerformance=False, argShowCandlestick=True,
argShowMarketData=False, argShowReturns=False)
holdinvalobj.show()
return
""" called on right click menu selection """
def menuShowScriptBuySell(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
return
# Now get the purchase price if available
holdinvalobj = BackTestSMA(master=self.root, argkey=self.key, argscript=script_name,
argscripttree=self.output_tree, argavgsmall=10, argavglarge=20, arglookbackyears=1,
argIsTest=self.bool_test, argDataFolder=self.datafolderpath)
holdinvalobj.findScriptPerformance(argShowPerformance=False, argShowCandlestick=False,
argShowMarketData=True, argShowReturns=False)
holdinvalobj.show()
return
""" called on right click menu selection """
def menuShowScriptReturns(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
return
# Now get the purchase price if available
holdinvalobj = BackTestSMA(master=self.root, argkey=self.key, argscript=script_name,
argscripttree=self.output_tree, argavgsmall=10, argavglarge=20, arglookbackyears=1,
argIsTest=self.bool_test, argDataFolder=self.datafolderpath)
holdinvalobj.findScriptPerformance(argShowPerformance=False, argShowCandlestick=False,
argShowMarketData=False, argShowReturns=True)
holdinvalobj.show()
return
def menuResearchGraphs(self):
obj = classAllGraphs(master=self.root, argistestmode=self.bool_test,
argkey=self.key, argscript='', argmenucalled=True, arggraphid=-1,
argoutputtree=self.output_tree, argdatafolder=self.datafolderpath)
obj.InitializeWindow()
# command handler for stock quote button
def menuGetStockQuote(self):
obj = classGetQuote(master=self.root, argkey=self.key, argoutputtree=self.output_tree, argIsTest=self.bool_test, argDataFolder=self.datafolderpath)
obj.show()
return;
# command handler for intra day
def menuGetIntraDay(self):
return True
# command handler for daily stock
def menuDailyStock(self):
return True
# This method is called from right click event
def TreeViewSelectionChanged(self):
tree_depth = self.output_tree.get_children()
if(len(tree_depth) > 0): #make sure call was not from resetExisting
tempParent = self.output_tree.get_parent_item()
if(len(self.currentScript) == 0):
self.currentScript = tempParent
elif (tempParent != self.currentScript): #check if any graphs are shown in figure & clear them if there are
for i in range(len(self.ax)):
self.ax[i].clear()
self.ax[i].set_visible(False)
self.dfDaily = DataFrame()
self.dfSMA = DataFrame()
self.dfIntra = DataFrame()
self.dfVWMP = DataFrame()
self.dfRSI = DataFrame()
self.dfStoch = DataFrame()
self.dfMACD = DataFrame()
self.dfAROON = DataFrame()
self.dfBBANDS = DataFrame()
self.dfADX = DataFrame()
self.mouseClickMoveEnableDisable(False)
self.graphctr = 1
self.currentScript = tempParent
self.f.clear()
self.setFigureCommonConfig(self.currentScript)
#self.f.suptitle("", size='small')
return True
else:
self.currentScript = ''
for i in range(len(self.ax)):
self.ax[i].clear()
self.ax[i].set_visible(False)
self.dfDaily = DataFrame()
self.dfSMA = DataFrame()
self.dfIntra = DataFrame()
self.dfVWMP = DataFrame()
self.dfRSI = DataFrame()
self.dfStoch = DataFrame()
self.dfMACD = DataFrame()
self.dfAROON = DataFrame()
self.dfBBANDS = DataFrame()
self.dfADX = DataFrame()
self.mouseClickMoveEnableDisable(False)
self.graphctr = 1
self.f.clear()
self.setFigureCommonConfig(self.currentScript)
return True
return False
# This method is called by each right click plot menu handlers when menu variable is False
# indicating user does not want to see the specific menu graph.
# Here we reduce index of all graphs, whoose index is greater than the current, by one
def clearandresetGraphs(self, argDictIndex, argDictKey):
#ax = plt.subplot(111)
#ax.change_geometry(3,1,1)
#first clear the current deselected graph
try:
self.ax[argDictIndex].clear()
self.ax[argDictIndex].set_visible(False)
self.f.delaxes(self.ax[argDictIndex])
if(self.graphctr > 1):
currdict = self.dictgraphmenu[argDictIndex]
for each in range(0, len(self.dictgraphmenu)):
tempdict = self.dictgraphmenu[each]
for key in tempdict:
if( currdict[argDictKey][2] < tempdict[key][2]):
tempdict[key] = (tempdict[key][0], tempdict[key][1], tempdict[key][2]-1)
self.ax[each].change_geometry(tempdict[key][0], tempdict[key][1], tempdict[key][2])
self.graphctr -= 1
elif(self.graphctr == 1):
self.mouseClickMoveEnableDisable(False)
except Exception as e:
msgbx.showerror("Clear & Reset Graph", "Exception: " + str(e))
return False
return True
# argLookbackYears - is the no of years we want to go back from today
# if today is 2020-03-23 & argLookbackYears = 1, return will be 2019-03-23
# the expetion takes care of leap year
def getPastDateFromToday(self, argLookbackYears):
try:
dt = date.today()
dt = dt.replace(year=dt.year-argLookbackYears)
except ValueError:
dt = dt.replace(year=dt.year-argLookbackYears, day=dt.day-1)
return str(dt)
#common method to set figure variables called by each right click plot menu handlers
def setFigureCommonConfig(self, script_name):
self.f.suptitle(script_name, size='xx-small', y=.996, weight='semibold')
#self.f.tight_layout()
#self.f.legend(loc='upper right')
#self.output_canvas.set_window_title(script_name)
# toolbar=NavigationToolbar2Tk(output_canvas, output_canvas.get_tk_widget())
self.output_canvas.draw()
self.toolbar.update()
#common method called by each right click menu handlers to set respective Axes properties
# when a new graph is to be shown
def setAxesCommonConfig(self, argAxesIndex, argAxesKey, argScriptName, argTitle):
if(self.graphctr == 1):
self.mouseClickMoveEnableDisable(True)
self.dictgraphmenu[argAxesIndex][argAxesKey] = (self.dictgraphmenu[argAxesIndex][argAxesKey][0], self.dictgraphmenu[argAxesIndex][argAxesKey][1], self.graphctr)
self.graphctr += 1
self.ax[argAxesIndex].tick_params(direction='out', length=6, width=2, colors='black',
grid_color='black', grid_alpha=0.5, labelsize='xx-small')
self.ax[argAxesIndex].tick_params(axis='x', labelrotation=30)
self.ax[argAxesIndex].grid(True)
self.ax[argAxesIndex].set_title(argTitle, size='xx-small')
self.ax[argAxesIndex].legend(fontsize='xx-small')
#Helper method to reverse the state of right click menu
def reverseMenutick(self, argCurrentMenuState):
if(argCurrentMenuState.get() == True):
return False
return True
#When user selects a new script from Tree View, this method will set the right click
# menu handlers to False, called from right click even handlers
def resetMenuticktoFalse(self):
self.POSrightclickmenuDailyVsSMA.set(False)
self.POSrightclickmenuAROON.set(False)
self.POSrightclickmenuBBands.set(False)
self.POSrightclickmenuIntraDay.set(False)
self.POSrightclickmenuMACD.set(False)
self.POSrightclickmenuRSI.set(False)
self.POSrightclickmenuADX.set(False)
self.POSrightclickmenuStochasticOscillator.set(False)
self.POSrightclickmenuVWAP.set(False)
# Method to bind & unbind the mouse move & mouse click events in plot area
# Called from setAxesCommonConfig when graphctr = 1 to bind the events
# Called from clearandresetGraphs when graphctr = 1 to unbind
def mouseClickMoveEnableDisable(self, argbFlag):
if(argbFlag == True):
#self.cid_leftclick = self.output_canvas.callbacks.connect('button_press_event', self.on_click_graphs)
#self.cid_leftrelease = self.output_canvas.callbacks.connect('button_release_event', self.on_release_graphs)
self.cid_mouse_move = self.output_canvas.callbacks.connect('motion_notify_event', self.on_mouse_move)
else:
#if(self.cid_leftclick != None):
# self.output_canvas.callbacks.disconnect(self.cid_leftclick)
#self.cid_leftclick = None
#if(self.cid_leftrelease != None):
# self.output_canvas.callbacks.disconnect(self.cid_leftrelease)
#self.cid_leftrelease = None
self.xmouseposition = None
self.ymouseposition = None
if(self.cid_mouse_move != None):
self.output_canvas.callbacks.disconnect(self.cid_mouse_move)
self.cid_mouse_move = None
""" Method - rightclickmenuDailyVsSMA
Mouse right click- Method shows daily timeseries for selected stock within the app window"""
def rightclickmenuDailyVsSMA(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
self.POSrightclickmenuDailyVsSMA.set(self.reverseMenutick(self.POSrightclickmenuDailyVsSMA))
return
#menutext = self.popup_menu_righclick.entrycget(self.POSrightclickmenuDailyVsSMA, 'label')
#menu.entryconfigure(self.POSrightclickmenuDailyVsSMA, label=menutext[1:])
if(self.POSrightclickmenuDailyVsSMA.get() == False):
self.clearandresetGraphs(0, 'm1')
self.setFigureCommonConfig(script_name)
return
# Get the data, returns a tuple
# aapl_data is a pandas dataframe, aapl_meta_data is a dict
try:
if self.bool_test:
testobj = PrepareTestData(argFolder=self.datafolderpath, argOutputSize='compact')
self.dfDaily = testobj.loadDaily(script_name)
if(self.dfSMA.empty):
self.dfSMA = testobj.loadSMA(script_name)
else:
self.dfDaily, aapl_meta_data = self.ts.get_daily(symbol=script_name)
if(self.dfSMA.empty):
self.dfSMA, aapl_meta_sma = self.ti.get_sma(symbol=script_name)
#the daily compact data has data for 100 days
self.dfDaily=self.dfDaily.sort_index(axis=0, ascending=False)
self.dfSMA=self.dfSMA.sort_index(axis=0, ascending=False)
#Commenting as we are not taking FULL data from get_daily
#pastdate = self.getPastDateFromToday(self.LookbackYears)
#aapl_data=aapl_data.loc[aapl_data.index[:] >= pastdate]
#aapl_sma=aapl_sma.loc[aapl_sma.index[:] >= pastdate]
#commenting the annotation code below as the graph is too small to annotate
"""listpurchasprice = list()
childrows = self.output_tree.get_children(script_name)
for child in childrows:
# now get rows values only for self holding, we will not store market data
if(str(child).upper().find(self.output_tree.HOLDINGVAL) >= 0):
child_val = self.output_tree.item(child, 'values')
listpurchasprice.append([child_val[0], child_val[1]])"""
sizeofdaily = self.dfDaily.index.size
#self.dfSMA = self.dfSMA.head(sizeofdaily)
# Visualization
self.ax[0].clear()
#self.ax[0].set_visible(True)
self.ax[0] = self.f.add_subplot(self.dictgraphmenu[0]['m1'][0], self.dictgraphmenu[0]['m1'][1], self.graphctr, gid=0, visible=True, label='Daily Close Vs SMA')#, title=script_name, label='Daily close price', xlabel='Date', ylabel='Closing price')
self.ax[0].plot(self.dfDaily['4. close'], label='Close', gid=0, marker='*', markersize = 5, markevery=5, picker=5)
#self.ax[0].plot(self.dfDaily['4. close'], 'x', markersize=3)
self.ax[0].plot(self.dfSMA.head(sizeofdaily)['SMA'], gid=0, label='20 SMA', picker=5)
self.ax[0].lines[0].set_pickradius(1)
self.ax[0].lines[1].set_pickradius(2)
#commenting annotations
"""for eachrow in listpurchasprice:
if ((eachrow[0] != '') and (eachrow[1] != '')):
self.ax[0].annotate(eachrow[0], (mdates.datestr2num(eachrow[1]), float(eachrow[0])),
xytext=(15,15), textcoords='offset points', arrowprops=dict(arrowstyle='-|>'))"""
self.setAxesCommonConfig(0, 'm1', script_name, 'Daily Vs 20 SMA')
#self.f.autofmt_xdate()
self.setFigureCommonConfig(script_name)
except Exception as e:
msgbx.showerror('Error', 'Exception in Daily Vs SMA: ' + str(e))
self.POSrightclickmenuDailyVsSMA.set(self.reverseMenutick(self.POSrightclickmenuDailyVsSMA))
""" Method - rightclickmenuIntraDay
Mouse right click- Method shows intraday close timeseries for selected stock within the app window"""
def rightclickmenuIntraDay(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
self.POSrightclickmenuIntraDay.set(self.reverseMenutick(self.POSrightclickmenuIntraDay))
return
if(self.POSrightclickmenuIntraDay.get() == False):
self.clearandresetGraphs(1, 'm2')
self.setFigureCommonConfig(script_name)
return
# Get the data, returns a tuple
# aapl_data is a pandas dataframe, aapl_meta_data is a dict
try:
if(self.bool_test == True):
testobj = PrepareTestData(argFolder=self.datafolderpath)
if(self.dfIntra.empty):
self.dfIntra = testobj.loadIntra(script_name)
else:
if(self.dfIntra.empty):
self.dfIntra, aapl_meta_data = self.ts.get_intraday(symbol=script_name, interval='5min')
self.dfIntra=self.dfIntra.sort_index(axis=0, ascending=False)
latestdt = self.dfIntra.index[0]
latestdt = str(str(latestdt.year) + '-' + str(latestdt.month) + '-' + str(latestdt.day) + ' 00:00:00')
self.dfIntra = self.dfIntra.loc[self.dfIntra.index[:] >= latestdt]
# Visualization
self.ax[1].clear()
self.ax[1] = self.f.add_subplot(self.dictgraphmenu[1]['m2'][0], self.dictgraphmenu[1]['m2'][1], self.graphctr, gid=1, visible=True, label='Intra-Day')#, title=script_name, label='Intra-day', xlabel='Date', ylabel='Intra-day close', visible=True)
self.ax[1].plot(self.dfIntra['4. close'], gid=1, label='Intra-day', marker='x', markersize=5, markevery=5, picker = 5)
self.setAxesCommonConfig(1, 'm2', script_name, 'Intra-day')
self.setFigureCommonConfig(script_name)
except Exception as e:
msgbx.showerror("Error", "Error in IntraDay: " + str(e))
self.POSrightclickmenuIntraDay.set(self.reverseMenutick(self.POSrightclickmenuIntraDay))
def rightclickmenuVWAP(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
self.POSrightclickmenuVWAP.set(self.reverseMenutick(self.POSrightclickmenuVWAP))
return
if(self.POSrightclickmenuVWAP.get() == False):
self.clearandresetGraphs(2, 'm3')
self.setFigureCommonConfig(script_name)
return
try:
if self.bool_test:
testobj = PrepareTestData(argFolder=self.datafolderpath)
self.dfVWMP = testobj.loadVWMP(script_name)
else:
self.dfVWMP, meta_vwap = self.ti.get_vwap(symbol=script_name)
self.dfVWMP=self.dfVWMP.sort_index(axis=0, ascending=False)
latestdt = self.dfVWMP.index[0]
latestdt = str(str(latestdt.year) + '-' + str(latestdt.month) + '-' + str(latestdt.day) + ' 00:00:00')
self.dfVWMP = self.dfVWMP.loc[self.dfVWMP.index[:] >= latestdt]
# Visualization
self.ax[2].clear()
#self.ax[2].set_visible(True)
self.ax[2] = self.f.add_subplot(self.dictgraphmenu[2]['m3'][0], self.dictgraphmenu[2]['m3'][1], self.graphctr, gid=2, visible=True, label='VWAP')
#, title=script_name, label='Intra-day', xlabel='Date', ylabel='Intra-day close', visible=True)
sdateyearback = self.getPastDateFromToday(self.LookbackYears)
self.ax[2].plot(self.dfVWMP.loc[self.dfVWMP.index[:] >= sdateyearback, 'VWAP'], gid=2,label='VWAP', picker=5)
self.setAxesCommonConfig(2, 'm3', script_name, 'Vol Wt Avg Price')
self.setFigureCommonConfig(script_name)
except Exception as e:
msgbx.showerror("Error", "Error in VWAP: " + str(e))
self.POSrightclickmenuVWAP.set(self.reverseMenutick(self.POSrightclickmenuVWAP))
def rightclickmenuRSI(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
self.POSrightclickmenuRSI.set(self.reverseMenutick(self.POSrightclickmenuRSI))
return
if(self.POSrightclickmenuRSI.get() == False):
self.clearandresetGraphs(3, 'm4')
self.setFigureCommonConfig(script_name)
return
try:
if self.bool_test:
testobj = PrepareTestData(argFolder=self.datafolderpath)
self.dfRSI = testobj.loadRSI(script_name)
else:
self.dfRSI, meta_rsi = self.ti.get_rsi(symbol=script_name)
self.dfRSI = self.dfRSI.sort_index(axis=0, ascending=False)
#self.dfRSI = self.dfRSI.head(sizeofintra)
# Visualization
self.ax[3].clear()
#self.ax[3].set_visible(True)
#color = 'tab:red'
self.ax[3] = self.f.add_subplot(self.dictgraphmenu[3]['m4'][0], self.dictgraphmenu[3]['m4'][1], self.graphctr, gid=3, visible=True, label='RSI')#, title=script_name, label='Intra-day', xlabel='Date', ylabel='Intra-day close', visible=True)
#self.ax[3].tick_params(axis='y', labelcolor=color)
#twinax = self.ax[3].twinx()
#color = 'tab:blue'
sdateyearback = self.getPastDateFromToday(self.LookbackYears)
self.ax[3].plot(self.dfRSI.loc[self.dfRSI.index[:] >= sdateyearback, 'RSI'], gid=3,label='RSI', picker=5)
#twinax.tick_params(axis='y', labelcolor=color)
self.setAxesCommonConfig(3, 'm4', script_name, 'RSI')
self.setFigureCommonConfig(script_name)
except Exception as e:
msgbx.showerror("Error", "Error in RSI: " + str(e))
self.POSrightclickmenuVWAP.set(self.reverseMenutick(self.POSrightclickmenuVWAP))
def rightclickmenuADX(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
self.POSrightclickmenuADX.set(self.reverseMenutick(self.POSrightclickmenuADX))
return
if(self.POSrightclickmenuADX.get() == False):
self.clearandresetGraphs(4, 'm5')
self.setFigureCommonConfig(script_name)
return
try:
if self.bool_test:
testobj = PrepareTestData(argFolder=self.datafolderpath)
self.dfADX = testobj.loadADX(script_name)
else:
self.dfADX, meta_adx = self.ti.get_adx(symbol=script_name)
self.dfADX = self.dfADX.sort_index(axis=0, ascending=False)
# Visualization
self.ax[4].clear()
#self.ax[4].set_visible(True)
self.ax[4] = self.f.add_subplot(self.dictgraphmenu[4]['m5'][0], self.dictgraphmenu[4]['m5'][1], self.graphctr, gid=4, visible=True, label='ADX')
#, title=script_name, label='Intra-day', xlabel='Date', ylabel='Intra-day close', visible=True)
sdateyearback = self.getPastDateFromToday(self.LookbackYears)
self.ax[4].plot(self.dfADX.loc[self.dfADX.index[:] >= sdateyearback, 'ADX'], gid=4,label='ADX', picker=5)
self.setAxesCommonConfig(4, 'm5', script_name, 'ADX')
self.setFigureCommonConfig(script_name)
except Exception as e:
msgbx.showerror("Error", "Error in ADX: " + str(e))
self.POSrightclickmenuADX.set(self.reverseMenutick(self.POSrightclickmenuADX))
def rightclickmenuStochasticOscillator(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
self.POSrightclickmenuStochasticOscillator.set(self.reverseMenutick(self.POSrightclickmenuStochasticOscillator))
return
if(self.POSrightclickmenuStochasticOscillator.get() == False):
self.clearandresetGraphs(5, 'm6')
self.setFigureCommonConfig(script_name)
return
try:
if self.bool_test:
testobj = PrepareTestData(argFolder=self.datafolderpath)
self.dfStoch = testobj.loadStochasticOscillator(script_name)
else:
self.dfStoch, meta_stoch = self.ti.get_stoch(symbol=script_name, interval='daily',
fastkperiod=5, slowkperiod=3, slowdperiod=3, slowkmatype=0, slowdmatype=0)
#data_stoch = data_stoch.sort_index(axis=0, ascending=False)
self.dfStoch = self.dfStoch.sort_index(axis=0, ascending=False)
# Visualization
self.ax[5].clear()
#self.ax[5].set_visible(True)
self.ax[5] = self.f.add_subplot(self.dictgraphmenu[5]['m6'][0], self.dictgraphmenu[5]['m6'][1], self.graphctr, gid=5, visible=True, label='STOCH')
#, title=script_name, label='Intra-day', xlabel='Date', ylabel='Intra-day close', visible=True)
sdateyearback = self.getPastDateFromToday(self.LookbackYears)
self.ax[5].plot(self.dfStoch.loc[self.dfStoch.index[:] >= sdateyearback, 'SlowK'], 'b-', gid=5, label='SlowK MA', picker=5)
self.ax[5].plot(self.dfStoch.loc[self.dfStoch.index[:] >= sdateyearback, 'SlowD'], 'r-', gid=5, label='SlowD MA', picker=5)
self.setAxesCommonConfig(5, 'm6', script_name, 'Stoch Oscillator')
self.setFigureCommonConfig(script_name)
except Exception as e:
msgbx.showerror("Error", "Error in STOCH: " + str(e))
self.POSrightclickmenuStochasticOscillator.set(self.reverseMenutick(self.POSrightclickmenuStochasticOscillator))
def rightclickmenuMACD(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
self.POSrightclickmenuMACD.set(self.reverseMenutick(self.POSrightclickmenuMACD))
return
if(self.POSrightclickmenuMACD.get() == False):
self.clearandresetGraphs(6, 'm7')
self.setFigureCommonConfig(script_name)
return
try:
if self.bool_test:
testobj = PrepareTestData(argFolder=self.datafolderpath)
self.dfMACD = testobj.loadMACD(script_name)
else:
self.dfMACD, meta_macd = self.ti.get_macd(symbol=script_name, interval='daily',
series_type='close', fastperiod=12, slowperiod=26, signalperiod=9)
self.dfMACD = self.dfMACD.sort_index(axis=0, ascending=False)
# Visualization
self.ax[6].clear()
#self.ax[6].set_visible(True)
self.ax[6] = self.f.add_subplot(self.dictgraphmenu[6]['m7'][0], self.dictgraphmenu[6]['m7'][1], self.graphctr, gid=6, visible=True, label='MACD')
#, title=script_name, label='Intra-day', xlabel='Date', ylabel='Intra-day close', visible=True)
sdateyearback = self.getPastDateFromToday(self.LookbackYears)
self.ax[6].plot(self.dfMACD.loc[self.dfMACD.index[:] >= sdateyearback, 'MACD_Signal'], 'r-', gid=6, label='Signal', picker=5)
self.ax[6].plot(self.dfMACD.loc[self.dfMACD.index[:] >= sdateyearback, 'MACD'], 'y-', gid=6, label='MACD', picker=5)
self.ax[6].plot(self.dfMACD.loc[self.dfMACD.index[:] >= sdateyearback, 'MACD_Hist'], 'b-', gid=6, label='History', picker=5)
self.setAxesCommonConfig(6, 'm7', script_name, 'MACD')
self.setFigureCommonConfig(script_name)
except Exception as e:
msgbx.showerror("Error", "Error in MACD: "+ str(e))
self.POSrightclickmenuMACD.set(self.reverseMenutick(self.POSrightclickmenuMACD))
def rightclickmenuAROON(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
self.POSrightclickmenuAROON.set(self.reverseMenutick(self.POSrightclickmenuAROON))
return
if(self.POSrightclickmenuAROON.get() == False):
self.clearandresetGraphs(7, 'm8')
self.setFigureCommonConfig(script_name)
return
try:
if self.bool_test:
testobj = PrepareTestData(argFolder=self.datafolderpath)
self.dfAROON = testobj.loadAROON(script_name)
else:
self.dfAROON, meta_aroon = self.ti.get_aroon(symbol=script_name)
self.dfAROON = self.dfAROON.sort_index(axis=0, ascending=False)
# Visualization
self.ax[7].clear()
#self.ax[7].set_visible(True)
self.ax[7] = self.f.add_subplot(self.dictgraphmenu[7]['m8'][0], self.dictgraphmenu[7]['m8'][1], self.graphctr, gid=7, visible=True, label='AROON')
#, title=script_name, label='Intra-day', xlabel='Date', ylabel='Intra-day close', visible=True)
sdateyearback = self.getPastDateFromToday(self.LookbackYears)
self.ax[7].plot(self.dfAROON.loc[self.dfAROON.index[:] >= sdateyearback, 'Aroon Up'], 'r-', gid=7, label='Up', picker=5)
self.ax[7].plot(self.dfAROON.loc[self.dfAROON.index[:] >= sdateyearback, 'Aroon Down'], 'b-', gid=7, label='Down', picker=5)
self.setAxesCommonConfig(7, 'm8', script_name, 'Aroon')
self.setFigureCommonConfig(script_name)
except Exception as e:
msgbx.showerror("Error", "Error in AROON: " + str(e))
self.POSrightclickmenuAROON.set(self.reverseMenutick(self.POSrightclickmenuAROON))
def rightclickmenuBBands(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
self.POSrightclickmenuBBands.set(self.reverseMenutick(self.POSrightclickmenuBBands))
return
if(self.POSrightclickmenuBBands.get() == False):
self.clearandresetGraphs(8, 'm9')
self.setFigureCommonConfig(script_name)
return
try:
if self.bool_test:
testobj = PrepareTestData(argFolder=self.datafolderpath)
self.dfBBANDS=testobj.loadBBands(script_name)
else:
self.dfBBANDS, meta_bbands = self.ti.get_bbands(symbol=script_name, interval='daily',
time_period=20, series_type='close',nbdevup=2, nbdevdn=2, matype=0)
self.dfBBANDS = self.dfBBANDS.sort_index(axis=0, ascending=False)
# Visualization
self.ax[8].clear()
#self.ax[8].set_visible(True)
self.ax[8] = self.f.add_subplot(self.dictgraphmenu[8]['m9'][0], self.dictgraphmenu[8]['m9'][1], self.graphctr, gid=8, visible=True, label='BBANDS')
#, title=script_name, label='Intra-day', xlabel='Date', ylabel='Intra-day close', visible=True)
sdateyearback = self.getPastDateFromToday(self.LookbackYears)
self.ax[8].plot(self.dfBBANDS.loc[self.dfBBANDS.index[:] >= sdateyearback, 'Real Middle Band'], 'r-', gid=8, label='Middle', picker=5)
self.ax[8].plot(self.dfBBANDS.loc[self.dfBBANDS.index[:] >= sdateyearback, 'Real Upper Band'], 'b-', gid=8, label='Upper', picker=5)
self.ax[8].plot(self.dfBBANDS.loc[self.dfBBANDS.index[:] >= sdateyearback, 'Real Lower Band'], 'y-', gid=8, label='Lower', picker=5)
self.setAxesCommonConfig(8, 'm9', script_name, 'Bollinger Bands')
self.setFigureCommonConfig(script_name)
except Exception as e:
msgbx.showerror("Error", "Error in BBANDS: " + str(e))
self.POSrightclickmenuAROON.set(self.reverseMenutick(self.POSrightclickmenuAROON))
def testCompareSMANOTUSED(self):
script_name = self.output_tree.get_parent_item()
if(len(script_name) <=0):
msgbx.showwarning("Warning", "Please select valid row")
return
# Now get the purchase price if available
listpurchasprice = list()
childrows = self.output_tree.get_children(script_name)