riteshcp commited on
Commit
21aaa71
β€’
1 Parent(s): a040c5e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +94 -88
app.py CHANGED
@@ -2,8 +2,11 @@ import streamlit as st
2
  import yfinance as yf
3
  import pandas as pd
4
  from datetime import datetime, timedelta, time
 
 
 
5
 
6
- # Define the fallback list of ticker symbols
7
  TICKER_SYMBOLS = [
8
  "AADHARHFC", "AARTIIND", "AAVAS", "ABBOTINDIA", "ACE", "ADANIENSOL", "ADANIENT", "ADANIGREEN", "ADANIPORTS",
9
  "ADANIPOWER", "ATGL", "AWL", "ABCAPITAL", "ABFRL", "ABREL", "ABSLAMC", "AEGISLOG", "AFFLE", "AJANTPHARM",
@@ -33,6 +36,16 @@ TICKER_SYMBOLS = [
33
  "UPL", "VEDL", "WIPRO", "YESBANK", "ZEEL", "ZOMATO", "ZYDUSLIFE"
34
  ]
35
 
 
 
 
 
 
 
 
 
 
 
36
  # Function to check if the market is open
37
  def is_market_open():
38
  now = datetime.now().time()
@@ -42,93 +55,86 @@ def is_market_open():
42
 
43
  # Function to calculate pivot point and support/resistance levels
44
  def calculate_pivot_levels(stock_data):
45
- high = stock_data['High'].iloc[-1]
46
- low = stock_data['Low'].iloc[-1]
47
- close = stock_data['Close'].iloc[-1]
48
-
49
- # Calculate pivot point
50
- pivot = (high + low + close) / 3
51
-
52
- # Calculate support and resistance levels
53
- resistance1 = (2 * pivot) - low
54
- support1 = (2 * pivot) - high
55
- resistance2 = pivot + (high - low)
56
- support2 = pivot - (high - low)
57
- resistance3 = high + 2 * (pivot - low)
58
- support3 = low - 2 * (high - pivot)
59
-
60
- levels = {
61
- 'Pivot Point': pivot,
62
- 'Resistance 1': resistance1,
63
- 'Support 1': support1,
64
- 'Resistance 2': resistance2,
65
- 'Support 2': support2,
66
- 'Resistance 3': resistance3,
67
- 'Support 3': support3
68
- }
69
- return levels
70
-
71
- # Function to fetch stock data
 
 
72
  @st.cache_data(ttl=300) # Cache for 5 minutes
73
  def get_stock_data(symbol):
74
- nse_symbol = f"{symbol}.NS"
75
- today = datetime.today().date()
76
- stock = yf.download(nse_symbol, start=today - timedelta(days=5), end=today + timedelta(days=1), interval='1d', progress=False)
77
- return stock.tail(1) if not stock.empty else pd.DataFrame()
78
-
79
- # Streamlit UI
80
- def main():
81
- st.title("Support and Resistance Level Calculator for NIFTY 500 Stocks")
82
-
83
- # Load ticker symbols
84
- ticker_list = TICKER_SYMBOLS
85
-
86
- # Select a ticker from the list
87
- symbol = st.selectbox("Select a Stock Symbol", ticker_list)
88
-
89
- # Check if the market is currently open and display a warning
90
- if is_market_open():
91
- st.warning("Market is currently open. Data may be incomplete until after market hours (3:30 PM IST).")
92
-
93
- if symbol:
94
- # Refresh button for getting the latest data
95
- if st.button("πŸ”„ Refresh Data"):
96
- get_stock_data.clear() # Clear cached data for stock
97
-
98
- # Fetch stock data
99
- with st.spinner("Fetching stock data..."):
100
- stock_data = get_stock_data(symbol)
101
-
102
- # Display stock data if available
103
- if not stock_data.empty:
104
- levels = calculate_pivot_levels(stock_data)
105
-
106
- # Display current price
107
- current_price = stock_data['Close'].iloc[-1]
108
- st.metric("Current Price", f"β‚Ή{current_price:.2f}")
109
-
110
- # Display support and resistance levels in columns
111
- st.subheader(f"Support and Resistance Levels for {symbol}")
112
- col1, col2, col3 = st.columns(3)
113
-
114
- # Resistance levels
115
- with col1:
116
- st.write("### Resistance Levels")
117
- for i in range(3, 0, -1):
118
- st.write(f"R{i}: β‚Ή{levels[f'Resistance {i}']:.2f}")
119
-
120
- # Pivot Point
121
- with col2:
122
- st.write("### Pivot Point")
123
- st.write(f"PP: β‚Ή{levels['Pivot Point']:.2f}")
124
-
125
- # Support levels
126
- with col3:
127
- st.write("### Support Levels")
128
- for i in range(1, 4):
129
- st.write(f"S{i}: β‚Ή{levels[f'Support {i}']:.2f}")
130
  else:
131
- st.error("No data available for the selected stock. Please try again later or select a different stock.")
132
-
133
- if __name__ == "__main__":
134
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import yfinance as yf
3
  import pandas as pd
4
  from datetime import datetime, timedelta, time
5
+ import requests
6
+ from requests.adapters import HTTPAdapter
7
+ from urllib3.util.retry import Retry
8
 
9
+ # Define the list of ticker symbols for user selection
10
  TICKER_SYMBOLS = [
11
  "AADHARHFC", "AARTIIND", "AAVAS", "ABBOTINDIA", "ACE", "ADANIENSOL", "ADANIENT", "ADANIGREEN", "ADANIPORTS",
12
  "ADANIPOWER", "ATGL", "AWL", "ABCAPITAL", "ABFRL", "ABREL", "ABSLAMC", "AEGISLOG", "AFFLE", "AJANTPHARM",
 
36
  "UPL", "VEDL", "WIPRO", "YESBANK", "ZEEL", "ZOMATO", "ZYDUSLIFE"
37
  ]
38
 
39
+ # Streamlit App Title
40
+ st.title("Pivot Point Calculator for Indian Share Market")
41
+
42
+ # Ticker Selection
43
+ selected_ticker = st.selectbox("Select a Ticker Symbol", TICKER_SYMBOLS)
44
+
45
+ # Date input
46
+ start_date = st.date_input("Select Start Date for Historical Data")
47
+ end_date = st.date_input("Select End Date for Historical Data")
48
+
49
  # Function to check if the market is open
50
  def is_market_open():
51
  now = datetime.now().time()
 
55
 
56
  # Function to calculate pivot point and support/resistance levels
57
  def calculate_pivot_levels(stock_data):
58
+ try:
59
+ high = stock_data['High'].iloc[-1]
60
+ low = stock_data['Low'].iloc[-1]
61
+ close = stock_data['Close'].iloc[-1]
62
+
63
+ pivot = (high + low + close) / 3
64
+
65
+ resistance1 = (2 * pivot) - low
66
+ support1 = (2 * pivot) - high
67
+ resistance2 = pivot + (high - low)
68
+ support2 = pivot - (high - low)
69
+ resistance3 = high + 2 * (pivot - low)
70
+ support3 = low - 2 * (high - pivot)
71
+
72
+ levels = {
73
+ 'Pivot Point': pivot,
74
+ 'Resistance 1': resistance1,
75
+ 'Support 1': support1,
76
+ 'Resistance 2': resistance2,
77
+ 'Support 2': support2,
78
+ 'Resistance 3': resistance3,
79
+ 'Support 3': support3
80
+ }
81
+ return levels
82
+ except Exception as e:
83
+ st.error(f"Error calculating pivot levels: {str(e)}")
84
+ return None
85
+
86
+ # Function to fetch stock data with retry logic and proper error handling
87
  @st.cache_data(ttl=300) # Cache for 5 minutes
88
  def get_stock_data(symbol):
89
+ try:
90
+ nse_symbol = f"{symbol}.NS"
91
+ today = datetime.today().date()
92
+
93
+ # Set up a retry session to handle intermittent connection issues
94
+ session = requests.Session()
95
+ retries = Retry(total=5, backoff_factor=0.5, status_forcelist=[500, 502, 503, 504])
96
+ session.mount('https://', HTTPAdapter(max_retries=retries))
97
+
98
+ # Use the session to download data
99
+ stock = yf.download(
100
+ nse_symbol,
101
+ start=today - timedelta(days=5),
102
+ end=today + timedelta(days=1),
103
+ interval='1d',
104
+ progress=False,
105
+ session=session
106
+ )
107
+
108
+ if not stock.empty:
109
+ return stock.tail(1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  else:
111
+ st.warning("No data available for the selected stock.")
112
+ return pd.DataFrame()
113
+
114
+ except Exception as e:
115
+ st.error(f"Error fetching data for {symbol}: {str(e)}")
116
+ return pd.DataFrame()
117
+
118
+ # Load Data
119
+ if st.button("Calculate Pivot Points"):
120
+ if selected_ticker:
121
+ # Download historical data using yfinance
122
+ try:
123
+ data = get_stock_data(selected_ticker)
124
+ if not data.empty:
125
+ # Display historical data
126
+ st.subheader("Historical Data")
127
+ st.dataframe(data.tail())
128
+
129
+ # Calculate pivot points and support/resistance levels
130
+ levels = calculate_pivot_levels(data)
131
+ if levels:
132
+ st.subheader(f"Pivot Point Calculations for {selected_ticker}")
133
+ for level_name, value in levels.items():
134
+ st.write(f"{level_name}: {float(value):.2f}")
135
+ else:
136
+ st.error("No data available for the selected ticker and date range. Please try again.")
137
+ except Exception as e:
138
+ st.error(f"An error occurred: {e}")
139
+ else:
140
+ st.error("Please select a valid ticker symbol.")