Anupam251272
commited on
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Install required packages
|
2 |
+
#!pip install gradio yfinance transformers torch pandas plotly requests beautifulsoup4
|
3 |
+
|
4 |
+
import gradio as gr
|
5 |
+
import yfinance as yf
|
6 |
+
import pandas as pd
|
7 |
+
import torch
|
8 |
+
import plotly.graph_objects as go
|
9 |
+
import plotly.express as px
|
10 |
+
from transformers import pipeline
|
11 |
+
from datetime import datetime, timedelta
|
12 |
+
import requests
|
13 |
+
from bs4 import BeautifulSoup
|
14 |
+
import numpy as np
|
15 |
+
|
16 |
+
# Check for GPU availability
|
17 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
18 |
+
print(f"Using device: {device}")
|
19 |
+
|
20 |
+
# Initialize models
|
21 |
+
summarizer = pipeline("summarization", model="facebook/bart-large-cnn", device=device)
|
22 |
+
sentiment_analyzer = pipeline("sentiment-analysis", model="finiteautomata/bertweet-base-sentiment-analysis", device=device)
|
23 |
+
|
24 |
+
class CompanyResearchAgent:
|
25 |
+
def __init__(self):
|
26 |
+
self.cache = {}
|
27 |
+
|
28 |
+
def get_stock_data(self, symbol, period="1y"):
|
29 |
+
"""Fetch stock data using yfinance"""
|
30 |
+
try:
|
31 |
+
stock = yf.Ticker(symbol)
|
32 |
+
hist = stock.history(period=period)
|
33 |
+
return stock, hist
|
34 |
+
except Exception as e:
|
35 |
+
return None, None
|
36 |
+
|
37 |
+
def create_stock_chart(self, hist):
|
38 |
+
"""Create interactive stock price chart"""
|
39 |
+
if hist is None or hist.empty:
|
40 |
+
return None
|
41 |
+
|
42 |
+
fig = go.Figure()
|
43 |
+
fig.add_trace(go.Candlestick(
|
44 |
+
x=hist.index,
|
45 |
+
open=hist['Open'],
|
46 |
+
high=hist['High'],
|
47 |
+
low=hist['Low'],
|
48 |
+
close=hist['Close'],
|
49 |
+
name='Stock Price'
|
50 |
+
))
|
51 |
+
fig.update_layout(
|
52 |
+
title="Stock Price History",
|
53 |
+
yaxis_title="Price",
|
54 |
+
xaxis_title="Date",
|
55 |
+
template="plotly_dark"
|
56 |
+
)
|
57 |
+
return fig
|
58 |
+
|
59 |
+
def get_news_sentiment(self, company_name):
|
60 |
+
"""Analyze news sentiment"""
|
61 |
+
try:
|
62 |
+
url = f"https://news.google.com/rss/search?q={company_name}+when:7d"
|
63 |
+
response = requests.get(url)
|
64 |
+
soup = BeautifulSoup(response.content, 'xml')
|
65 |
+
titles = [item.title.text for item in soup.find_all('item')[:5]]
|
66 |
+
|
67 |
+
sentiments = sentiment_analyzer(titles)
|
68 |
+
sentiment_scores = [s['score'] for s in sentiments]
|
69 |
+
avg_sentiment = sum(sentiment_scores) / len(sentiment_scores)
|
70 |
+
|
71 |
+
return {
|
72 |
+
'average_sentiment': round(avg_sentiment, 2),
|
73 |
+
'recent_news': titles
|
74 |
+
}
|
75 |
+
except Exception as e:
|
76 |
+
return {
|
77 |
+
'average_sentiment': 0,
|
78 |
+
'recent_news': ['Unable to fetch news']
|
79 |
+
}
|
80 |
+
|
81 |
+
def generate_swot(self, stock, company_name):
|
82 |
+
"""Generate SWOT analysis using company data"""
|
83 |
+
if stock is None:
|
84 |
+
return "Unable to generate SWOT analysis - invalid stock data"
|
85 |
+
|
86 |
+
info = stock.info
|
87 |
+
|
88 |
+
# Create SWOT analysis text
|
89 |
+
swot_text = f"""
|
90 |
+
Company Analysis for {company_name}:
|
91 |
+
Sector: {info.get('sector', 'N/A')}
|
92 |
+
Industry: {info.get('industry', 'N/A')}
|
93 |
+
Market Cap: ${info.get('marketCap', 0):,.2f}
|
94 |
+
P/E Ratio: {info.get('trailingPE', 'N/A')}
|
95 |
+
Revenue Growth: {info.get('revenueGrowth', 'N/A')}
|
96 |
+
"""
|
97 |
+
|
98 |
+
# Summarize SWOT analysis
|
99 |
+
summary = summarizer(swot_text, max_length=150, min_length=50)[0]['summary_text']
|
100 |
+
return summary
|
101 |
+
|
102 |
+
def analyze_company(self, symbol):
|
103 |
+
"""Main analysis function"""
|
104 |
+
try:
|
105 |
+
# Get stock data
|
106 |
+
stock, hist = self.get_stock_data(symbol)
|
107 |
+
if stock is None:
|
108 |
+
return "Invalid stock symbol", None, None, None
|
109 |
+
|
110 |
+
# Create visualization
|
111 |
+
stock_chart = self.create_stock_chart(hist)
|
112 |
+
|
113 |
+
# Get company info
|
114 |
+
info = stock.info
|
115 |
+
company_name = info.get('longName', symbol)
|
116 |
+
|
117 |
+
# Generate SWOT analysis
|
118 |
+
swot_analysis = self.generate_swot(stock, company_name)
|
119 |
+
|
120 |
+
# Get news sentiment
|
121 |
+
sentiment_data = self.get_news_sentiment(company_name)
|
122 |
+
|
123 |
+
# Prepare company overview
|
124 |
+
# Fixed: Indentation adjusted to align with the function definition
|
125 |
+
company_overview = (
|
126 |
+
f"## {company_name} ({symbol})\n\n"
|
127 |
+
f"**Sector:** {info.get('sector', 'N/A')}\n"
|
128 |
+
f"**Industry:** {info.get('industry', 'N/A')}\n"
|
129 |
+
f"**Market Cap:** ${info.get('marketCap', 0):,.2f}\n"
|
130 |
+
f"**Current Price:** ${info.get('currentPrice', 0):,.2f}\n\n"
|
131 |
+
f"### News Sentiment Score: {sentiment_data['average_sentiment']}\n\n"
|
132 |
+
"Recent News:\n"
|
133 |
+
+ "\n".join(f"- {news}" for news in sentiment_data['recent_news']) + "\n\n"
|
134 |
+
f"### SWOT Analysis Summary:\n"
|
135 |
+
f"{swot_analysis}"
|
136 |
+
)
|
137 |
+
|
138 |
+
return company_overview, stock_chart, None, None
|
139 |
+
except Exception as e:
|
140 |
+
return f"Error analyzing company: {str(e)}", None, None, None
|
141 |
+
|
142 |
+
# Create Gradio interface
|
143 |
+
def create_interface():
|
144 |
+
agent = CompanyResearchAgent()
|
145 |
+
|
146 |
+
with gr.Blocks(theme=gr.themes.Base()) as interface:
|
147 |
+
gr.Markdown("# Company Research Agent 📈")
|
148 |
+
gr.Markdown("Enter a stock symbol (e.g., AAPL, GOOGL, MSFT)")
|
149 |
+
|
150 |
+
with gr.Row():
|
151 |
+
symbol_input = gr.Textbox(label="Stock Symbol")
|
152 |
+
analyze_btn = gr.Button("Analyze Company", variant="primary")
|
153 |
+
|
154 |
+
with gr.Row():
|
155 |
+
with gr.Column():
|
156 |
+
overview_output = gr.Markdown(label="Company Overview")
|
157 |
+
with gr.Column():
|
158 |
+
chart_output = gr.Plot(label="Stock Price Chart")
|
159 |
+
|
160 |
+
analyze_btn.click(
|
161 |
+
fn=agent.analyze_company,
|
162 |
+
inputs=[symbol_input],
|
163 |
+
outputs=[overview_output, chart_output]
|
164 |
+
)
|
165 |
+
|
166 |
+
return interface
|
167 |
+
|
168 |
+
# Launch the interface
|
169 |
+
interface = create_interface()
|
170 |
+
interface.launch(debug=True, share=True)
|