-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.py
More file actions
2469 lines (2163 loc) · 112 KB
/
app.py
File metadata and controls
2469 lines (2163 loc) · 112 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
"""
Streamlit Application for RRG Chart Visualization
Visualizes Relative Rotation Graphs for different sectors on daily and weekly basis
Redesigned UI with three-pane layout: Left (Settings), Middle (Chart), Right (Selection)
"""
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
from datetime import datetime, timedelta
import sys
import os
import colorsys
import time
from dotenv import load_dotenv
import warnings
import logging
# Suppress all Streamlit warnings about Session State API
# This prevents warning messages from appearing in the UI
warnings.filterwarnings("ignore", message=".*Session State API.*", category=UserWarning)
warnings.filterwarnings("ignore", message=".*was created with a default value but also had its value set via the Session State API.*", category=UserWarning)
warnings.filterwarnings("ignore", message=".*created with a default value but also had its value set via the Session State API.*", category=UserWarning)
warnings.filterwarnings("ignore", message=".*default value but also had its value set.*", category=UserWarning)
warnings.filterwarnings("ignore", message=".*The widget with key.*was created with a default value but also had its value set via the Session State API.*", category=UserWarning)
# Suppress Streamlit session state logging
logging.getLogger("streamlit.runtime.state.session_state").setLevel(logging.ERROR)
logging.getLogger("streamlit.runtime.state").setLevel(logging.ERROR)
# Suppress all UserWarnings (Streamlit uses these for widget warnings)
warnings.filterwarnings("ignore", category=UserWarning)
# Load environment variables from .env file
load_dotenv()
# Add src to path
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
from loaders.AngelOneLoader import AngelOneLoader
from rrg_calculator import RRGCalculator
from sectors import BENCHMARKS, SECTORS, SUB_SECTORS
from token_fetcher import get_token_from_symbol
from scrip_master_search import search_indices, search_stocks, search_etfs, get_item_by_symbol, get_stocks, get_etfs, get_indices, get_etfs
# Custom CSS to remove top margin and make UI compact
st.markdown("""
<style>
.main .block-container {
padding-top: 0.5rem;
padding-bottom: 1rem;
}
h3 {
font-size: 1.2rem;
margin-bottom: 0.3rem;
margin-top: 0;
}
</style>
""", unsafe_allow_html=True)
# Load API credentials from environment variables
API_CONFIG = {
"API_KEY": os.getenv("API_KEY", ""),
"CLIENT_ID": os.getenv("CLIENT_ID", ""),
"PASSWORD": os.getenv("PASSWORD", ""),
"TOTP_TOKEN": os.getenv("TOTP_TOKEN", ""),
"EXCHANGE": os.getenv("EXCHANGE", "NSE")
}
# Validate that all required credentials are present
if not all([API_CONFIG["API_KEY"], API_CONFIG["CLIENT_ID"], API_CONFIG["PASSWORD"], API_CONFIG["TOTP_TOKEN"]]):
st.error("⚠️ Missing API credentials! Please create a .env file with your AngelOne API credentials. See .env.example for reference.")
st.stop()
# Page configuration
st.set_page_config(
page_title="RRG Chart Visualization",
page_icon="📊",
layout="wide",
initial_sidebar_state="collapsed"
)
# Major indices to initialize on first load (sectoral indices)
MAJOR_INDICES = [
"NIFTY Bank",
"NIFTY Financial Services",
"NIFTY IT",
"NIFTY FMCG",
"NIFTY Pharma",
"NIFTY Healthcare",
"NIFTY Auto",
"NIFTY Metal",
"NIFTY Energy",
"NIFTY Realty",
"NIFTY PSU Bank",
"NIFTY Infrastructure"
]
# Default stocks to show when Stock tab is selected
DEFAULT_STOCKS = [
"RELIANCE-EQ",
"TCS-EQ",
"HDFCBANK-EQ",
"INFY-EQ",
"ICICIBANK-EQ",
"HINDUNILVR-EQ"
]
# Default ETFs to show when ETF tab is selected
DEFAULT_ETFS = [
"BANKBEES-EQ",
"GOLDBEES-EQ",
"JUNIORBEES-EQ",
"ITBEES-EQ"
]
# Initialize session state
if 'loader' not in st.session_state:
st.session_state.loader = None
if 'token_cache' not in st.session_state:
st.session_state.token_cache = {}
if 'selected_indices' not in st.session_state:
st.session_state.selected_indices = []
if 'selected_stocks' not in st.session_state:
st.session_state.selected_stocks = []
if 'selected_etfs' not in st.session_state:
st.session_state.selected_etfs = []
if 'active_tab' not in st.session_state:
st.session_state.active_tab = "Index"
if 'is_initialized' not in st.session_state:
st.session_state.is_initialized = False
if 'chart_cache_key' not in st.session_state:
st.session_state.chart_cache_key = None
if 'cached_chart' not in st.session_state:
st.session_state.cached_chart = None
if 'cached_items_data' not in st.session_state:
st.session_state.cached_items_data = None
if 'cached_calculator' not in st.session_state:
st.session_state.cached_calculator = None
if 'animation_date_index' not in st.session_state:
st.session_state.animation_date_index = None
if 'is_animating' not in st.session_state:
st.session_state.is_animating = False
if 'available_dates' not in st.session_state:
st.session_state.available_dates = []
# Per-tab animation state
if 'use_animation_index' not in st.session_state:
st.session_state.use_animation_index = False
if 'use_animation_stock' not in st.session_state:
st.session_state.use_animation_stock = False
if 'use_animation_etf' not in st.session_state:
st.session_state.use_animation_etf = False
def initialize_default_items():
"""Initialize default items based on active tab"""
active_tab = st.session_state.get('active_tab', 'Index')
# Set default timeframe to weekly on first load
if 'timeframe' not in st.session_state:
st.session_state.timeframe = 'weekly'
# Initialize indices if Index tab is active and no indices selected
if active_tab == "Index" and not st.session_state.selected_indices:
try:
all_indices = get_indices()
major_indices_dict = {}
for idx in all_indices:
# Skip NIFTY 50 and NIFTY (exact matches)
if idx['symbol'].upper() in ['NIFTY 50', 'NIFTY', 'NIFTY50'] or idx['name'].upper() in ['NIFTY 50', 'NIFTY', 'NIFTY50']:
continue
# Match by symbol first
if idx['symbol'] in MAJOR_INDICES:
major_indices_dict[idx['symbol']] = idx
else:
# Try to match by name (use word boundaries to avoid partial matches)
idx_name_upper = idx['name'].upper()
idx_symbol_upper = idx['symbol'].upper()
for major in MAJOR_INDICES:
major_upper = major.upper()
# Exact symbol match
if idx_symbol_upper == major_upper:
if major not in major_indices_dict:
major_indices_dict[major] = idx
break
# Check if name matches exactly or as a complete word (not substring)
elif (idx_name_upper == major_upper or
idx_name_upper.replace(' ', '') == major_upper.replace(' ', '') or
# Match as complete word (not substring) - e.g., "NIFTY IT" matches "NIFTY IT" but not "NIFTY 50"
(major_upper in idx_name_upper and
(idx_name_upper.startswith(major_upper + ' ') or
idx_name_upper.endswith(' ' + major_upper) or
' ' + major_upper + ' ' in idx_name_upper))):
if major not in major_indices_dict:
major_indices_dict[major] = idx
break
# Add to selected indices
for major_symbol in MAJOR_INDICES:
if major_symbol in major_indices_dict:
idx_item = major_indices_dict[major_symbol]
if not any(x['symbol'] == idx_item['symbol'] for x in st.session_state.selected_indices):
st.session_state.selected_indices.append(idx_item)
except Exception:
pass
# Initialize stocks if Stock tab is active and no stocks selected
elif active_tab == "Stock" and not st.session_state.selected_stocks:
try:
all_stocks = get_stocks()
for default_symbol in DEFAULT_STOCKS:
# Find stock by symbol
stock_item = next((s for s in all_stocks if s['symbol'] == default_symbol), None)
if stock_item and not any(x['symbol'] == stock_item['symbol'] for x in st.session_state.selected_stocks):
st.session_state.selected_stocks.append(stock_item)
except Exception:
pass
# Initialize ETFs if ETF tab is active and no ETFs selected
elif active_tab == "ETF" and not st.session_state.selected_etfs:
try:
all_etfs = get_etfs()
for default_symbol in DEFAULT_ETFS:
# Find ETF by symbol
etf_item = next((e for e in all_etfs if e['symbol'] == default_symbol), None)
if etf_item and not any(x['symbol'] == etf_item['symbol'] for x in st.session_state.selected_etfs):
st.session_state.selected_etfs.append(etf_item)
except Exception:
pass
def generate_unique_colors(count: int) -> list:
"""Generate unique colors for chart tails"""
colors = []
for i in range(count):
hue = i / count
saturation = 0.7 + (i % 3) * 0.1
lightness = 0.5 + (i % 2) * 0.1
rgb = colorsys.hls_to_rgb(hue, lightness, saturation)
hex_color = '#{:02x}{:02x}{:02x}'.format(
int(rgb[0] * 255),
int(rgb[1] * 255),
int(rgb[2] * 255)
)
colors.append(hex_color)
return colors
def initialize_api_loader():
"""Initialize AngelOne API loader with retry logic and better error handling"""
# Close existing loader if timeframe changed
if st.session_state.loader is not None:
try:
st.session_state.loader.close()
except:
pass
# Retry logic for connection timeouts
max_retries = 3
retry_delay = 2 # seconds
for attempt in range(max_retries):
try:
loader = AngelOneLoader(
config=API_CONFIG,
tf=st.session_state.get('timeframe', 'daily'),
period=st.session_state.get('period', 200)
)
return loader
except Exception as e:
error_str = str(e).lower()
# Check if it's a connection timeout error
is_timeout = ('timeout' in error_str or
'connection' in error_str or
'max retries' in error_str or
'connecttimeouterror' in error_str)
if is_timeout and attempt < max_retries - 1:
# Retry with exponential backoff
import time
time.sleep(retry_delay * (attempt + 1))
continue
else:
# Only show error on final attempt or for non-timeout errors
if attempt == max_retries - 1:
# Log error silently - don't show error message to user
import logging
logger = logging.getLogger(__name__)
logger.warning(f"Failed to initialize API loader after {max_retries} attempts: {e}")
# Don't show st.error - let the app continue without loader
# The generate_chart function will handle None loader gracefully
elif not is_timeout:
# Non-timeout errors - log but don't retry
import logging
logger = logging.getLogger(__name__)
logger.error(f"Failed to initialize API loader: {e}")
return None
return None
def get_token(symbol):
"""Get token for symbol, using cache if available"""
if symbol in st.session_state.token_cache:
return st.session_state.token_cache[symbol]
token = get_token_from_symbol(symbol)
if token:
st.session_state.token_cache[symbol] = token
return token
def get_stock_data(loader, symbol, token):
"""Get stock data from loader"""
try:
df = loader.get(symbol, token)
if df is None or df.empty:
return None
return df
except Exception as e:
# Log the error for debugging
import logging
logger = logging.getLogger(__name__)
logger.error(f"Error fetching data for {symbol} (token: {token}): {e}")
return None
def create_rrg_chart_with_animation(items_data, calculator, tail_count=8, colors_map=None, filtered_dates=None):
"""
Create RRG chart with Plotly animation frames for smooth transitions
:param items_data: Dict of {symbol: (rs_series, momentum_series, df)}
:param calculator: RRGCalculator instance
:param tail_count: Number of tail points to show
:param colors_map: Dict mapping symbol to color
:param filtered_dates: List of dates to create frames for
"""
fig = go.Figure()
if not filtered_dates or not items_data:
# Return empty chart if no dates or data
fig.update_xaxes(title_text="RS Ratio", range=[93, 107], showgrid=True, gridwidth=1, gridcolor='lightgray')
fig.update_yaxes(title_text="RS Momentum", range=[93, 107], showgrid=True, gridwidth=1, gridcolor='lightgray')
# Add quadrant backgrounds for empty chart
fig.add_shape(type="rect", x0=93, y0=100, x1=100, y1=107, fillcolor="#b1ebff", layer="below", line_width=0)
fig.add_shape(type="rect", x0=100, y0=100, x1=107, y1=107, fillcolor="#bdffc9", layer="below", line_width=0)
fig.add_shape(type="rect", x0=100, y0=93, x1=107, y1=100, fillcolor="#fff7b8", layer="below", line_width=0)
fig.add_shape(type="rect", x0=93, y0=93, x1=100, y1=100, fillcolor="#ffb9c6", layer="below", line_width=0)
fig.add_hline(y=100, line_dash="dash", line_color="black", line_width=0.5)
fig.add_vline(x=100, line_dash="dash", line_color="black", line_width=0.5)
fig.update_layout(
title=f"RRG Chart - {st.session_state.get('benchmark_name', 'NIFTY 50')} ({st.session_state.get('timeframe', 'daily').upper()})",
height=600,
hovermode='closest',
template='plotly_white',
legend=dict(orientation="h", yanchor="bottom", y=-0.35, xanchor="center", x=0.5)
)
return fig
# Calculate step for frames (fewer frames for performance)
step = max(1, len(filtered_dates) // (50 * tail_count))
frame_dates = filtered_dates[::step]
if frame_dates[-1] != filtered_dates[-1]:
frame_dates.append(filtered_dates[-1])
# Calculate global axis range from all data
x_min, x_max = 200, 0
y_min, y_max = 200, 0
for symbol, (rs_series, momentum_series, df) in items_data.items():
if len(rs_series) > 0 and len(momentum_series) > 0:
x_min = min(x_min, rs_series.min())
x_max = max(x_max, rs_series.max())
y_min = min(y_min, momentum_series.min())
y_max = max(y_max, momentum_series.max())
# Calculate symmetric range around center (100, 100)
center_x, center_y = 100, 100
if x_min >= 200 or x_max <= 0:
x_range = y_range = 7
else:
# Calculate maximum distance from center on each axis
# Add reasonable padding (5% of data range, minimum 1.5 units)
x_data_range = x_max - x_min
y_data_range = y_max - y_min
x_padding = max(x_data_range * 0.05, 1.5)
y_padding = max(y_data_range * 0.05, 1.5)
x_dist_from_center = max(abs(x_min - center_x), abs(x_max - center_x)) + x_padding
y_dist_from_center = max(abs(y_min - center_y), abs(y_max - center_y)) + y_padding
x_range = max(x_dist_from_center, 7)
y_range = max(y_dist_from_center, 7)
# Calculate axis limits
x_axis_min = center_x - x_range
x_axis_max = center_x + x_range
y_axis_min = center_y - y_range
y_axis_max = center_y + y_range
# Add quadrant backgrounds (stretched to corners based on calculated ranges)
fig.add_shape(
type="rect",
x0=x_axis_min, y0=100, x1=center_x, y1=y_axis_max,
fillcolor="#b1ebff", # Light blue - Improving
layer="below",
line_width=0,
)
fig.add_shape(
type="rect",
x0=center_x, y0=100, x1=x_axis_max, y1=y_axis_max,
fillcolor="#bdffc9", # Light green - Leading
layer="below",
line_width=0,
)
fig.add_shape(
type="rect",
x0=center_x, y0=y_axis_min, x1=x_axis_max, y1=100,
fillcolor="#fff7b8", # Light yellow - Weakening
layer="below",
line_width=0,
)
fig.add_shape(
type="rect",
x0=x_axis_min, y0=y_axis_min, x1=center_x, y1=100,
fillcolor="#ffb9c6", # Light pink - Lagging
layer="below",
line_width=0,
)
# Add quadrant lines (static)
fig.add_hline(y=100, line_dash="dash", line_color="black", line_width=0.5)
fig.add_vline(x=100, line_dash="dash", line_color="black", line_width=0.5)
# Create frames for each date
frames = []
for frame_date in frame_dates:
cutoff_ts = pd.Timestamp(frame_date) if not isinstance(frame_date, pd.Timestamp) else frame_date
frame_data = []
for symbol, (rs_series, momentum_series, df) in items_data.items():
# Filter data up to cutoff_date
rs_filtered = rs_series[rs_series.index <= cutoff_ts]
momentum_filtered = momentum_series[momentum_series.index <= cutoff_ts]
if len(rs_filtered) == 0 or len(momentum_filtered) == 0:
continue
if len(rs_filtered) < tail_count or len(momentum_filtered) < tail_count:
continue
try:
rs_tail = rs_filtered.iloc[-tail_count:]
momentum_tail = momentum_filtered.iloc[-tail_count:]
current_rs = rs_filtered.iloc[-1]
current_momentum = momentum_filtered.iloc[-1]
except (IndexError, KeyError):
continue
color = colors_map.get(symbol, "#000000") if colors_map else "#000000"
# Tail line trace
frame_data.append(go.Scatter(
x=rs_tail.values,
y=momentum_tail.values,
mode='lines+markers',
name=symbol,
line=dict(color=color, width=2),
marker=dict(size=8, color=color),
hovertemplate=f'<b>{symbol}</b><br>' +
'RS: %{x:.2f}<br>' +
'Momentum: %{y:.2f}<br>' +
'<extra></extra>',
showlegend=True
))
# Current point trace
frame_data.append(go.Scatter(
x=[current_rs],
y=[current_momentum],
mode='markers+text',
name=f'{symbol} (Current)',
marker=dict(size=15, color=color, symbol='circle'),
text=[symbol],
textposition="top center",
textfont=dict(size=10, color=color),
hovertemplate=f'<b>{symbol}</b><br>RS: {current_rs:.2f}<br>Momentum: {current_momentum:.2f}<br>Quadrant: {calculator.get_quadrant(current_rs, current_momentum)}<br><extra></extra>',
showlegend=False
))
# Create frame
frames.append(go.Frame(
data=frame_data,
name=str(frame_date)
))
# Add initial traces (empty, will be populated by first frame)
for symbol in items_data.keys():
color = colors_map.get(symbol, "#000000") if colors_map else "#000000"
fig.add_trace(go.Scatter(
x=[],
y=[],
mode='lines+markers',
name=symbol,
line=dict(color=color, width=2),
marker=dict(size=8, color=color),
showlegend=True
))
fig.add_trace(go.Scatter(
x=[],
y=[],
mode='markers+text',
name=f'{symbol} (Current)',
marker=dict(size=15, color=color, symbol='circle'),
showlegend=False
))
# Set axis ranges (using calculated ranges)
fig.update_xaxes(
title_text="RS Ratio",
range=[x_axis_min, x_axis_max],
showgrid=True,
gridwidth=1,
gridcolor='lightgray'
)
fig.update_yaxes(
title_text="RS Momentum",
range=[y_axis_min, y_axis_max],
showgrid=True,
gridwidth=1,
gridcolor='lightgray'
)
# Add quadrant labels positioned within chart bounds (after axis ranges are set)
# Position labels at 15% from edges, ensuring they're visible and bold
label_x_offset = x_range * 0.15
label_y_offset = y_range * 0.15
min_offset = 1.0 # Minimum offset to ensure visibility
label_x_left = max(center_x - x_range + max(label_x_offset, min_offset), center_x - x_range + 1.0)
label_x_right = min(center_x + x_range - max(label_x_offset, min_offset), center_x + x_range - 1.0)
label_y_bottom = max(center_y - y_range + max(label_y_offset, min_offset), center_y - y_range + 1.0)
label_y_top = min(center_y + y_range - max(label_y_offset, min_offset), center_y + y_range - 1.0)
fig.add_annotation(
x=label_x_left,
y=label_y_top,
text="<b>Improving</b>",
showarrow=False,
font=dict(size=13, color="black", family="Arial Black"),
bgcolor="rgba(255,255,255,0.7)",
bordercolor="black",
borderwidth=1
)
fig.add_annotation(
x=label_x_right,
y=label_y_top,
text="<b>Leading</b>",
showarrow=False,
font=dict(size=13, color="black", family="Arial Black"),
bgcolor="rgba(255,255,255,0.7)",
bordercolor="black",
borderwidth=1
)
fig.add_annotation(
x=label_x_right,
y=label_y_bottom,
text="<b>Weakening</b>",
showarrow=False,
font=dict(size=13, color="black", family="Arial Black"),
bgcolor="rgba(255,255,255,0.7)",
bordercolor="black",
borderwidth=1
)
fig.add_annotation(
x=label_x_left,
y=label_y_bottom,
text="<b>Lagging</b>",
showarrow=False,
font=dict(size=13, color="black", family="Arial Black"),
bgcolor="rgba(255,255,255,0.7)",
bordercolor="black",
borderwidth=1
)
# Add frames
fig.frames = frames
# Animation controls
fig.update_layout(
title=f"RRG Chart - {st.session_state.get('benchmark_name', 'NIFTY 50')} ({st.session_state.get('timeframe', 'daily').upper()})",
height=600,
hovermode='closest',
template='plotly_white',
margin=dict(b=75, l=50, r=50, t=50),
legend=dict(orientation="h", yanchor="bottom", y=-0.35, xanchor="center", x=0.5),
updatemenus=[{
"buttons": [
{
"args": [None, {
"frame": {"duration": 300, "redraw": True},
"fromcurrent": True,
"transition": {"duration": 200, "easing": "linear"}
}],
"label": "▶️ Play",
"method": "animate"
},
{
"args": [[None], {
"frame": {"duration": 0, "redraw": True},
"mode": "immediate",
"transition": {"duration": 0}
}],
"label": "⏸️ Pause",
"method": "animate"
}
],
"direction": "left",
"pad": {"r": 10, "t": 1},
"showactive": True,
"type": "buttons",
"x": 0.1,
"xanchor": "right",
"y": -0.355,
"yanchor": "top"
}],
sliders=[{
"active": len(frames) - 1,
"yanchor": "top",
"xanchor": "left",
"currentvalue": {
"prefix": "Date: ",
"visible": True,
"xanchor": "right"
},
"transition": {"duration": 200, "easing": "linear"},
"pad": {"b": 10, "t": 1},
"len": 0.9,
"x": 0.1,
"y": -0.36,
"steps": [
{
"args": [[frame.name], {
"frame": {"duration": 0, "redraw": True},
"mode": "immediate",
"transition": {"duration": 0}
}],
"label": pd.Timestamp(frame.name).strftime('%d %b %Y') if isinstance(frame.name, str) else str(frame.name),
"method": "animate"
}
for frame in frames
]
}]
)
return fig
def precompute_charts_for_dates(items_data, calculator, tail_count, colors_map, dates):
"""
Precompute RRG charts for all dates in the given list.
Returns a dictionary mapping date (as normalized timestamp) to chart figure.
"""
precomputed = {}
for date in dates:
# Normalize date for consistent key
if isinstance(date, pd.Timestamp):
date_key = date.normalize()
else:
date_key = pd.Timestamp(date).normalize()
# Create chart for this date
fig = create_rrg_chart(
items_data,
None,
calculator,
tail_count=tail_count,
colors_map=colors_map,
cutoff_date=date_key
)
precomputed[date_key] = fig
return precomputed
def create_rrg_chart(items_data, benchmark_data, calculator, tail_count=8, colors_map=None, cutoff_date=None):
"""
Create RRG chart using Plotly
:param items_data: Dict of {symbol: (rs_series, momentum_series, df)}
:param benchmark_data: Benchmark DataFrame
:param calculator: RRGCalculator instance
:param tail_count: Number of tail points to show
:param colors_map: Dict mapping symbol to color
:param cutoff_date: Optional datetime to filter data up to this date
"""
fig = go.Figure()
# Track min/max for axis limits
x_min, x_max = 200, 0
y_min, y_max = 200, 0
# Plot each item
for symbol, (rs_series, momentum_series, df) in items_data.items():
# Filter data up to cutoff_date if provided
if cutoff_date is not None:
# Convert cutoff_date to pandas Timestamp and normalize to date only (no time component)
cutoff_ts = pd.Timestamp(cutoff_date) if not isinstance(cutoff_date, pd.Timestamp) else cutoff_date
cutoff_ts = cutoff_ts.normalize() # Remove time component for exact date matching
# Filter series to only include dates up to and including cutoff_date
# Normalize index dates for comparison to ensure exact date matching (especially for weekly charts)
rs_mask = [pd.Timestamp(d).normalize() <= cutoff_ts for d in rs_series.index]
momentum_mask = [pd.Timestamp(d).normalize() <= cutoff_ts for d in momentum_series.index]
rs_series = rs_series[rs_mask]
momentum_series = momentum_series[momentum_mask]
# Validate that we have enough data
if len(rs_series) == 0 or len(momentum_series) == 0:
continue
if len(rs_series) < tail_count or len(momentum_series) < tail_count:
continue
try:
# Get tail data (last tail_count points up to cutoff_date)
rs_tail = rs_series.iloc[-tail_count:]
momentum_tail = momentum_series.iloc[-tail_count:]
# Get current values (last point up to cutoff_date)
current_rs = rs_series.iloc[-1]
current_momentum = momentum_series.iloc[-1]
except (IndexError, KeyError):
# Skip items with invalid data
continue
# Get unique color for this symbol
color = colors_map.get(symbol, "#000000") if colors_map else "#000000"
# Update min/max
x_min = min(x_min, rs_tail.min())
x_max = max(x_max, rs_tail.max())
y_min = min(y_min, momentum_tail.min())
y_max = max(y_max, momentum_tail.max())
# Add tail line
fig.add_trace(go.Scatter(
x=rs_tail.values,
y=momentum_tail.values,
mode='lines+markers',
name=symbol,
line=dict(color=color, width=2),
marker=dict(size=8, color=color),
hovertemplate=f'<b>{symbol}</b><br>' +
'RS: %{x:.2f}<br>' +
'Momentum: %{y:.2f}<br>' +
'<extra></extra>',
showlegend=True
))
# Add current point with label
fig.add_trace(go.Scatter(
x=[current_rs],
y=[current_momentum],
mode='markers+text',
name=f'{symbol} (Current)',
marker=dict(size=15, color=color, symbol='circle'),
text=[symbol],
textposition="top center",
textfont=dict(size=10, color=color),
hovertemplate=f'<b>{symbol}</b><br>' +
f'RS: {current_rs:.2f}<br>' +
f'Momentum: {current_momentum:.2f}<br>' +
f'Quadrant: {calculator.get_quadrant(current_rs, current_momentum)}<br>' +
'<extra></extra>',
showlegend=False
))
# Calculate symmetric range around center (100, 100)
# The center point (100, 100) should always be exactly in the middle
center_x = 100
center_y = 100
if x_min >= 200 or x_max <= 0:
# No data - use default symmetric range
x_range = 7 # Default range: 93 to 107 (7 units on each side)
y_range = 7
else:
# Calculate maximum distance from center on each axis
# Add reasonable padding (5% of data range, minimum 1.5 units)
x_data_range = x_max - x_min
y_data_range = y_max - y_min
x_padding = max(x_data_range * 0.05, 1.5)
y_padding = max(y_data_range * 0.05, 1.5)
x_dist_from_center = max(abs(x_min - center_x), abs(x_max - center_x)) + x_padding
y_dist_from_center = max(abs(y_min - center_y), abs(y_max - center_y)) + y_padding
# Ensure minimum range for visibility
x_range = max(x_dist_from_center, 7)
y_range = max(y_dist_from_center, 7)
# Calculate axis limits
x_axis_min = center_x - x_range
x_axis_max = center_x + x_range
y_axis_min = center_y - y_range
y_axis_max = center_y + y_range
# Add quadrant backgrounds (stretched to corners based on calculated ranges)
fig.add_shape(
type="rect",
x0=x_axis_min, y0=100, x1=center_x, y1=y_axis_max,
fillcolor="#b1ebff", # Light blue - Improving
layer="below",
line_width=0,
)
fig.add_shape(
type="rect",
x0=center_x, y0=100, x1=x_axis_max, y1=y_axis_max,
fillcolor="#bdffc9", # Light green - Leading
layer="below",
line_width=0,
)
fig.add_shape(
type="rect",
x0=center_x, y0=y_axis_min, x1=x_axis_max, y1=100,
fillcolor="#fff7b8", # Light yellow - Weakening
layer="below",
line_width=0,
)
fig.add_shape(
type="rect",
x0=x_axis_min, y0=y_axis_min, x1=center_x, y1=100,
fillcolor="#ffb9c6", # Light pink - Lagging
layer="below",
line_width=0,
)
# Add quadrant lines
fig.add_hline(y=100, line_dash="dash", line_color="black", line_width=0.5)
fig.add_vline(x=100, line_dash="dash", line_color="black", line_width=0.5)
# Set symmetric ranges centered at (100, 100)
fig.update_xaxes(
title_text="RS Ratio",
range=[x_axis_min, x_axis_max],
showgrid=True,
gridwidth=1,
gridcolor='lightgray'
)
fig.update_yaxes(
title_text="RS Momentum",
range=[y_axis_min, y_axis_max],
showgrid=True,
gridwidth=1,
gridcolor='lightgray'
)
# Add quadrant labels positioned within chart bounds (after axis ranges are set)
# Position labels at 15% from edges, ensuring they're visible and bold
label_x_offset = x_range * 0.15
label_y_offset = y_range * 0.15
min_offset = 1.0 # Minimum offset to ensure visibility
label_x_left = max(center_x - x_range + max(label_x_offset, min_offset), center_x - x_range + 1.0)
label_x_right = min(center_x + x_range - max(label_x_offset, min_offset), center_x + x_range - 1.0)
label_y_bottom = max(center_y - y_range + max(label_y_offset, min_offset), center_y - y_range + 1.0)
label_y_top = min(center_y + y_range - max(label_y_offset, min_offset), center_y + y_range - 1.0)
fig.add_annotation(
x=label_x_left,
y=label_y_top,
text="<b>Improving</b>",
showarrow=False,
font=dict(size=13, color="black", family="Arial Black"),
bgcolor="rgba(255,255,255,0.7)",
bordercolor="black",
borderwidth=1
)
fig.add_annotation(
x=label_x_right,
y=label_y_top,
text="<b>Leading</b>",
showarrow=False,
font=dict(size=13, color="black", family="Arial Black"),
bgcolor="rgba(255,255,255,0.7)",
bordercolor="black",
borderwidth=1
)
fig.add_annotation(
x=label_x_right,
y=label_y_bottom,
text="<b>Weakening</b>",
showarrow=False,
font=dict(size=13, color="black", family="Arial Black"),
bgcolor="rgba(255,255,255,0.7)",
bordercolor="black",
borderwidth=1
)
fig.add_annotation(
x=label_x_left,
y=label_y_bottom,
text="<b>Lagging</b>",
showarrow=False,
font=dict(size=13, color="black", family="Arial Black"),
bgcolor="rgba(255,255,255,0.7)",
bordercolor="black",
borderwidth=1
)
# Update title with cutoff date if provided
title_date = cutoff_date.strftime('%d %b %Y') if cutoff_date else datetime.now().strftime('%d %b %Y')
fig.update_layout(
title=f"RRG Chart - {st.session_state.get('benchmark_name', 'NIFTY 50')} ({st.session_state.get('timeframe', 'daily').upper()}) - {title_date}",
height=600,
hovermode='closest',
template='plotly_white',
legend=dict(
orientation="h",
yanchor="bottom",
y=-0.2,
xanchor="center",
x=0.5
)
)
return fig
def generate_chart():
"""Generate RRG chart based on current selections and settings"""
# Get selected items ONLY from the active tab
all_selected = []
active_tab = st.session_state.get('active_tab', 'Index')
# Only add items from the active tab
if active_tab == "Index":
for idx in st.session_state.selected_indices:
token = idx.get("token")
all_selected.append(("Index", idx["symbol"], idx["name"], token))
elif active_tab == "Stock":
for stock in st.session_state.selected_stocks:
# Use .get() to handle missing token key gracefully
token = stock.get("token")
all_selected.append(("Stock", stock["symbol"], stock["name"], token))
elif active_tab == "ETF":
for etf in st.session_state.selected_etfs:
token = etf.get("token")
all_selected.append(("ETF", etf["symbol"], etf["name"], token))
# Always return a chart (even if no items selected, will show quadrants only)
# Initialize items_data as empty dict if no selections
items_data = {}
calculator = None
benchmark_df = None
# Get computation method
use_standard_jdk = st.session_state.get('computation_method', 'Enhanced') == 'Standard JDK'
timeframe = st.session_state.get('timeframe', 'weekly')
# For Standard JDK, period is used for ROC calculation (taken from roc_shift slider)
# For Enhanced, roc_shift is used for ROC calculation
roc_shift = st.session_state.get('roc_shift', 10)
if use_standard_jdk:
# Standard JDK uses period for ROC calculation
standard_period = roc_shift
else:
# Enhanced uses roc_shift for ROC calculation
standard_period = st.session_state.get('roc_period', 20) # Deprecated, kept for compatibility
if not all_selected:
# Return empty chart with just quadrants
calculator = RRGCalculator(
window=st.session_state.get('window', 14),
period=standard_period,
ema_span=14, # Fixed in formula
roc_shift=roc_shift,
ema_roc_span=st.session_state.get('ema_roc_span', 14),
use_standard_jdk=use_standard_jdk
)
fig = create_rrg_chart(items_data, None, calculator, tail_count=st.session_state.get('tail_count', 8))
return fig, items_data, calculator
# Check if loader needs to be reinitialized (timeframe changed)
current_timeframe = st.session_state.get('timeframe', 'daily')
needs_reinit = False
if st.session_state.loader is None:
needs_reinit = True
else:
# Check if timeframe changed
loader_tf = getattr(st.session_state.loader, 'tf', None)
if loader_tf != current_timeframe:
needs_reinit = True
# Reinitialize loader if needed
if needs_reinit:
if st.session_state.loader is not None:
try:
st.session_state.loader.close()