Spaces:
Running
Running
# Required imports | |
import yfinance as yf | |
import pandas as pd | |
import numpy as np | |
from scipy.signal import find_peaks | |
import plotly.graph_objects as go | |
import plotly.express as px | |
import streamlit as st | |
from plotly.subplots import make_subplots | |
# Define functions for technical indicators | |
def compute_macd(data, slow=26, fast=12, smooth=9): | |
exp1 = data['Close'].ewm(span=fast, adjust=False).mean() | |
exp2 = data['Close'].ewm(span=slow, adjust=False).mean() | |
macd = exp1 - exp2 | |
signal = macd.ewm(span=smooth, adjust=False).mean() | |
return macd, signal | |
def compute_rsi(data, window=14): | |
delta = data['Close'].diff() | |
gain = (delta.where(delta > 0, 0)).rolling(window=window).mean() | |
loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean() | |
rs = gain / loss | |
return 100 - (100 / (1 + rs)) | |
def compute_bollinger(data, window=20, num_std=2): | |
rolling_mean = data['Close'].rolling(window=window).mean() | |
rolling_std = data['Close'].rolling(window=window).std() | |
upper_band = rolling_mean + (rolling_std * num_std) | |
lower_band = rolling_mean - (rolling_std * num_std) | |
return upper_band, lower_band | |
# Streamlit UI - Introduction and How to Use the App | |
st.title("Advanced Stock Analysis Tool") | |
st.markdown(""" | |
Welcome to the advanced stock analysis application designed for both beginner and seasoned traders. This version includes RSI, MACD, Bollinger Bands, and volume indicators, along with the original features. | |
**Features**: | |
- View stock price movements and indicators over time. | |
- Analyze technical indicators such as RSI, MACD, and Bollinger Bands. | |
- Identify and visualize MA crossovers which are significant for trading strategies. | |
- Download charts for offline analysis. | |
**Instructions**: | |
1. Enter a stock symbol in the sidebar. | |
2. Select your desired time period. | |
3. Explore the indicators and make informed trading decisions. | |
""") | |
# User Inputs | |
sidebar = st.sidebar | |
symbol = sidebar.text_input("Enter stock symbol", "AAPL") | |
period = sidebar.selectbox("Select period", ["1mo", "3mo", "6mo", "1y", "2y", "5y", "10y", "ytd", "max"]) | |
# Fetch stock data | |
data = yf.download(symbol, period=period) | |
# Calculate technical indicators | |
data['MA20'] = data['Close'].rolling(window=20).mean() | |
data['MA50'] = data['Close'].rolling(window=50).mean() | |
data['MA200'] = data['Close'].rolling(window=200).mean() | |
data['RSI'] = compute_rsi(data) | |
data['MACD'], data['Signal'] = compute_macd(data) | |
data['Upper_Band'], data['Lower_Band'] = compute_bollinger(data) | |
# Detect MA crossovers | |
cross_above = (data['MA20'].shift(14) < data['MA50'].shift(14)) & (data['MA20'] > data['MA50']) | |
cross_below = (data['MA20'].shift(14) > data['MA50'].shift(14)) & (data['MA20'] < data['MA50']) | |
# Plot setup | |
fig = make_subplots(rows=3, cols=1, shared_xaxes=True, vertical_spacing=0.02, | |
subplot_titles=('Stock Price and Moving Averages', 'Volume and Bollinger Bands', 'RSI and MACD')) | |
# Add traces for price and moving averages | |
fig.add_trace(go.Scatter(x=data.index, y=data['Close'], name='Close Price'), row=1, col=1) | |
fig.add_trace(go.Scatter(x=data.index, y=data['MA20'], name='20-Period MA', line=dict(color='green')), row=1, col=1) | |
fig.add_trace(go.Scatter(x=data.index, y=data['MA50'], name='50-Period MA', line=dict(color='blue')), row=1, col=1) | |
fig.add_trace(go.Scatter(x=data.index, y=data['MA200'], name='200-Period MA', line=dict(color='red')), row=1, col=1) | |
fig.add_trace(go.Scatter(x=data.index[cross_above], y=data['MA20'][cross_above], mode='markers', marker=dict(color='green', size=10), name='Golden Cross'), row=1, col=1) | |
fig.add_trace(go.Scatter(x=data.index[cross_below], y=data['MA20'][cross_below], mode='markers', marker=dict(color='red', size=10), name='Death Cross'), row=1, col=1) | |
# Add traces for Bollinger Bands and volume | |
fig.add_trace(go.Bar(x=data.index, y=data['Volume'], name='Volume'), row=2, col=1) | |
fig.add_trace(go.Scatter(x=data.index, y=data['Upper_Band'], name='Upper Bollinger Band', line=dict(color='purple')), row=2, col=1) | |
fig.add_trace(go.Scatter(x=data.index, y=data['Lower_Band'], name='Lower Bollinger Band', line=dict(color='purple')), row=2, col=1) | |
# Add traces for RSI and MACD | |
fig.add_trace(go.Scatter(x=data.index, y=data['RSI'], name='RSI', line=dict(color='orange')), row=3, col=1) | |
fig.add_trace(go.Scatter(x=data.index, y=data['MACD'], name='MACD', line=dict(color='pink')), row=3, col=1) | |
fig.add_trace(go.Scatter(x=data.index, y=data['Signal'], name='MACD Signal', line=dict(color='cyan')), row=3, col=1) | |
# Layout adjustments | |
fig.update_layout(height=1200, width=800, showlegend=True) | |
fig.update_yaxes(title_text="Price", row=1, col=1) | |
fig.update_yaxes(title_text="Volume", row=2, col=1) | |
fig.update_yaxes(title_text="Index Value", row=3, col=1) | |
# Display the chart with a download button | |
st.plotly_chart(fig) | |
fig.write_html("stock_analysis_chart.html") | |
st.markdown("[Download Chart](stock_analysis_chart.html)") | |
# The code provides a detailed analysis and visual representation of the stock data with added technical indicators, fulfilling the advanced requirements of both beginner and seasoned traders. | |