aiqtech commited on
Commit
2af2718
·
verified ·
1 Parent(s): a7925b2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -18
app.py CHANGED
@@ -1,10 +1,14 @@
1
  import gradio as gr
2
  import yfinance as yf
3
  from prophet import Prophet
 
4
  import pandas as pd
5
  from datetime import datetime
6
  import plotly.graph_objects as go
7
 
 
 
 
8
  def download_data(ticker, start_date='2010-01-01'):
9
  """ 주식 데이터를 다운로드하고 포맷을 조정하는 함수 """
10
  data = yf.download(ticker, start=start_date)
@@ -20,37 +24,46 @@ def download_data(ticker, start_date='2010-01-01'):
20
 
21
  def predict_future_prices(ticker, periods=1825):
22
  data = download_data(ticker)
23
-
24
  # Prophet 모델 생성 및 학습
25
- model = Prophet(daily_seasonality=False, weekly_seasonality=False, yearly_seasonality=True)
26
- model.fit(data)
27
-
 
 
 
 
 
 
 
28
  # 미래 데이터 프레임 생성 및 예측
29
- future = model.make_future_dataframe(periods=periods, freq='D')
30
- forecast = model.predict(future)
31
-
 
 
32
  # 예측 결과 그래프 생성
33
- forecast['ds'] = forecast['ds'].dt.strftime('%Y-%m-%d')
34
  fig = go.Figure()
35
- fig.add_trace(go.Scatter(x=forecast['ds'], y=forecast['yhat'], mode='lines', name='Forecast (Blue)'))
 
36
  fig.add_trace(go.Scatter(x=data['ds'], y=data['y'], mode='lines', name='Actual (Black)', line=dict(color='black')))
37
-
38
- return fig, forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]
39
 
40
- # Gradio 인터페이스 설정 실행
41
- with gr.Blocks() as app:
 
42
  with gr.Row():
43
  ticker_input = gr.Textbox(value="AAPL", label="Enter Stock Ticker for Forecast")
44
  periods_input = gr.Number(value=1825, label="Forecast Period (days)")
45
  forecast_button = gr.Button("Generate Forecast")
46
-
47
- forecast_chart = gr.Plot(label="Forecast Chart")
48
- forecast_data = gr.Dataframe(label="Forecast Data")
49
-
50
  forecast_button.click(
51
  fn=predict_future_prices,
52
  inputs=[ticker_input, periods_input],
53
- outputs=[forecast_chart, forecast_data]
54
  )
55
 
56
  app.launch()
 
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 predict_future_prices(ticker, periods=1825):
10
+ data = download_data(ticker)
11
+
12
  def download_data(ticker, start_date='2010-01-01'):
13
  """ 주식 데이터를 다운로드하고 포맷을 조정하는 함수 """
14
  data = yf.download(ticker, start=start_date)
 
24
 
25
  def predict_future_prices(ticker, periods=1825):
26
  data = download_data(ticker)
 
27
  # Prophet 모델 생성 및 학습
28
+ model_prophet = Prophet(daily_seasonality=False, weekly_seasonality=False, yearly_seasonality=True)
29
+ model_prophet.fit(data)
30
+ # 미래 데이터 프레임 생성 및 예측
31
+ future = model_prophet.make_future_dataframe(periods=periods, freq='D')
32
+ forecast_prophet = model_prophet.predict(future)
33
+ # Linear Regression 모델 생성 및 학습
34
+ model_lr = LinearRegression()
35
+ X = pd.to_numeric(pd.Series(range(len(data))))
36
+ y = data['y'].values
37
+ model_lr.fit(X.values.reshape(-1, 1), y)
38
  # 미래 데이터 프레임 생성 및 예측
39
+ future_dates = pd.date_range(start=data['ds'].iloc[-1], periods=periods+1, freq='D')[1:]
40
+ future_lr = pd.DataFrame({'ds': future_dates})
41
+ future_lr['ds'] = future_lr['ds'].dt.strftime('%Y-%m-%d')
42
+ X_future = pd.to_numeric(pd.Series(range(len(data), len(data) + len(future_lr))))
43
+ future_lr['yhat'] = model_lr.predict(X_future.values.reshape(-1, 1))
44
  # 예측 결과 그래프 생성
45
+ forecast_prophet['ds'] = forecast_prophet['ds'].dt.strftime('%Y-%m-%d')
46
  fig = go.Figure()
47
+ fig.add_trace(go.Scatter(x=forecast_prophet['ds'], y=forecast_prophet['yhat'], mode='lines', name='Prophet Forecast (Blue)'))
48
+ fig.add_trace(go.Scatter(x=future_lr['ds'], y=future_lr['yhat'], mode='lines', name='Linear Regression Forecast (Red)', line=dict(color='red')))
49
  fig.add_trace(go.Scatter(x=data['ds'], y=data['y'], mode='lines', name='Actual (Black)', line=dict(color='black')))
50
+ return fig, forecast_prophet[['ds', 'yhat', 'yhat_lower', 'yhat_upper']], future_lr[['ds', 'yhat']]
 
51
 
52
+ css = """footer { visibility: hidden; }"""
53
+
54
+ with gr.Blocks(css=css) as app:
55
  with gr.Row():
56
  ticker_input = gr.Textbox(value="AAPL", label="Enter Stock Ticker for Forecast")
57
  periods_input = gr.Number(value=1825, label="Forecast Period (days)")
58
  forecast_button = gr.Button("Generate Forecast")
59
+ forecast_chart = gr.Plot(label="Forecast Chart")
60
+ forecast_data_prophet = gr.Dataframe(label="Prophet Forecast Data")
61
+ forecast_data_lr = gr.Dataframe(label="Linear Regression Forecast Data")
62
+
63
  forecast_button.click(
64
  fn=predict_future_prices,
65
  inputs=[ticker_input, periods_input],
66
+ outputs=[forecast_chart, forecast_data_prophet, forecast_data_lr]
67
  )
68
 
69
  app.launch()