File size: 8,191 Bytes
687d3dc 8d3265b 2bdbf95 ac80e92 2bdbf95 8d3265b 97a16e9 ac80e92 97a16e9 ac80e92 97a16e9 8d3265b 97a16e9 ac80e92 97a16e9 8d3265b 97a16e9 8d3265b 97a16e9 8d3265b 97a16e9 8d3265b 97a16e9 8d3265b 97a16e9 8d3265b 97a16e9 2bdbf95 |
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 |
import subprocess
# ํ์ํ ๋ผ์ด๋ธ๋ฌ๋ฆฌ ์ค์น ๋ฐ ์
๋ฐ์ดํธ
subprocess.run(["pip", "install", "--upgrade", "pip"])
subprocess.run(["pip", "install", "--upgrade", "openai", "yfinance", "gradio", "matplotlib", "Pillow"])
import os
import matplotlib.font_manager as fm
import matplotlib.pyplot as plt
import yfinance as yf
import numpy as np
import re # ํ๊ธ๋ง ๋จ๊ธฐ๊ธฐ ์ํ ์ ๊ท ํํ์์ ์ฌ์ฉ
# 1. ๋๋๊ณ ๋ ํฐํธ ์ค์น ๋ฐ ์ ์ฉ
def install_nanum_font():
try:
subprocess.run(["apt-get", "update"], check=True)
subprocess.run(["apt-get", "install", "-y", "fonts-nanum"], check=True)
subprocess.run(["fc-cache", "-fv"], check=True)
except Exception as e:
print(f"ํฐํธ ์ค์น ์ค ์ค๋ฅ๊ฐ ๋ฐ์ํ์ต๋๋ค: {e}")
install_nanum_font()
# ๋๋๊ณ ๋ ํฐํธ ๊ฒฝ๋ก ์ค์ ๋ฐ ๊ฐ์ ์ ์ฉ
font_path = '/usr/share/fonts/truetype/nanum/NanumGothic.ttf'
if os.path.exists(font_path):
fm.fontManager.addfont(font_path)
else:
print("ํฐํธ๋ฅผ ์ฐพ์ ์ ์์ต๋๋ค.")
# ๋๋๊ณ ๋ ํฐํธ ๊ฐ์ ์ ์ฉ
font_prop = fm.FontProperties(fname=font_path)
plt.rcParams['font.family'] = font_prop.get_name()
plt.rcParams['axes.unicode_minus'] = False # ๋ง์ด๋์ค ๋ถํธ ๊นจ์ง ๋ฐฉ์ง
# 2. yfinance๋ก ์ฃผ๊ฐ ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ (์ผ์ฑ์ ์ ์์)
ticker = '005930.KS' # ์ผ์ฑ์ ์ ํฐ์ปค
stock = yf.Ticker(ticker)
stock_data = stock.history(period="max")
# ์ฃผ๊ฐ ๋ฐ์ดํฐ ์ถ๋ ฅ ํ์ธ
print(stock_data.head()) # ์ฃผ๊ฐ ๋ฐ์ดํฐ ์ผ๋ถ ํ์ธ
# 3. ์ฃผ๊ฐ ๋ฐ์ดํฐ ์๊ฐํ (pandas ๋ฐ์ดํฐํ๋ ์์ numpy ๋ฐฐ์ด๋ก ๋ณํํ์ฌ ์ฒ๋ฆฌ)
plt.figure(figsize=(10, 6))
# ์ธ๋ฑ์ค์ ์ข
๊ฐ ๋ฐ์ดํฐ๋ฅผ numpy ๋ฐฐ์ด๋ก ๋ณํ
dates = stock_data.index.to_numpy()
closing_prices = stock_data['Close'].to_numpy()
# ์ฃผ๊ฐ ๋ฐ์ดํฐ ์๊ฐํ
plt.plot(dates, closing_prices, label='์ผ์ฑ์ ์ ์ข
๊ฐ')
# ๊ทธ๋ํ ์ ๋ชฉ, ์ถ ๋ผ๋ฒจ์ ํ๊ธ๋ก ์ค์
plt.title('์ผ์ฑ์ ์ ์ฃผ๊ฐ ์ถ์ด', fontproperties=font_prop)
plt.xlabel('๋ ์ง', fontproperties=font_prop)
plt.ylabel('์ข
๊ฐ', fontproperties=font_prop)
plt.legend(prop=font_prop)
# B ์ฝ๋
# ์ดํ ์ฝ๋ ์คํ
import requests
import gradio as gr
import yfinance as yf
import matplotlib.pyplot as plt
import io
from PIL import Image
from datetime import datetime, timedelta
from openai import OpenAI
# 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
# ํ๊ธ๋ง ์ถ์ถํ๋ ์ ๊ท ํํ์
korean_only_summary = re.sub(r'[^๊ฐ-ํฃ\s]', '', summary)
return korean_only_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๋ฐ์ด์คํ"],
["๋์ค๋ฅ ์์ด 1์"],
["๋์ค๋ฅ ์ ์ฝ์ฃผ ์์ด 1์"],
["๋์ค๋ฅ ๋ฐ์ด์คํ
์์ด 1์"],
["์ฝ์คํผ ์์ด 1์"],
["์ฝ์ค๋ฅ ์์ด 1์"]]
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()
|