riteshcp commited on
Commit
d833f1d
·
verified ·
1 Parent(s): b90b365

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +66 -85
app.py CHANGED
@@ -1,99 +1,80 @@
1
- # app.py
2
- # Import necessary libraries
3
  import yfinance as yf
4
  import pandas as pd
5
  import matplotlib.pyplot as plt
6
  import seaborn as sns
7
  import streamlit as st
8
- from datetime import date
9
 
10
- # Set up environment and install required libraries (already installed in this case)
11
- # !pip install yfinance pandas matplotlib seaborn streamlit
12
-
13
- # Fetch real-time market data for NIFTY 50 (^NSEI) and other indices
14
- nifty_50 = yf.Ticker('^NSEI')
15
- data = nifty_50.history(period='1y')
16
-
17
- # Store the data in a pandas DataFrame for further analysis
18
- df = pd.DataFrame(data)
19
-
20
- # Calculate technical indicators using pandas
21
- df['MA20'] = df['Close'].rolling(window=20).mean()
22
- df['MA50'] = df['Close'].rolling(window=50).mean()
23
-
24
- df['RSI'] = 100 - (100 / (1 + df['Close'].diff().ewm(span=14, adjust=False).mean()))
25
-
26
- macd_line = df['Close'].ewm(span=12, adjust=False).mean()
27
- signal_line = macd_line.ewm(span=26, adjust=False).mean()
28
-
29
- df['MACD'] = macd_line - signal_line
30
-
31
- # Calculate On-Balance Volume (OBV)
32
- df['OBV'] = df['Volume']
33
-
34
- # Visualize data using matplotlib
35
- plt.figure(figsize=(12,6))
36
- sns.lineplot(x=df.index, y=df['Close'], label='Close Price')
37
- sns.lineplot(x=df.index, y=df['MA20'], label='MA20')
38
- sns.lineplot(x=df.index, y=df['MA50'], label='MA50')
39
-
40
- plt.title('Moving Averages and Close Prices')
41
- plt.xlabel('Date')
42
- plt.ylabel('Price')
43
- plt.legend()
44
- plt.show()
45
-
46
- # Visualize RSI with thresholds for overbought and oversold conditions
47
- plt.figure(figsize=(12,6))
48
- sns.lineplot(x=df.index, y=df['RSI'], label='RSI')
49
-
50
- if df['RSI'].max() > 70:
51
- plt.axhline(y=70, color='r', linestyle='--')
52
- elif df['RSI'].min() < 30:
53
- plt.axhline(y=30, color='g', linestyle='--')
54
-
55
- plt.title('Relative Strength Index (RSI)')
56
- plt.xlabel('Date')
57
- plt.ylabel('RSI Value')
58
- plt.legend()
59
- plt.show()
60
-
61
- # Create an interactive dashboard using Streamlit
62
- st.title('NIFTY 50 Data Overview')
63
-
64
- st.write(df.head())
65
-
66
- st.subheader('Close Price')
67
- fig, ax = plt.subplots(figsize=(12,6))
68
- sns.lineplot(x=df.index, y=df['Close'])
69
  st.pyplot(fig)
70
 
71
- st.subheader('Moving Averages and RSI')
72
- fig, ax = plt.subplots(figsize=(12,6))
73
- sns.lineplot(x=df.index, y=df['MA20'], label='MA20')
74
- sns.lineplot(x=df.index, y=df['MA50'], label='MA50')
75
- sns.lineplot(x=df.index, y=df['RSI'], label='RSI')
76
-
77
- if df['RSI'].max() > 70:
78
- plt.axhline(y=70, color='r', linestyle='--')
79
- elif df['RSI'].min() < 30:
80
- plt.axhline(y=30, color='g', linestyle='--')
81
-
82
- plt.title('Moving Averages and RSI')
83
- plt.xlabel('Date')
84
- plt.ylabel('Price/Value')
85
  plt.legend()
 
86
  st.pyplot(fig)
87
 
88
- # Allow users to interact with the data
89
- st.subheader('Select Timeframe:')
90
  timeframes = ['1d', '5d', '1mo', '3mo', '6mo', '1y', '2y', '5y', '10y', 'ytd', 'max']
91
- selected_timeframe = st.selectbox('', timeframes)
92
 
93
- st.subheader('Set Alerts:')
94
- alert_type = st.selectbox('', ['Price', 'RSI'])
95
- alert_value = st.number_input('Enter value')
96
 
97
- # Run the Streamlit app
98
- if __name__ == '__main__':
99
- st.run()
 
 
 
