Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,15 +1,16 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
import yfinance as yf
|
| 3 |
import pandas as pd
|
|
|
|
| 4 |
from prophet import Prophet
|
| 5 |
import plotly.graph_objs as go
|
| 6 |
import google.generativeai as genai
|
| 7 |
-
import
|
|
|
|
| 8 |
|
| 9 |
# Streamlit app details
|
| 10 |
st.set_page_config(page_title="TechyTrade", layout="wide")
|
| 11 |
|
| 12 |
-
# Custom CSS
|
| 13 |
st.markdown("""
|
| 14 |
<style>
|
| 15 |
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;700&display=swap');
|
|
@@ -38,11 +39,11 @@ st.markdown("""
|
|
| 38 |
</style>
|
| 39 |
""", unsafe_allow_html=True)
|
| 40 |
|
| 41 |
-
# Sidebar
|
| 42 |
with st.sidebar:
|
| 43 |
st.title("📊 TechyTrade")
|
| 44 |
-
ticker = st.text_input("Enter a stock ticker (e.g. AAPL) 🏷️", "AAPL")
|
| 45 |
-
period = st.selectbox("Enter a time frame ⏳", ("
|
| 46 |
forecast_period = st.slider("Select forecast period (days) 🔮", min_value=1, max_value=365, value=30)
|
| 47 |
st.write("Select Technical Indicators:")
|
| 48 |
sma_checkbox = st.checkbox("Simple Moving Average (SMA)")
|
|
@@ -53,21 +54,27 @@ with st.sidebar:
|
|
| 53 |
google_api_key = st.text_input("Enter your Google API Key 🔑", type="password")
|
| 54 |
button = st.button("Submit 🚀")
|
| 55 |
|
| 56 |
-
# Load generative model
|
| 57 |
@st.cache_resource
|
| 58 |
def load_model(api_key):
|
| 59 |
genai.configure(api_key=api_key)
|
| 60 |
return genai.GenerativeModel('gemini-1.5-flash')
|
| 61 |
|
| 62 |
-
#
|
| 63 |
-
def generate_reasons(
|
| 64 |
model = load_model(api_key)
|
| 65 |
-
prompt = f"Based on the following stock price graph description:\n\n{
|
| 66 |
response = model.generate_content(prompt)
|
| 67 |
return response.text
|
| 68 |
|
| 69 |
-
#
|
| 70 |
def format_value(value):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
suffixes = ["", "K", "M", "B", "T"]
|
| 72 |
suffix_index = 0
|
| 73 |
while value >= 1000 and suffix_index < len(suffixes) - 1:
|
|
@@ -75,7 +82,7 @@ def format_value(value):
|
|
| 75 |
suffix_index += 1
|
| 76 |
return f"${value:.1f}{suffixes[suffix_index]}"
|
| 77 |
|
| 78 |
-
# Technical
|
| 79 |
def calculate_sma(data, window):
|
| 80 |
return data.rolling(window=window).mean()
|
| 81 |
|
|
@@ -103,38 +110,105 @@ def calculate_bollinger_bands(data, window):
|
|
| 103 |
lower_band = sma - (std * 2)
|
| 104 |
return upper_band, lower_band
|
| 105 |
|
| 106 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
if button:
|
| 108 |
-
if not ticker
|
| 109 |
st.error("Please provide a valid stock ticker.")
|
| 110 |
-
elif not
|
|
|
|
|
|
|
| 111 |
st.error("Please provide a valid Google API Key.")
|
| 112 |
else:
|
| 113 |
try:
|
| 114 |
-
with st.spinner(
|
| 115 |
-
#
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
# Plot historical stock price data
|
| 122 |
-
if period == "1D":
|
| 123 |
-
history = stock.history(period="1d", interval="1h")
|
| 124 |
-
elif period == "5D":
|
| 125 |
-
history = stock.history(period="5d", interval="1d")
|
| 126 |
-
elif period == "1M":
|
| 127 |
-
history = stock.history(period="1mo", interval="1d")
|
| 128 |
-
elif period == "6M":
|
| 129 |
-
history = stock.history(period="6mo", interval="1wk")
|
| 130 |
-
elif period == "YTD":
|
| 131 |
-
history = stock.history(period="ytd", interval="1mo")
|
| 132 |
-
elif period == "1Y":
|
| 133 |
-
history = stock.history(period="1y", interval="1mo")
|
| 134 |
-
elif period == "5Y":
|
| 135 |
-
history = stock.history(period="5y", interval="3mo")
|
| 136 |
-
|
| 137 |
-
# Create a plotly figure
|
| 138 |
fig = go.Figure()
|
| 139 |
fig.add_trace(go.Scatter(x=history.index, y=history['Close'], mode='lines', name='Close Price'))
|
| 140 |
|
|
@@ -142,21 +216,17 @@ if button:
|
|
| 142 |
if sma_checkbox:
|
| 143 |
sma = calculate_sma(history['Close'], window=20)
|
| 144 |
fig.add_trace(go.Scatter(x=history.index, y=sma, mode='lines', name='SMA (20)'))
|
| 145 |
-
|
| 146 |
if ema_checkbox:
|
| 147 |
ema = calculate_ema(history['Close'], window=20)
|
| 148 |
fig.add_trace(go.Scatter(x=history.index, y=ema, mode='lines', name='EMA (20)'))
|
| 149 |
-
|
| 150 |
if rsi_checkbox:
|
| 151 |
rsi = calculate_rsi(history['Close'], window=14)
|
| 152 |
fig.add_trace(go.Scatter(x=history.index, y=rsi, mode='lines', name='RSI (14)', yaxis='y2'))
|
| 153 |
fig.update_layout(yaxis2=dict(title='RSI', overlaying='y', side='right'))
|
| 154 |
-
|
| 155 |
if macd_checkbox:
|
| 156 |
macd, signal = calculate_macd(history['Close'])
|
| 157 |
fig.add_trace(go.Scatter(x=history.index, y=macd, mode='lines', name='MACD'))
|
| 158 |
fig.add_trace(go.Scatter(x=history.index, y=signal, mode='lines', name='Signal Line'))
|
| 159 |
-
|
| 160 |
if bollinger_checkbox:
|
| 161 |
upper_band, lower_band = calculate_bollinger_bands(history['Close'], window=20)
|
| 162 |
fig.add_trace(go.Scatter(x=history.index, y=upper_band, mode='lines', name='Upper Band'))
|
|
@@ -170,101 +240,79 @@ if button:
|
|
| 170 |
)
|
| 171 |
st.plotly_chart(fig, use_container_width=True)
|
| 172 |
|
| 173 |
-
|
|
|
|
| 174 |
|
| 175 |
-
|
| 176 |
-
country = info.get('country', 'N/A')
|
| 177 |
-
sector = info.get('sector', 'N/A')
|
| 178 |
-
industry = info.get('industry', 'N/A')
|
| 179 |
-
market_cap = info.get('marketCap', 'N/A')
|
| 180 |
-
ent_value = info.get('enterpriseValue', 'N/A')
|
| 181 |
-
employees = info.get('fullTimeEmployees', 'N/A')
|
| 182 |
|
|
|
|
| 183 |
stock_info = [
|
| 184 |
("Stock Info", "Value"),
|
| 185 |
-
("Country
|
| 186 |
-
("Sector
|
| 187 |
-
("Industry
|
| 188 |
-
("Market Cap
|
| 189 |
-
("Enterprise Value
|
| 190 |
-
("Employees
|
| 191 |
]
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
# Display price information as a dataframe
|
| 197 |
-
current_price = info.get('currentPrice', 'N/A')
|
| 198 |
-
prev_close = info.get('previousClose', 'N/A')
|
| 199 |
-
day_high = info.get('dayHigh', 'N/A')
|
| 200 |
-
day_low = info.get('dayLow', 'N/A')
|
| 201 |
-
ft_week_high = info.get('fiftyTwoWeekHigh', 'N/A')
|
| 202 |
-
ft_week_low = info.get('fiftyTwoWeekLow', 'N/A')
|
| 203 |
-
|
| 204 |
price_info = [
|
| 205 |
("Price Info", "Value"),
|
| 206 |
-
("Current Price
|
| 207 |
-
("Previous Close
|
| 208 |
-
("Day High
|
| 209 |
-
("Day Low
|
| 210 |
-
("52 Week High
|
| 211 |
-
("52 Week Low
|
| 212 |
]
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
# Display business metrics as a dataframe
|
| 218 |
-
forward_eps = info.get('forwardEps', 'N/A')
|
| 219 |
-
forward_pe = info.get('forwardPE', 'N/A')
|
| 220 |
-
peg_ratio = info.get('pegRatio', 'N/A')
|
| 221 |
-
dividend_rate = info.get('dividendRate', 'N/A')
|
| 222 |
-
dividend_yield = info.get('dividendYield', 'N/A')
|
| 223 |
-
recommendation = info.get('recommendationKey', 'N/A')
|
| 224 |
-
|
| 225 |
biz_metrics = [
|
| 226 |
("Business Metrics", "Value"),
|
| 227 |
-
("EPS (FWD)
|
| 228 |
-
("P/E (FWD)
|
| 229 |
-
("PEG Ratio
|
| 230 |
-
("Div Rate (FWD)
|
| 231 |
-
("Div Yield (FWD)
|
| 232 |
-
("Recommendation
|
| 233 |
]
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
col3.dataframe(df, width=400, hide_index=True)
|
| 237 |
|
| 238 |
-
#
|
| 239 |
-
|
| 240 |
-
df_forecast = history.reset_index()[['Date', 'Close']]
|
| 241 |
-
df_forecast['Date'] = pd.to_datetime(df_forecast['Date']).dt.tz_localize(None) # Remove timezone information
|
| 242 |
-
df_forecast.columns = ['ds', 'y']
|
| 243 |
|
| 244 |
m = Prophet(daily_seasonality=True)
|
| 245 |
-
m.fit(
|
| 246 |
|
| 247 |
future = m.make_future_dataframe(periods=forecast_period)
|
| 248 |
forecast = m.predict(future)
|
| 249 |
|
|
|
|
| 250 |
fig2 = go.Figure()
|
| 251 |
fig2.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat'], mode='lines', name='Forecast'))
|
| 252 |
-
fig2.add_trace(go.Scatter(x=
|
| 253 |
-
fig2.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat_lower'], mode='lines', name='Lower Confidence Interval', line=dict(dash='dash')))
|
| 254 |
fig2.update_layout(
|
| 255 |
-
title=
|
| 256 |
xaxis_title="Date",
|
| 257 |
-
yaxis_title="
|
| 258 |
-
hovermode="x unified"
|
| 259 |
)
|
| 260 |
st.plotly_chart(fig2, use_container_width=True)
|
| 261 |
|
| 262 |
-
# Generate reasons
|
| 263 |
-
|
| 264 |
-
reasons = generate_reasons(
|
| 265 |
|
| 266 |
-
st.subheader("
|
| 267 |
st.write(reasons)
|
| 268 |
|
| 269 |
except Exception as e:
|
| 270 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import streamlit as st
|
|
|
|
| 2 |
import pandas as pd
|
| 3 |
+
import numpy as np
|
| 4 |
from prophet import Prophet
|
| 5 |
import plotly.graph_objs as go
|
| 6 |
import google.generativeai as genai
|
| 7 |
+
import requests
|
| 8 |
+
from datetime import datetime
|
| 9 |
|
| 10 |
# Streamlit app details
|
| 11 |
st.set_page_config(page_title="TechyTrade", layout="wide")
|
| 12 |
|
| 13 |
+
# Custom CSS from HF version
|
| 14 |
st.markdown("""
|
| 15 |
<style>
|
| 16 |
@import url('https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;700&display=swap');
|
|
|
|
| 39 |
</style>
|
| 40 |
""", unsafe_allow_html=True)
|
| 41 |
|
| 42 |
+
# Sidebar inputs
|
| 43 |
with st.sidebar:
|
| 44 |
st.title("📊 TechyTrade")
|
| 45 |
+
ticker = st.text_input("Enter a stock ticker (e.g. AAPL) 🏷️", "AAPL").upper().strip()
|
| 46 |
+
period = st.selectbox("Enter a time frame ⏳", ("1M", "6M", "1Y", "5Y"), index=0)
|
| 47 |
forecast_period = st.slider("Select forecast period (days) 🔮", min_value=1, max_value=365, value=30)
|
| 48 |
st.write("Select Technical Indicators:")
|
| 49 |
sma_checkbox = st.checkbox("Simple Moving Average (SMA)")
|
|
|
|
| 54 |
google_api_key = st.text_input("Enter your Google API Key 🔑", type="password")
|
| 55 |
button = st.button("Submit 🚀")
|
| 56 |
|
| 57 |
+
# Load generative model (cache)
|
| 58 |
@st.cache_resource
|
| 59 |
def load_model(api_key):
|
| 60 |
genai.configure(api_key=api_key)
|
| 61 |
return genai.GenerativeModel('gemini-1.5-flash')
|
| 62 |
|
| 63 |
+
# Generate AI-based reasons
|
| 64 |
+
def generate_reasons(fig_desc, stock_info, price_info, biz_metrics, api_key):
|
| 65 |
model = load_model(api_key)
|
| 66 |
+
prompt = f"Based on the following stock price graph description:\n\n{fig_desc}\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 Analyze the trends and give recommendations and insights."
|
| 67 |
response = model.generate_content(prompt)
|
| 68 |
return response.text
|
| 69 |
|
| 70 |
+
# Format large numbers with suffix
|
| 71 |
def format_value(value):
|
| 72 |
+
if value == "N/A" or value is None:
|
| 73 |
+
return "N/A"
|
| 74 |
+
try:
|
| 75 |
+
value = float(value)
|
| 76 |
+
except:
|
| 77 |
+
return "N/A"
|
| 78 |
suffixes = ["", "K", "M", "B", "T"]
|
| 79 |
suffix_index = 0
|
| 80 |
while value >= 1000 and suffix_index < len(suffixes) - 1:
|
|
|
|
| 82 |
suffix_index += 1
|
| 83 |
return f"${value:.1f}{suffixes[suffix_index]}"
|
| 84 |
|
| 85 |
+
# Technical indicator calculations (same as HF version)
|
| 86 |
def calculate_sma(data, window):
|
| 87 |
return data.rolling(window=window).mean()
|
| 88 |
|
|
|
|
| 110 |
lower_band = sma - (std * 2)
|
| 111 |
return upper_band, lower_band
|
| 112 |
|
| 113 |
+
# Alpha Vantage stock data retrieval function
|
| 114 |
+
def get_stock_data_alpha_vantage(ticker, period):
|
| 115 |
+
# Use TIME_SERIES_DAILY or TIME_SERIES_WEEKLY depending on period
|
| 116 |
+
api_key = "656HG6SEB317EFAB"
|
| 117 |
+
function = "TIME_SERIES_DAILY"
|
| 118 |
+
interval_days = 1
|
| 119 |
+
if period == "1M":
|
| 120 |
+
outputsize = "compact" # last 100 days approx
|
| 121 |
+
elif period == "6M":
|
| 122 |
+
outputsize = "full"
|
| 123 |
+
elif period == "1Y":
|
| 124 |
+
outputsize = "full"
|
| 125 |
+
elif period == "5Y":
|
| 126 |
+
# Alpha Vantage free API doesn't support 5Y directly, fallback to full daily
|
| 127 |
+
outputsize = "full"
|
| 128 |
+
else:
|
| 129 |
+
outputsize = "compact"
|
| 130 |
+
|
| 131 |
+
url = f"https://www.alphavantage.co/query?function={function}&symbol={ticker}&outputsize={outputsize}&apikey={api_key}"
|
| 132 |
+
response = requests.get(url)
|
| 133 |
+
data = response.json()
|
| 134 |
+
|
| 135 |
+
if "Time Series (Daily)" not in data:
|
| 136 |
+
raise ValueError(f"Error fetching data for ticker {ticker}: {data.get('Note') or data.get('Error Message') or 'Unknown error'}")
|
| 137 |
+
|
| 138 |
+
df = pd.DataFrame.from_dict(data["Time Series (Daily)"], orient='index')
|
| 139 |
+
df = df.rename(columns={
|
| 140 |
+
'1. open': 'Open',
|
| 141 |
+
'2. high': 'High',
|
| 142 |
+
'3. low': 'Low',
|
| 143 |
+
'4. close': 'Close',
|
| 144 |
+
'5. volume': 'Volume'
|
| 145 |
+
})
|
| 146 |
+
df.index = pd.to_datetime(df.index)
|
| 147 |
+
df = df.sort_index()
|
| 148 |
+
|
| 149 |
+
# Filter date range based on selected period
|
| 150 |
+
now = pd.Timestamp.now()
|
| 151 |
+
if period == "1M":
|
| 152 |
+
cutoff = now - pd.DateOffset(months=1)
|
| 153 |
+
elif period == "6M":
|
| 154 |
+
cutoff = now - pd.DateOffset(months=6)
|
| 155 |
+
elif period == "1Y":
|
| 156 |
+
cutoff = now - pd.DateOffset(years=1)
|
| 157 |
+
elif period == "5Y":
|
| 158 |
+
cutoff = now - pd.DateOffset(years=5)
|
| 159 |
+
else:
|
| 160 |
+
cutoff = df.index.min()
|
| 161 |
+
|
| 162 |
+
df = df[df.index >= cutoff]
|
| 163 |
+
|
| 164 |
+
# Convert columns to float
|
| 165 |
+
for col in ['Open', 'High', 'Low', 'Close', 'Volume']:
|
| 166 |
+
df[col] = df[col].astype(float)
|
| 167 |
+
|
| 168 |
+
return df
|
| 169 |
+
|
| 170 |
+
# Dummy function to simulate getting stock info (Alpha Vantage does not provide all info)
|
| 171 |
+
def get_stock_info_alpha_vantage(ticker):
|
| 172 |
+
# Return dummy or partial info for demo
|
| 173 |
+
return {
|
| 174 |
+
"country": "N/A",
|
| 175 |
+
"sector": "N/A",
|
| 176 |
+
"industry": "N/A",
|
| 177 |
+
"marketCap": "N/A",
|
| 178 |
+
"enterpriseValue": "N/A",
|
| 179 |
+
"fullTimeEmployees": "N/A",
|
| 180 |
+
"currentPrice": "N/A",
|
| 181 |
+
"previousClose": "N/A",
|
| 182 |
+
"dayHigh": "N/A",
|
| 183 |
+
"dayLow": "N/A",
|
| 184 |
+
"fiftyTwoWeekHigh": "N/A",
|
| 185 |
+
"fiftyTwoWeekLow": "N/A",
|
| 186 |
+
"forwardEps": "N/A",
|
| 187 |
+
"forwardPE": "N/A",
|
| 188 |
+
"pegRatio": "N/A",
|
| 189 |
+
"dividendRate": "N/A",
|
| 190 |
+
"dividendYield": "N/A",
|
| 191 |
+
"recommendationKey": "N/A",
|
| 192 |
+
"longName": ticker
|
| 193 |
+
}
|
| 194 |
+
|
| 195 |
+
# Main execution on button click
|
| 196 |
if button:
|
| 197 |
+
if not ticker:
|
| 198 |
st.error("Please provide a valid stock ticker.")
|
| 199 |
+
elif not alpha_vantage_api_key:
|
| 200 |
+
st.error("Please provide a valid Alpha Vantage API Key.")
|
| 201 |
+
elif not google_api_key:
|
| 202 |
st.error("Please provide a valid Google API Key.")
|
| 203 |
else:
|
| 204 |
try:
|
| 205 |
+
with st.spinner("Fetching and processing data..."):
|
| 206 |
+
# Get stock data from Alpha Vantage
|
| 207 |
+
history = get_stock_data_alpha_vantage(ticker, alpha_vantage_api_key, period)
|
| 208 |
+
|
| 209 |
+
st.subheader(f"{ticker} - {ticker}")
|
| 210 |
+
|
| 211 |
+
# Plot historical Close price
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
fig = go.Figure()
|
| 213 |
fig.add_trace(go.Scatter(x=history.index, y=history['Close'], mode='lines', name='Close Price'))
|
| 214 |
|
|
|
|
| 216 |
if sma_checkbox:
|
| 217 |
sma = calculate_sma(history['Close'], window=20)
|
| 218 |
fig.add_trace(go.Scatter(x=history.index, y=sma, mode='lines', name='SMA (20)'))
|
|
|
|
| 219 |
if ema_checkbox:
|
| 220 |
ema = calculate_ema(history['Close'], window=20)
|
| 221 |
fig.add_trace(go.Scatter(x=history.index, y=ema, mode='lines', name='EMA (20)'))
|
|
|
|
| 222 |
if rsi_checkbox:
|
| 223 |
rsi = calculate_rsi(history['Close'], window=14)
|
| 224 |
fig.add_trace(go.Scatter(x=history.index, y=rsi, mode='lines', name='RSI (14)', yaxis='y2'))
|
| 225 |
fig.update_layout(yaxis2=dict(title='RSI', overlaying='y', side='right'))
|
|
|
|
| 226 |
if macd_checkbox:
|
| 227 |
macd, signal = calculate_macd(history['Close'])
|
| 228 |
fig.add_trace(go.Scatter(x=history.index, y=macd, mode='lines', name='MACD'))
|
| 229 |
fig.add_trace(go.Scatter(x=history.index, y=signal, mode='lines', name='Signal Line'))
|
|
|
|
| 230 |
if bollinger_checkbox:
|
| 231 |
upper_band, lower_band = calculate_bollinger_bands(history['Close'], window=20)
|
| 232 |
fig.add_trace(go.Scatter(x=history.index, y=upper_band, mode='lines', name='Upper Band'))
|
|
|
|
| 240 |
)
|
| 241 |
st.plotly_chart(fig, use_container_width=True)
|
| 242 |
|
| 243 |
+
# Get dummy stock info (replace with real API if available)
|
| 244 |
+
info = get_stock_info_alpha_vantage(ticker)
|
| 245 |
|
| 246 |
+
col1, col2, col3 = st.columns(3)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 247 |
|
| 248 |
+
# Stock info dataframe
|
| 249 |
stock_info = [
|
| 250 |
("Stock Info", "Value"),
|
| 251 |
+
("Country", info["country"]),
|
| 252 |
+
("Sector", info["sector"]),
|
| 253 |
+
("Industry", info["industry"]),
|
| 254 |
+
("Market Cap", info["marketCap"]),
|
| 255 |
+
("Enterprise Value", info["enterpriseValue"]),
|
| 256 |
+
("Employees", info["fullTimeEmployees"])
|
| 257 |
]
|
| 258 |
+
df_stock_info = pd.DataFrame(stock_info[1:], columns=stock_info[0])
|
| 259 |
+
col1.dataframe(df_stock_info, width=400, hide_index=True)
|
| 260 |
+
|
| 261 |
+
# Price info dataframe (mostly N/A here)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 262 |
price_info = [
|
| 263 |
("Price Info", "Value"),
|
| 264 |
+
("Current Price", info["currentPrice"]),
|
| 265 |
+
("Previous Close", info["previousClose"]),
|
| 266 |
+
("Day High", info["dayHigh"]),
|
| 267 |
+
("Day Low", info["dayLow"]),
|
| 268 |
+
("52 Week High", info["fiftyTwoWeekHigh"]),
|
| 269 |
+
("52 Week Low", info["fiftyTwoWeekLow"])
|
| 270 |
]
|
| 271 |
+
df_price_info = pd.DataFrame(price_info[1:], columns=price_info[0])
|
| 272 |
+
col2.dataframe(df_price_info, width=400, hide_index=True)
|
| 273 |
+
|
| 274 |
+
# Business metrics dataframe (mostly N/A here)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 275 |
biz_metrics = [
|
| 276 |
("Business Metrics", "Value"),
|
| 277 |
+
("EPS (FWD)", info["forwardEps"]),
|
| 278 |
+
("P/E (FWD)", info["forwardPE"]),
|
| 279 |
+
("PEG Ratio", info["pegRatio"]),
|
| 280 |
+
("Div Rate (FWD)", info["dividendRate"]),
|
| 281 |
+
("Div Yield (FWD)", info["dividendYield"]),
|
| 282 |
+
("Recommendation", info["recommendationKey"])
|
| 283 |
]
|
| 284 |
+
df_biz_metrics = pd.DataFrame(biz_metrics[1:], columns=biz_metrics[0])
|
| 285 |
+
col3.dataframe(df_biz_metrics, width=400, hide_index=True)
|
|
|
|
| 286 |
|
| 287 |
+
# Prepare data for forecasting
|
| 288 |
+
forecast_df = history.reset_index()[['index', 'Close']].rename(columns={'index': 'ds', 'Close': 'y'})
|
|
|
|
|
|
|
|
|
|
| 289 |
|
| 290 |
m = Prophet(daily_seasonality=True)
|
| 291 |
+
m.fit(forecast_df)
|
| 292 |
|
| 293 |
future = m.make_future_dataframe(periods=forecast_period)
|
| 294 |
forecast = m.predict(future)
|
| 295 |
|
| 296 |
+
st.subheader("Forecasted Stock Price")
|
| 297 |
fig2 = go.Figure()
|
| 298 |
fig2.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat'], mode='lines', name='Forecast'))
|
| 299 |
+
fig2.add_trace(go.Scatter(x=forecast_df['ds'], y=forecast_df['y'], mode='lines', name='Actual'))
|
|
|
|
| 300 |
fig2.update_layout(
|
| 301 |
+
title="Prophet Forecast",
|
| 302 |
xaxis_title="Date",
|
| 303 |
+
yaxis_title="Price"
|
|
|
|
| 304 |
)
|
| 305 |
st.plotly_chart(fig2, use_container_width=True)
|
| 306 |
|
| 307 |
+
# Generate AI-based reasons using Google Gemini
|
| 308 |
+
fig_description = "Line chart of stock closing prices and technical indicators as shown above."
|
| 309 |
+
reasons = generate_reasons(fig_description, df_stock_info.to_string(), df_price_info.to_string(), df_biz_metrics.to_string(), google_api_key)
|
| 310 |
|
| 311 |
+
st.subheader("AI-based Stock Analysis and Recommendations")
|
| 312 |
st.write(reasons)
|
| 313 |
|
| 314 |
except Exception as e:
|
| 315 |
+
st.error(f"Error: {e}")
|
| 316 |
+
|
| 317 |
+
else:
|
| 318 |
+
st.info("Enter details and click Submit to start analyzing the stock.")
|