Update app.py
Browse files
app.py
CHANGED
@@ -4,23 +4,29 @@ import numpy as np
|
|
4 |
import plotly.graph_objects as go
|
5 |
import streamlit as st
|
6 |
import altair as alt
|
7 |
-
import matplotlib.pyplot as plt
|
8 |
-
import seaborn as sns
|
9 |
from bs4 import BeautifulSoup
|
10 |
import requests
|
11 |
from datetime import datetime
|
12 |
from rich import print
|
13 |
-
import jsonschema
|
14 |
|
15 |
# Step 1: Define a function to fetch real-time market data up to the current date
|
16 |
def fetch_data(ticker_symbol):
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
21 |
|
22 |
# Step 2: Define a function to calculate indicators
|
23 |
def calculate_indicators(df, lengthEMA=3, lengthRSI=14, momentumLength=3, trendLength=50):
|
|
|
|
|
|
|
24 |
# Calculate Moving Averages
|
25 |
df['MA20'] = df['Close'].rolling(window=20).mean()
|
26 |
df['MA50'] = df['Close'].rolling(window=50).mean()
|
@@ -60,97 +66,98 @@ st.title("Advanced Indian Share Market Analysis")
|
|
60 |
st.sidebar.header("Select Stock Ticker")
|
61 |
|
62 |
# Add a stock selector input box
|
63 |
-
ticker_symbol = st.sidebar.text_input("Enter Stock Ticker (e.g., RELIANCE.NS
|
64 |
|
65 |
# Step 4: Fetch Data and Calculate Indicators
|
66 |
try:
|
67 |
nifty_data = fetch_data(ticker_symbol)
|
68 |
nifty_data = calculate_indicators(nifty_data)
|
69 |
|
70 |
-
# Step 5: Display Stock Data
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
|
87 |
-
|
88 |
-
|
89 |
-
|
90 |
-
|
91 |
-
|
92 |
-
|
93 |
-
|
94 |
-
|
95 |
-
|
96 |
-
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
-
|
102 |
-
|
103 |
-
|
104 |
-
|
105 |
-
|
106 |
-
|
107 |
-
|
108 |
-
|
109 |
-
|
110 |
-
|
111 |
-
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
122 |
-
|
123 |
-
|
124 |
-
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
|
131 |
-
|
132 |
-
|
133 |
-
|
134 |
-
|
135 |
-
|
136 |
-
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
-
|
142 |
-
|
143 |
-
|
144 |
-
|
145 |
-
|
146 |
-
|
147 |
-
|
148 |
-
|
149 |
-
|
150 |
-
|
151 |
-
|
152 |
-
|
153 |
-
|
|
|
154 |
|
155 |
except Exception as e:
|
156 |
st.error(f"An error occurred: {str(e)}")
|
|
|
4 |
import plotly.graph_objects as go
|
5 |
import streamlit as st
|
6 |
import altair as alt
|
|
|
|
|
7 |
from bs4 import BeautifulSoup
|
8 |
import requests
|
9 |
from datetime import datetime
|
10 |
from rich import print
|
|
|
11 |
|
12 |
# Step 1: Define a function to fetch real-time market data up to the current date
|
13 |
def fetch_data(ticker_symbol):
|
14 |
+
try:
|
15 |
+
ticker = yf.Ticker(ticker_symbol)
|
16 |
+
end_date = datetime.now().strftime('%Y-%m-%d') # Get the current date
|
17 |
+
data = ticker.history(start="2023-01-01", end=end_date) # Fetches data from the start of this year to the current date
|
18 |
+
if data.empty:
|
19 |
+
raise ValueError("No data found for the given ticker. Please check the ticker symbol.")
|
20 |
+
return data
|
21 |
+
except Exception as e:
|
22 |
+
st.error(f"An error occurred while fetching data: {str(e)}")
|
23 |
+
return pd.DataFrame()
|
24 |
|
25 |
# Step 2: Define a function to calculate indicators
|
26 |
def calculate_indicators(df, lengthEMA=3, lengthRSI=14, momentumLength=3, trendLength=50):
|
27 |
+
if df.empty:
|
28 |
+
return df
|
29 |
+
|
30 |
# Calculate Moving Averages
|
31 |
df['MA20'] = df['Close'].rolling(window=20).mean()
|
32 |
df['MA50'] = df['Close'].rolling(window=50).mean()
|
|
|
66 |
st.sidebar.header("Select Stock Ticker")
|
67 |
|
68 |
# Add a stock selector input box
|
69 |
+
ticker_symbol = st.sidebar.text_input("Enter Stock Ticker (e.g., RELIANCE.NS for NSE or TCS.BO for BSE)", "^NSEI")
|
70 |
|
71 |
# Step 4: Fetch Data and Calculate Indicators
|
72 |
try:
|
73 |
nifty_data = fetch_data(ticker_symbol)
|
74 |
nifty_data = calculate_indicators(nifty_data)
|
75 |
|
76 |
+
# Step 5: Display Stock Data if available
|
77 |
+
if not nifty_data.empty:
|
78 |
+
st.subheader(f"Data Overview for {ticker_symbol}")
|
79 |
+
st.write(nifty_data.tail())
|
80 |
+
|
81 |
+
# Step 6: Interactive Visualization Using Plotly
|
82 |
+
st.subheader(f"Interactive Buy and Sell Signals for {ticker_symbol}")
|
83 |
+
fig = go.Figure()
|
84 |
+
|
85 |
+
# Add Close Price line
|
86 |
+
fig.add_trace(go.Scatter(
|
87 |
+
x=nifty_data.index,
|
88 |
+
y=nifty_data['Close'],
|
89 |
+
mode='lines',
|
90 |
+
name='Close Price',
|
91 |
+
line=dict(color='blue')
|
92 |
+
))
|
93 |
+
|
94 |
+
# Add Trend SMA line
|
95 |
+
fig.add_trace(go.Scatter(
|
96 |
+
x=nifty_data.index,
|
97 |
+
y=nifty_data['TrendSMA'],
|
98 |
+
mode='lines',
|
99 |
+
name='Trend SMA',
|
100 |
+
line=dict(color='gray')
|
101 |
+
))
|
102 |
+
|
103 |
+
# Plot Buy Signals
|
104 |
+
buy_signals = nifty_data[nifty_data['BuySignal']]
|
105 |
+
fig.add_trace(go.Scatter(
|
106 |
+
x=buy_signals.index,
|
107 |
+
y=buy_signals['Close'],
|
108 |
+
mode='markers',
|
109 |
+
name='Buy Signal',
|
110 |
+
marker=dict(symbol='triangle-up', color='green', size=10)
|
111 |
+
))
|
112 |
+
|
113 |
+
# Plot Sell Signals
|
114 |
+
sell_signals = nifty_data[nifty_data['SellSignal']]
|
115 |
+
fig.add_trace(go.Scatter(
|
116 |
+
x=sell_signals.index,
|
117 |
+
y=sell_signals['Close'],
|
118 |
+
mode='markers',
|
119 |
+
name='Sell Signal',
|
120 |
+
marker=dict(symbol='triangle-down', color='red', size=10)
|
121 |
+
))
|
122 |
+
|
123 |
+
# Update layout for better readability
|
124 |
+
fig.update_layout(
|
125 |
+
title=f"Buy and Sell Signals with Trend Filter for {ticker_symbol}",
|
126 |
+
xaxis_title="Date",
|
127 |
+
yaxis_title="Close Price",
|
128 |
+
legend_title="Legend",
|
129 |
+
template="plotly_dark"
|
130 |
+
)
|
131 |
+
|
132 |
+
st.plotly_chart(fig)
|
133 |
+
|
134 |
+
# Step 7: Altair Chart for Moving Averages
|
135 |
+
st.subheader(f"Moving Averages for {ticker_symbol}")
|
136 |
+
alt_chart = alt.Chart(nifty_data.reset_index()).mark_line().encode(
|
137 |
+
x='Date:T',
|
138 |
+
y=alt.Y('MA20:Q', title='Moving Average (20-day)'),
|
139 |
+
color=alt.value('orange')
|
140 |
+
).properties(title="20-Day Moving Average")
|
141 |
+
st.altair_chart(alt_chart, use_container_width=True)
|
142 |
+
|
143 |
+
# Step 8: Market News Integration Using BeautifulSoup
|
144 |
+
st.sidebar.header("Latest Market News")
|
145 |
+
news_url = 'https://www.moneycontrol.com/news/'
|
146 |
+
response = requests.get(news_url)
|
147 |
+
soup = BeautifulSoup(response.content, 'html.parser')
|
148 |
+
|
149 |
+
headlines = [headline.text for headline in soup.find_all('h2')[:5]]
|
150 |
+
st.sidebar.subheader("Top 5 News Headlines")
|
151 |
+
for idx, headline in enumerate(headlines, 1):
|
152 |
+
st.sidebar.write(f"{idx}. {headline}")
|
153 |
+
|
154 |
+
# Step 9: Alerts Using Rich Library
|
155 |
+
st.sidebar.subheader("Set Alerts:")
|
156 |
+
alert_type = st.sidebar.selectbox('Alert Type', ['Price', 'RSI'])
|
157 |
+
alert_value = st.sidebar.number_input('Enter Alert Value')
|
158 |
+
|
159 |
+
if alert_value:
|
160 |
+
print(f"[bold cyan]Alert Set for {alert_type} at Value:[/bold cyan] {alert_value}")
|
161 |
|
162 |
except Exception as e:
|
163 |
st.error(f"An error occurred: {str(e)}")
|