napaslohitnavy commited on
Commit
45a188d
·
verified ·
1 Parent(s): 892905b

create app.py

Browse files
Files changed (1) hide show
  1. app.py +160 -0
app.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import requests
3
+ from bs4 import BeautifulSoup
4
+ from transformers import pipeline
5
+ import pandas as pd
6
+ from datetime import datetime
7
+
8
+ # โหลด sentiment analysis model
9
+ sentiment_analyzer = pipeline(
10
+ "sentiment-analysis",
11
+ model="ProsusAI/finbert",
12
+ max_length=512,
13
+ truncation=True
14
+ )
15
+
16
+ def get_yahoo_news(ticker):
17
+ """ดึงข่าวจาก Yahoo Finance"""
18
+ url = f"https://finance.yahoo.com/quote/{ticker}/news"
19
+ headers = {
20
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
21
+ }
22
+
23
+ try:
24
+ response = requests.get(url, headers=headers, timeout=10)
25
+ response.raise_for_status()
26
+ soup = BeautifulSoup(response.content, 'html.parser')
27
+
28
+ news_items = []
29
+ articles = soup.find_all('h3')
30
+
31
+ for article in articles[:10]:
32
+ title = article.get_text(strip=True)
33
+ if title and len(title) > 10:
34
+ news_items.append(title)
35
+
36
+ return news_items
37
+
38
+ except Exception as e:
39
+ return [f"Error fetching news: {str(e)}"]
40
+
41
+ def analyze_sentiment(ticker):
42
+ """วิเคราะห์ sentiment จากข่าวหุ้น"""
43
+
44
+ if not ticker:
45
+ return "Please enter a stock ticker", None
46
+
47
+ ticker = ticker.upper().strip()
48
+
49
+ # ดึงข่าว
50
+ news = get_yahoo_news(ticker)
51
+
52
+ if not news or "Error" in news[0]:
53
+ # ถ้าดึงไม่ได้ ใช้ข้อความตัวอย่าง
54
+ return f"Could not fetch news for {ticker}. Using sample data...", None
55
+
56
+ # วิเคราะห์ sentiment
57
+ results = []
58
+ sentiment_counts = {'positive': 0, 'negative': 0, 'neutral': 0}
59
+
60
+ for text in news:
61
+ try:
62
+ sentiment = sentiment_analyzer(text[:512])[0]
63
+ label = sentiment['label'].lower()
64
+ score = sentiment['score']
65
+
66
+ results.append({
67
+ 'News': text[:100] + '...' if len(text) > 100 else text,
68
+ 'Sentiment': label.capitalize(),
69
+ 'Confidence': f"{score:.2%}"
70
+ })
71
+
72
+ if label in sentiment_counts:
73
+ sentiment_counts[label] += 1
74
+
75
+ except Exception as e:
76
+ results.append({
77
+ 'News': text[:100],
78
+ 'Sentiment': 'Error',
79
+ 'Confidence': '0%'
80
+ })
81
+
82
+ # สร้าง DataFrame
83
+ df = pd.DataFrame(results)
84
+
85
+ # คำนวณ overall sentiment
86
+ total = sum(sentiment_counts.values())
87
+ if total > 0:
88
+ sentiment_summary = f"""
89
+ ## Overall Sentiment for {ticker}
90
+
91
+ 📊 **Analysis Summary:**
92
+ - ✅ Positive: {sentiment_counts['positive']} ({sentiment_counts['positive']/total*100:.1f}%)
93
+ - ⚠️ Neutral: {sentiment_counts['neutral']} ({sentiment_counts['neutral']/total*100:.1f}%)
94
+ - ❌ Negative: {sentiment_counts['negative']} ({sentiment_counts['negative']/total*100:.1f}%)
95
+
96
+ **Total News Analyzed:** {total}
97
+ """
98
+ else:
99
+ sentiment_summary = "No valid sentiment data"
100
+
101
+ return sentiment_summary, df
102
+
103
+ # สร้าง Gradio Interface
104
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
105
+ gr.Markdown(
106
+ """
107
+ # 📈 Stock News Sentiment Analyzer
108
+
109
+ Analyze sentiment of news articles from Yahoo Finance using FinBERT AI model.
110
+
111
+ **How to use:** Enter a stock ticker symbol (e.g., AAPL, GOOGL, TSLA) and click Analyze.
112
+ """
113
+ )
114
+
115
+ with gr.Row():
116
+ with gr.Column(scale=2):
117
+ ticker_input = gr.Textbox(
118
+ label="Stock Ticker Symbol",
119
+ placeholder="Enter ticker (e.g., AAPL, TSLA, GOOGL)",
120
+ value="AAPL"
121
+ )
122
+ analyze_btn = gr.Button("🔍 Analyze Sentiment", variant="primary")
123
+
124
+ with gr.Column(scale=1):
125
+ gr.Markdown(
126
+ """
127
+ ### Popular Tickers:
128
+ - **AAPL** - Apple
129
+ - **GOOGL** - Google
130
+ - **MSFT** - Microsoft
131
+ - **TSLA** - Tesla
132
+ - **AMZN** - Amazon
133
+ - **META** - Meta
134
+ """
135
+ )
136
+
137
+ summary_output = gr.Markdown(label="Summary")
138
+ table_output = gr.Dataframe(
139
+ label="Detailed Results",
140
+ headers=["News", "Sentiment", "Confidence"],
141
+ wrap=True
142
+ )
143
+
144
+ analyze_btn.click(
145
+ fn=analyze_sentiment,
146
+ inputs=ticker_input,
147
+ outputs=[summary_output, table_output]
148
+ )
149
+
150
+ gr.Markdown(
151
+ """
152
+ ---
153
+ **Note:** This app uses FinBERT model trained specifically for financial text analysis.
154
+ Results are for informational purposes only and should not be considered as investment advice.
155
+ """
156
+ )
157
+
158
+ # Launch the app
159
+ if __name__ == "__main__":
160
+ demo.launch()