StockPulse / app.py
llllllllllllllllllllllllllleeeeeeeeeeeeee's picture
Update app.py
b25c845 verified
raw
history blame
6.73 kB
import subprocess
import sys
import os
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import io
from PIL import Image
from datetime import datetime
import gradio as gr
import yfinance as yf
from openai import OpenAI
import requests
# ํŒจํ‚ค์ง€ ์„ค์น˜ (ํ•„์š”ํ•œ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ ์„ค์น˜ ๋ฐ ์—…๋ฐ์ดํŠธ)
def install_packages():
subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "pip"])
subprocess.check_call([sys.executable, "-m", "pip", "install", "--upgrade", "openai", "yfinance", "gradio", "matplotlib", "Pillow"])
# ํŒจํ‚ค์ง€ ์„ค์น˜
install_packages()
# ๋‚˜๋ˆ”๊ณ ๋”• ํฐํŠธ ๋‹ค์šด๋กœ๋“œ ๋ฐ ์„ค์ •
def download_and_setup_font():
font_url = 'https://github.com/naver/nanumfont/blob/master/ttf/NanumGothic.ttf?raw=true'
font_path = os.path.join(os.path.expanduser("~"), 'NanumGothic.ttf')
response = requests.get(font_url)
with open(font_path, 'wb') as f:
f.write(response.content)
fm.fontManager.addfont(font_path)
font_prop = fm.FontProperties(fname=font_path)
plt.rcParams['font.family'] = font_prop.get_name()
plt.rcParams['axes.unicode_minus'] = False # ๋งˆ์ด๋„ˆ์Šค ๋ถ€ํ˜ธ ๊นจ์ง ๋ฐฉ์ง€
# ํฐํŠธ ์„ค์ •
download_and_setup_font()
# Perplexity AI API ์„ค์ •
API_KEY = "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" # ์—ฌ๊ธฐ์— Perplexity AI API ํ‚ค๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”.
def get_real_news_summary(company, date):
# OpenAI ํด๋ผ์ด์–ธํŠธ ์ดˆ๊ธฐํ™”
client = OpenAI(api_key=API_KEY, base_url="https://api.perplexity.ai")
# API ์š”์ฒญ์„ ์œ„ํ•œ ๋ฉ”์‹œ์ง€ ๊ตฌ์„ฑ
messages = [
{"role": "system", "content": "You are a helpful assistant that summarizes stock news in Korean."},
{"role": "user", "content": f"Summarize the latest stock news for {company} on {date} in Korean. If there's no specific news for that date, provide the most recent relevant information."}
]
try:
# API ์š”์ฒญ
response = client.chat.completions.create(
model="llama-3.1-sonar-large-128k-online",
messages=messages
)
# ์‘๋‹ต์—์„œ ์š”์•ฝ ์ถ”์ถœ
summary = response.choices[0].message.content
return summary
except Exception as e:
return f"๋‰ด์Šค ์š”์•ฝ ์ค‘ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค: {str(e)}"
# ๋‰ด์Šค ์š”์•ฝ์„ ๊ฐ€์ ธ์˜ค๋Š” ํ•จ์ˆ˜
def handle_click(input_value, date_clicked):
return get_real_news_summary(input_value, date_clicked)
# Gradio์—์„œ ์‚ฌ์šฉํ•  ํ•จ์ˆ˜ (๋‰ด์Šค ์š”์•ฝ ํฌํ•จ)
def update_news(input_value, selected_date):
if selected_date == "" or selected_date is None:
return "๋‚ ์งœ๋ฅผ ์„ ํƒํ•ด์ฃผ์„ธ์š”."
else:
return handle_click(input_value, selected_date)
# ์ข…๋ชฉ๋ช…๊ณผ ํ‹ฐ์ปค๋ฅผ ๋งคํ•‘ํ•˜๋Š” ๋”•์…”๋„ˆ๋ฆฌ
name_to_ticker = {
"์‚ผ์„ฑ์ „์ž": "005930.KS",
"SK๋ฐ”์ด์˜คํŒœ": "326030.KS",
"Apple": "AAPL",
# ํ•„์š”ํ•œ ์ข…๋ชฉ๋“ค์„ ์ถ”๊ฐ€ํ•˜์„ธ์š”
}
# ์ฃผ๊ฐ€ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ  ์กฐ๊ฑด์— ๋งž๋Š” ๋‚ ์งœ์™€ ๊ทธ๋ž˜ํ”„๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋Š” ํ•จ์ˆ˜
def display_stock_with_highlight(input_value, change_type, percent_change):
try:
ticker = name_to_ticker.get(input_value, input_value)
stock = yf.Ticker(ticker)
stock_data = stock.history(period="5y") # ์ตœ๊ทผ 5๋…„ ๋ฐ์ดํ„ฐ๋กœ ์ œํ•œ
if stock_data.empty:
return "์ฃผ๊ฐ€ ๋ฐ์ดํ„ฐ๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค.", []
stock_data['Change'] = stock_data['Close'].pct_change() * 100
percent_change = float(percent_change)
if change_type == "์ƒ์Šน":
highlight_data = stock_data[stock_data['Change'] >= percent_change]
color = "darkorange"
elif change_type == "ํ•˜๋ฝ":
highlight_data = stock_data[stock_data['Change'] <= -percent_change]
color = "purple"
else:
return "Invalid change type", []
dates = stock_data.index.to_numpy()
closing_prices = stock_data['Close'].to_numpy()
plt.figure(figsize=(10, 6))
plt.plot(dates, closing_prices, color='gray', label=input_value)
plt.scatter(highlight_data.index, highlight_data['Close'], color=color, label=f'{change_type} ํฌ์ธํŠธ')
for index, row in highlight_data.iterrows():
plt.text(index, row['Close'], index.strftime('%Y-%m-%d'), fontsize=10, fontweight='bold', color=color, ha='right')
plt.axvline(x=index, color=color, linestyle='--', linewidth=1) # x์ถ•๊ณผ์˜ ์—ฐ๊ฒฐ์„  ์ ์„ ์œผ๋กœ ํ‘œ์‹œ
plt.title(f'{input_value} ์ฃผ๊ฐ€ ์ถ”์ด ({change_type} ํ‘œ์‹œ)')
plt.xlabel('๋‚ ์งœ')
plt.ylabel('์ข…๊ฐ€')
plt.legend()
buf = io.BytesIO()
plt.savefig(buf, format='png')
plt.close()
buf.seek(0)
img = Image.open(buf)
highlight_dates = highlight_data.index.strftime('%Y-%m-%d').tolist()
return img, gr.update(choices=highlight_dates)
except Exception as e:
return f"Error processing data: {e}", gr.update(choices=[])
# Gradio ์ธํ„ฐํŽ˜์ด์Šค ์ƒ์„ฑ (3์—ด ๋ ˆ์ด์•„์›ƒ)
with gr.Blocks() as demo:
gr.Markdown("## ์ฃผ๊ฐ€ ๊ทธ๋ž˜ํ”„์™€ ๋‰ด์Šค ์š”์•ฝ")
with gr.Row():
with gr.Column(): # ์ž…๋ ฅ๊ฐ’์„ ๋‹ด์„ ์ฒซ ๋ฒˆ์งธ ์—ด
input_value = gr.Textbox(label="์ข…๋ชฉ๋ช… ๋˜๋Š” ํ‹ฐ์ปค ์ž…๋ ฅ", placeholder="์˜ˆ: SK๋ฐ”์ด์˜คํŒœ, AAPL")
change_type = gr.Dropdown(choices=["์ƒ์Šน", "ํ•˜๋ฝ"], label="์ƒ์Šน ๋˜๋Š” ํ•˜๋ฝ ์„ ํƒ", value="์ƒ์Šน")
percent_change = gr.Textbox(label="๋ณ€๋™ ํผ์„ผํŠธ (%)", placeholder="์˜ˆ: 10", value="10")
submit_btn = gr.Button("Submit")
# ์˜ˆ์ œ
examples = [["SK๋ฐ”์ด์˜คํŒœ"],
["Apple"],
["์‚ผ์„ฑ์ „์ž"],
["005930.KS"],
["AAPL"]]
gr.Examples(examples=examples, inputs=[input_value])
with gr.Column(): # ๊ทธ๋ž˜ํ”„๋ฅผ ์ถœ๋ ฅํ•  ๋‘ ๋ฒˆ์งธ ์—ด
plot = gr.Image(label="์ฃผ๊ฐ€ ๊ทธ๋ž˜ํ”„")
date_dropdown = gr.Dropdown(label="์กฐ๊ฑด์— ํ•ด๋‹นํ•˜๋Š” ๋‚ ์งœ ์„ ํƒ", choices=[])
with gr.Column(): # ๋‰ด์Šค ์š”์•ฝ์„ ์ถœ๋ ฅํ•  ์„ธ ๋ฒˆ์งธ ์—ด
news_output = gr.Textbox(label="๋‰ด์Šค ์š”์•ฝ")
# Submit ๋ฒ„ํŠผ ํด๋ฆญ ์‹œ ๊ทธ๋ž˜ํ”„ ๋ฐ ๋‚ ์งœ ๋“œ๋กญ๋‹ค์šด ์—…๋ฐ์ดํŠธ
submit_btn.click(
fn=display_stock_with_highlight,
inputs=[input_value, change_type, percent_change],
outputs=[plot, date_dropdown]
)
# ๋‚ ์งœ ์„ ํƒ ์‹œ ๋‰ด์Šค ์š”์•ฝ ์—…๋ฐ์ดํŠธ
date_dropdown.change(
fn=update_news,
inputs=[input_value, date_dropdown],
outputs=[news_output]
)
# Gradio ์‹คํ–‰
demo.launch()