File size: 8,726 Bytes
4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf 996aec5 4a2e1bf |
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 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 |
import logging
import gradio as gr
import pandas as pd
import torch
import numpy as np
import matplotlib.pyplot as plt
from GoogleNews import GoogleNews
from transformers import pipeline
from datetime import datetime, timedelta
import matplotlib
matplotlib.use('Agg')
# Set up logging
logging.basicConfig(
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
)
SENTIMENT_ANALYSIS_MODEL = (
"mrm8488/distilroberta-finetuned-financial-news-sentiment-analysis"
)
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
logging.info(f"Using device: {DEVICE}")
logging.info("Initializing sentiment analysis model...")
sentiment_analyzer = pipeline(
"sentiment-analysis", model=SENTIMENT_ANALYSIS_MODEL, device=DEVICE
)
logging.info("Model initialized successfully")
def fetch_articles(query, max_articles=100):
try:
logging.info(f"Fetching up to {max_articles} articles for query: '{query}'")
googlenews = GoogleNews(lang="en")
googlenews.search(query)
# ์ฒซ ํ์ด์ง ๊ฒฐ๊ณผ ๊ฐ์ ธ์ค๊ธฐ
articles = googlenews.result()
# ๋ชฉํ ๊ธฐ์ฌ ์์ ๋๋ฌํ ๋๊น์ง ์ถ๊ฐ ํ์ด์ง ๊ฐ์ ธ์ค๊ธฐ
page = 2
while len(articles) < max_articles and page <= 20: # ์ต๋ 20ํ์ด์ง๊น์ง ์๋
logging.info(f"Fetched {len(articles)} articles so far. Getting page {page}...")
googlenews.get_page(page)
page_results = googlenews.result()
# ์ ๊ฒฐ๊ณผ๊ฐ ์์ผ๋ฉด ์ค๋จ
if not page_results:
logging.info(f"No more results found after page {page-1}")
break
articles.extend(page_results)
page += 1
# ์ต๋ ๊ธฐ์ฌ ์๋ก ์ ํ
articles = articles[:max_articles]
logging.info(f"Successfully fetched {len(articles)} articles")
return articles
except Exception as e:
logging.error(
f"Error while searching articles for query: '{query}'. Error: {e}"
)
raise gr.Error(
f"Unable to search articles for query: '{query}'. Try again later...",
duration=5,
)
def analyze_article_sentiment(article):
logging.info(f"Analyzing sentiment for article: {article['title']}")
sentiment = sentiment_analyzer(article["desc"])[0]
article["sentiment"] = sentiment
return article
def calculate_sentiment_score(sentiment_label):
"""
๊ฐ์ฑ ๋ ์ด๋ธ์ ๋ฐ๋ฅธ ๊ธฐ๋ณธ ์ ์ ๊ณ์ฐ
- positive: +3์
- neutral: 0์
- negative: -3์
"""
base_score = {
'positive': 3,
'neutral': 0,
'negative': -3
}.get(sentiment_label, 0)
return base_score
def analyze_asset_sentiment(asset_name):
logging.info(f"Starting sentiment analysis for asset: {asset_name}")
logging.info("Fetching up to 100 articles")
articles = fetch_articles(asset_name, max_articles=100)
logging.info("Analyzing sentiment of each article")
analyzed_articles = [analyze_article_sentiment(article) for article in articles]
# ๊ฐ ๊ธฐ์ฌ์ ๋ํ ๊ฐ์ฑ ์ ์ ๊ณ์ฐ (๊ฐ์ค์น ์์)
for article in analyzed_articles:
sentiment_label = article["sentiment"]["label"]
article["score"] = calculate_sentiment_score(sentiment_label)
logging.info("Sentiment analysis completed")
# ์ข
ํฉ ์ ์ ๊ณ์ฐ ๋ฐ ๊ทธ๋ํ ์์ฑ
sentiment_summary = create_sentiment_summary(analyzed_articles, asset_name)
return convert_to_dataframe(analyzed_articles), sentiment_summary
def create_sentiment_summary(analyzed_articles, asset_name):
"""
๊ฐ์ฑ ๋ถ์ ๊ฒฐ๊ณผ๋ฅผ ์์ฝํ๊ณ ๊ทธ๋ํ๋ก ์๊ฐํ
"""
total_articles = len(analyzed_articles)
positive_count = sum(1 for a in analyzed_articles if a["sentiment"]["label"] == "positive")
neutral_count = sum(1 for a in analyzed_articles if a["sentiment"]["label"] == "neutral")
negative_count = sum(1 for a in analyzed_articles if a["sentiment"]["label"] == "negative")
# ์ ์ ํฉ๊ณ
score_sum = sum(a["score"] for a in analyzed_articles)
# ๊ทธ๋ํ ์์ฑ
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 6))
# 1. ๊ฐ์ฑ ๋ถํฌ ํ์ด ์ฐจํธ
labels = ['Positive', 'Neutral', 'Negative']
sizes = [positive_count, neutral_count, negative_count]
colors = ['green', 'gray', 'red']
ax1.pie(sizes, labels=labels, colors=colors, autopct='%1.1f%%', startangle=90)
ax1.axis('equal')
ax1.set_title(f'Sentiment Distribution for {asset_name}')
# 2. ๋ ์ง๋ณ ๊ฐ์ฑ ์ ์ (์ ๋ ฌ)
sorted_articles = sorted(analyzed_articles, key=lambda x: x.get("date", ""), reverse=True)
# ์ต๋ ํ์ํ ๊ธฐ์ฌ ์ (๊ฐ๋
์ฑ์ ์ํด)
max_display = min(20, len(sorted_articles))
display_articles = sorted_articles[:max_display]
dates = [a.get("date", "")[:10] for a in display_articles] # ๋ ์ง ๋ถ๋ถ๋ง ํ์
scores = [a.get("score", 0) for a in display_articles]
# ์ ์์ ๋ฐ๋ฅธ ์์ ์ค์
bar_colors = ['green' if s > 0 else 'red' if s < 0 else 'gray' for s in scores]
bars = ax2.bar(range(len(dates)), scores, color=bar_colors)
ax2.set_xticks(range(len(dates)))
ax2.set_xticklabels(dates, rotation=45, ha='right')
ax2.set_ylabel('Sentiment Score')
ax2.set_title(f'Recent Article Scores for {asset_name}')
ax2.axhline(y=0, color='black', linestyle='-', alpha=0.3)
# ์์ฝ ํ
์คํธ ์ถ๊ฐ
summary_text = f"""
Analysis Summary for {asset_name}:
Total Articles: {total_articles}
Positive: {positive_count} ({positive_count/total_articles*100:.1f}%)
Neutral: {neutral_count} ({neutral_count/total_articles*100:.1f}%)
Negative: {negative_count} ({negative_count/total_articles*100:.1f}%)
Total Score Sum: {score_sum:.2f}
Average Score: {score_sum/total_articles:.2f}
"""
plt.figtext(0.5, 0.01, summary_text, ha='center', fontsize=10, bbox={"facecolor":"orange", "alpha":0.2, "pad":5})
plt.tight_layout(rect=[0, 0.1, 1, 0.95])
# ์ด๋ฏธ์ง ์ ์ฅ
fig_path = f"sentiment_summary_{asset_name.replace(' ', '_')}.png"
plt.savefig(fig_path)
plt.close()
return fig_path
def convert_to_dataframe(analyzed_articles):
df = pd.DataFrame(analyzed_articles)
df["Title"] = df.apply(
lambda row: f'<a href="{row["link"]}" target="_blank">{row["title"]}</a>',
axis=1,
)
df["Description"] = df["desc"]
df["Date"] = df["date"]
def sentiment_badge(sentiment):
colors = {
"negative": "red",
"neutral": "gray",
"positive": "green",
}
color = colors.get(sentiment, "grey")
return f'<span style="background-color: {color}; color: white; padding: 2px 6px; border-radius: 4px;">{sentiment}</span>'
df["Sentiment"] = df["sentiment"].apply(lambda x: sentiment_badge(x["label"]))
# ์ ์ ์ปฌ๋ผ ์ถ๊ฐ
df["Score"] = df["score"]
return df[["Sentiment", "Title", "Description", "Date", "Score"]]
with gr.Blocks() as iface:
gr.Markdown("# Trading Asset Sentiment Analysis")
gr.Markdown(
"Enter the name of a trading asset, and I'll fetch up to 100 recent articles and analyze their sentiment!"
)
with gr.Row():
input_asset = gr.Textbox(
label="Asset Name",
lines=1,
placeholder="Enter the name of the trading asset...",
)
with gr.Row():
analyze_button = gr.Button("Analyze Sentiment", size="sm")
gr.Examples(
examples=[
"Bitcoin",
"Tesla",
"Apple",
"Amazon",
],
inputs=input_asset,
)
with gr.Row():
with gr.Column():
with gr.Blocks():
gr.Markdown("## Sentiment Summary")
sentiment_summary = gr.Image(type="filepath", label="Sentiment Analysis Summary")
with gr.Row():
with gr.Column():
with gr.Blocks():
gr.Markdown("## Articles and Sentiment Analysis")
articles_output = gr.Dataframe(
headers=["Sentiment", "Title", "Description", "Date", "Score"],
datatype=["markdown", "html", "markdown", "markdown", "number"],
wrap=False,
)
analyze_button.click(
analyze_asset_sentiment,
inputs=[input_asset],
outputs=[articles_output, sentiment_summary],
)
logging.info("Launching Gradio interface")
iface.queue().launch() |