stock_analysis / app.py
wajidengg's picture
Update app.py
a644249 verified
import yfinance as yf
import pandas as pd
import numpy as np
import streamlit as st
from ta.momentum import RSIIndicator
from ta.trend import MACD
from ta.volatility import BollingerBands
# Function to fetch data from Yahoo Finance
def fetch_data(stock_ticker):
stock_data = yf.Ticker(stock_ticker)
df = stock_data.history(period="1y")
return df, stock_data
# Function to calculate fundamental metrics
def calculate_fundamentals(stock_data):
market_price = stock_data.history(period="1d")['Close'].iloc[-1]
eps = stock_data.info.get('regularMarketEPS', stock_data.info.get('epsTrailingTwelveMonths', 0))
if eps == 0:
eps = 0
shares_outstanding = stock_data.info.get('sharesOutstanding', 0)
book_value = stock_data.info.get('bookValue', 0)
annual_dividend = stock_data.info.get('dividendRate', 0)
revenue = stock_data.info.get('totalRevenue', 0)
debt = stock_data.info.get('totalDebt', 0)
cash = stock_data.info.get('cash', 0)
# Calculate P/E, P/B, Dividend Yield
pe_ratio = market_price / eps if eps != 0 else None
pb_ratio = market_price / book_value if book_value != 0 else None
dividend_yield = (annual_dividend / market_price) * 100 if annual_dividend else 0
# Additional ratios
ps_ratio = stock_data.info.get('marketCap', 0) / revenue if revenue != 0 else None
de_ratio = debt / stock_data.info.get('totalEquity', 1)
# Calculate PEG ratio
peg_ratio = pe_ratio / (stock_data.info.get('earningsGrowth', 0) if stock_data.info.get('earningsGrowth', 0) != 0 else 1)
return {
"P/E Ratio": pe_ratio,
"EPS": eps,
"P/B Ratio": pb_ratio,
"Dividend Yield (%)": dividend_yield,
"P/S Ratio": ps_ratio,
"D/E Ratio": de_ratio,
"PEG Ratio": peg_ratio
}
# Function for Buy/Sell Signal based on P/E, RSI, Moving Averages
def generate_buy_sell_signal(pe_ratio, rsi, sma_50, sma_200):
signal = "Hold"
if pe_ratio and pe_ratio < 15:
signal = "Buy"
elif rsi > 70:
signal = "Sell"
elif sma_50 > sma_200:
signal = "Buy"
elif sma_50 < sma_200:
signal = "Sell"
return signal
# Function to calculate DCF (Discounted Cash Flow) Model
def calculate_dcf(stock_data, growth_rate=0.05, discount_rate=0.08):
fcf = stock_data.info.get('freeCashflow', 0) # Example: FCF (Free Cash Flow)
if fcf == 0:
return None
# Project future FCF for 5 years
future_fcf = [fcf * (1 + growth_rate) ** i for i in range(1, 6)]
# Calculate DCF value
dcf_value = sum([cf / (1 + discount_rate) ** i for i, cf in enumerate(future_fcf, 1)])
return dcf_value
# Streamlit UI
def app():
st.title("Stock Prediction and Analysis")
# User input for stock ticker
stock_ticker = st.text_input("Enter Stock Ticker (e.g., AAPL, TATAMOTORS.NS):")
if stock_ticker:
# Fetch stock data
df, stock_data = fetch_data(stock_ticker)
# Display stock data and technical indicators
st.write(f"**Displaying last 5 rows of {stock_ticker} data:**")
st.write(df.tail())
# Calculate fundamental metrics
fundamentals = calculate_fundamentals(stock_data)
st.subheader("Fundamental Analysis")
st.write(fundamentals)
# Calculate technical indicators (SMA, RSI)
sma_50 = df['Close'].rolling(window=50).mean().iloc[-1]
sma_200 = df['Close'].rolling(window=200).mean().iloc[-1]
rsi_indicator = RSIIndicator(df['Close'])
rsi = rsi_indicator.rsi().iloc[-1]
# Display technical indicators
st.write(f"50-day SMA: {sma_50}")
st.write(f"200-day SMA: {sma_200}")
st.write(f"RSI: {rsi}")
# Generate Buy/Sell Signal
buy_sell_signal = generate_buy_sell_signal(fundamentals['P/E Ratio'], rsi, sma_50, sma_200)
st.subheader("Buy/Sell Signal")
st.write(f"Signal: {buy_sell_signal}")
# DCF Value (example)
dcf_value = calculate_dcf(stock_data)
if dcf_value:
st.subheader("Discounted Cash Flow (DCF) Analysis")
st.write(f"DCF Value: {dcf_value}")
else:
st.write("DCF not available due to lack of Free Cash Flow data")
# Run the app
if __name__ == "__main__":
app()