TechyTrade / app.py
swayam-the-coder's picture
Update app.py
f481748 verified
raw
history blame contribute delete
No virus
12 kB
import streamlit as st
import yfinance as yf
import pandas as pd
from prophet import Prophet
import plotly.graph_objs as go
import google.generativeai as genai
import numpy as np
# Streamlit app details
st.set_page_config(page_title="TechyTrade", layout="wide")
# Custom CSS
st.markdown("""
<style>
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;700&display=swap');
body {
background-color: #f4f4f9;
color: #333;
font-family: 'Montserrat', sans-serif;
}
.sidebar .sidebar-content {
background-color: #2c3e50;
color: white;
}
h1, h2, h3 {
color: #2980b9;
}
.css-1v3fvcr {
color: #2980b9 !important;
}
.css-17eq0hr {
font-family: 'Montserrat', sans-serif !important;
}
.css-2trqyj {
font-family: 'Montserrat', sans-serif !important;
}
</style>
""", unsafe_allow_html=True)
# Sidebar
with st.sidebar:
st.title("๐Ÿ“Š TechyTrade")
ticker = st.text_input("Enter a stock ticker (e.g. AAPL) ๐Ÿท๏ธ", "AAPL")
period = st.selectbox("Enter a time frame โณ", ("1D", "5D", "1M", "6M", "YTD", "1Y", "5Y"), index=2)
forecast_period = st.slider("Select forecast period (days) ๐Ÿ”ฎ", min_value=1, max_value=365, value=30)
st.write("Select Technical Indicators:")
sma_checkbox = st.checkbox("Simple Moving Average (SMA)")
ema_checkbox = st.checkbox("Exponential Moving Average (EMA)")
rsi_checkbox = st.checkbox("Relative Strength Index (RSI)")
macd_checkbox = st.checkbox("Moving Average Convergence Divergence (MACD)")
bollinger_checkbox = st.checkbox("Bollinger Bands")
google_api_key = st.text_input("Enter your Google API Key ๐Ÿ”‘", type="password")
button = st.button("Submit ๐Ÿš€")
# Load generative model
@st.cache_resource
def load_model(api_key):
genai.configure(api_key=api_key)
return genai.GenerativeModel('gemini-1.5-flash')
# Function to generate reasons using the generative model
def generate_reasons(fig, stock_info, price_info, biz_metrics, api_key):
model = load_model(api_key)
prompt = f"Based on the following stock price graph description:\n\n{fig}\n\n and the tables:\n\n{stock_info}\n\n and\n\n{price_info}\n\n and\n\n{biz_metrics}\n\n and analyze the trends and give recommendations and insights."
response = model.generate_content(prompt)
return response.text
# Function to format large numbers
def format_value(value):
suffixes = ["", "K", "M", "B", "T"]
suffix_index = 0
while value >= 1000 and suffix_index < len(suffixes) - 1:
value /= 1000
suffix_index += 1
return f"${value:.1f}{suffixes[suffix_index]}"
# Technical Indicators Functions
def calculate_sma(data, window):
return data.rolling(window=window).mean()
def calculate_ema(data, window):
return data.ewm(span=window, adjust=False).mean()
def calculate_rsi(data, window):
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 / loss
return 100 - (100 / (1 + rs))
def calculate_macd(data, short_window=12, long_window=26, signal_window=9):
short_ema = calculate_ema(data, short_window)
long_ema = calculate_ema(data, long_window)
macd = short_ema - long_ema
signal = calculate_ema(macd, signal_window)
return macd, signal
def calculate_bollinger_bands(data, window):
sma = calculate_sma(data, window)
std = data.rolling(window=window).std()
upper_band = sma + (std * 2)
lower_band = sma - (std * 2)
return upper_band, lower_band
# If Submit button is clicked
if button:
if not ticker.strip():
st.error("Please provide a valid stock ticker.")
elif not google_api_key.strip():
st.error("Please provide a valid Google API Key.")
else:
try:
with st.spinner('Please wait...'):
# Retrieve stock data
stock = yf.Ticker(ticker)
info = stock.info
st.subheader(f"{ticker} - {info.get('longName', 'N/A')}")
# Plot historical stock price data
if period == "1D":
history = stock.history(period="1d", interval="1h")
elif period == "5D":
history = stock.history(period="5d", interval="1d")
elif period == "1M":
history = stock.history(period="1mo", interval="1d")
elif period == "6M":
history = stock.history(period="6mo", interval="1wk")
elif period == "YTD":
history = stock.history(period="ytd", interval="1mo")
elif period == "1Y":
history = stock.history(period="1y", interval="1mo")
elif period == "5Y":
history = stock.history(period="5y", interval="3mo")
# Create a plotly figure
fig = go.Figure()
fig.add_trace(go.Scatter(x=history.index, y=history['Close'], mode='lines', name='Close Price'))
# Add Technical Indicators
if sma_checkbox:
sma = calculate_sma(history['Close'], window=20)
fig.add_trace(go.Scatter(x=history.index, y=sma, mode='lines', name='SMA (20)'))
if ema_checkbox:
ema = calculate_ema(history['Close'], window=20)
fig.add_trace(go.Scatter(x=history.index, y=ema, mode='lines', name='EMA (20)'))
if rsi_checkbox:
rsi = calculate_rsi(history['Close'], window=14)
fig.add_trace(go.Scatter(x=history.index, y=rsi, mode='lines', name='RSI (14)', yaxis='y2'))
fig.update_layout(yaxis2=dict(title='RSI', overlaying='y', side='right'))
if macd_checkbox:
macd, signal = calculate_macd(history['Close'])
fig.add_trace(go.Scatter(x=history.index, y=macd, mode='lines', name='MACD'))
fig.add_trace(go.Scatter(x=history.index, y=signal, mode='lines', name='Signal Line'))
if bollinger_checkbox:
upper_band, lower_band = calculate_bollinger_bands(history['Close'], window=20)
fig.add_trace(go.Scatter(x=history.index, y=upper_band, mode='lines', name='Upper Band'))
fig.add_trace(go.Scatter(x=history.index, y=lower_band, mode='lines', name='Lower Band'))
fig.update_layout(
title=f"Historical Stock Prices for {ticker}",
xaxis_title="Date",
yaxis_title="Close Price",
hovermode="x unified"
)
st.plotly_chart(fig, use_container_width=True)
col1, col2, col3 = st.columns(3)
# Display stock information as a dataframe
country = info.get('country', 'N/A')
sector = info.get('sector', 'N/A')
industry = info.get('industry', 'N/A')
market_cap = info.get('marketCap', 'N/A')
ent_value = info.get('enterpriseValue', 'N/A')
employees = info.get('fullTimeEmployees', 'N/A')
stock_info = [
("Stock Info", "Value"),
("Country ", country),
("Sector ", sector),
("Industry ", industry),
("Market Cap ", format_value(market_cap)),
("Enterprise Value ", format_value(ent_value)),
("Employees ", employees)
]
df = pd.DataFrame(stock_info[1:], columns=stock_info[0])
col1.dataframe(df, width=400, hide_index=True)
# Display price information as a dataframe
current_price = info.get('currentPrice', 'N/A')
prev_close = info.get('previousClose', 'N/A')
day_high = info.get('dayHigh', 'N/A')
day_low = info.get('dayLow', 'N/A')
ft_week_high = info.get('fiftyTwoWeekHigh', 'N/A')
ft_week_low = info.get('fiftyTwoWeekLow', 'N/A')
price_info = [
("Price Info", "Value"),
("Current Price ", f"${current_price:.2f}"),
("Previous Close ", f"${prev_close:.2f}"),
("Day High ", f"${day_high:.2f}"),
("Day Low ", f"${day_low:.2f}"),
("52 Week High ", f"${ft_week_high:.2f}"),
("52 Week Low ", f"${ft_week_low:.2f}")
]
df = pd.DataFrame(price_info[1:], columns=price_info[0])
col2.dataframe(df, width=400, hide_index=True)
# Display business metrics as a dataframe
forward_eps = info.get('forwardEps', 'N/A')
forward_pe = info.get('forwardPE', 'N/A')
peg_ratio = info.get('pegRatio', 'N/A')
dividend_rate = info.get('dividendRate', 'N/A')
dividend_yield = info.get('dividendYield', 'N/A')
recommendation = info.get('recommendationKey', 'N/A')
biz_metrics = [
("Business Metrics", "Value"),
("EPS (FWD) ", f"{forward_eps:.2f}"),
("P/E (FWD) ", f"{forward_pe:.2f}"),
("PEG Ratio ", f"{peg_ratio:.2f}"),
("Div Rate (FWD) ", f"${dividend_rate:.2f}"),
("Div Yield (FWD) ", f"{dividend_yield * 100:.2f}%"),
("Recommendation ", recommendation.capitalize())
]
df = pd.DataFrame(biz_metrics[1:], columns=biz_metrics[0])
col3.dataframe(df, width=400, hide_index=True)
# Forecasting
st.subheader("Stock Price Forecast ๐Ÿ”ฎ")
df_forecast = history.reset_index()[['Date', 'Close']]
df_forecast['Date'] = pd.to_datetime(df_forecast['Date']).dt.tz_localize(None) # Remove timezone information
df_forecast.columns = ['ds', 'y']
m = Prophet(daily_seasonality=True)
m.fit(df_forecast)
future = m.make_future_dataframe(periods=forecast_period)
forecast = m.predict(future)
fig2 = go.Figure()
fig2.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat'], mode='lines', name='Forecast'))
fig2.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat_upper'], mode='lines', name='Upper Confidence Interval', line=dict(dash='dash')))
fig2.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat_lower'], mode='lines', name='Lower Confidence Interval', line=dict(dash='dash')))
fig2.update_layout(
title=f"Stock Price Forecast for {ticker}",
xaxis_title="Date",
yaxis_title="Predicted Close Price",
hovermode="x unified"
)
st.plotly_chart(fig2, use_container_width=True)
# Generate reasons based on forecast
graph_description = f"The stock price forecast graph for {ticker} shows the predicted close prices along with the upper and lower confidence intervals for the next {forecast_period} days."
reasons = generate_reasons(fig, stock_info, price_info, biz_metrics, google_api_key)
st.subheader("Investment Analysis")
st.write(reasons)
except Exception as e:
st.exception(f"An error occurred: {e}")