mytest2_app / utils /plotting.py
cryman38's picture
Upload 14 files
aaa66d0 verified
import base64
import io
import matplotlib.pyplot as plt
import pandas as pd
from concurrent.futures import ThreadPoolExecutor, as_completed
import FinanceDataReader as fdr
def get_stock_prices(stock_code, days):
try:
df = fdr.DataReader(stock_code)
df = df[df.index >= df.index.max() - pd.DateOffset(days=days)] # ์ตœ๊ทผ days์ผ ๋ฐ์ดํ„ฐ๋กœ ์ œํ•œ
return df['Close']
except Exception as e:
print(f"Failed to fetch data for {stock_code}: {e}")
return None
def plot_stock_prices(stock_codes, days):
# ์ฃผ์‹ ๊ทธ๋ž˜ํ”„ ์ƒ์„ฑ์„ ์œ„ํ•œ ๋ณ‘๋ ฌ ์ฒ˜๋ฆฌ
stock_prices = {}
with ThreadPoolExecutor() as executor:
futures = {executor.submit(get_stock_prices, stock_code.strip(), int(days)): stock_code.strip() for stock_code in stock_codes.split(',')}
for future in as_completed(futures):
stock_code = futures[future]
try:
prices = future.result()
if prices is not None:
stock_prices[stock_code] = prices
except Exception as e:
print(f"Failed to fetch data for {stock_code}: {e}")
# ๊ฐ ์ฃผ์‹์— ๋Œ€ํ•œ ๊ทธ๋ž˜ํ”„๋ฅผ ๊ทธ๋ฆผ
plt.figure(figsize=(10, 6))
for stock_code, prices in stock_prices.items():
relative_prices = prices / prices.iloc[0] # ์ฒซ ๋ฒˆ์งธ ๋ฐ์ดํ„ฐ ํฌ์ธํŠธ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์ƒ๋Œ€์  ๊ฐ€๊ฒฉ ๊ณ„์‚ฐ
plt.plot(prices.index, relative_prices, label=stock_code.upper()) # ์ฃผ์‹ ์ฝ”๋“œ๋ฅผ ๋Œ€๋ฌธ์ž๋กœ ํ‘œ์‹œ
plt.xlabel('Date')
plt.ylabel('Relative Price (Normalized to 1)')
plt.title(f'Relative Stock Prices Over the Last {days} Days')
plt.legend()
# ๊ทธ๋ž˜ํ”„๋ฅผ HTML๋กœ ๋ณ€ํ™˜ํ•˜์—ฌ ๋ฐ˜ํ™˜
html_graph = io.BytesIO()
plt.savefig(html_graph, format='png', dpi=300)
html_graph.seek(0)
graph_encoded = base64.b64encode(html_graph.getvalue()).decode()
graph_html = f'<img src="data:image/png;base64,{graph_encoded}"/>'
return graph_html