Spaces:
Sleeping

riteshcp commited on
Commit
1f13d95
·
verified ·
1 Parent(s): d044111

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +209 -15
app.py CHANGED
@@ -2,12 +2,40 @@ import streamlit as st
2
  import pandas as pd
3
  import yfinance as yf
4
  import ta
 
 
 
 
5
 
6
- # Streamlit Title
7
- st.title("NIFTY 500 RSI Divergence Scanner - Test Mode")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
  @st.cache_data
10
  def load_stock_list(csv_path='ind_nifty500list.csv'):
 
 
 
11
  try:
12
  stock_list = pd.read_csv(csv_path)
13
  if 'Symbol' not in stock_list.columns:
@@ -29,25 +57,191 @@ if stock_list.empty:
29
 
30
  tickers = stock_list['Symbol'].tolist()
31
 
32
- # Select a single known ticker
33
- test_ticker = 'RELIANCE'
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- # Fetch data
 
 
 
 
36
  def fetch_stock_data(ticker, period="6mo", interval="1d"):
37
- yf_ticker = ticker if ticker.endswith('.NS') else f"{ticker}.NS"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  try:
39
- data = yf.download(yf_ticker, period=period, interval=interval, progress=False)
40
- if data.empty:
41
- st.warning(f"No data fetched for {yf_ticker}. Please check the ticker symbol.")
42
  return data
43
  except Exception as e:
