Repository navigation
Expand file tree
/
Copy pathchartwithdb.py
More file actions
2320 lines (1863 loc) · 101 KB
/
Copy pathchartwithdb.py
File metadata and controls
2320 lines (1863 loc) · 101 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
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
# import modin.pandas as pd
# import modin.config as cfg
# # Configure Modin ONCE
# os.environ["MODIN_ENGINE"] = "dask"
# cfg.Engine.put("dask")
# import modin.pandas as pd
# import modin.config as cfg
# # Configure Modin ONCE
# os.environ["MODIN_ENGINE"] = "ray"
# cfg.Engine.put("ray")
import warnings
warnings.filterwarnings("ignore", category=UserWarning, message="Pick support for PolyCollection is missing")
### Tkinter ###
import tkinter as tk
from tkinter import ttk
from tkinter import ttk, messagebox, filedialog, Listbox, Label, Message
from tkcalendar import Calendar, DateEntry
#### Matplotlib mplfinance
import matplotlib as matplotlib
matplotlib.use("TkAgg")
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.lines import Line2D
import matplotlib.patches as patches
import matplotlib.ticker as ticker
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
import matplotlib.dates as mdates
import mplfinance as mpf
import mplcursors
from matplotlib.widgets import Cursor
### database, data processing and historical data
import yfinance as yf
import psycopg2
import pandas as pd
### Technical Analysis
from ta.momentum import RSIIndicator, StochRSIIndicator
from ta.trend import CCIIndicator
from ta.volatility import BollingerBands
from tradingview_ta import TA_Handler, Interval, Exchange
import talib
import talipp ## try to use this
# from finta import TA
#### Standard Libraries
import numpy as np
from datetime import datetime, timedelta
import threading
import asyncio
import json
import redis
import pygame
import random
import html
import ctypes
from numba import njit
import subprocess
import os
import sam_functions
# from detectCSpatterns import get_filtered_patterns
#################################################################
double_click_update = False
###################### py game audio player ############################################
# Initialize the mixer pygame mixer to play audio on my site.
pygame.mixer.init()
def play_audio():
# Load the MP3 file
pygame.mixer.music.load("audio/tradefearless.mp3")
# Play the audio
pygame.mixer.music.play()
################################################################
# Database connection
conn = psycopg2.connect(
dbname="stockdata",
user="postgres",
password="Subhan$007",
host="localhost",
port="5432"
)
cur = conn.cursor()
# Create tables if they don't exist
cur.execute("""
CREATE TABLE IF NOT EXISTS tickers (
symbol VARCHAR(20) PRIMARY KEY
);
""")
cur.execute("""
CREATE TABLE IF NOT EXISTS daily_prices (
symbol VARCHAR(20),
date DATE,
open FLOAT,
high FLOAT,
low FLOAT,
close FLOAT,
volume BIGINT,
PRIMARY KEY (symbol, date),
FOREIGN KEY (symbol) REFERENCES tickers(symbol)
);
""")
# Add column to daily_prices table if it doesn't exist
cur.execute("""
ALTER TABLE daily_prices
ADD COLUMN IF NOT EXISTS rsi3 FLOAT,
ADD COLUMN IF NOT EXISTS rsi14 FLOAT,
ADD COLUMN IF NOT EXISTS stochrsi14 FLOAT,
ADD COLUMN IF NOT EXISTS stochrsi14_d FLOAT,
ADD COLUMN IF NOT EXISTS stochrsi14_k FLOAT,
ADD COLUMN IF NOT EXISTS bb_percent_b FLOAT,
ADD COLUMN IF NOT EXISTS cci3 FLOAT,
ADD COLUMN IF NOT EXISTS cci12 FLOAT,
ADD COLUMN IF NOT EXISTS ma7 FLOAT,
ADD COLUMN IF NOT EXISTS ma10 FLOAT,
ADD COLUMN IF NOT EXISTS ma21 FLOAT,
ADD COLUMN IF NOT EXISTS ma32 FLOAT,
ADD COLUMN IF NOT EXISTS ma43 FLOAT,
ADD COLUMN IF NOT EXISTS ma54 FLOAT,
ADD COLUMN IF NOT EXISTS ma63 FLOAT,
ADD COLUMN IF NOT EXISTS ma189 FLOAT,
ADD COLUMN IF NOT EXISTS mamix14 FLOAT,
ADD COLUMN IF NOT EXISTS mamix42 FLOAT,
ADD COLUMN IF NOT EXISTS vwma25 FLOAT,
ADD COLUMN IF NOT EXISTS volsma5 FLOAT,
ADD COLUMN IF NOT EXISTS volsma20 FLOAT,
ADD COLUMN IF NOT EXISTS traderule1 BOOLEAN,
ADD COLUMN IF NOT EXISTS traderule2 BOOLEAN,
ADD COLUMN IF NOT EXISTS traderule3 BOOLEAN,
ADD COLUMN IF NOT EXISTS traderule4 BOOLEAN,
ADD COLUMN IF NOT EXISTS traderule5 BOOLEAN,
ADD COLUMN IF NOT EXISTS traderule6 BOOLEAN,
ADD COLUMN IF NOT EXISTS traderule7 BOOLEAN,
ADD COLUMN IF NOT EXISTS traderule8 BOOLEAN,
ADD COLUMN IF NOT EXISTS traderule9 BOOLEAN,
ADD COLUMN IF NOT EXISTS traderule10 BOOLEAN,
ADD COLUMN IF NOT EXISTS notes TEXT;
""")
conn.commit()
### CReating Custom Chart Style
# Define the style
samie_style = {
"base_mpl_style": "nightclouds",
"marketcolors": {
"candle": {"up": "#8ad5ef", "down": "#f72e05"},
"edge": {"up": "#8ad5ef", "down": "#f72e05"},
"wick": {"up": "#247252", "down": "#ef4f60"},
"ohlc": {"up": "green", "down": "red"},
"volume": {"up": "#067887", "down": "#ff6060"},
"vcedge": {"up": "#000000", "down": "#000000"},
"vcdopcod": False,
"alpha": 1,
},
"mavcolors": ["#ad7739", "#a63ab2", "#62b8ba"],
"facecolor": "#1b1f24",
"gridcolor": "#2c2e31",
"gridstyle": "--",
"y_on_right": True,
"rc": {
"axes.grid": True,
"axes.grid.axis": "y",
"axes.edgecolor": "#474d56",
"axes.titlecolor": "red",
"figure.facecolor": "#161a1e",
"figure.titlesize": "x-large",
"figure.titleweight": "semibold",
},
"base_mpf_style": "nightclouds",
}
# samie_style_obj = mpf.make_mpf_style(
# base_mpl_style="seaborn",
# rc={
# "axes.facecolor": "#202020",
# "axes.grid": False,
# "xtick.color": "w",
# "ytick.color": "w",
# "grid.color": "#31363F",
# "text.color": "w",
# "figure.facecolor": "#202020",
# },
# style_dict={
# "candlestick": {
# "colorup": "#00ff00",
# "colordown": "#ff0000",
# "linewidth": 1,
# "edgecolor": "w",
# },
# "volume": {
# "colorup": "#00ff00",
# "colordown": "#ff0000",
# },
# },
# )
# samie_style = mpf.make_mpf_style(base_mpf_style='charles',
# marketcolors=mpf.make_marketcolors(up='green', down='black', inherit=True))
samie_style_obj = mpf.make_mpf_style(**samie_style)
# Create a Matplotlib figure and canvas
fig = Figure(figsize=(14.5, 8), dpi=100)
fig.set_edgecolor('blue')
fig.set_facecolor('#131722')
fig.text(0.99, 0.95, 'MashaAllah', fontsize=10, ha='right', color='green')
def fetch_data_from_db(symbol, selected_period):
# Convert selected_period to days
period_days = convert_period_to_days(selected_period)
# Calculate the start date for the data
end_date = datetime.now().date()
start_date = end_date - timedelta(days=period_days)
try:
# Check if data exists for the entire period
cur.execute("SELECT COUNT(*) FROM daily_prices WHERE symbol = %s AND date >= %s AND date <= %s", (symbol, start_date, end_date))
data_count = cur.fetchone()[0]
expected_data_points = period_days + 1 # Include the end date
if data_count == expected_data_points:
print(f"All data available for {symbol} for the past {selected_period}")
return
except Exception as e:
print(f"An error occured: {e}")
conn.rollback()
# Fetch the data from the database
@njit
def convert_period_to_days(selected_period):
if selected_period == '5d':
return 5
elif selected_period == '1mo':
return 30
elif selected_period == '3mo':
return 90
elif selected_period == '6mo':
return 180
elif selected_period == '9mo':
return 270
elif selected_period == '1y':
return 365
elif selected_period == '2y':
return 730
elif selected_period == '3y':
return 1095
elif selected_period == '4y':
return 1460
elif selected_period == '5y':
return 1825
elif selected_period == '6y':
return 2190
elif selected_period == '7y':
return 2555
elif selected_period == '8y':
return 2920
elif selected_period == '9y':
return 3285
elif selected_period == '10y':
return 3650
else:
raise ValueError("Invalid period format")
def volume_formatter(x, pos):
return f'{x:,.0f}'
def price_formatter(x, pos):
return f'{x:,.2f}'
data_needed_days = 1460
# @njit
async def calculate_and_store_rsi_cci(symbol):
"""Calculates RSI3 & RSI14 for the given symbol and stores it in the database."""
# Fetch the last calculated RSI date
cur.execute("SELECT MAX(date) FROM daily_prices WHERE symbol = %s AND rsi3 IS NOT NULL", (symbol,))
# last_rsi_date = cur.fetchone()[0]
end_date = datetime.now().date()
last_rsi_date = end_date - timedelta(days=data_needed_days)
# Fetch only new data
cur.execute("SELECT date, close, high, low FROM daily_prices WHERE symbol = %s AND date > %s ORDER BY date", (symbol, last_rsi_date or '1900-01-01'))
rows = cur.fetchall()
if len(rows) < 3:
print(f"Not enough new data to calculate RSI3, BBpB and CCIs for {symbol}")
return
df = pd.DataFrame(rows, columns=['date', 'close', 'high', 'low'])
# Calculate RSI and CCI
rsi_indicator = RSIIndicator(close=df['close'], window=3)
rsi_indicator14 = RSIIndicator(close=df['close'], window=14)
df['rsi3'] = rsi_indicator.rsi()
df['rsi14'] = rsi_indicator14.rsi()
### CCI
cci = CCIIndicator(high=df['high'], low=df['low'], close=df['close'], window=3, constant=0.015)
df['cci3'] = cci.cci()
cci12 = CCIIndicator(high=df['high'], low=df['low'], close=df['close'], window=12, constant=0.015)
df['cci12'] = cci12.cci()
#### stochrsi
# Assuming df is your DataFrame
stochrsi14 = StochRSIIndicator(close=df['close'], window=14, smooth1=3, smooth2=3)
df['stochrsi14'] = stochrsi14.stochrsi()
df['stochrsi14_k'] = stochrsi14.stochrsi_k()
df['stochrsi14_d'] = stochrsi14.stochrsi_d()
#### bollingerband %b
# Calculate Bollinger Bands
bb_indicator = BollingerBands(close=df['close'], window=20, window_dev=2)
# Add Bollinger Band %B to the dataframe
df['bb_percent_b'] = bb_indicator.bollinger_pband()
# Prepare batch updates
updates = [(row['rsi3'], row['rsi14'], row['cci3'], row['cci12'], row['stochrsi14'], row['stochrsi14_k'], row['stochrsi14_d'], row['bb_percent_b'], symbol, row['date']) for _, row in df.iterrows() if not pd.isna(row['rsi3']) and not pd.isna(row['rsi14']) and not pd.isna(row['cci3']) and not pd.isna(row['cci12']) and not pd.isna(row['stochrsi14']) and not pd.isna(row['stochrsi14_k']) and not pd.isna(row['stochrsi14_d']) ]
# Perform bulk update
cur.executemany(
"UPDATE daily_prices SET rsi3 = %s, rsi14 = %s, cci3 = %s, cci12 = %s, stochrsi14 = %s, stochrsi14_k = %s, stochrsi14_d = %s, bb_percent_b = %s WHERE symbol = %s AND date = %s",
updates
)
conn.commit()
print(f"RSI3,rsi14, CCI3 & 12, StochRSI14, BBpB calculated and stored for {symbol}")
# @njit
async def calculate_and_store_ma(symbol):
# Initialize Redis connection
redis_client = redis.Redis(host='localhost', port=6379, db=0)
# Get last update timestamp
last_update = await get_last_update(symbol)
# Fetch only new data
cur.execute("""
SELECT date, close, volume, ma7, ma10, ma21, ma32, ma43, ma54, ma63, ma189, mamix14, mamix42, vwma25, volsma5, volsma20
FROM daily_prices
WHERE symbol = %s AND (date > %s OR %s IS NULL)
ORDER BY date
""", (symbol, last_update, last_update))
rows = cur.fetchall()
if not rows:
print(f"No new data to process for {symbol}")
return
dates = [row[0] for row in rows]
df = pd.DataFrame({
'close': [row[1] for row in rows],
'volume': [row[2] for row in rows]
}, index=dates)
df = df.fillna(0)
# Calculate moving averages
for ma in [7, 10, 21, 32, 43, 54, 63, 189]:
df[f'ma{ma}'] = df['close'].rolling(window=ma).mean()
df['mamix14'] = ((df['ma7'] + df['ma21']) / 2).rolling(window=2).mean()
df['mamix42'] = ((df['ma21'] + df['ma63']) / 2).rolling(window=2).mean()
df['CloseVolume'] = df['close'] * df['volume']
df['vwma25'] = df['CloseVolume'].rolling(window=25).sum() / df['volume'].rolling(window=25).sum()
df['volsma5'] = (df['volume']).rolling(window=5).mean()
df['volsma20'] = (df['volume']).rolling(window=20).mean()
# Prepare batch updates
updates = []
for date, row in df.iterrows():
updates.append((
float(row['ma7']),
float(row['ma10']),
float(row['ma21']),
float(row['ma32']),
float(row['ma43']),
float(row['ma54']),
float(row['ma63']),
float(row['ma189']),
float(row['mamix14']),
float(row['mamix42']),
float(row['vwma25']),
float(row['volsma5']),
float(row['volsma20']),
symbol, date
))
# Cache the data
redis_client.set(f"{symbol}_{date}", json.dumps(row.to_dict()))
# Perform bulk update
await bulk_update(updates)
print(f"Moving Averages are updated for {symbol}")
async def get_last_update(symbol):
# cur.execute("SELECT MAX(date) FROM daily_prices WHERE symbol = %s", (symbol,))
cur.execute("SELECT MIN(date) FROM daily_prices WHERE symbol = %s", (symbol,))
last_date = cur.fetchone()[0]
return last_date if last_date else datetime(1970, 1, 1).date()
async def bulk_update(updates):
cur.executemany("""
UPDATE daily_prices
SET ma7 = COALESCE(%s, ma7),
ma10 = COALESCE(%s, ma10),
ma21 = COALESCE(%s, ma21),
ma32 = COALESCE(%s, ma32),
ma43 = COALESCE(%s, ma43),
ma54 = COALESCE(%s, ma54),
ma63 = COALESCE(%s, ma63),
ma189 = COALESCE(%s, ma189),
mamix14 = COALESCE(%s, mamix14),
mamix42 = COALESCE(%s, mamix42),
vwma25 = COALESCE(%s, vwma25),
volsma5 = COALESCE(%s, volsma5),
volsma20 = COALESCE(%s, volsma20)
WHERE symbol = %s AND date = %s
""", updates)
conn.commit()
# Run the function asynchronously
# asyncio.run(calculate_and_store_ma(symbol))
#############################################???????????????????????????????#############################
def plot_resampled_chart(symbol, selected_period, resample_freq='ME'):
# Convert period to a format suitable for SQL query
period_map = {
'1mo': '1 month', '3mo': '3 months', '6mo': '6 months', '9mo': '9 months',
'1y': '1 year', '2y': '2 years', '3y': '3 years', '4y': '4 years',
'5y': '5 years', '6y': '6 years', '7y': '7 years', '8y': '8 years',
'9y': '9 years', '10y': '10 years', 'max': '100 years'
}
sql_period = period_map.get(selected_period)
# Fetch data from database
cur.execute("SELECT date, open, high, low, close, volume, rsi3, ma7, ma21, ma63, ma189, mamix14, mamix42, vwma25, traderule1, traderule2, traderule3, traderule4, traderule5, traderule6, traderule7, traderule8, volsma5, volsma20, cci3, cci12, bb_percent_b, rsi14, traderule9, traderule10 FROM daily_prices WHERE symbol = %s AND date >= NOW() - INTERVAL %s ORDER BY date", (symbol, sql_period))
rows = cur.fetchall()
if not rows:
fetch_data_from_db(symbol, selected_period)
cur.execute("SELECT date, open, high, low, close, volume, rsi3, ma7, ma21, ma63, ma189, mamix14, mamix42, vwma25, traderule1, traderule2, traderule3, traderule4, traderule5, traderule6, traderule7, traderule8, volsma5, volsma20, cci3, cci12, bb_percent_b, rsi14, traderule9, traderule10 FROM daily_prices WHERE symbol = %s AND date >= NOW() - INTERVAL %s ORDER BY date", (symbol, sql_period))
rows = cur.fetchall()
data = {
'Date': [row[0] for row in rows],
'Open': [round(row[1], 2) for row in rows],
'High': [round(row[2], 2) for row in rows],
'Low': [round(row[3], 2) for row in rows],
'Close': [round(row[4], 2) for row in rows],
'Volume': [row[5] for row in rows],
'rsi3': [row[6] for row in rows],
'ma7': [row[7] for row in rows],
'ma21': [row[8] for row in rows],
'ma63': [row[9] for row in rows],
'ma189': [row[10] for row in rows],
'mamix14':[row[11] for row in rows],
'mamix42':[row[12] for row in rows],
'vwma25':[row[13] for row in rows],
'traderule1': [row[14] for row in rows],
'traderule2':[row[15] for row in rows],
'traderule3':[row[16] for row in rows],
'traderule4':[row[17] for row in rows],
'traderule5':[row[18] for row in rows],
'traderule6':[row[19] for row in rows],
'traderule7':[row[20] for row in rows],
'traderule8':[row[21] for row in rows],
'volsma5':[row[22] for row in rows],
'volsma20':[row[23] for row in rows],
'cci3':[row[24] for row in rows],
'cci12':[row[25] for row in rows],
'bb_percent_b':[row[26] for row in rows],
'rsi14':[row[27] for row in rows],
'traderule9':[row[28] for row in rows],
'traderule10':[row[29] for row in rows]
}
df = pd.DataFrame(data)
df.set_index('Date', inplace=True)
df.index = df.index.astype(str)
df.index = pd.to_datetime(df.index) # Ensure the index is a DatetimeIndex
# Define resampling rules
resample_dict = {
'Open': 'first',
'High': 'max',
'Low': 'min',
'Close': 'last',
'Volume': 'sum',
'rsi3': 'last',
'ma7': 'last',
'ma21': 'last',
'ma63': 'last',
'ma189': 'last',
'mamix14': 'last',
'mamix42': 'last',
'vwma25': 'last',
'traderule1': 'last',
'traderule2': 'last',
'traderule3': 'last',
'traderule4': 'last',
'traderule5': 'last',
'traderule6': 'last',
'traderule7': 'last',
'traderule8': 'last',
'volsma5': 'last',
'volsma20': 'last',
'cci3': 'last',
'cci12': 'last',
'bb_percent_b': 'last',
'rsi14': 'last',
'traderule9': 'last',
'traderule10': 'last'
}
##### Tradingview Technical Analysis Recomendation.
# clean_symbol = watchlist.get(watchlist.curselection()).replace(".NS", "")
# print(clean_symbol)
# ta_symbol = TA_Handler( symbol=clean_symbol, screener="india", exchange="NSE", interval=Interval.INTERVAL_1_DAY)
# print(ta_symbol.get_analysis().summary)['RECOMMENDATION']
# recommend = ta_symbol.get_analysis().summary
# ta_symbol.get_analysis().summary# Resample data only if necessary
if resample_freq != 'D':
resampled_df = df.resample(resample_freq).agg(resample_dict)
else:
resampled_df = df # Use the original daily data
if not resampled_df.empty:
latest_data = resampled_df.iloc[-1]
prev_close = resampled_df.iloc[-2]['Close'] if len(resampled_df) > 1 else 0
percent_change = ((latest_data['Close'] - prev_close) / prev_close) * 100 if prev_close != 0 else 0
latest_info = (
f"TF: {resample_freq}, "
f"Date: {latest_data.name.strftime('%b %d %Y')}, "
f"Open: {latest_data['Open']:.2f}, "
f"High: {latest_data['High']:.2f}, "
f"Low: {latest_data['Low']:.2f}, "
f"Close: {latest_data['Close']:.2f}, "
f"Chg: {percent_change:.2f}% , "
# f"Recommendation: {recommend['RECOMMENDATION']}"
)
else:
latest_info = "No data available"
#these lines are highlighting the Low values in your DataFrame where each respective trading rule is met,
# and setting the value to NaN where the rule is not met.
### to plot on low of the candle .. we are collecting lows
resampled_df['traderule1_highlight'] = np.where(resampled_df['traderule1'], resampled_df['Low'] * 0.999, np.nan)
resampled_df['traderule2_highlight'] = np.where(resampled_df['traderule2'], resampled_df['Low'] * 0.995, np.nan)
resampled_df['traderule3_highlight'] = np.where(resampled_df['traderule3'], resampled_df['Low'] * 0.990, np.nan)
resampled_df['traderule4_highlight'] = np.where(resampled_df['traderule4'], resampled_df['Low'] * 0.985, np.nan)
resampled_df['traderule5_highlight'] = np.where(resampled_df['traderule5'], resampled_df['Low'] * 0.980, np.nan)
resampled_df['traderule6_highlight'] = np.where(resampled_df['traderule6'], resampled_df['Low'] * 0.975, np.nan)
resampled_df['traderule7_highlight'] = np.where(resampled_df['traderule7'], resampled_df['Low'] * 0.970, np.nan)
resampled_df['traderule8_highlight'] = np.where(resampled_df['traderule8'], resampled_df['Low'] * 0.965, np.nan)
resampled_df['traderule9_highlight'] = np.where(resampled_df['traderule9'], resampled_df['Low'] * 0.960, np.nan)
resampled_df['traderule10_highlight'] = np.where(resampled_df['traderule10'], resampled_df['Low'] * 0.955, np.nan)
# resampled_df['traderule3_highlight'] = np.where(resampled_df['traderule3'], resampled_df['Low'] * 1.05, np.nan) # to add 5%
# resampled_df['traderule3_highlight'] = np.where(resampled_df['traderule3'], resampled_df['Low'] * 0.95, np.nan) # to minus 5%
resampled_df['traderule3_high'] = np.where(resampled_df['traderule3'], resampled_df['High'], np.nan) # to plot a line taking high
resampled_df['traderule3_low'] = np.where(resampled_df['traderule3'], resampled_df['Low'], np.nan) # to plot a line taking high
resampled_df['traderule4_high'] = np.where(resampled_df['traderule4'], resampled_df['High'], np.nan) # to plot a line taking high
resampled_df['traderule4_low'] = np.where(resampled_df['traderule4'], resampled_df['Low'], np.nan) # to plot a line taking high
resampled_df['traderule5_high'] = np.where(resampled_df['traderule5'], resampled_df['High'], np.nan) # to plot a line taking high
resampled_df['traderule5_low'] = np.where(resampled_df['traderule5'], resampled_df['Low'], np.nan) # to plot a line taking high
resampled_df['traderule7_high'] = np.where(resampled_df['traderule7'], resampled_df['High'], np.nan) # to plot a line taking high
resampled_df['traderule7_low'] = np.where(resampled_df['traderule7'], resampled_df['Low'], np.nan) # to plot a line taking high
resampled_df['traderule8_high'] = np.where(resampled_df['traderule8'], resampled_df['Low'] + (resampled_df['High'] - resampled_df['Low']) * 0.3, np.nan) # to plot a line taking a value below hl2 and above 30% of candle.
resampled_df['traderule8_low'] = np.where(resampled_df['traderule8'], resampled_df['Low'], np.nan) # to plot a line taking high
resampled_df['traderule9_high'] = np.where(resampled_df['traderule9'], resampled_df['Low'] + (resampled_df['High'] - resampled_df['Low']) * 0.3, np.nan) # to plot a line taking a value below hl2 and above 30% of candle.
resampled_df['traderule9_low'] = np.where(resampled_df['traderule9'], resampled_df['Low'], np.nan) # to plot a line taking high
resampled_df['traderule10_high'] = np.where(resampled_df['traderule10'], resampled_df['High'], np.nan) # to plot a line taking high
resampled_df['traderule10_low'] = np.where(resampled_df['traderule10'], resampled_df['Low'], np.nan) # to plot a line taking high
traderule3_high = resampled_df['traderule3_high'].dropna()
traderule3_low = resampled_df['traderule3_low'].dropna()
traderule4_high = resampled_df['traderule4_high'].dropna()
traderule4_low = resampled_df['traderule4_low'].dropna()
traderule5_high = resampled_df['traderule5_high'].dropna()
traderule5_low = resampled_df['traderule5_low'].dropna()
traderule7_high = resampled_df['traderule7_high'].dropna()
traderule7_low = resampled_df['traderule7_low'].dropna()
## Traderule 8 is high probable to taking these values and ploting on chart.
traderule8_high_values = resampled_df['traderule8_high'].dropna()
traderule8_low_values = resampled_df['traderule8_low'].dropna()
# I am collecting the high and low values of traderules only if more than one rule is met. To plot lines below.
# To complare all traderules taking them in variable. Add the traderules as you add new ones
traderule_columns = resampled_df[['traderule1', 'traderule2', 'traderule3', 'traderule4', 'traderule5', 'traderule6', 'traderule7', 'traderule8', 'traderule9', 'traderule10']]
# Use the variable in your np.where condition
resampled_df['highlight2_high'] = np.where((traderule_columns.sum(axis=1) > 2) & (traderule_columns.sum(axis=1) < 4), resampled_df['High'], np.nan)
resampled_df['highlight2_low'] = np.where((traderule_columns.sum(axis=1) > 2) & (traderule_columns.sum(axis=1) < 4), resampled_df['Low'], np.nan)
highlight2_high_values = resampled_df['highlight2_high'].dropna()
highlight2_low_values = resampled_df['highlight2_low'].dropna()
resampled_df['highlight3_high'] = np.where((traderule_columns.sum(axis=1) >= 4) & (traderule_columns.sum(axis=1) < 6), resampled_df['High'], np.nan)
resampled_df['highlight3_low'] = np.where((traderule_columns.sum(axis=1) >= 4) & (traderule_columns.sum(axis=1) < 6), resampled_df['Low'], np.nan)
highlight3_high_values = resampled_df['highlight3_high'].dropna()
highlight3_low_values = resampled_df['highlight3_low'].dropna()
resampled_df['highlight5_high'] = np.where((traderule_columns.sum(axis=1) >= 6) & (traderule_columns.sum(axis=1) < 10), resampled_df['High'], np.nan)
resampled_df['highlight5_low'] = np.where((traderule_columns.sum(axis=1) >= 6) & (traderule_columns.sum(axis=1) < 10), resampled_df['Low'], np.nan)
highlight5_high_values = resampled_df['highlight5_high'].dropna()
highlight5_low_values = resampled_df['highlight5_low'].dropna()
# if not traderule3_high.empty:
# addplot = []
# for value in traderule3_high:
# addplot.append(mpf.make_addplot([value]*len(resampled_df), ax=ax1, color='#7572f1', linestyle='--'))
fig.clear()
# Adjust the layout to stretch the chart
fig.tight_layout()
fig.subplots_adjust(left=0.05, right=0.95, top=0.95, bottom=0.05)
# Create the subplots
ax1 = fig.add_subplot(4, 1, 1)
ax2 = fig.add_subplot(4, 1, 2, sharex=ax1)
ax3 = fig.add_subplot(4, 1, 3, sharex=ax1)
ax4 = fig.add_subplot(4, 1, 4, sharex=ax1)
AXS_BG_Color = '#000000ff'
ax1.set_facecolor(AXS_BG_Color)
ax2.set_facecolor(AXS_BG_Color)
ax3.set_facecolor(AXS_BG_Color)
ax4.set_facecolor(AXS_BG_Color)
addplot = [
# mpf.make_addplot(resampled_df['ma7'], ax=ax1, color='red'),
# mpf.make_addplot(resampled_df['ma21'], ax=ax1, color='black'),
# mpf.make_addplot(resampled_df['ma63'], ax=ax1, color='green'),
mpf.make_addplot(resampled_df['traderule1_highlight'], ax=ax1, type='scatter', markersize=100, marker='s', color='#bcf5bc'), # working code
mpf.make_addplot(resampled_df['traderule2_highlight'], ax=ax1, type='scatter', markersize=100, marker='^', color='#1e90ff'), # working code
mpf.make_addplot(resampled_df['traderule3_highlight'], ax=ax1, type='scatter', markersize=100, marker='s', color='#7572f1'), # working code
mpf.make_addplot(resampled_df['traderule4_highlight'], ax=ax1, type='scatter', markersize=100, marker='d', color='#ff00ff'), # New color for traderule4
mpf.make_addplot(resampled_df['traderule5_highlight'], ax=ax1, type='scatter', markersize=100, marker='^', color='#0fff00'), # New color for traderule5
mpf.make_addplot(resampled_df['traderule6_highlight'], ax=ax1, type='scatter', markersize=100, marker='^', color='#007117'), # New color for traderule6
mpf.make_addplot(resampled_df['traderule7_highlight'], ax=ax1, type='scatter', markersize=100, marker='*', color='#fff000'), # New color for traderule7
mpf.make_addplot(resampled_df['traderule8_highlight'], ax=ax1, type='scatter', markersize=100, marker='*', color='#0fff00'), # New color for traderule8
mpf.make_addplot(resampled_df['traderule9_highlight'], ax=ax1, type='scatter', markersize=50, marker='x', color='#000fff'), # New color for traderule9
mpf.make_addplot(resampled_df['traderule10_highlight'], ax=ax1, type='scatter', markersize=100, marker='1', color='#00fff0'), # New color for traderule10
# mpf.make_addplot([horizontal_line]*len(resampled_df), ax=ax1, color='#7572f1', linestyle='--') working code for only one time occurance
]
################################################################################################################
########################################################## Working Code below #################################################
# Define your market colors
mcgreen = mpf.make_marketcolors(base_mpf_style='yahoo', up='limegreen', down='yellow', ohlc='limegreen', edge='inherit', wick='inherit')
style = mpf.make_mpf_style(marketcolors=mcgreen)
# Define volume conditions
VolumeUpCondition = (resampled_df['Volume'] > resampled_df['Volume'].rolling(window=20).mean() * 1.5) & (resampled_df['Close'] > resampled_df['Open'])
VolumeDownCondition = (resampled_df['Volume'] > resampled_df['Volume'].rolling(window=20).mean() * 1.5) & (resampled_df['Close'] <= resampled_df['Open'])
# Initialize an empty DataFrame to store the candles to be plotted
new_resampled_df = resampled_df.copy()
new_resampled_df.loc[~(VolumeUpCondition | VolumeDownCondition), ['Open', 'High', 'Low', 'Close']] = new_resampled_df.loc[VolumeUpCondition | VolumeDownCondition, ['Open', 'High', 'Low', 'Close']].ffill()
# Define the length of the trend triangle
triangle_len = triangle_length_var.get() + 1
def create_trend_line_data(resampled_df, condition_index, is_up_condition):
today_high = resampled_df.loc[condition_index, 'High']
today_low = resampled_df.loc[condition_index, 'Low']
initial_diff = today_high - today_low
end_date = min(condition_index + pd.Timedelta(days=triangle_len), resampled_df.index[-1])
date_range = (end_date - condition_index).days + 1
step_size = 1 / date_range
trend_high = []
trend_low = []
for i in range(date_range):
current_date = condition_index + pd.Timedelta(days=i)
if current_date <= resampled_df.index[-1]:
if is_up_condition:
new_high = today_high - (initial_diff * step_size * i)
new_low = today_low # Keeping low constant
else:
new_high = today_high # Keeping high constant
new_low = today_low + (initial_diff * step_size * i)
trend_high.append(new_high)
trend_low.append(new_low)
else:
trend_high.append(np.nan)
trend_low.append(np.nan)
return trend_high, trend_low
# Find the indices where the volume conditions are True
up_condition_indices = resampled_df.index[VolumeUpCondition].tolist()
down_condition_indices = resampled_df.index[VolumeDownCondition].tolist()
# Create trend line data for up conditions
trend_highs_up = pd.DataFrame(index=resampled_df.index, columns=[f'TrendHighUp_{i}' for i in range(len(up_condition_indices))])
trend_lows_up = pd.DataFrame(index=resampled_df.index, columns=[f'TrendLowUp_{i}' for i in range(len(up_condition_indices))])
for i, idx in enumerate(up_condition_indices):
high, low = create_trend_line_data(resampled_df, idx, is_up_condition=True)
start_idx = resampled_df.index.get_loc(idx)
end_idx = min(start_idx + triangle_len, len(resampled_df))
trend_highs_up.iloc[start_idx:end_idx, i] = high[:end_idx-start_idx]
trend_lows_up.iloc[start_idx:end_idx, i] = low[:end_idx-start_idx]
addplot.append(mpf.make_addplot(trend_highs_up[f'TrendHighUp_{i}'], color='#ad0afd', linestyle='--', ax=ax1, alpha=1))
addplot.append(mpf.make_addplot(trend_lows_up[f'TrendLowUp_{i}'], color='#0bf77d', linestyle='--', ax=ax1, alpha=1))
# Create trend line data for down conditions
trend_highs_down = pd.DataFrame(index=resampled_df.index, columns=[f'TrendHighDown_{i}' for i in range(len(down_condition_indices))])
trend_lows_down = pd.DataFrame(index=resampled_df.index, columns=[f'TrendLowDown_{i}' for i in range(len(down_condition_indices))])
for i, idx in enumerate(down_condition_indices):
high, low = create_trend_line_data(resampled_df, idx, is_up_condition=False)
start_idx = resampled_df.index.get_loc(idx)
end_idx = min(start_idx + triangle_len, len(resampled_df))
trend_highs_down.iloc[start_idx:end_idx, i] = high[:end_idx-start_idx]
trend_lows_down.iloc[start_idx:end_idx, i] = low[:end_idx-start_idx]
addplot.append(mpf.make_addplot(trend_highs_down[f'TrendHighDown_{i}'], color='#de0c62', linestyle='--', ax=ax1, alpha=1))
addplot.append(mpf.make_addplot(trend_lows_down[f'TrendLowDown_{i}'], color='#08ff08', linestyle='--', ax=ax1, alpha=1))
#################################################################################################################
show_ma189 = False
show_mamix14 = True
show_mamix42 = True
show_vwma25 = True
show_volsma5 = True
show_rsi3 = True
show_rsi14 = True
show_cci3 = True
show_cci12 = True
show_volume_candle = True
show_trendlines = True
### RSI SEttings
rsi_overbought_mask = resampled_df['rsi3'] > 60
rsi_oversold_mask = resampled_df['rsi3'] < 40
cci_overbought_mask = resampled_df['cci3'] > 50
cci_oversold_mask = resampled_df['cci3'] < -50
if show_ma189:
addplot.append(mpf.make_addplot(resampled_df['ma189'], ax=ax1, color='purple', width=0.5))
if show_mamix14:
addplot.append(mpf.make_addplot(resampled_df['mamix14'], ax=ax1, color='blue')),
if show_mamix42:
addplot.append(mpf.make_addplot(resampled_df['mamix42'], ax=ax1, color='red', width=0.5)),
if show_vwma25:
addplot.append(mpf.make_addplot(resampled_df['vwma25'], ax=ax1, color='#37B7C3')),
if show_volsma5:
addplot.append(mpf.make_addplot(resampled_df['volsma5'], ax=ax2, color='#ff00ff')),
if show_rsi3:
addplot.append(mpf.make_addplot(resampled_df['rsi3'], ax=ax3, color='#1e90ff'))
addplot.append(mpf.make_addplot(resampled_df['rsi3'].where(rsi_overbought_mask), ax=ax3, color='green', fill_between={'y1': 60, 'y2': 100, 'alpha': 0.3}))
addplot.append(mpf.make_addplot(resampled_df['rsi3'].where(rsi_oversold_mask), ax=ax3, color='red', fill_between={'y1': 0, 'y2': 40, 'alpha': 0.3}))
if show_rsi14:
addplot.append(mpf.make_addplot(resampled_df['rsi14'], ax=ax3, color='#2f01ee'))
if show_cci3:
addplot.append(mpf.make_addplot(resampled_df['cci3'], ax=ax4, color='#1e90ff'))
addplot.append(mpf.make_addplot(resampled_df['cci3'].where(cci_overbought_mask), ax=ax4, color='green', fill_between={'y1': 50, 'y2': 100, 'alpha': 0.3}))
addplot.append(mpf.make_addplot(resampled_df['cci3'].where(cci_oversold_mask), ax=ax4, color='red', fill_between={'y1': -100, 'y2': -50, 'alpha': 0.3}))
if show_cci12:
addplot.append(mpf.make_addplot(resampled_df['cci12'], ax=ax4, color='#6600ee'))
if show_volume_candle:# Check if there are any rows that meet the condition
if not new_resampled_df.empty:
addplot.append(mpf.make_addplot(new_resampled_df[['Open', 'High', 'Low', 'Close', 'Volume']], ax=ax1, type='candle', marketcolors=mcgreen))
################################## main plot dont delete #########################################################################
# mpf.plot(resampled_df, type='candle', style=samie_style_obj, ax=ax1, volume=ax2, datetime_format='%b %d', addplot=addplot) # working code
mpf.plot(resampled_df, type='candle', style=samie_style_obj, ax=ax1, volume=ax2, datetime_format='%m-%d', addplot=addplot, returnfig=True)
##################################################################################################################################
# Create a custom cursor
cursor = mplcursors.cursor(ax1, hover=True)
# Function to find the nearest candle
def find_nearest_candle(sel):
x, y = sel.target
# Convert x from float to nearest index
index = int(round(x))
return index, resampled_df.iloc[index]
# Custom picking function
def custom_pick(artist, mouseevent):
if isinstance(artist, plt.Rectangle):
mouse_x = mouseevent.xdata
candle_index = int(round(mouse_x))
return True, {'index': candle_index}
return False, {}
# Modified tooltip function
def custom_tooltip(sel):
index, row = find_nearest_candle(sel)
open_price = row['Open']
high_price = row['High']
low_price = row['Low']
close_price = row['Close']
date = row.name
prev_close = resampled_df['Close'].iloc[index-1] if index > 0 else open_price
pct_chg = ((close_price - prev_close) / prev_close) * 100 if prev_close != 0 else 0
sel.annotation.set_text(
f"Date: {date.strftime('%Y-%m-%d')}\n"
f"Open: {open_price:.2f}\n"
f"High: {high_price:.2f}\n"
f"Low: {low_price:.2f}\n"
f"Close: {close_price:.2f}\n"
f"Chg: {pct_chg:.2f}%"
)
sel.annotation.get_bbox_patch().set_facecolor("lightgray")
sel.annotation.get_bbox_patch().set_alpha(0.7)
sel.annotation.set_fontsize(10)
sel.annotation.get_bbox_patch().set_edgecolor("darkgray")
sel.annotation.get_bbox_patch().set_linewidth(1)
sel.annotation.set_zorder(1000)
# Set the custom picking function
ax1.figure.canvas.mpl_connect('pick_event', lambda event: custom_pick(event.artist, event.mouseevent))
# Connect the modified tooltip function
cursor.connect("add", custom_tooltip)
#####################################################################################################################
ax1.set_title(f' {selected_period} : {latest_info}', loc='left', fontsize=10, color='dodgerblue', y=1)
# ax1.set_ylabel('Price')
ax1.grid(axis='both', which='both', linestyle='-.', linewidth=0.3, color='#31363F')
ax2.grid(axis='both', which='both', linestyle='-.', linewidth=0.3, color='#31363F')
ax3.grid(axis='both', which='both', linestyle='-.', linewidth=0.3, color='#31363F')
ax4.grid(axis='both', which='both', linestyle='-.', linewidth=0.3, color='#31363F')
ax1.tick_params(axis='y', colors='dodgerblue')
ax2.tick_params(axis='y', colors='dodgerblue')
ax3.tick_params(axis='y', colors='dodgerblue')
ax4.tick_params(axis='y', colors='dodgerblue')
ax4.tick_params(axis='x', colors='dodgerblue')
# Enhanced Gridlines for ax1 (Price Chart)
# ax1.grid(True, which='both', linestyle='--', linewidth=0.5, color='gray') # Major and minor grids for ax1
data_range = resampled_df['Close'].max() - resampled_df['Close'].min()
# tick_interval = data_range * 0.05 # 5% of the data range
def round_to_nearest_five_paisa(value):
rounded_value = round(value * 20) / 20.0
return rounded_value
# data_range = 1.23 # Replace with your actual data range
# tick_interval = data_range * 0.10
# rounded_tick_interval = round_to_nearest_five_cents(tick_interval)
# print(rounded_tick_interval)
tick_interval = data_range * 0.033 # 3.3% of the data range
rounded_tick_interval = round_to_nearest_five_paisa(tick_interval)
# Set y-axis major ticks at every 5% of the data range
ax1.yaxis.set_major_locator(ticker.MultipleLocator(rounded_tick_interval))
# ax1.set_ylim([resampled_df['Low'].min(), resampled_df['High'].max()]) # working code.. sets you graph to max and min values
# Set the title on the primary axes to include the symbol name
# ax1.set_title(f'{symbol} Stock Price ({selected_period})', loc='center', fontsize=16, fontweight='bold')
############ working code for line below for drawing lines.. dont delete.
# if not traderule3_high.empty:
# for value in traderule3_high:
# ax1.axhline(y=value, color='#7572f1', linestyle=':')
# if not traderule3_low.empty:
# # for value in traderule3_low: ### working code
# # ax1.axhline(y=value * 0.95, color='#ff000f', linestyle='--') ### working code
# for value in traderule3_low:
# ax1.axhline(y=value * 0.98, color='#ff000f', linestyle=':')
# ax1.text(resampled_df.index[-1], value * 0.98, f'{value:.2f}', va='center', ha='left',
# bbox=dict(facecolor='#0042a1', edgecolor='black', alpha=0.7, boxstyle='round,pad=0.5'))
# if not traderule4_high.empty:
# for value in traderule4_high:
# ax1.axhline(y=value, color='#abcddcba', linestyle='--')
# if not traderule4_low.empty:
# # for value in traderule4_low: ### working code
# # ax1.axhline(y=value * 0.95, color='#fabfab', linestyle='--') ### working code
# for value in traderule4_low:
# ax1.axhline(y=value * 0.98, color='#fabcfabc', linestyle='--')
# ax1.text(resampled_df.index[-1], value * 0.98, f'{value:.2f}', va='center', ha='left',
# bbox=dict(facecolor='#7572f1', edgecolor='black', alpha=0.7))
# ax1.set_yscale('log')
# ax1.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, p: f'{x:.2f}'))
# ax1.yaxis.set_major_formatter(ticker.FuncFormatter(price_formatter))
############################################################################################
if not highlight5_high_values.empty:
for value in highlight5_high_values:
ax1.axhline(y=value, color='#ff000f', linestyle='--', linewidth=0.8)
if not highlight5_low_values.empty:
for value in highlight5_low_values:
ax1.axhline(y=value * 0.95, color='#0042a1', linestyle='--', linewidth=0.8) ### working code
if not highlight3_high_values.empty:
for value in highlight3_high_values:
ax1.axhline(y=value, color='#ff3b46', linestyle='--', linewidth=0.8)
if not highlight3_low_values.empty:
for value in highlight3_low_values:
ax1.axhline(y=value * 0.95, color='#004cbb', linestyle='--', linewidth=0.8) ### working code
if not highlight2_high_values.empty:
for value in highlight2_high_values:
ax1.axhline(y=value, color='#ff626b', linestyle='--', linewidth=0.8)
if not highlight2_low_values.empty:
for value in highlight2_low_values:
ax1.axhline(y=value * 0.95, color='#0061ee', linestyle='--', linewidth=0.8) ### working code
#### Plotting for TRaderule 8
if not traderule8_high_values.empty:
for index, value in resampled_df['traderule8_high'].items():
if pd.notnull(value):
ax1.axhline(y=value, color='#0fffa1', linestyle='--', linewidth=0.8)
if not traderule8_low_values.empty:
for index, value in resampled_df['traderule8_low'].items():
if pd.notnull(value):
ax1.axhline(y=value, color='#0042a1', linestyle='--', linewidth=0.8)