Spaces:
Sleeping
Sleeping
File size: 6,276 Bytes
c582a7c 8b434b2 c582a7c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 |
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() |