1
  import yfinance as yf
2
  import pandas as pd
3
  import matplotlib.pyplot as plt
4
  import seaborn as sns
5
  import streamlit as st
 
6
 
7
+ # Step 1: Define a function to fetch real-time market data
8
+ def fetch_data(ticker_symbol):
9
+ ticker = yf.Ticker(ticker_symbol)
10
+ data = ticker.history(period="1y") # Fetches 1 year of historical data
11
+ return data
12
+
13
+ # Step 2: Define a function to calculate technical indicators
14
+ def calculate_indicators(df):
15
+ # Calculate Moving Averages
16
+ df['MA20'] = df['Close'].rolling(window=20).mean()
17
+ df['MA50'] = df['Close'].rolling(window=50).mean()
18
+
19
+ # Calculate RSI
20
+ delta = df['Close'].diff(1)
21
+ gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
22
+ loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
23
+ rs = gain / loss
24
+ df['RSI'] = 100 - (100 / (1 + rs))
25
+
26
+ # Calculate MACD
27
+ df['EMA12'] = df['Close'].ewm(span=12, adjust=False).mean()
28
+ df['EMA26'] = df['Close'].ewm(span=26, adjust=False).mean()
29
+ df['MACD'] = df['EMA12'] - df['EMA26']
30
+ df['Signal'] = df['MACD'].ewm(span=9, adjust=False).mean()
31
+
32
+ # Calculate OBV
33
+ df['OBV'] = (df['Volume'] * ((df['Close'] - df['Close'].shift(1)) > 0).astype(int) -
34
+ df['Volume'] * ((df['Close'] - df['Close'].shift(1)) < 0).astype(int)).cumsum()
35
+
36
+ return df
37
+
38
+ # Step 3: Streamlit UI Setup for Stock Selection
39
+ st.title("Indian Share Market Analysis")
40
+
41
+ # Add a stock selector input box
42
+ st.sidebar.header("Select Stock Ticker")
43
+ ticker_symbol = st.sidebar.text_input("Enter Stock Ticker (e.g., RELIANCE.NS, ^NSEI)", "^NSEI")
44
+
45
+ # Step 4: Fetch Data and Calculate Indicators
46
+ nifty_data = fetch_data(ticker_symbol)
47
+ nifty_data = calculate_indicators(nifty_data)
48
+
49
+ # Step 5: Display Stock Data
50
+ st.subheader(f"Data Overview for {ticker_symbol}")
51
+ st.write(nifty_data.head())
52
+
53
+ # Step 6: Visualizations
54
+ st.subheader(f"Close Price for {ticker_symbol}")
55
+ fig, ax = plt.subplots(figsize=(12, 6))
56
+ sns.lineplot(x=nifty_data.index, y=nifty_data['Close'])
 
 
 
 
 
 
 
 
 
57
  st.pyplot(fig)
58
 
59
+ st.subheader(f"Moving Averages and RSI for {ticker_symbol}")
60
+ fig, ax = plt.subplots(figsize=(12, 6))
61
+ sns.lineplot(x=nifty_data.index, y=nifty_data['MA20'], label='MA20')
62
+ sns.lineplot(x=nifty_data.index, y=nifty_data['MA50'], label='MA50')
63
+ sns.lineplot(x=nifty_data.index, y=nifty_data['RSI'], label='RSI')
64
+ plt.axhline(y=70, color='red', linestyle='--', label='Overbought (70)')
65
+ plt.axhline(y=30, color='green', linestyle='--', label='Oversold (30)')
 
 
 
 
 
 
 
66
  plt.legend()
67
+ plt.title("Moving Averages and RSI")
68
  st.pyplot(fig)
69
 
70
+ # Step 7: Interactive Timeframe Selection and Alerts
71
+ st.sidebar.subheader("Select Timeframe:")
72
  timeframes = ['1d', '5d', '1mo', '3mo', '6mo', '1y', '2y', '5y', '10y', 'ytd', 'max']
73
+ selected_timeframe = st.sidebar.selectbox('Timeframe', timeframes)
74
 
75
+ st.sidebar.subheader("Set Alerts:")
76
+ alert_type = st.sidebar.selectbox('Alert Type', ['Price', 'RSI'])
77
+ alert_value = st.sidebar.number_input('Enter Alert Value')
78
 
79
+ # Step 8: Run the Streamlit App (Note: Do not use st.run())
80
+ # Save as `app.py` and run it using `streamlit run app.py`