Spaces:
Paused
Paused
Upload 2 files
Browse files- app.py +85 -0
- requirements.txt +8 -0
app.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
import yfinance as yf
|
| 3 |
+
from prophet import Prophet
|
| 4 |
+
from sklearn.linear_model import LinearRegression
|
| 5 |
+
import pandas as pd
|
| 6 |
+
from datetime import datetime
|
| 7 |
+
import plotly.graph_objects as go
|
| 8 |
+
|
| 9 |
+
def download_data(ticker, start_date='2010-01-01'):
|
| 10 |
+
"""
|
| 11 |
+
주식 데이터를 다운로드하고 포맷을 조정하는 함수
|
| 12 |
+
"""
|
| 13 |
+
data = yf.download(ticker, start=start_date)
|
| 14 |
+
if data.empty:
|
| 15 |
+
raise ValueError(f"No data returned for {ticker}")
|
| 16 |
+
data.reset_index(inplace=True)
|
| 17 |
+
if 'Adj Close' in data.columns:
|
| 18 |
+
data = data[['Date', 'Adj Close']]
|
| 19 |
+
data.rename(columns={'Date': 'ds', 'Adj Close': 'y'}, inplace=True)
|
| 20 |
+
else:
|
| 21 |
+
raise ValueError("Expected 'Adj Close' in columns")
|
| 22 |
+
return data
|
| 23 |
+
|
| 24 |
+
def predict_future_prices(ticker, periods=1825):
|
| 25 |
+
data = download_data(ticker)
|
| 26 |
+
|
| 27 |
+
# Prophet 모델 생성 및 학습
|
| 28 |
+
model_prophet = Prophet(daily_seasonality=False, weekly_seasonality=False, yearly_seasonality=True)
|
| 29 |
+
model_prophet.fit(data)
|
| 30 |
+
|
| 31 |
+
# 미래 데이터 프레임 생성 및 예측
|
| 32 |
+
future = model_prophet.make_future_dataframe(periods=periods, freq='D')
|
| 33 |
+
forecast_prophet = model_prophet.predict(future)
|
| 34 |
+
|
| 35 |
+
# Linear Regression 모델 생성 및 학습
|
| 36 |
+
model_lr = LinearRegression()
|
| 37 |
+
X = pd.to_numeric(pd.Series(range(len(data))))
|
| 38 |
+
y = data['y'].values
|
| 39 |
+
model_lr.fit(X.values.reshape(-1, 1), y)
|
| 40 |
+
|
| 41 |
+
# 미래 데이터 프레임 생성 및 예측
|
| 42 |
+
future_dates = pd.date_range(start=data['ds'].iloc[-1], periods=periods+1, freq='D')[1:]
|
| 43 |
+
future_lr = pd.DataFrame({'ds': future_dates})
|
| 44 |
+
future_lr['ds'] = future_lr['ds'].dt.strftime('%Y-%m-%d')
|
| 45 |
+
X_future = pd.to_numeric(pd.Series(range(len(data), len(data) + len(future_lr))))
|
| 46 |
+
future_lr['yhat'] = model_lr.predict(X_future.values.reshape(-1, 1))
|
| 47 |
+
|
| 48 |
+
# 예측 결과 그래프 생성
|
| 49 |
+
forecast_prophet['ds'] = forecast_prophet['ds'].dt.strftime('%Y-%m-%d')
|
| 50 |
+
fig = go.Figure()
|
| 51 |
+
fig.add_trace(go.Scatter(x=forecast_prophet['ds'], y=forecast_prophet['yhat'], mode='lines', name='Prophet Forecast (Blue)'))
|
| 52 |
+
fig.add_trace(go.Scatter(x=future_lr['ds'], y=future_lr['yhat'], mode='lines', name='Linear Regression Forecast (Red)', line=dict(color='red')))
|
| 53 |
+
fig.add_trace(go.Scatter(x=data['ds'], y=data['y'], mode='lines', name='Actual (Black)', line=dict(color='black')))
|
| 54 |
+
|
| 55 |
+
return fig, forecast_prophet[['ds', 'yhat', 'yhat_lower', 'yhat_upper']], future_lr[['ds', 'yhat']]
|
| 56 |
+
|
| 57 |
+
css = """footer { visibility: hidden; }"""
|
| 58 |
+
|
| 59 |
+
with gr.Blocks(css=css) as app:
|
| 60 |
+
gr.Markdown("""
|
| 61 |
+
<style>
|
| 62 |
+
.markdown-text h2 {
|
| 63 |
+
font-size: 12px; # 폰트 크기를 12px로 설정
|
| 64 |
+
}
|
| 65 |
+
</style>
|
| 66 |
+
<h2>AIQ StockAI: 글로벌 자산(주식, 지수, BTC, 상품 등) 미래 주가 예측 AI 서비스</h2>
|
| 67 |
+
<h2>전세계 모든 티커 보기(야후 파이낸스): <a href="https://finance.yahoo.com/most-active" target="_blank">여기를 클릭</a></h2>
|
| 68 |
+
""")
|
| 69 |
+
|
| 70 |
+
with gr.Row():
|
| 71 |
+
ticker_input = gr.Textbox(value="NVDA", label="Enter Stock Ticker for Forecast")
|
| 72 |
+
periods_input = gr.Number(value=1825, label="Forecast Period (days)")
|
| 73 |
+
forecast_button = gr.Button("Generate Forecast")
|
| 74 |
+
|
| 75 |
+
forecast_chart = gr.Plot(label="Forecast Chart")
|
| 76 |
+
forecast_data_prophet = gr.Dataframe(label="Prophet Forecast Data")
|
| 77 |
+
forecast_data_lr = gr.Dataframe(label="Linear Regression Forecast Data")
|
| 78 |
+
|
| 79 |
+
forecast_button.click(
|
| 80 |
+
fn=predict_future_prices,
|
| 81 |
+
inputs=[ticker_input, periods_input],
|
| 82 |
+
outputs=[forecast_chart, forecast_data_prophet, forecast_data_lr]
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
app.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PyPortfolioOpt
|
| 2 |
+
gradio
|
| 3 |
+
yfinance
|
| 4 |
+
prophet
|
| 5 |
+
plotly
|
| 6 |
+
pandas
|
| 7 |
+
numpy
|
| 8 |
+
scikit-learn
|