Spaces:
Sleeping
Sleeping
File size: 1,997 Bytes
aaa66d0 |
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 |
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
|