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

Update app.py

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