44
- st.error(f"Error fetching data for {yf_ticker}: {e}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
  return pd.DataFrame()
46
 
47
- data = fetch_stock_data(test_ticker)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
48
 
49
- if not data.empty:
50
- st.write(f"**Data for {test_ticker}**")
51
- st.dataframe(data)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  else:
53
- st.write(f"No data available for {test_ticker}.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import pandas as pd
3
  import yfinance as yf
4
  import ta
5
+ from concurrent.futures import ThreadPoolExecutor, as_completed
6
+ from datetime import datetime
7
+ import logging
8
+ import time
9
 
10
+ # -------------------------------
11
+ # Streamlit App Configuration
12
+ # -------------------------------
13
+
14
+ # Set the page layout to wide for better visibility
15
+ st.set_page_config(layout="wide")
16
+
17
+ # Configure logging
18
+ logging.basicConfig(level=logging.INFO)
19
+ logger = logging.getLogger()
20
+
21
+ # Set the title of the app
22
+ st.title("NIFTY 500 RSI Divergence Scanner")
23
+
24
+ # Add a description
25
+ st.markdown("""
26
+ This application scans **NIFTY 500** stocks to identify RSI (Relative Strength Index) divergences.
27
+ RSI divergence occurs when the price movement and RSI indicator move in opposite directions, potentially signaling a trend reversal.
28
+ """)
29
+
30
+ # -------------------------------
31
+ # Load NIFTY 500 Stock List
32
+ # -------------------------------
33
 
34
  @st.cache_data
35
  def load_stock_list(csv_path='ind_nifty500list.csv'):
36
+ """
37
+ Loads the NIFTY 500 stock list from a CSV file.
38
+ """
39
  try:
40
  stock_list = pd.read_csv(csv_path)
41
  if 'Symbol' not in stock_list.columns:
 
57
 
58
  tickers = stock_list['Symbol'].tolist()
59
 
60
+ # -------------------------------
61
+ # User Inputs (Sidebar)
62
+ # -------------------------------
63
+
64
+ # Sidebar for user inputs
65
+ st.sidebar.header("User Inputs")
66
+
67
+ # Multi-select Dropdown for Stock Selection
68
+ selected_stocks = st.sidebar.multiselect(
69
+ 'Select Stocks for Screening',
70
+ tickers,
71
+ default=tickers # Select all by default
72
+ )
73
+
74
+ # RSI Parameters
75
+ st.sidebar.subheader("RSI Parameters")
76
+ rsi_period = st.sidebar.slider('RSI Period', min_value=7, max_value=28, value=14, step=1)
77
+ rsi_lower_bound = st.sidebar.slider('RSI Lower Bound', min_value=10, max_value=50, value=30, step=5)
78
+ rsi_upper_bound = st.sidebar.slider('RSI Upper Bound', min_value=50, max_value=90, value=70, step=5)
79
 
80
+ # -------------------------------
81
+ # Processing Functions
82
+ # -------------------------------
83
+
84
+ @st.cache_data
85
  def fetch_stock_data(ticker, period="6mo", interval="1d"):
86
+ """
87
+ Fetches historical stock data using yfinance.
88
+ Attempts multiple suffixes if data is not found.
89
+ """
90
+ suffixes = ['', '.NS'] # Add other suffixes if needed
91
+ for suffix in suffixes:
92
+ yf_ticker = f"{ticker}{suffix}"
93
+ try:
94
+ data = yf.download(yf_ticker, period=period, interval=interval, progress=False)
95
+ if not data.empty:
96
+ logger.info(f"Data fetched for {yf_ticker}")
97
+ return data, yf_ticker
98
+ else:
99
+ logger.warning(f"No data for {yf_ticker}")
100
+ except Exception as e:
101
+ logger.error(f"Error fetching data for {yf_ticker}: {e}")
102
+ # If all suffixes fail
103
+ logger.error(f"No data fetched for {ticker} with suffixes {suffixes}")
104
+ return pd.DataFrame(), None
105
+
106
+ def calculate_rsi(data, window):
107
+ """
108
+ Calculates the RSI using the ta library.
109
+ """
110
  try:
111
+ rsi_indicator = ta.momentum.RSIIndicator(close=data['Close'], window=window)
112
+ data['RSI'] = rsi_indicator.rsi()
 
113
  return data
114
  except Exception as e:
115
+ st.error(f"Error calculating RSI: {e}")
116
+ return data
117
+
118
+ def identify_divergence(data, lower_bound, upper_bound):
119
+ """
120
+ Identifies RSI divergence in the stock data.
121
+ """
122
+ try:
123
+ data['Price Change'] = data['Close'].diff()
124
+ data['RSI Change'] = data['RSI'].diff()
125
+ # Divergence Condition: Price and RSI moving in opposite directions
126
+ data['Divergence'] = (data['Price Change'] * data['RSI Change'] < 0).astype(int)
127
+ # Filter for RSI levels and Divergence
128
+ divergence_days = data[
129
+ ((data['RSI'] < lower_bound) | (data['RSI'] > upper_bound)) &
130
+ (data['Divergence'] == 1)
131
+ ]
132
+ return divergence_days
133
+ except Exception as e:
134
+ st.error(f"Error identifying divergence: {e}")
135
  return pd.DataFrame()
136
 
137
+ def process_ticker(ticker, rsi_period, lower_bound, upper_bound):
138
+ """
139
+ Processes a single ticker to identify RSI divergence.
140
+ """
141
+ time.sleep(0.1) # Slight delay to prevent rate limiting
142
+ data, yf_ticker = fetch_stock_data(ticker)
143
+ if data.empty:
144
+ logger.warning(f"No data fetched for {ticker}")
145
+ return {'Ticker': ticker, 'Divergence Dates': [], 'Error': 'No data fetched.'}
146
+
147
+ data = calculate_rsi(data, rsi_period)
148
+ divergence_days = identify_divergence(data, lower_bound, upper_bound)
149
+
150
+ if not divergence_days.empty:
151
+ # Convert Timestamps to date strings
152
+ divergence_dates = [date.strftime('%Y-%m-%d') for date in divergence_days.index]
153
+ return {'Ticker': ticker, 'Divergence Dates': divergence_dates, 'Error': None}
154
+ else:
155
+ return {'Ticker': ticker, 'Divergence Dates': [], 'Error': None}
156
+
157
+ # -------------------------------
158
+ # Scan Stocks for RSI Divergence
159
+ # -------------------------------
160
+
161
+ st.header("RSI Divergence Results")
162
+
163
+ # Initialize a list to hold divergence results
164
+ divergence_results = []
165
+
166
+ # Initialize a list to hold errors
167
+ error_results = []
168
 
169
+ # Progress bar setup
170
+ progress_bar = st.progress(0)
171
+ status_text = st.empty()
172
+
173
+ total_stocks = len(selected_stocks)
174
+ completed_stocks = 0
175
+
176
+ if selected_stocks:
177
+ # Use ThreadPoolExecutor for parallel processing
178
+ with ThreadPoolExecutor(max_workers=10) as executor:
179
+ # Dictionary to keep track of futures
180
+ future_to_ticker = {executor.submit(process_ticker, ticker, rsi_period, rsi_lower_bound, rsi_upper_bound): ticker for ticker in selected_stocks}
181
+
182
+ for future in as_completed(future_to_ticker):
183
+ ticker = future_to_ticker[future]
184
+ try:
185
+ result = future.result()
186
+ if result['Error']:
187
+ error_results.append(result)
188
+ elif result['Divergence Dates']:
189
+ divergence_results.append(result)
190
+ except Exception as e:
191
+ error_results.append({'Ticker': ticker, 'Divergence Dates': [], 'Error': str(e)})
192
+ finally:
193
+ completed_stocks += 1
194
+ progress_percentage = completed_stocks / total_stocks
195
+ progress_bar.progress(progress_percentage)
196
+ status_text.text(f"Processing {completed_stocks} of {total_stocks} stocks...")
197
+
198
+ # Finalize progress bar
199
+ progress_bar.empty()
200
+ status_text.empty()
201
+
202
+ # -------------------------------
203
+ # Display Divergence Results
204
+ # -------------------------------
205
+
206
+ if divergence_results:
207
+ st.success("RSI Divergence Found in the Following Stocks:")
208
+ for item in divergence_results:
209
+ divergence_dates = ', '.join(item['Divergence Dates'])
210
+ st.markdown(f"**{item['Ticker']}** - Divergence Dates: {divergence_dates}")
211
+ else:
212
+ st.info("No RSI divergences found for the selected stocks.")
213
+
214
+ # -------------------------------
215
+ # Display Errors (If Any)
216
+ # -------------------------------
217
+
218
+ if error_results:
219
+ st.header("Errors Encountered")
220
+ for item in error_results:
221
+ st.error(f"**{item['Ticker']}** - Error: {item['Error']}")
222
  else:
223
+ st.warning("Please select at least one stock to begin screening.")
224
+
225
+ # -------------------------------
226
+ # Show Raw Data Option
227
+ # -------------------------------
228
+
229
+ if st.sidebar.checkbox('Show Stock Data'):
230
+ st.header("Raw Stock Data")
231
+ for ticker in selected_stocks:
232
+ st.subheader(f"Stock Data for: {ticker}")
233
+ data, yf_ticker = fetch_stock_data(ticker)
234
+ if data.empty:
235
+ st.write("No data available.")
236
+ continue
237
+ data = calculate_rsi(data, rsi_period)
238
+ st.dataframe(data)
239
+
240
+ # -------------------------------
241
+ # Footer
242
+ # -------------------------------
243
+
244
+ st.markdown("""
245
+ ---
246
+ **Disclaimer:** This tool is for informational purposes only and does not constitute financial advice. Please consult with a financial advisor before making investment decisions.
247
+ """)