Sooteemon commited on
Commit
99fb303
·
verified ·
1 Parent(s): b5400ea

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +12 -34
app.py CHANGED
@@ -1,32 +1,23 @@
1
  import gradio as gr
2
  import pandas as pd
3
  from scraper import YahooFinanceScraper
4
- from sentiment_analyzer import NewsAnalyzer # --- MODIFIED: Import new class ---
5
  import time
6
- from collections import Counter # --- ADDED: For counting themes/impacts ---
7
 
8
  # Initialize components
9
- print("Initializing Yahoo Finance News Analyzer...") # --- MODIFIED ---
10
  scraper = YahooFinanceScraper()
11
- analyzer = NewsAnalyzer() # --- MODIFIED: Use new class ---
12
 
13
  def get_sentiment_color(sentiment):
14
  """กำหนดสีตาม sentiment"""
15
- colors = {
16
- "Positive": "🟢",
17
- "Negative": "🔴",
18
- "Neutral": "🟡"
19
- }
20
  return colors.get(sentiment, "⚪")
21
 
22
- # --- ADDED: New helper function for impact ---
23
  def get_impact_color(impact):
24
  """กำหนดสีตาม impact"""
25
- colors = {
26
- "Opportunity": "🟢", # ใช้สีเขียวเหมือน Positive
27
- "Risk": "🔴", # ใช้สีแดงเหมือน Negative
28
- "Neutral": "🟡"
29
- }
30
  return colors.get(impact, "⚪")
31
 
32
  def analyze_news(search_type, search_input, num_articles):
@@ -34,10 +25,8 @@ def analyze_news(search_type, search_input, num_articles):
34
  ฟังก์ชันหลักในการวิเคราะห์ข่าว
35
  """
36
  try:
37
- # Update progress
38
  yield "กำลังดึงข่าว...", None, None
39
 
40
- # Fetch news based on search type
41
  if search_type == "Latest News":
42
  news_list = scraper.get_latest_news(max_articles=int(num_articles))
43
  elif search_type == "Stock Symbol":
@@ -57,7 +46,6 @@ def analyze_news(search_type, search_input, num_articles):
57
 
58
  yield f"พบข่าว {len(news_list)} รายการ | กำลังวิเคราะห์ sentiment, theme, และ impact...", None, None
59
 
60
- # Analyze sentiment, theme, and impact
61
  results = analyzer.analyze_batch(news_list)
62
 
63
  # Create summary statistics
@@ -67,11 +55,9 @@ def analyze_news(search_type, search_input, num_articles):
67
  neutral = sum(1 for r in results if r['sentiment'] == 'Neutral')
68
  avg_score = sum(r['score'] for r in results) / total if total > 0 else 0
69
 
70
- # --- ADDED: Theme and Impact Statistics ---
71
  theme_counts = Counter(r.get('theme', 'N/A') for r in results)
72
  impact_counts = Counter(r.get('impact', 'N/A') for r in results)
73
 
74
- # Overall sentiment
75
  if positive > negative and positive > neutral:
76
  overall = "📈 Positive (Bullish)"
77
  elif negative > positive and negative > neutral:
@@ -79,7 +65,6 @@ def analyze_news(search_type, search_input, num_articles):
79
  else:
80
  overall = "📊 Neutral"
81
 
82
- # --- MODIFIED: Updated summary block ---
83
  summary = f"""## 📊 สรุปผลการวิเคราะห์
84
  **ภาพรวม:** {overall} | **คะแนนเฉลี่ย:** {avg_score:.2f}/1.0
85
 
@@ -107,11 +92,12 @@ def analyze_news(search_type, search_input, num_articles):
107
  s_emoji = get_sentiment_color(result['sentiment'])
108
  i_emoji = get_impact_color(result.get('impact', 'N/A'))
109
 
110
- # --- MODIFIED: Added Theme and Impact to detailed view ---
111
  detailed_results += f"""### {i}. {s_emoji} {result['title']}
112
  **Theme:** {result.get('theme', 'N/A')} | **Impact:** {i_emoji} {result.get('impact', 'N/A')}
113
  **Sentiment:** {result['sentiment']} | **Score:** {result['score']:.2f}
114
  **เผยแพร่:** {result['published']}
 
115
  **คำอธิบาย AI:** {result['explanation']}
116
  [🔗 อ่านต่อ]({result['link']})
117
  ---"""
@@ -119,7 +105,6 @@ def analyze_news(search_type, search_input, num_articles):
119
  # Create DataFrame for table view
120
  df_data = []
121
  for result in results:
122
- # --- MODIFIED: Added Theme and Impact to dataframe ---
123
  df_data.append({
124
  'Title': result['title'][:60] + '...' if len(result['title']) > 60 else result['title'],
125
  'Theme': result.get('theme', 'N/A'),
@@ -131,7 +116,6 @@ def analyze_news(search_type, search_input, num_articles):
131
  })
