-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathstocks_1.py
2087 lines (1090 loc) · 55.9 KB
/
stocks_1.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
#! python
''' Modified the SentDex stock graphing solution found on YouTube. Context
included the series on graphing a Stock, buidling an S&P 500 heatmap,
Tkinter UI series for Bitcoin:
https://www.pythonprogramming.net/
http://www.sentdex.com/
Added GUI, Configuration (ini), Sentiment Analysis and Similar stocks.
Additional software written by John "Bucbowie" Askew. I take full
responsibility for any bugs or design flaws and by no means is
meant to represent the brand "SentDex", nor https://www.pythonprogramming.net/.
TTTTTTTTTT D D
TT D D
TT D D
TT ooooo -- D D ooooo
TT o o D D o o
TT 00000 D D ooooo
1. Convert OHLC to Heiken Ashi OHLC (See Formulaz)
'''
import os, sys
#-------------------------------------#
def popupmsg(msg):
#-------------------------------------#
import tkinter as tk
from tkinter import ttk
popup = tk.Tk()
popup.wm_title(" Warning!")
label = ttk.Label(popup, text = msg)
label.grid(row = 3, column = 5)
B1 = ttk.Button(popup, text = "Okay", command = lambda: popup.destroy())
B1.grid(row = 5, column = 5)
popup.mainloop()
dir_path = os.path.dirname(os.path.realpath(__file__))
os.chdir(dir_path)
try:
from tools_predict_one_day import Prediction_Test
except Exception as e:
msg = "Unable to load tools_predict_generic.py...Skipping predicted prices"
print(e)
popupmsg(msg)
try:
from tools_predict_seven_days import Predict_7_days
except Exception as e:
msg = "Unable to load tools_predict_generic.py...Skipping load tools_predict_seven_days"
print(e)
popupmsg(msg)
try:
from tools_parse_config import ParseConfig
except:
msg = "Unable to find config file. Using defaults"
popupmsg(msg)
movavg_window_days_short_term = 10 #Moving Average 10 days (quick)
movavg_window_days_long_term = 30 #Moving Average 30 days (slow)
macd_periods_long_term = 26
macd_periods_short_term = 12
expma_periods = 9
pct_chg = 'new'
boll = 'y'
boll_window = 20
boll_weight = 2
fib = 'y'
try:
import mpl_finance
except:
os.system('pip install mpl_finance')
import mpl_finance
from formulas import *
from tools_scrape import *
from tools_get_stock_corr import corr
try:
from tools_get_company import *
except:
print("#########################################")
print("ERROR: unable to find tools_get_company.")
print(" Web Sentiment Analysis using")
print(" stock symbol and not company name!")
print("#########################################")
try:
from tools_scrape_profile import *
except:
print("#########################################")
print("ERROR: unable to find tools_scrape_profile.")
print(" using stock symbol and no company info!")
print("#########################################")
try:
from stocks_alt_info import altAnalysis
except Exception as e:
print("Unable to access python module stocks_alt_info. Skipping financial details and continuing on...")
print(e)
try:
import csv
except:
os.system("pip3 install csv")
import csv
import datetime as dt
from datetime import timedelta
try:
import requests
except:
os.system('pip install requests')
import requests
try:
import matplotlib as mpl
except:
os.system('pip3 install matplotlib')
import matplotlib as mpl
try:
import matplotlib.pyplot as plt
except:
os.system("pip3 install matplotlib")
import matplotlib.pyplot as plt
from matplotlib import style
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
try:
import mpl_finance
except:
os.system('pip install mpl_finance')
import mpl_finance
from mpl_finance import candlestick_ohlc
from matplotlib.widgets import Button
try:
import pandas as pd
except:
os.system('pip3 install pandas')
import pandas as pd
try:
import numpy as np
except:
os.system("pip3 install numpy")
import numpy as np
try:
import pandas_datareader.data as web
except:
os.system("pip3 install pandas-datareader")
import pandas_datareader.data as web
try:
from pylab import *
except:
os.system('pip install pylab')
from pylab import *
try:
import re
except:
os.system("pip3 install re")
import re
try:
import getpass
except:
os.system('pip install getpass')
import getpass
try:
import subprocess
except:
os.system("pip install subprocess")
import subprocess
import sys
try:
from datetime import datetime, timedelta
except:
os.system("pip3 install datetime")
from datetime import datetime, timedelta
import time
from pandas.plotting import register_matplotlib_converters
import json
import pprint
style.use('fivethirtyeight')
plt.rcParams['axes.formatter.useoffset'] = False
pd.plotting.register_matplotlib_converters()
stock_date_adj = int(0)
a = ParseConfig()
movavg_window_days_short_term, movavg_window_days_long_term, macd_periods_long_term, macd_periods_short_term, expma_periods, rsi_overbought, rsi_oversold, pct_chg, boll, boll_window_days, boll_weight, fib, sel_stocks, atradx, chomf = a.run()
##
### Convert numeric config settings to integer. String vars need no conversion.
##
movavg_window_days_short_term = int(movavg_window_days_short_term)
movavg_window_days_long_term = int(movavg_window_days_long_term)
macd_periods_long_term = int(macd_periods_long_term)
macd_periods_short_term = int(macd_periods_short_term)
expma_periods = int(expma_periods)
rsi_overbought = int(rsi_overbought)
rsi_oversold = int(rsi_oversold)
boll_window_days = int(boll_window_days)
boll_weight = int(boll_weight)
atradx = int(atradx)
chomf = int(chomf)
########################################################
# Functions (before Main Logic)
########################################################
#-------------------------------------#
def CHMoF(df_ch, chomf_period =chomf):
#-------------------------------------#
CHMF = []
MFMs = []
MFVs = []
x = chomf_period
while x < len(df_ch['Date']):
PeriodVolume = 0
volRange = df_ch['Volume'][x - chomf_period: x]
for eachVol in volRange:
PeriodVolume += eachVol
x += 1
MFMs = ( ( ( df_ch['Close'] - df_ch['Low'] ) - ( df_ch["High"] - df_ch['Close'] ) ) / ( df_ch['High'] - df_ch['Low'] ) )
MFVs = MFMs *(PeriodVolume)
y = chomf_period
while y < len(MFVs):
PeriodVolume = 0
volRange = df_ch['Volume'][y - chomf_period: y]
for eachVol in volRange:
PeriodVolume += eachVol
consider = MFVs[y - chomf_period:y]
tfsMFV = 0
for eachMFV in consider:
tfsMFV += eachMFV
tfsCMF = tfsMFV/PeriodVolume
CHMF.append(tfsCMF)
y +=1
return CHMF
#-------------------------------------#
def calc_DM(df_dm):
#-------------------------------------#
Date = df_atr['Date']
Open = df_atr['Open']
High = df_atr['High']
Low = df_atr['Low']
Close = df_atr['Close']
YOpen = df_dm['Open'].shift(1)
YHigh = df_dm['High'].shift(1)
YLow = df_dm['Low'].shift(1)
YClose = df_dm['Close'].shift(1)
#
## Start calculations
#
PDM = pd.Series([])
NDM = pd.Series([])
for i in range(len(Date)):
moveUp = High[i] - YHigh[i]
moveDown = YLow[i] - Low[i]
if ( 0 < moveUp ) and (moveUp > moveDown):
PDM[i] = moveUp
else:
PDM[i] = 0
if (0 < moveDown ) and ( moveDown > moveUp):
NDM[i] = moveDown
else:
NDM [i]= 0
return Date, PDM, NDM
#-------------------------------------#
def calcDIs(df_dm):
#-------------------------------------#
PosDMs = pd.Series([])
NegDMs = pd.Series([])
DMDate, PosDMs, NegDMs = calc_DM(df_dm)
expPosDM = calc_ema(PosDMs, atradx)
expNegDM = calc_ema(NegDMs, atradx)
return expPosDM, expNegDM
#-------------------------------------#
def calc_true_range(df_atr):
#-------------------------------------#
Date = df_atr['Date']
Open = df_atr['Open']
High = df_atr['High']
Low = df_atr['Low']
Close = df_atr['Close']
x = High - Low
y = abs(High - Close.shift(1))
z = abs(Low - Close.shift(1))
TR = pd.Series([])
for i in range(len(Date)):
if ( y[i] <= x[i]) and (x[i] >= z[i]):
TR[i] = x[i]
elif (x [i] <= y[i]) and (y[i] >= z[i]):
TR[i] = y[i]
elif ( x[i] <= z[i]) and (z[i] >= y[i]):
TR[i] = z[i]
return Date, TR
#-------------------------------------------------------#
def calc_rsi(prices, n=14):
#-------------------------------------------------------#
deltas = np.diff(prices)
seed = deltas[:n + 1]
up = seed[seed >= 0].sum()/n
down = -seed[seed < 0].sum()/n
try:
rs = up/down
except:
rs = up
rsi = np.zeros_like(prices)
rsi[:n] = 100. - 100./(1. + rs)
for i in range(n, len(prices)):
delta = deltas[i - 1]
if delta > 0:
upval = delta
downval = 0.
else:
upval = .0
downval = -delta
up = (up * (n - 1) + upval) / n
down = (down * (n - 1) + downval) / n
rs = up/down
rsi[i] = 100. - 100./(1. + rs)
return rsi
#-------------------------------------------------------#
def moving_average(values, window):
#-------------------------------------------------------#
weights = np.repeat(1.0, window) / window #Numpy repeat - repeats items in array - "window" times
smas = np.convolve(values, weights, 'valid') #Numpy convolve - returns the discrete, linear convolution of 2 seq.
#https://stackoverflow.com/questions/20036663/understanding-numpys-convolve
return smas
#-------------------------------------------------------#
def calc_ema(values,window):
#-------------------------------------------------------#
weights = np.exp(np.linspace(-1, 0., window))
weights /= weights.sum()
a = np.convolve(values, weights, mode = 'full')[:len(values)]
a[:window] = a[window]
return a
#-------------------------------------------------------#
def rotate_xaxis(owner):
#-------------------------------------------------------#
for label in owner.xaxis.get_ticklabels():
label.set_rotation(45)
label.set_fontsize(5.5)
#-------------------------------------------------------#
def set_labels(owner):
#-------------------------------------------------------#
owner.set_ylabel('Price', fontsize=8, fontweight =5, color = 'g')
#-------------------------------------------------------#
def hide_frame(owner):
#-------------------------------------------------------#
owner.grid(False)
owner.xaxis.set_visible(False)
owner.yaxis.set_visible(False)
owner.set_xlabel(False)
#-------------------------------------------------------#
def set_spines(owner):
#-------------------------------------------------------#
owner.spines['left'].set_color('m')
owner.spines['left'].set_linewidth(1)
owner.spines['right'].set_visible(False) #color('m')
owner.spines['top'].set_color('m')
owner.spines['top'].set_linewidth(1)
owner.spines['bottom'].set_visible(False)
#######################################
# H O U S K E E P I N G
#######################################
if __name__ == '__main__':
if len(sys.argv) > 2:
stock_date_adj = sys.argv[2]
else:
stock_date_adj = int(365)
if len(sys.argv) > 1:
if sys.argv[1]:
ax1_subject = sys.argv[1]
ax2_sent_subject = ax1_subject
else:
ax1_subject = 'JCP'
ax2_sent_subject = ax1_subject
else:
ax1_subject = 'JCP'
ax2_sent_subject = ax1_subject
#######################################
# M A I N L O G I C
#######################################
#-----------------------------------#
# Variables
#-----------------------------------#
user = getpass.getuser()
provider = 'yahoo'
currPath = os.getcwd() # Directory you are in NOW
savePath = 'askew' # We will be creating this new sub-directory
myPath = (currPath + '/' + savePath)# The full path of the new sub-dir
dir_path = os.path.dirname(os.path.realpath(__file__))
##
### Fibbonacci Retracements - which column to use.
### compare Close to Adj_Close.
##
fibbonacci_column = 'Close'
bollinger_column = 'Close'
#-----------------------------------#
# Grab Dates
#-----------------------------------#
start = ( dt.datetime.now() - dt.timedelta(days = int(stock_date_adj)) ) # Format is year, month, day
end = dt.datetime.today() # format of today() = [yyyy, mm, dd] - list of integers
market_open = dt.datetime.strptime("09:00", "%H:%M")
market_open = dt.datetime.time(market_open)
#-----------------------------------#
# Call to get data - if exists and current, fine.
# if not, it will be scraped using
# the stock symbols loaded at
# beginning of tools_build_datawarehouse.py
#-----------------------------------#
try:
saveFile=(myPath + '/{}'.format(ax1_subject) + '.csv') # The RESUlTS we are saving on a daily basis
st = os.stat(saveFile)
if (os.path.exists(saveFile)) and (( dt.datetime.now().time() < market_open) or ((dt.date.fromtimestamp(st.st_mtime) == dt.date.today()))):
pass
elif os.path.exists(saveFile) and dt.date.fromtimestamp(st.st_mtime) != dt.date.today():
try:
subprocess.call(["python", dir_path + "/" + "tools_build_datawarehouse.py"])
except:
msg = ("Unable to rebuild:", ax1_subject, "Aborting. Either BAD ticker or python pgm tools_build_datawarehouse.py is NOT in same directory?")
print(msg)
sys.exit(0)
except:
subprocess.call(["python", dir_path + "/" + "tools_build_datawarehouse.py"])
########################################################
## Let's define our canvas, before we go after the data
#########################################################
plot_row = 18 + 122 + 35 + 50 # On-going expansion. Sloppy...
plot_col = 20
fig , ax = plt.subplots(figsize=(19,10), dpi=110,frameon=False, sharex = True, sharey = True) #Too Bad, I really liked this color, facecolor = '#FFFFFA')
plt.box(on = None)
plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='lower'))
ax1_year = plt.subplot2grid((plot_row,plot_col), (0, 0), rowspan = 10, colspan = 4)
ax1_ohlc = plt.subplot2grid((plot_row,plot_col), (23, 0), rowspan = 10, colspan = 4, sharex = ax1_year, sharey = ax1_year)
ax1_ma = plt.subplot2grid((plot_row,plot_col), (47, 0), rowspan = 10, colspan = 4, sharex = ax1_year, sharey = ax1_year)
ax1_rsi = plt.subplot2grid((plot_row,plot_col), (70, 0), rowspan = 10, colspan = 4, sharex = ax1_year)
ax1_macd = plt.subplot2grid((plot_row,plot_col), (94, 0), rowspan = 10, colspan = 4, sharex = ax1_year)
ax1_vol = plt.subplot2grid((plot_row,plot_col), (121,0), rowspan = 10, colspan = 4, sharex = ax1_year)
ax1_vol.yaxis.set_major_formatter(FormatStrFormatter('%10d'))
ax1_tot = plt.subplot2grid((plot_row,plot_col), (155,0), rowspan = 30, colspan = 1)
ax1_tot2 = plt.subplot2grid((plot_row,plot_col), (155,3), rowspan = 30, colspan = 1)
##
### ax_b comes first so other graphs can sharex with ax_b
##
ax_b = plt.subplot2grid((plot_row,plot_col), (12, 6), rowspan = 83, colspan = 6)
ax_vol = plt.subplot2grid((plot_row,plot_col), (137,6), rowspan = 40, colspan = 6, sharex = ax_b)
ax_adx = plt.subplot2grid((plot_row, plot_col), (95, 6), rowspan = 20, colspan = 6, sharex = ax_b)
ax_macd = plt.subplot2grid((plot_row,plot_col), (116, 6), rowspan = 20, colspan = 6, sharex = ax_b)
ax_a = plt.subplot2grid((plot_row,plot_col), (0, 6), rowspan = 12, colspan = 6, sharex = ax_b)
ax2_sent = plt.subplot2grid((plot_row,plot_col), (0, 13), rowspan = 30, colspan = 3)
ax2_sent_plots = plt.subplot2grid((plot_row,plot_col), (50, 13), rowspan = 40, colspan = 3)
ax_sent_chart = plt.subplot2grid((plot_row,plot_col), (110,13), rowspan = 60, colspan = 3)
ax3_sim_stock1 = plt.subplot2grid((plot_row, plot_col), (0, 17), rowspan = 30, colspan = 20)
ax3_sim_stock2 = plt.subplot2grid((plot_row, plot_col), (50 ,17), rowspan = 30, colspan = 20)
ax3_sim_stock3 = plt.subplot2grid((plot_row, plot_col), (110,17), rowspan = 30, colspan = 20)
ax3_sim_stock1.set_visible(False)
ax3_sim_stock2.set_visible(False)
ax3_sim_stock3.set_visible(False)
ax_footer_1a = plt.subplot2grid((plot_row, plot_col), (195,0), rowspan = 100, colspan = 4)
ax_footer_1b = plt.subplot2grid((plot_row, plot_col), (195,5), rowspan = 100, colspan = 4)
ax_footer_2 = plt.subplot2grid((plot_row, plot_col), (195,10), rowspan = 100, colspan = 9)
########################################################
# #### ##### ### ### # # #
# # # # # # # # ##
# # # # # # # # # #
# # # # # # # # #
# # # # # # # # #
# ### # ### ### # # #####
########################################################
# Populate Data
########################################################
os.chdir(myPath)
try:
df = pd.read_csv((ax1_subject + '.csv'), parse_dates=True, index_col =0)
except Exception as e:
print("stocks_1.py did not find", ax1_subject, "information. As it's not in the datawarehouse, is the ticker symbol spelled correctly?")
print(e)
popupmsg("Symbol " + ax1_subject + " is not found! -- Spelling?")
sys.exit(0)
#-------------------------------------#
# Save off a copy of pristine df for predictions
#-------------------------------------#
df_predict_1day_b4 = df[:]
df_predict_7day_b4 = df[:]
try:
a = altAnalysis(ax1_subject)
company_json = a.run()
except Exception as e:
print("Unable to extract Accounting details from program stock_alt_info.py. Skipping accounting details.")
print(e)
'''Capture OHLC before resetting index'''
if int(stock_date_adj) >= 270:
# df_ohlc = df['Adj_Close'].resample('10D').ohlc()
df_ohlc = df['Adj_Close'].resample('5D').ohlc()
elif int(stock_date_adj) >= 180 and int(stock_date_adj) < 270:
df_ohlc = df['Adj_Close'].resample('2D').ohlc()
else:
df_ohlc = df['Adj_Close'].resample('1D').ohlc()
#######################################
# Calculate Average True Range
#######################################
#-------------------------------------#
# Start with calc. True Range, first
#-------------------------------------#
df_atr = df[:]
df_atr.reset_index(inplace = True)
df_atr = df_atr[['Date', 'Open', 'High', "Low", "Close"]]
x = 1
TRDates = []
TrueRanges = []
TRDates, TrueRanges = calc_true_range(df_atr)
#----------------------------------------#
# Now calc Avg. True Range
#----------------------------------------#
ATR = calc_ema(TrueRanges, atradx)
##########################################
# Calculate ADX
##########################################
df_dm = df
df_dm.reset_index(inplace = True)
df_dm = df_dm[['Date', 'Open', 'High', 'Low', 'Close']]
expPosDM = []
expNegDM = []
expPosDM, expNegDM = calcDIs(df_dm)
xx = 0
PDIs = []
NDIs = []
while xx < len(ATR):
try:
PDI = 100 * (expPosDM[xx] / ATR[xx])
PDIs.append(PDI)
NDI = 100 * (expNegDM[xx] / ATR[xx])
NDIs.append(NDI)
xx += 1
except:
continue
xxx = 0
DXs = []
while xxx < (len(df_dm['Date'][1:])):
try:
DX = 100 * ( ( abs( PDIs[xxx] - NDIs[xxx]) ) / 1 )
DX = 100 * ( ( abs( PDIs[xxx] - NDIs[xxx]) ) / (PDIs[xxx] + NDIs[xxx]) )
DXs.append(DX)
xxx += 1
except:
continue
ADX = calc_ema(DXs, atradx)
df_atr['ADX'] = [0.0] * len(df_atr['Date'])
##########################################
# Calculate OHLC - Candlestick
##########################################
df_ohlc.reset_index(inplace = True)
df_ohlc = df_ohlc[df_ohlc.Date > (dt.datetime.now() - dt.timedelta(days = int(stock_date_adj)))]
df_ohlc.set_index('Date', inplace = True)
df.reset_index(inplace = True)
df = df[df.Date > (dt.datetime.now() - dt.timedelta(days = int(stock_date_adj)))]
df.set_index('Date', inplace = True)
########################################################
#Define DATA and attributes