riteshcp commited on
Commit
4b273d3
·
verified ·
1 Parent(s): 95008a8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -146
app.py CHANGED
@@ -1,146 +1,106 @@
1
- import streamlit as st
2
- import pandas as pd
3
- import os
4
- import yfinance as yf
5
- import numpy as np
6
- import datetime
7
-
8
- def load_data(filename):
9
- if os.path.exists(filename):
10
- st.write(f"File found: {filename}")
11
- try:
12
- data = pd.read_csv(filename)
13
- return data
14
- except pd.errors.EmptyDataError:
15
- st.error("CSV file is empty. Please fetch the data again.")
16
- return None
17
- except pd.errors.ParserError:
18
- st.error("Error parsing the CSV file. Please check the file format.")
19
- return None
20
- else:
21
- st.write(f"File not found: {filename}")
22
- return None
23
-
24
- def fetch_stock_data(symbol, start_date, end_date, interval):
25
- try:
26
- valid_intervals = {
27
- "1m": 8, # 1-minute data is available for up to 8 days
28
- "2m": 60, # 2-minute data is available for up to 60 days
29
- "5m": 60, # 5-minute data is available for up to 60 days
30
- "15m": 60, # 15-minute data is available for up to 60 days
31
- "30m": 60, # 30-minute data is available for up to 60 days
32
- "60m": 730, # 60-minute data is available for up to 730 days (2 years)
33
- "90m": 730, # 90-minute data is available for up to 730 days (2 years)
34
- "1h": 730, # 1-hour data is available for up to 730 days (2 years)
35
- "1d": 10000, # Daily data is available for up to maximum available
36
- "5d": 10000, # 5-day data is available for up to maximum available
37
- "1wk": 10000,# Weekly data is available for up to maximum available
38
- "1mo": 10000,# Monthly data is available for up to maximum available
39
- "3mo": 10000 # Quarterly data is available for up to maximum available
40
- }
41
-
42
- if interval not in valid_intervals:
43
- st.error(f"Invalid interval: {interval}. Please choose from {list(valid_intervals.keys())}")
44
- return
45
-
46
- max_days = valid_intervals[interval]
47
- start_date_pd = pd.to_datetime(start_date)
48
- end_date_pd = pd.to_datetime(end_date)
49
- max_start_date = end_date_pd - pd.to_timedelta(max_days, unit='d')
50
-
51
- if start_date_pd < max_start_date:
52
- st.warning(f"The selected start date exceeds the maximum allowed range for {interval} interval. Adjusting start date to {max_start_date.strftime('%Y-%m-%d')}")
53
- start_date_pd = max_start_date
54
-
55
- ticker = yf.Ticker(symbol)
56
- data = ticker.history(start=start_date_pd.strftime('%Y-%m-%d'), end=end_date_pd.strftime('%Y-%m-%d'), interval=interval)
57
- if not data.empty:
58
- # Calculate On-Balance Volume (OBV)
59
- data['OBV'] = (np.sign(data['Close'].diff()) * data['Volume']).fillna(0).cumsum()
60
- # Calculate Relative Strength Index (RSI)
61
- delta = data['Close'].diff()
62
- gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
63
- loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
64
- rs = gain / loss
65
- data['RSI'] = 100 - (100 / (1 + rs))
66
- # Calculate Exponential Moving Average (EMA)
67
- data['EMA'] = data['Close'].ewm(span=20, adjust=False).mean()
68
- # Calculate Simple Moving Average (SMA)
69
- data['SMA'] = data['Close'].rolling(window=20).mean()
70
- data.to_csv(f'{symbol}_{interval}.csv', index=False)
71
- st.write(f"Data for {symbol} fetched and saved successfully with OBV, RSI, EMA, and SMA included.")
72
- else:
73
- st.error(f"No data available for {symbol}. Please check the symbol or try a different date range.")
74
- except Exception as e:
75
- st.error(f"Error fetching data for {symbol}: {e}")
76
-
77
- # Ensure stock list CSV for Hugging Face Spaces
78
- STOCK_LIST_FILE = 'stock_list.csv'
79
-
80
- def update_stock_list():
81
- try:
82
- # Placeholder list of Indian stock symbols, as Yahoo Finance does not provide a full list directly
83
- stock_symbols = [
84
- "RELIANCE.NS", "TCS.NS", "INFY.NS", "HDFCBANK.NS", "ICICIBANK.NS",
85
- "KOTAKBANK.NS", "SBIN.NS", "LT.NS", "HINDUNILVR.NS", "BHARTIARTL.NS"
86
- ]
87
- df = pd.DataFrame(stock_symbols, columns=["Symbol"])
88
- df.to_csv(STOCK_LIST_FILE, index=False)
89
- st.write("Stock list updated successfully.")
90
- except Exception as e:
91
- st.error(f"Error updating stock list: {e}")
92
-
93
- # Load or update stock list
94
- if not os.path.exists(STOCK_LIST_FILE) or (datetime.datetime.now() - datetime.datetime.fromtimestamp(os.path.getmtime(STOCK_LIST_FILE))).days > 7:
95
- update_stock_list()
96
-
97
- # Load stock list from CSV
98
- stock_list = pd.read_csv(STOCK_LIST_FILE)['Symbol'].tolist()
99
-
100
- # Streamlit app layout
101
- st.title("Share Market Data")
102
- symbol = st.selectbox("Select Stock Symbol", options=stock_list)
103
- interval = st.selectbox("Select Data Interval", options=["1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d", "5d", "1wk", "1mo", "3mo"])
104
-
105
- # Allow user to select a start date
106
- start_date = st.date_input("Select Start Date", pd.to_datetime('2023-01-01'))
107
- end_date = pd.to_datetime('today').strftime('%Y-%m-%d')
108
-
109
- valid_intervals = {
110
- "1m": 8, # 1-minute data is available for up to 8 days
111
- "2m": 60, # 2-minute data is available for up to 60 days
112
- "5m": 60, # 5-minute data is available for up to 60 days
113
- "15m": 60, # 15-minute data is available for up to 60 days
114
- "30m": 60, # 30-minute data is available for up to 60 days
115
- "60m": 730, # 60-minute data is available for up to 730 days (2 years)
116
- "90m": 730, # 90-minute data is available for up to 730 days (2 years)
117
- "1h": 730, # 1-hour data is available for up to 730 days (2 years)
118
- "1d": 10000, # Daily data is available for up to maximum available
119
- "5d": 10000, # 5-day data is available for up to maximum available
120
- "1wk": 10000,# Weekly data is available for up to maximum available
121
- "1mo": 10000,# Monthly data is available for up to maximum available
122
- "3mo": 10000 # Quarterly data is available for up to maximum available
123
- }
124
-
125
- max_days = valid_intervals[interval]
126
- end_date_pd = pd.to_datetime('today')
127
- max_start_date = end_date_pd - pd.to_timedelta(max_days, unit='d')
128
-
129
- # Adjust the start date if it exceeds the limit
130
- if pd.to_datetime(start_date) < max_start_date:
131
- st.warning(f"The selected start date exceeds the maximum allowed range for {interval} interval. Adjusting start date to {max_start_date.strftime('%Y-%m-%d')}")
132
- start_date = max_start_date
133
-
134
- fetch_data = st.button("Fetch and Save Data")
135
-
136
- if fetch_data and symbol:
137
- fetch_stock_data(symbol, start_date.strftime('%Y-%m-%d'), end_date, interval)
138
-
139
- if symbol:
140
- filename = f'{symbol}_{interval}.csv'
141
- data = load_data(filename)
142
- if data is not None:
143
- st.write(f"Data from {start_date.strftime('%Y-%m-%d')} to {end_date} at interval {interval}")
144
- st.write(data)
145
- else:
146
- st.error(f"Data for {symbol} not found. Please fetch and store the data first.")
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import yfinance as yf
4
+ import numpy as np
5
+ import datetime
6
+
7
+ def fetch_stock_data(symbol, start_date, end_date, interval):
8
+ try:
9
+ valid_intervals = {
10
+ "1m": 8, # 1-minute data is available for up to 8 days
11
+ "2m": 60, # 2-minute data is available for up to 60 days
12
+ "5m": 60, # 5-minute data is available for up to 60 days
13
+ "15m": 60, # 15-minute data is available for up to 60 days
14
+ "30m": 60, # 30-minute data is available for up to 60 days
15
+ "60m": 730, # 60-minute data is available for up to 730 days (2 years)
16
+ "90m": 730, # 90-minute data is available for up to 730 days (2 years)
17
+ "1h": 730, # 1-hour data is available for up to 730 days (2 years)
18
+ "1d": 10000, # Daily data is available for up to maximum available
19
+ "5d": 10000, # 5-day data is available for up to maximum available
20
+ "1wk": 10000,# Weekly data is available for up to maximum available
21
+ "1mo": 10000,# Monthly data is available for up to maximum available
22
+ "3mo": 10000 # Quarterly data is available for up to maximum available
23
+ }
24
+
25
+ if interval not in valid_intervals:
26
+ st.error(f"Invalid interval: {interval}. Please choose from {list(valid_intervals.keys())}")
27
+ return
28
+
29
+ max_days = valid_intervals[interval]
30
+ start_date_pd = pd.to_datetime(start_date)
31
+ end_date_pd = pd.to_datetime(end_date)
32
+ max_start_date = end_date_pd - pd.to_timedelta(max_days, unit='d')
33
+
34
+ if start_date_pd < max_start_date:
35
+ st.warning(f"The selected start date exceeds the maximum allowed range for {interval} interval. Adjusting start date to {max_start_date.strftime('%Y-%m-%d')}")
36
+ start_date_pd = max_start_date
37
+
38
+ ticker = yf.Ticker(symbol)
39
+ data = ticker.history(start=start_date_pd.strftime('%Y-%m-%d'), end=end_date_pd.strftime('%Y-%m-%d'), interval=interval)
40
+ if not data.empty:
41
+ data.reset_index(inplace=True)
42
+ data.rename(columns={'index': 'Datetime'}, inplace=True)
43
+ # Calculate On-Balance Volume (OBV)
44
+ data['OBV'] = (np.sign(data['Close'].diff()) * data['Volume']).fillna(0).cumsum()
45
+ # Calculate Relative Strength Index (RSI)
46
+ delta = data['Close'].diff()
47
+ gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
48
+ loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
49
+ rs = gain / loss
50
+ data['RSI'] = 100 - (100 / (1 + rs))
51
+ # Calculate Exponential Moving Average (EMA)
52
+ data['EMA'] = data['Close'].ewm(span=20, adjust=False).mean()
53
+ # Calculate Simple Moving Average (SMA)
54
+ data['SMA'] = data['Close'].rolling(window=20).mean()
55
+
56
+ st.write(f"Data for {symbol} fetched successfully with OBV, RSI, EMA, and SMA included.")
57
+ st.write(data)
58
+ else:
59
+ st.error(f"No data available for {symbol}. Please check the symbol or try a different date range.")
60
+ except Exception as e:
61
+ st.error(f"Error fetching data for {symbol}: {e}")
62
+
63
+ # Stock List
64
+ stock_list = [
65
+ "RELIANCE.NS", "TCS.NS", "INFY.NS", "HDFCBANK.NS", "ICICIBANK.NS",
66
+ "KOTAKBANK.NS", "SBIN.NS", "LT.NS", "HINDUNILVR.NS", "BHARTIARTL.NS"
67
+ ]
68
+
69
+ # Streamlit app layout
70
+ st.title("Share Market Data")
71
+ symbol = st.selectbox("Select Stock Symbol", options=stock_list)
72
+ interval = st.selectbox("Select Data Interval", options=["1m", "2m", "5m", "15m", "30m", "60m", "90m", "1h", "1d", "5d", "1wk", "1mo", "3mo"])
73
+
74
+ # Allow user to select a start date
75
+ start_date = st.date_input("Select Start Date", pd.to_datetime('2023-01-01'))
76
+ end_date = pd.to_datetime('today').strftime('%Y-%m-%d')
77
+
78
+ valid_intervals = {
79
+ "1m": 8, # 1-minute data is available for up to 8 days
80
+ "2m": 60, # 2-minute data is available for up to 60 days
81
+ "5m": 60, # 5-minute data is available for up to 60 days
82
+ "15m": 60, # 15-minute data is available for up to 60 days
83
+ "30m": 60, # 30-minute data is available for up to 60 days
84
+ "60m": 730, # 60-minute data is available for up to 730 days (2 years)
85
+ "90m": 730, # 90-minute data is available for up to 730 days (2 years)
86
+ "1h": 730, # 1-hour data is available for up to 730 days (2 years)
87
+ "1d": 10000, # Daily data is available for up to maximum available
88
+ "5d": 10000, # 5-day data is available for up to maximum available
89
+ "1wk": 10000,# Weekly data is available for up to maximum available
90
+ "1mo": 10000,# Monthly data is available for up to maximum available
91
+ "3mo": 10000 # Quarterly data is available for up to maximum available
92
+ }
93
+
94
+ max_days = valid_intervals[interval]
95
+ end_date_pd = pd.to_datetime('today')
96
+ max_start_date = end_date_pd - pd.to_timedelta(max_days, unit='d')
97
+
98
+ # Adjust the start date if it exceeds the limit
99
+ if pd.to_datetime(start_date) < max_start_date:
100
+ st.warning(f"The selected start date exceeds the maximum allowed range for {interval} interval. Adjusting start date to {max_start_date.strftime('%Y-%m-%d')}")
101
+ start_date = max_start_date
102
+
103
+ fetch_data = st.button("Fetch and Display Data")
104
+
105
+ if fetch_data and symbol:
106
+ fetch_stock_data(symbol, start_date.strftime('%Y-%m-%d'), end_date, interval)