132
 
133
  df = pd.DataFrame(df_data)
134
-
135
  final_output = summary + detailed_results
136
 
137
  yield final_output, df, "✅ วิเคราะห์เสร็จสมบูรณ์!"
@@ -140,9 +124,8 @@ def analyze_news(search_type, search_input, num_articles):
140
  error_msg = f"❌ เกิดข้อผิดพลาด: {str(e)}"
141
  yield error_msg, None, error_msg
142
 
143
- # Create Gradio Interface
144
- with gr.Blocks(title="Yahoo Finance News Analyzer", theme=gr.themes.Soft()) as demo: # --- MODIFIED ---
145
-
146
  gr.Markdown("""
147
  # 📈 Yahoo Finance News Analyzer
148
  วิเคราะห์ข่าวการเงินจาก Yahoo Finance ด้วย AI แบบครบวงจร
@@ -153,7 +136,7 @@ with gr.Blocks(title="Yahoo Finance News Analyzer", theme=gr.themes.Soft()) as d
153
  - วิเคราะห์ Impact (ผลกระทบ: โอกาส หรือ ความเสี่ยง)
154
  - ให้คะแนนความมั่นใจและคำอธิบาย
155
  - รองรับค้นหาตาม Stock Symbol และ Keyword
156
- """) # --- MODIFIED ---
157
 
158
  with gr.Row():
159
  with gr.Column(scale=1):
@@ -162,13 +145,11 @@ with gr.Blocks(title="Yahoo Finance News Analyzer", theme=gr.themes.Soft()) as d
162
  value="Latest News",
163
  label="ประเภทการค้นหา"
164
  )
165
-
166
  search_input = gr.Textbox(
167
  label="Ticker Symbol / Keyword",
168
  placeholder="เช่น AAPL, TSLA, AI, cryptocurrency",
169
  info="ใส่เฉพาะเมื่อเลือก Stock Symbol หรือ Keyword"
170
  )
171
-
172
  num_articles = gr.Slider(
173
  minimum=5,
174
  maximum=20,
@@ -176,9 +157,7 @@ with gr.Blocks(title="Yahoo Finance News Analyzer", theme=gr.themes.Soft()) as d
176
  step=1,
177
  label="จำนวนข่าว"
178
  )
179
-
180
  analyze_btn = gr.Button("🔍 วิเคราะห์ข่าว", variant="primary", size="lg")
181
-
182
  status = gr.Textbox(label="สถานะ", interactive=False)
183
 
184
  with gr.Column(scale=2):
@@ -209,9 +188,8 @@ with gr.Blocks(title="Yahoo Finance News Analyzer", theme=gr.themes.Soft()) as d
209
  - **Sentiment:** Positive (ดี), Negative (แย่), Neutral (กลาง)
210
  - **Theme:** หัวข้อหลักของข่าว (เช่น ผลประกอบการ, สินค้าใหม่)
211
  - **Impact:** ผลกระทบต่อบริษัท (🟢 Opportunity - โอกาส, 🔴 Risk - ความเสี่ยง)
212
- """) # --- MODIFIED ---
213
 
214
- # Connect button to function
215
  analyze_btn.click(
216
  fn=analyze_news,
217
  inputs=[search_type, search_input, num_articles],
 
1
  import gradio as gr
2
  import pandas as pd
3
  from scraper import YahooFinanceScraper
4
+ from sentiment_analyzer import NewsAnalyzer # Import new class
5
  import time
6
+ from collections import Counter # For counting themes/impacts
7
 
8
  # Initialize components
9
+ print("Initializing Yahoo Finance News Analyzer...")
10
  scraper = YahooFinanceScraper()
11
+ analyzer = NewsAnalyzer() # Use new class
12
 
13
  def get_sentiment_color(sentiment):
14
  """กำหนดสีตาม sentiment"""
15
+ colors = { "Positive": "🟢", "Negative": "🔴", "Neutral": "🟡" }
 
 
 
 
16
  return colors.get(sentiment, "⚪")
17
 
 
18
  def get_impact_color(impact):
19
  """กำหนดสีตาม impact"""
20
+ colors = { "Opportunity": "🟢", "Risk": "🔴", "Neutral": "🟡" }
 
 
 
 
21
  return colors.get(impact, "⚪")
22
 
23
  def analyze_news(search_type, search_input, num_articles):
 
25
  ฟังก์ชันหลักในการวิเคราะห์ข่าว
26
  """
27
  try:
 
28
  yield "กำลังดึงข่าว...", None, None
29
 
 
30
  if search_type == "Latest News":
31
  news_list = scraper.get_latest_news(max_articles=int(num_articles))
