ujaganna's picture
Update app.py
899a973 verified
import yfinance as yf
import pandas as pd
import streamlit as st
from fpdf import FPDF
import requests
from bs4 import BeautifulSoup
from textblob import TextBlob
# Function to fetch financial statements
def get_financials(ticker):
stock = yf.Ticker(ticker)
return stock.balance_sheet, stock.financials, stock.cashflow
# Function to compute key financial ratios
def calculate_ratios(balance_sheet, income_statement):
try:
ratios = {
"Current Ratio": balance_sheet.loc["Current Assets"][0] / balance_sheet.loc["Current Liabilities"][0],
"Debt-to-Equity": balance_sheet.loc["Long Term Debt"][0] / balance_sheet.loc["Stockholders Equity"][0],
"Net Profit Margin": income_statement.loc["Net Income"][0] / income_statement.loc["Total Revenue"][0]
}
except Exception as e:
ratios = {"Error": f"Could not compute ratios: {e}"}
return ratios
# Function to fetch latest news headlines for sentiment analysis
def get_news_sentiment(ticker):
url = f"https://finance.yahoo.com/quote/{ticker}/news"
headers = {'User-Agent': 'Mozilla/5.0'}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
headlines = [h.text for h in soup.find_all('h3')][:5] # Get top 5 headlines
sentiments = {}
for headline in headlines:
sentiment_score = TextBlob(headline).sentiment.polarity
sentiments[headline] = "Positive" if sentiment_score > 0 else "Negative" if sentiment_score < 0 else "Neutral"
return sentiments
# Function to generate a PDF report
def generate_report(ticker, ratios, sentiments):
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=12)
pdf.cell(200, 10, f"Financial Report for {ticker}", ln=True, align='C')
pdf.ln(10)
pdf.cell(200, 10, "Key Financial Ratios:", ln=True)
for key, value in ratios.items():
pdf.cell(200, 10, f"{key}: {value:.2f}" if isinstance(value, (int, float)) else f"{key}: {value}", ln=True)
pdf.ln(10)
pdf.cell(200, 10, "Recent News Sentiment Analysis:", ln=True)
for news, sentiment in sentiments.items():
pdf.multi_cell(0, 10, f"{news} - Sentiment: {sentiment}")
pdf.output("financial_report.pdf")
# Streamlit UI
st.title("AI-Based Financial Analysis App")
ticker = st.text_input("Enter Stock Ticker Symbol (e.g., AAPL, TSLA, MSFT)")
if st.button("Analyze"):
try:
balance_sheet, income_statement, cash_flow = get_financials(ticker)
ratios = calculate_ratios(balance_sheet, income_statement)
sentiments = get_news_sentiment(ticker)
generate_report(ticker, ratios, sentiments)
st.success("Financial Report Generated: financial_report.pdf")
with open("financial_report.pdf", "rb") as file:
st.download_button("Download Report", file, file_name="financial_report.pdf", mime="application/pdf")
st.write("### Key Financial Ratios")
for key, value in ratios.items():
st.write(f"**{key}**: {value:.2f}" if isinstance(value, (int, float)) else f"**{key}**: {value}")
st.write("### Recent News Sentiment Analysis")
for news, sentiment in sentiments.items():
st.write(f"**{news}** - Sentiment: {sentiment}")
except Exception as e:
st.error(f"Error: {e}")