cutechicken's picture
Update app.py
b6d676c verified
Raw
History Blame Contribute Delete
22.7 kB
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
import yfinance as yf
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")
# 상μž₯ μ’…λͺ© 심볼 맀핑을 μœ„ν•œ 일반적인 μ’…λͺ©λͺ… 사전 (ν•„μš”μ— 따라 ν™•μž₯)
COMMON_TICKERS = {
"apple": "AAPL",
"microsoft": "MSFT",
"amazon": "AMZN",
"google": "GOOGL",
"alphabet": "GOOGL",
"facebook": "META",
"meta": "META",
"tesla": "TSLA",
"nvidia": "NVDA",
"netflix": "NFLX",
"amd": "AMD",
"intel": "INTC",
"ibm": "IBM",
"oracle": "ORCL",
"paypal": "PYPL",
"adobe": "ADBE",
"cisco": "CSCO",
"bitcoin": "BTC-USD",
"ethereum": "ETH-USD",
"dogecoin": "DOGE-USD",
"cardano": "ADA-USD",
"xrp": "XRP-USD",
"litecoin": "LTC-USD",
"samsung": "005930.KS", # ν•œκ΅­ μ‚Όμ„±μ „μž
"hyundai": "005380.KS", # ν˜„λŒ€μžλ™μ°¨
"sk hynix": "000660.KS", # SKν•˜μ΄λ‹‰μŠ€
"lg": "003550.KS", # LG
"lge": "066570.KS", # LGμ „μž
"ncsoft": "036570.KS", # μ—”μ”¨μ†Œν”„νŠΈ
"kakao": "035720.KS", # 카카였
"naver": "035420.KS", # 넀이버
"ν˜„λŒ€μ°¨": "005380.KS", # ν˜„λŒ€μžλ™μ°¨
"μ‚Όμ„±μ „μž": "005930.KS", # μ‚Όμ„±μ „μž
"μ‚Όμ„±": "005930.KS", # μ‚Όμ„±μ „μž
"카카였": "035720.KS", # 카카였
"넀이버": "035420.KS", # 넀이버
}
def fetch_articles(query, max_articles=30):
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 <= 10: # μ΅œλŒ€ 10νŽ˜μ΄μ§€κΉŒμ§€λ§Œ μ‹œλ„
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_time_weight(article_date_str):
"""
기사 μ‹œκ°„ κΈ°μ€€μœΌλ‘œ κ°€μ€‘μΉ˜ 계산
- 1μ‹œκ°„ λ‚΄ κΈ°μ‚¬λŠ” 24% κ°€μ€‘μΉ˜
- μ‹œκ°„μ΄ μ§€λ‚ μˆ˜λ‘ 1%μ”© κ°μ†Œ (μ΅œμ†Œ 1%)
- 예: 1μ‹œκ°„ λ‚΄ 기사 = 24%, 10μ‹œκ°„ μ „ 기사 = 15%, 24μ‹œκ°„ μ „ 기사 = 1%
- 24μ‹œκ°„ 이상이면 1%둜 κ³ μ •
"""
try:
# 기사 λ‚ μ§œ λ¬Έμžμ—΄ νŒŒμ‹± (λ‹€μ–‘ν•œ ν˜•μ‹ 처리)
date_formats = [
'%a, %d %b %Y %H:%M:%S %z', # κΈ°λ³Έ GoogleNews ν˜•μ‹
'%Y-%m-%d %H:%M:%S',
'%a, %d %b %Y %H:%M:%S',
'%Y-%m-%dT%H:%M:%S%z',
'%a %b %d, %Y',
'%d %b %Y'
]
parsed_date = None
for format_str in date_formats:
try:
parsed_date = datetime.strptime(article_date_str, format_str)
break
except ValueError:
continue
# μ–΄λ–€ ν˜•μ‹μœΌλ‘œλ„ νŒŒμ‹±ν•  수 μ—†μœΌλ©΄ ν˜„μž¬ μ‹œκ°„ κΈ°μ€€ 24μ‹œκ°„ μ „μœΌλ‘œ κ°€μ •
if parsed_date is None:
logging.warning(f"Could not parse date: {article_date_str}, using default 24h ago")
return 0.01 # μ΅œμ†Œ κ°€μ€‘μΉ˜ 1%
# ν˜„μž¬ μ‹œκ°„κ³Όμ˜ 차이 계산 (μ‹œκ°„ λ‹¨μœ„)
now = datetime.now()
if parsed_date.tzinfo is not None:
now = now.replace(tzinfo=parsed_date.tzinfo)
hours_diff = (now - parsed_date).total_seconds() / 3600
# 24μ‹œκ°„ 이내인 경우만 κ³ λ €
if hours_diff < 1: # 1μ‹œκ°„ 이내
return 0.24 # 24% κ°€μ€‘μΉ˜
elif hours_diff < 24: # 1~23μ‹œκ°„
# 1μ‹œκ°„λ‹Ή 1%μ”© κ°μ†Œ (1μ‹œκ°„ = 24%, 2μ‹œκ°„ = 23%, ...)
return max(0.01, 0.24 - ((hours_diff - 1) * 0.01))
else:
return 0.01 # 24μ‹œκ°„ 이상 μ§€λ‚œ κΈ°μ‚¬λŠ” 1% κ°€μ€‘μΉ˜
except Exception as e:
logging.error(f"Error calculating time weight: {e}")
return 0.01 # 였λ₯˜ λ°œμƒ μ‹œ μ΅œμ†Œ κ°€μ€‘μΉ˜ 적용
def calculate_sentiment_score(sentiment_label, time_weight):
"""
감성 λ ˆμ΄λΈ”μ— λ”°λ₯Έ κΈ°λ³Έ 점수 계산 및 μ‹œκ°„ κ°€μ€‘μΉ˜ 적용
- positive: +3점
- neutral: 0점
- negative: -3점
μ‹œκ°„ κ°€μ€‘μΉ˜λŠ” λ°±λΆ„μœ¨λ‘œ 적용 (κΈ°λ³Έ μ μˆ˜μ— κ°€μ€‘μΉ˜ % 만큼 μΆ”κ°€)
예:
- 1μ‹œκ°„ λ‚΄ 긍정 기사: 3점 + (3 * 24%) = 3 + 0.72 = 3.72점
- 10μ‹œκ°„ μ „ λΆ€μ • 기사: -3점 + (-3 * 15%) = -3 - 0.45 = -3.45점
"""
base_score = {
'positive': 3,
'neutral': 0,
'negative': -3
}.get(sentiment_label, 0)
# κ°€μ€‘μΉ˜λ₯Ό μ μš©ν•œ μΆ”κ°€ 점수 계산
weighted_addition = base_score * time_weight
return base_score, weighted_addition
def get_stock_ticker(asset_name):
"""
μžμ‚°λͺ…μœΌλ‘œλΆ€ν„° 주식 티컀 심볼을 μΆ”μΆœ
"""
logging.info(f"Identifying ticker for: {asset_name}")
# μ†Œλ¬Έμžλ‘œ λ³€ν™˜ν•˜μ—¬ λ§€ν•‘ 확인
asset_lower = asset_name.lower().strip()
# 직접 ν‹°μ»€λ‘œ μž…λ ₯ν•œ 경우 (λŒ€λ¬Έμž 3-5자 ν˜•νƒœ)
if asset_name.isupper() and 2 <= len(asset_name) <= 6:
logging.info(f"Input appears to be a ticker symbol: {asset_name}")
return asset_name
# 일반적인 μ’…λͺ©λͺ… λ§€ν•‘ 확인
if asset_lower in COMMON_TICKERS:
ticker = COMMON_TICKERS[asset_lower]
logging.info(f"Found ticker in common tickers map: {ticker}")
return ticker
# μ—¬λŸ¬ λ‹¨μ–΄λ‘œ 된 μ΄λ¦„μ˜ 각 뢀뢄에 λŒ€ν•œ 검색도 μ‹œλ„
asset_parts = asset_lower.split()
for part in asset_parts:
if part in COMMON_TICKERS:
ticker = COMMON_TICKERS[part]
logging.info(f"Found ticker for part '{part}': {ticker}")
return ticker
# κ·Έ μ™Έμ˜ 경우 직접 ν‹°μ»€λ‘œ μ‹œλ„
potential_ticker = asset_name.upper().replace(" ", "")
if 2 <= len(potential_ticker) <= 6:
# μ‹€μ œλ‘œ μ‘΄μž¬ν•˜λŠ”μ§€ 확인
try:
logging.info(f"Trying potential ticker: {potential_ticker}")
test_data = yf.download(potential_ticker, period="1d", progress=False)
if not test_data.empty:
logging.info(f"Valid ticker found: {potential_ticker}")
return potential_ticker
except Exception as e:
logging.debug(f"Error testing potential ticker: {e}")
# κ·Έ μ™Έμ˜ 경우 yfinance둜 검색 μ‹œλ„ (info 데이터)
try:
# 일뢀 ν‹°μ»€λŠ” 직접 yfinance 기반 κ²€μƒ‰μœΌλ‘œλŠ” 였λ₯˜κ°€ λ°œμƒν•  수 있음
ticker_search = yf.Ticker(asset_name)
try:
info = ticker_search.info
if 'symbol' in info and info['symbol']:
ticker = info['symbol']
logging.info(f"Found ticker from info API: {ticker}")
return ticker
except (ValueError, KeyError, TypeError) as e:
logging.debug(f"Error getting ticker info: {e}")
pass
except Exception as e:
logging.debug(f"Error initializing ticker object: {e}")
# μΆ”κ°€ μ‹œλ„: 일반적인 λ―Έκ΅­ μ¦μ‹œ 티컀 ν˜•μ‹ 확인
major_exchanges = ["", ".KS", ".KQ", "-USD"] # μ£Όμš” κ±°λž˜μ†Œ 접미사 (ν•œκ΅­ 포함)
for exchange in major_exchanges:
try:
test_ticker = f"{asset_name.upper().replace(' ', '')}{exchange}"
logging.info(f"Trying with exchange suffix: {test_ticker}")
test_data = yf.download(test_ticker, period="1d", progress=False)
if not test_data.empty:
logging.info(f"Valid ticker found with suffix: {test_ticker}")
return test_ticker
except:
pass
logging.warning(f"Could not identify ticker for: {asset_name}")
return None
def create_stock_chart(ticker, period="1mo"):
"""
주식 티컀에 λŒ€ν•œ 차트 생성
"""
try:
logging.info(f"Fetching stock data for {ticker}")
# Graceful handling for problematic symbols
try:
stock_data = yf.download(ticker, period=period, progress=False)
except Exception as dl_error:
logging.error(f"Error downloading stock data: {dl_error}")
# Try alternative symbol format
if "-" in ticker:
alt_ticker = ticker.replace("-", ".")
logging.info(f"Trying alternative ticker format: {alt_ticker}")
stock_data = yf.download(alt_ticker, period=period, progress=False)
else:
raise dl_error
if len(stock_data) == 0:
logging.warning(f"No stock data found for ticker: {ticker}")
return None
# 데이터 확인 및 디버그 λ‘œκΉ…
logging.info(f"Downloaded data shape: {stock_data.shape}")
logging.info(f"Data columns: {stock_data.columns.tolist()}")
# κ·Έλž˜ν”„ μž‘μ„±
fig, ax = plt.subplots(figsize=(10, 6))
# μ’…κ°€ κ·Έλž˜ν”„ - λ©€ν‹°μΈλ±μŠ€ 처리
if isinstance(stock_data.columns, pd.MultiIndex):
# λ©€ν‹°μΈλ±μŠ€μΈ 경우 ('Close', ticker) ν˜•νƒœ
close_col = ('Close', ticker)
if close_col in stock_data.columns:
ax.plot(stock_data.index, stock_data[close_col], label='Close Price', color='blue')
# 이동평균선 μΆ”κ°€ (20일)
if len(stock_data) > 20:
stock_data['MA20'] = stock_data[close_col].rolling(window=20).mean()
ax.plot(stock_data.index, stock_data['MA20'], label='20-day MA', color='orange')
# κ±°λž˜λŸ‰ μ„œλΈŒν”Œλ‘― μΆ”κ°€ (κ±°λž˜λŸ‰μ΄ μžˆλŠ” 경우만)
volume_col = ('Volume', ticker)
if volume_col in stock_data.columns and not stock_data[volume_col].isna().all():
ax2 = ax.twinx()
ax2.bar(stock_data.index, stock_data[volume_col], alpha=0.3, color='gray', label='Volume')
ax2.set_ylabel('Volume')
# λ²”λ‘€ μΆ”κ°€ (κ±°λž˜λŸ‰ μžˆλŠ” 경우)
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax.legend(lines + lines2, labels + labels2, loc='upper left')
else:
# κ±°λž˜λŸ‰ μ—†λŠ” 경우 μ’…κ°€λ§Œ ν‘œμ‹œ
ax.legend(loc='upper left')
else:
raise ValueError(f"Close column not found in data columns: {stock_data.columns}")
else:
# 일반 인덱슀인 경우
if 'Close' in stock_data.columns:
ax.plot(stock_data.index, stock_data['Close'], label='Close Price', color='blue')
# 이동평균선 μΆ”κ°€ (20일)
if len(stock_data) > 20:
stock_data['MA20'] = stock_data['Close'].rolling(window=20).mean()
ax.plot(stock_data.index, stock_data['MA20'], label='20-day MA', color='orange')
# κ±°λž˜λŸ‰ μ„œλΈŒν”Œλ‘― μΆ”κ°€ (κ±°λž˜λŸ‰μ΄ μžˆλŠ” 경우만)
if 'Volume' in stock_data.columns and not stock_data['Volume'].isna().all():
ax2 = ax.twinx()
ax2.bar(stock_data.index, stock_data['Volume'], alpha=0.3, color='gray', label='Volume')
ax2.set_ylabel('Volume')
# λ²”λ‘€ μΆ”κ°€ (κ±°λž˜λŸ‰ μžˆλŠ” 경우)
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax.legend(lines + lines2, labels + labels2, loc='upper left')
else:
# κ±°λž˜λŸ‰ μ—†λŠ” 경우 μ’…κ°€λ§Œ ν‘œμ‹œ
ax.legend(loc='upper left')
else:
raise ValueError(f"Close column not found in data columns: {stock_data.columns}")
# 차트 μŠ€νƒ€μΌλ§
ax.set_title(f"{ticker} Stock Price")
ax.set_xlabel('Date')
ax.set_ylabel('Price')
ax.grid(True, alpha=0.3)
plt.tight_layout()
# 이미지 μ €μž₯
chart_path = f"stock_chart_{ticker.replace('-', '_').replace('.', '_')}.png"
plt.savefig(chart_path)
plt.close()
logging.info(f"Stock chart created: {chart_path}")
return chart_path
except Exception as e:
logging.error(f"Error creating stock chart for {ticker}: {e}")
# 였λ₯˜ λ°œμƒ μ‹œμ—λ„ κ·Έλž˜ν”„ 생성 μ‹œλ„ (κΈ°λ³Έ ν…μŠ€νŠΈ μ•ˆλ‚΄)
try:
fig, ax = plt.subplots(figsize=(10, 6))
ax.text(0.5, 0.5, f"Unable to load data for {ticker}\nError: {str(e)}",
horizontalalignment='center', verticalalignment='center', transform=ax.transAxes)
ax.set_axis_off()
chart_path = f"stock_chart_error_{ticker.replace('-', '_').replace('.', '_')}.png"
plt.savefig(chart_path)
plt.close()
return chart_path
except:
return None
def analyze_asset_sentiment(asset_name):
logging.info(f"Starting sentiment analysis for asset: {asset_name}")
logging.info("Fetching up to 30 articles")
articles = fetch_articles(asset_name, max_articles=30)
logging.info("Analyzing sentiment of each article")
analyzed_articles = [analyze_article_sentiment(article) for article in articles]
# 각 기사에 λŒ€ν•œ μ‹œκ°„ κ°€μ€‘μΉ˜ 및 감성 점수 계산
for article in analyzed_articles:
time_weight = calculate_time_weight(article["date"])
article["time_weight"] = time_weight
sentiment_label = article["sentiment"]["label"]
base_score, weighted_addition = calculate_sentiment_score(sentiment_label, time_weight)
article["base_score"] = base_score
article["weighted_addition"] = weighted_addition
article["total_score"] = base_score + weighted_addition
logging.info("Sentiment analysis completed")
# μ’…ν•© 점수 계산 및 κ·Έλž˜ν”„ 생성
sentiment_summary = create_sentiment_summary(analyzed_articles, asset_name)
# 주식 티컀 확인 및 차트 생성
stock_chart = None
ticker = get_stock_ticker(asset_name)
if ticker:
logging.info(f"Found ticker {ticker} for asset {asset_name}")
stock_chart = create_stock_chart(ticker)
return convert_to_dataframe(analyzed_articles), sentiment_summary, stock_chart, ticker
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")
# κΈ°λ³Έ 점수 합계
base_score_sum = sum(a["base_score"] for a in analyzed_articles)
# κ°€μ€‘μΉ˜ 적용 점수 합계
weighted_score_sum = sum(a["total_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(15, len(sorted_articles))
display_articles = sorted_articles[:max_display]
dates = [a.get("date", "")[:10] for a in display_articles] # λ‚ μ§œ λΆ€λΆ„λ§Œ ν‘œμ‹œ
scores = [a.get("total_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('Weighted 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}%)
Base Score Sum: {base_score_sum:.2f}
Weighted Score Sum: {weighted_score_sum:.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["Base Score"] = df["base_score"]
df["Weight"] = df["time_weight"].apply(lambda x: f"{x*100:.0f}%")
df["Total Score"] = df["total_score"].apply(lambda x: f"{x:.2f}")
return df[["Sentiment", "Title", "Description", "Date", "Base Score", "Weight", "Total Score"]]
def main():
with gr.Blocks() as iface:
gr.Markdown("# Trading Asset Sentiment Analysis")
gr.Markdown(
"Enter the name of a trading asset, and I'll fetch 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")
# 예제 μž…λ ₯값을 μ½”λ“œμ— μ •μ˜λœ 티컀 λ§€ν•‘μ˜ ν‚€λ“€λ‘œ 반영 (μ€‘λ³΅λ˜μ§€ μ•Šλ„λ‘ μ •λ ¬)
examples_list = sorted(set(COMMON_TICKERS.keys()), key=lambda x: x.lower())
gr.Examples(
examples=examples_list,
inputs=input_asset,
)
# 주식 차트 μ˜μ—­ μΆ”κ°€
with gr.Row():
with gr.Column():
with gr.Blocks():
gr.Markdown("## Stock Chart")
with gr.Row():
stock_chart = gr.Image(type="filepath", label="Stock Price Chart")
ticker_info = gr.Textbox(label="Ticker Symbol")
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", "Base Score", "Weight", "Total Score"],
datatype=["markdown", "html", "markdown", "markdown", "number", "markdown", "markdown"],
wrap=False,
)
analyze_button.click(
analyze_asset_sentiment,
inputs=[input_asset],
outputs=[articles_output, sentiment_summary, stock_chart, ticker_info],
)
logging.info("Launching Gradio interface")
iface.queue().launch()
if __name__ == "__main__":
main()