32
  elif search_type == "Stock Symbol":
 
46
 
47
  yield f"พบข่าว {len(news_list)} รายการ | กำลังวิเคราะห์ sentiment, theme, และ impact...", None, None
48
 
 
49
  results = analyzer.analyze_batch(news_list)
50
 
51
  # Create summary statistics
 
55
  neutral = sum(1 for r in results if r['sentiment'] == 'Neutral')
56
  avg_score = sum(r['score'] for r in results) / total if total > 0 else 0
57
 
 
58
  theme_counts = Counter(r.get('theme', 'N/A') for r in results)
59
  impact_counts = Counter(r.get('impact', 'N/A') for r in results)
60
 
 
61
  if positive > negative and positive > neutral:
62
  overall = "📈 Positive (Bullish)"
63
  elif negative > positive and negative > neutral:
 
65
  else:
66
  overall = "📊 Neutral"
67
 
 
68
  summary = f"""## 📊 สรุปผลการวิเคราะห์
69
  **ภาพรวม:** {overall} | **คะแนนเฉลี่ย:** {avg_score:.2f}/1.0
70
 
 
92
  s_emoji = get_sentiment_color(result['sentiment'])
93
  i_emoji = get_impact_color(result.get('impact', 'N/A'))
94
 
95
+ # --- MODIFIED: Re-added 'summary' and kept 'explanation' ---
96
  detailed_results += f"""### {i}. {s_emoji} {result['title']}
97
  **Theme:** {result.get('theme', 'N/A')} | **Impact:** {i_emoji} {result.get('impact', 'N/A')}
98
  **Sentiment:** {result['sentiment']} | **Score:** {result['score']:.2f}
99
  **เผยแพร่:** {result['published']}
100
+ **สรุปข่าว:** {result['summary'][:200]}{'...' if len(result['summary']) > 200 else ''}
101
  **คำอธิบาย AI:** {result['explanation']}
102
  [🔗 อ่านต่อ]({result['link']})
103
  ---"""
 
105
  # Create DataFrame for table view
106
  df_data = []
107
  for result in results:
 
108
  df_data.append({
109
  'Title': result['title'][:60] + '...' if len(result['title']) > 60 else result['title'],
110
  'Theme': result.get('theme', 'N/A'),
 
116
  })
117
 
118
  df = pd.DataFrame(df_data)
 
119
  final_output = summary + detailed_results
120
 
121
  yield final_output, df, "✅ วิเคราะห์เสร็จสมบูรณ์!"
 
124
  error_msg = f"❌ เกิดข้อผิดพลาด: {str(e)}"
125
  yield error_msg, None, error_msg
126
 
127
+ # Create Gradio Interface (No changes needed here, keeping it as is)
128
+ with gr.Blocks(title="Yahoo Finance News Analyzer", theme=gr.themes.Soft()) as demo:
 
129
  gr.Markdown("""
130
  # 📈 Yahoo Finance News Analyzer
131
  วิเคราะห์ข่าวการเงินจาก Yahoo Finance ด้วย AI แบบครบวงจร
 
136
  - วิเคราะห์ Impact (ผลกระทบ: โอกาส หรือ ความเสี่ยง)
137
  - ให้คะแนนความมั่นใจและคำอธิบาย
138
  - รองรับค้นหาตาม Stock Symbol และ Keyword
139
+ """)
140
 
141
  with gr.Row():
142
  with gr.Column(scale=1):
 
145
  value="Latest News",
146
  label="ประเภทการค้นหา"
147
  )
 
148
  search_input = gr.Textbox(
149
  label="Ticker Symbol / Keyword",
150
  placeholder="เช่น AAPL, TSLA, AI, cryptocurrency",
151
  info="ใส่เฉพาะเมื่อเลือก Stock Symbol หรือ Keyword"
152
  )
 
153
  num_articles = gr.Slider(
154
  minimum=5,
155
  maximum=20,
 
157
  step=1,
158
  label="จำนวนข่าว"
159
  )
 
160
  analyze_btn = gr.Button("🔍 วิเคราะห์ข่าว", variant="primary", size="lg")
 
161
  status = gr.Textbox(label="สถานะ", interactive=False)
162
 
163
  with gr.Column(scale=2):
 
188
  - **Sentiment:** Positive (ดี), Negative (แย่), Neutral (กลาง)
189
  - **Theme:** หัวข้อหลักของข่าว (เช่น ผลประกอบการ, สินค้าใหม่)
190
  - **Impact:** ผลกระทบต่อบริษัท (🟢 Opportunity - โอกาส, 🔴 Risk - ความเสี่ยง)
191
+ """)
192
 
 
193
  analyze_btn.click(
194
  fn=analyze_news,
195
  inputs=[search_type, search_input, num_articles],