Spaces:
Sleeping
Sleeping
File size: 4,301 Bytes
f2ec320 a644249 f2ec320 |
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 |
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()
|