Update app.py
Browse files515 unmodified lines5165175185195205219 unmodified lines5315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336348 unmodified lines643644645646647648649650651652653654655656657658659660661662515 unmodified lineselse:st.error("Failed to fetch stock data. Please try again.")def explore_data():st.header("Explore Stock Data")9 unmodified linesif st.button("Explore Data"):with st.spinner("Fetching and analyzing data..."):data = yf.download(ticker, period=period)if data is not None and not data.empty:st.subheader(f"{company_name} Stock Data")# Create tabs for different visualizationstab1, tab2, tab3, tab4, tab5 = st.tabs(["Price History", "OHLC", "Technical Indicators", "Volume & Turnover", "Statistics"])with tab1:# Stock Price Historyfig = go.Figure()fig.add_trace(go.Scatter(x=data.index, y=data['Open'], mode='lines', name='Open'))fig.add_trace(go.Scatter(x=data.index, y=data['High'], mode='lines', name='High'))fig.add_trace(go.Scatter(x=data.index, y=data['Low'], mode='lines', name='Low'))fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close'))# Add rolling mean and standard deviationdata['Rolling_Mean'] = data['Close'].rolling(window=20).mean()data['Rolling_Std'] = data['Close'].rolling(window=20).std()fig.add_trace(go.Scatter(x=data.index, y=data['Rolling_Mean'], mode='lines', name='20-day Rolling Mean', line=dict(dash='dash')))fig.add_trace(go.Scatter(x=data.index, y=data['Rolling_Std'], mode='lines', name='20-day Rolling Std', line=dict(dash='dot')))fig.update_layout(title=f"{company_name} Stock Price History",xaxis_title="Date",yaxis_title="Price",hovermode="x unified",template="plotly_dark")st.plotly_chart(fig, use_container_width=True)with tab2:# OHLC Chartohlc_fig = go.Figure(data=[go.Candlestick(x=data.index,open=data['Open'],high=data['High'],low=data['Low'],close=data['Close'])])ohlc_fig.update_layout(title=f"{company_name} OHLC Chart",xaxis_title="Date",yaxis_title="Price",template="plotly_dark",xaxis_rangeslider_visible=False)st.plotly_chart(ohlc_fig, use_container_width=True)with tab3:# Technical Indicatorsdata['SMA_20'] = SMAIndicator(close=data['Close'], window=20).sma_indicator()data['EMA_20'] = EMAIndicator(close=data['Close'], window=20).ema_indicator()bb = BollingerBands(close=data['Close'], window=20, window_dev=2)data['BB_High'] = bb.bollinger_hband()data['BB_Low'] = bb.bollinger_lband()data['RSI'] = RSIIndicator(close=data['Close']).rsi()fig = make_subplots(rows=2, cols=1, shared_xaxes=True,vertical_spacing=0.03,subplot_titles=("Price and Indicators", "RSI"),row_heights=[0.7, 0.3])fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close'), row=1, col=1)fig.add_trace(go.Scatter(x=data.index, y=data['SMA_20'], mode='lines', name='SMA 20'), row=1, col=1)fig.add_trace(go.Scatter(x=data.index, y=data['EMA_20'], mode='lines', name='EMA 20'), row=1, col=1)fig.add_trace(go.Scatter(x=data.index, y=data['BB_High'], mode='lines', name='BB High'), row=1, col=1)fig.add_trace(go.Scatter(x=data.index, y=data['BB_Low'], mode='lines', name='BB Low'), row=1, col=1)fig.add_trace(go.Scatter(x=data.index, y=data['RSI'], mode='lines', name='RSI'), row=2, col=1)fig.add_hline(y=70, line_dash="dash", line_color="red", row=2, col=1)fig.add_hline(y=30, line_dash="dash", line_color="green", row=2, col=1)fig.update_layout(height=800, title_text=f"{company_name} Technical Indicators",hovermode="x unified", template="plotly_dark")fig.update_xaxes(rangeslider_visible=False, row=2, col=1)fig.update_yaxes(title_text="Price", row=1, col=1)fig.update_yaxes(title_text="RSI", row=2, col=1)st.plotly_chart(fig, use_container_width=True)with tab4:# Volume and Turnoverfig = make_subplots(rows=2, cols=1, shared_xaxes=True,vertical_spacing=0.03,subplot_titles=("Volume", "Turnover (if available)"),row_heights=[0.5, 0.5])fig.add_trace(go.Bar(x=data.index, y=data['Volume'], name='Volume'), row=1, col=1)if 'Turnover' in data.columns:fig.add_trace(go.Bar(x=data.index, y=data['Turnover'], name='Turnover'), row=2, col=1)else:fig.add_annotation(text="Turnover data not available", xref="paper", yref="paper", x=0.5, y=0.25, showarrow=False)fig.update_layout(height=600, title_text=f"{company_name} Volume and Turnover",hovermode="x unified", template="plotly_dark")fig.update_xaxes(rangeslider_visible=False, row=2, col=1)fig.update_yaxes(title_text="Volume", row=1, col=1)fig.update_yaxes(title_text="Turnover", row=2, col=1)st.plotly_chart(fig, use_container_width=True)with tab5:# Display key statisticsst.subheader("Key Statistics")col1, col2, col3 = st.columns(3)8 unmodified linesst.metric("Avg Daily Return", f"{returns.mean():.2f}%")st.metric("Return Volatility", f"{returns.std():.2f}%")# Correlation Heatmapcorrelation = data[['Open', 'High', 'Low', 'Close', 'Volume']].corr()heatmap_fig = px.imshow(correlation, text_auto=True, aspect="auto", color_continuous_scale='Viridis')heatmap_fig.update_layout(title="Correlation Heatmap", template="plotly_dark")st.plotly_chart(heatmap_fig, use_container_width=True)# Display newsst.subheader("Latest News")news = fetch_news(company_name)for item in news:st.markdown(f"[{item['title']}]({item['link']}) ({item['pubDate']})")else:st.error("Failed to fetch data. Please try again.")if __name__ == "__main__":main()515 unmodified lines5165175185195205215225235245255265275285295305315325335345359 unmodified lines5455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467478 unmodified lines756757758759760761762763764765515 unmodified lineselse:st.error("Failed to fetch stock data. Please try again.")def calculate_bollinger_bands(data, window=20, num_std=2):rolling_mean = data.rolling(window=window).mean()rolling_std = data.rolling(window=window).std()upper_band = rolling_mean + (rolling_std * num_std)lower_band = rolling_mean - (rolling_std * num_std)return upper_band, lower_banddef calculate_rsi(data, window=14):delta = data.diff()gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()rs = gain / lossreturn 100 - (100 / (1 + rs))def explore_data():st.header("Explore Stock Data")9 unmodified linesif st.button("Explore Data"):with st.spinner("Fetching and analyzing data..."):try:data = yf.download(ticker, period=period)if data is not None and not data.empty:st.subheader(f"{company_name} Stock Data")# Create tabs for different visualizationstab1, tab2, tab3, tab4, tab5, tab6 = st.tabs(["Price History", "OHLC", "Technical Indicators","Volume Analysis", "Returns Distribution", "Moving Averages"])with tab1:st.markdown("""### Price HistoryThis chart shows the historical closing prices of the stock over time.**How to use**:- Use the slider at the bottom to zoom in on specific time periods.- Hover over the line to see exact prices at different dates.**How it helps**:- Identify long-term trends in the stock's price.- Spot key price levels and potential support/resistance areas.- Understand the overall price movement and volatility of the stock.""")fig = go.Figure()fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close'))fig.update_layout(title=f"{company_name} Stock Price History",xaxis_title="Date",yaxis_title="Price",hovermode="x unified",template="plotly_dark")st.plotly_chart(fig, use_container_width=True)with tab2:st.markdown("""### OHLC (Open-High-Low-Close) ChartThis candlestick chart shows the opening, high, low, and closing prices for each trading day.**How to use**:- Green candles indicate days where the closing price was higher than the opening price.- Red candles indicate days where the closing price was lower than the opening price.- The thin lines (wicks) show the high and low prices for the day.**How it helps**:- Identify daily price movements and volatility.- Spot potential reversal patterns or trends.- Understand the intraday price action of the stock.""")ohlc_fig = go.Figure(data=[go.Candlestick(x=data.index,open=data['Open'],high=data['High'],low=data['Low'],close=data['Close'])])ohlc_fig.update_layout(title=f"{company_name} OHLC Chart",xaxis_title="Date",yaxis_title="Price",template="plotly_dark",xaxis_rangeslider_visible=False)st.plotly_chart(ohlc_fig, use_container_width=True)with tab3:st.markdown("""### Technical IndicatorsThis chart displays various technical indicators alongside the stock price.**How to use**:- The top chart shows the stock price with SMA (Simple Moving Average), EMA (Exponential Moving Average), and Bollinger Bands.- The bottom chart shows the RSI (Relative Strength Index).**How it helps**:- Identify potential buy/sell signals using moving average crossovers.- Spot overbought or oversold conditions using RSI.- Understand price volatility using Bollinger Bands.- Combine multiple indicators for more robust trading decisions.""")data['SMA_20'] = data['Close'].rolling(window=20).mean()data['EMA_20'] = data['Close'].ewm(span=20, adjust=False).mean()data['Upper_BB'], data['Lower_BB'] = calculate_bollinger_bands(data['Close'])data['RSI'] = calculate_rsi(data['Close'])fig = make_subplots(rows=2, cols=1, shared_xaxes=True,vertical_spacing=0.03,subplot_titles=("Price and Indicators", "RSI"),row_heights=[0.7, 0.3])fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close'), row=1, col=1)fig.add_trace(go.Scatter(x=data.index, y=data['SMA_20'], mode='lines', name='SMA 20'), row=1, col=1)fig.add_trace(go.Scatter(x=data.index, y=data['EMA_20'], mode='lines', name='EMA 20'), row=1, col=1)fig.add_trace(go.Scatter(x=data.index, y=data['Upper_BB'], mode='lines', name='Upper BB'), row=1, col=1)fig.add_trace(go.Scatter(x=data.index, y=data['Lower_BB'], mode='lines', name='Lower BB'), row=1, col=1)fig.add_trace(go.Scatter(x=data.index, y=data['RSI'], mode='lines', name='RSI'), row=2, col=1)fig.add_hline(y=70, line_dash="dash", line_color="red", row=2, col=1)fig.add_hline(y=30, line_dash="dash", line_color="green", row=2, col=1)fig.update_layout(height=800, title_text=f"{company_name} Technical Indicators",hovermode="x unified", template="plotly_dark")fig.update_xaxes(rangeslider_visible=False, row=2, col=1)fig.update_yaxes(title_text="Price", row=1, col=1)fig.update_yaxes(title_text="RSI", row=2, col=1)st.plotly_chart(fig, use_container_width=True)with tab4:st.markdown("""### Volume AnalysisThis chart shows the trading volume alongside the stock price.**How to use**:- The top chart displays the daily trading volume.- The bottom chart shows the corresponding stock price.**How it helps**:- Identify periods of high and low trading activity.- Confirm price trends (higher volume often validates price movements).- Spot potential reversals (e.g., high volume at price extremes).- Understand the liquidity of the stock.""")fig = make_subplots(rows=2, cols=1, shared_xaxes=True,vertical_spacing=0.03,subplot_titles=("Volume", "Price"),row_heights=[0.7, 0.3])fig.add_trace(go.Bar(x=data.index, y=data['Volume'], name='Volume'), row=1, col=1)fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close Price'), row=2, col=1)fig.update_layout(height=600, title_text=f"{company_name} Volume Analysis",hovermode="x unified", template="plotly_dark")fig.update_xaxes(rangeslider_visible=False, row=2, col=1)fig.update_yaxes(title_text="Volume", row=1, col=1)fig.update_yaxes(title_text="Price", row=2, col=1)st.plotly_chart(fig, use_container_width=True)with tab5:st.markdown("""### Returns DistributionThis histogram shows the distribution of daily returns for the stock.**How to use**:- The x-axis represents the daily return percentages.- The y-axis shows the frequency of each return range.**How it helps**:- Understand the volatility and risk profile of the stock.- Identify the most common daily return ranges.- Spot any skewness or unusual patterns in returns.- Compare the stock's return distribution to a normal distribution for risk assessment.""")returns = data['Close'].pct_change().dropna()fig = go.Figure(data=[go.Histogram(x=returns, nbinsx=50)])fig.update_layout(title=f"{company_name} Returns Distribution",xaxis_title="Daily Returns",yaxis_title="Frequency",template="plotly_dark")st.plotly_chart(fig, use_container_width=True)with tab6:st.markdown("""### Moving AveragesThis chart shows the stock price along with 50-day and 200-day Simple Moving Averages (SMA).**How to use**:- The blue line represents the stock's closing price.- The orange line is the 50-day SMA.- The green line is the 200-day SMA.**How it helps**:- Identify long-term trends in the stock price.- Spot potential buy/sell signals when the price crosses above/below the moving averages.- Recognize "Golden Cross" (50-day crosses above 200-day) and "Death Cross" (50-day crosses below 200-day) signals.- Understand the overall momentum of the stock.""")data['SMA_50'] = data['Close'].rolling(window=50).mean()data['SMA_200'] = data['Close'].rolling(window=200).mean()fig = go.Figure()fig.add_trace(go.Scatter(x=data.index, y=data['Close'], mode='lines', name='Close'))fig.add_trace(go.Scatter(x=data.index, y=data['SMA_50'], mode='lines', name='50-day SMA'))fig.add_trace(go.Scatter(x=data.index, y=data['SMA_200'], mode='lines', name='200-day SMA'))fig.update_layout(title=f"{company_name} Moving Averages",xaxis_title="Date",yaxis_title="Price",template="plotly_dark",hovermode="x unified")st.plotly_chart(fig, use_container_width=True)# Display key statisticsst.subheader("Key Statistics")col1, col2, col3 = st.columns(3)8 unmodified linesst.metric("Avg Daily Return", f"{returns.mean():.2f}%")st.metric("Return Volatility", f"{returns.std():.2f}%")else:st.error("Failed to fetch data. Please try again.")except Exception as e:st.error(f"An error occurred: {str(e)}. Please try a different time period or check your internet connection.")if __name__ == "__main__":main()
app.py+209-106