DAY 29
2
AI & Data

## [Day29] 使用Prophet預測股票

### 前言

(圖片來源Url)

Modeling：建立時間序列的模型。這邊使用股票來做模型。
Forecast Evaluation：模型評估。
Surface Problems：呈現問題。
Visually Inspect Forecasts：以視覺化的方式呈現預測結果。

### 前置作業

``````conda install -c conda-forge fbprophet
``````

### 預先載入套件

``````# basic
import numpy as np
import pandas as pd

# get data

# visual
import matplotlib.pyplot as plt
%matplotlib inline

#time
import datetime as datetime

#Prophet
from fbprophet import Prophet

from sklearn import metrics
``````

### 讀取股票

2492：華新科

``````start = datetime.datetime(2015,1,5)
``````

### 收盤價

``````plt.style.use('ggplot')
``````

### 使用Prophet來預測股票

``````new_df_df_2492['y'] = np.log(new_df_df_2492['y'])
# 定義模型
model = Prophet()

# 訓練模型
model.fit(new_df_df_2492)

# 建構預測集
future = model.make_future_dataframe(periods=365) #forecasting for 1 year from now.

# 進行預測
forecast = model.predict(future)

figure=model.plot(forecast)
``````

``````df_2492_close = pd.DataFrame(df_2492['Adj Close'])
two_years = forecast.set_index('ds').join(df_2492_close)
two_years = two_years[['Adj Close', 'yhat', 'yhat_upper', 'yhat_lower' ]].dropna().tail(800)
two_years['yhat']=np.exp(two_years.yhat)
two_years['yhat_upper']=np.exp(two_years.yhat_upper)
two_years['yhat_lower']=np.exp(two_years.yhat_lower)
``````

### 計算誤差

``````two_years_AE = (two_years.yhat - two_years['Adj Close'])
two_years_AE.describe()
``````
``````# 輸出結果
count    800.000000
mean      -1.451949
std       14.302471
min      -88.053614
25%       -2.389504
50%        0.129703
75%        2.074819
max       64.853188
dtype: float64
``````

• MSE：均方誤差
``````print ("MSE:",metrics.mean_squared_error(two_years.yhat, two_years['Adj Close']))
``````
``````# 輸出結果
MSE: 206.41313426786152
``````

MSE越接近0越好

• MAE：平均絕對誤差
``````print ("MAE:",metrics.mean_absolute_error(two_years.yhat, two_years['Adj Close']))
``````
``````# 輸出結果
MAE: 7.052998896728383
``````

• 加上預測的上下限
``````fig, ax1 = plt.subplots(figsize=(10, 8))
ax1.plot(two_years.yhat)
ax1.plot(two_years.yhat_upper, color='black',  linestyle=':', alpha=0.5)
ax1.plot(two_years.yhat_lower, color='black',  linestyle=':', alpha=0.5)

ax1.set_title('華新科技實際和預測的誤差')
ax1.set_ylabel('Price')
ax1.set_xlabel('Date')
``````

Prophet

### 之前的章節

• 安裝環境
• 股票
• 程式碼位置
• github
因為作者本身也是第一次學習Python和寫程式文章，也是才碰股票沒幾天而已，所以編排上會有點亂，觀念可能也會錯誤，如果有疑問可以提出一起討論。

python 入門到分析股市30

### 1 則留言

0
draguitar
iT邦新手 5 級 ‧ 2019-08-19 15:16:06

new_df_df_2492['y'] = np.log(new_df_df_2492['y'])
NameError: name 'new_df_df_2492' is not defined

Summer iT邦新手 5 級 ‧ 2019-08-19 15:20:23 檢舉

https://github.com/lastsummer/learn_python_data_analysis/blob/master/06.stock/day29.ipynb 這裡有完整程式，在文章中沒有加上定義的程式碼。所以會出現not defined

draguitar iT邦新手 5 級 ‧ 2019-08-20 16:48:39 檢舉