DexterSptizu's picture
Update app.py
8b434b2 verified
import streamlit as st
import yfinance as yf
import plotly.graph_objects as go
from datetime import datetime, timedelta
import pandas as pd
st.set_page_config(layout="wide", page_title="Stock Analysis Dashboard")
def format_number(num):
"""Format large numbers to readable format with B/M suffix"""
if num >= 1e9:
return f"₹{num/1e9:.2f}B"
elif num >= 1e6:
return f"₹{num/1e6:.2f}M"
else:
return f"₹{num:,.2f}"
def create_price_chart(ticker_data):
"""Create interactive price chart using Plotly"""
fig = go.Figure(data=[go.Candlestick(x=ticker_data.index,
open=ticker_data['Open'],
high=ticker_data['High'],
low=ticker_data['Low'],
close=ticker_data['Close'])])
fig.update_layout(
title="Stock Price Movement",
yaxis_title="Price",
xaxis_title="Date",
template="plotly_dark"
)
return fig
def create_volume_chart(ticker_data):
"""Create volume chart using Plotly"""
fig = go.Figure(data=[go.Bar(x=ticker_data.index, y=ticker_data['Volume'])])
fig.update_layout(
title="Trading Volume",
yaxis_title="Volume",
xaxis_title="Date",
template="plotly_dark"
)
return fig
def main():
st.title("📊 Stock Information")
st.markdown("**Developed by : Venugopal Adep**")
# Input section
col1, col2 = st.columns([2,2])
with col1:
ticker_symbol = st.text_input("Enter Stock Ticker (e.g., RELIANCE.NS for Indian stocks):")
with col2:
period = st.selectbox("Select Time Period:",
["1mo", "3mo", "6mo", "1y", "2y", "5y", "max"],
index=2)
if ticker_symbol:
try:
# Fetch stock data
stock = yf.Ticker(ticker_symbol)
info = stock.info
hist_data = stock.history(period=period)
# Company Overview Section
st.header("Company Overview")
col1, col2, col3 = st.columns([1,1,1])
with col1:
st.metric("Current Price", format_number(info.get('currentPrice', 0)))
st.metric("Market Cap", format_number(info.get('marketCap', 0)))
with col2:
day_change = info.get('regularMarketChangePercent', 0)
st.metric("Day Change", f"{day_change:.2f}%")
st.metric("P/E Ratio", f"{info.get('forwardPE', 0):.2f}")
with col3:
st.metric("52 Week High", format_number(info.get('fiftyTwoWeekHigh', 0)))
st.metric("52 Week Low", format_number(info.get('fiftyTwoWeekLow', 0)))
# Price Charts
st.header("Price Analysis")
tab1, tab2 = st.tabs(["Price Chart", "Volume Chart"])
with tab1:
st.plotly_chart(create_price_chart(hist_data), use_container_width=True)
with tab2:
st.plotly_chart(create_volume_chart(hist_data), use_container_width=True)
# Detailed Information
st.header("Detailed Information")
col1, col2 = st.columns([1,1])
with col1:
st.subheader("Company Profile")
st.write("**Sector:**", info.get('sector', 'N/A'))
st.write("**Industry:**", info.get('industry', 'N/A'))
st.write("**Country:**", info.get('country', 'N/A'))
st.write("**Website:**", info.get('website', 'N/A'))
st.subheader("Key Statistics")
metrics_df = pd.DataFrame({
'Metric': [
'Beta',
'Dividend Yield (%)',
'Trailing P/E',
'Forward P/E',
'PEG Ratio',
'Price to Book'
],
'Value': [
f"{info.get('beta', 0):.2f}",
f"{info.get('dividendYield', 0)*100:.2f}",
f"{info.get('trailingPE', 0):.2f}",
f"{info.get('forwardPE', 0):.2f}",
f"{info.get('pegRatio', 0):.2f}",
f"{info.get('priceToBook', 0):.2f}"
]
})
st.dataframe(metrics_df, hide_index=True)
with col2:
st.subheader("Business Summary")
st.write(info.get('longBusinessSummary', 'No summary available'))
st.subheader("Financial Metrics")
financial_df = pd.DataFrame({
'Metric': [
'Revenue Growth',
'Gross Margins',
'Operating Margins',
'Profit Margins',
'Return on Equity',
'Return on Assets'
],
'Value': [
f"{info.get('revenueGrowth', 0)*100:.2f}%",
f"{info.get('grossMargins', 0)*100:.2f}%",
f"{info.get('operatingMargins', 0)*100:.2f}%",
f"{info.get('profitMargins', 0)*100:.2f}%",
f"{info.get('returnOnEquity', 0)*100:.2f}%",
f"{info.get('returnOnAssets', 0)*100:.2f}%"
]
})
st.dataframe(financial_df, hide_index=True)
# Historical Data Download Section
st.header("Download Historical Data")
csv = hist_data.to_csv()
st.download_button(
label="📥 Download Historical Data",
data=csv,
file_name=f"{ticker_symbol}_historical_data.csv",
mime="text/csv"
)
except Exception as e:
st.error(f"Error fetching data for {ticker_symbol}. Please check the ticker symbol and try again.")
st.error(f"Error details: {str(e)}")
if __name__ == "__main__":
main()