深度学习

2020 金融分析—线性回归和决策树

2020-06-21  本文已影响0人  zidea
cover

引入依赖

import numpy as np
import pandas as pd
from sklearn.tree import DecisionTreeRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
import matplotlib.pyplot as plt

import pandas_datareader as web

plt.style.use('bmh')

准备数据

df = web.DataReader("AAPL",data_source='yahoo',start='2012-01-01',end='2019,12,12')
df.head()

读取 AAPL (苹果的股价) 评估的股票数据,给出一个时间段是我们要研究的几年的数据。


plt.figure(figsize=(16,8))
plt.title("Apple")
plt.xlabel("Days")
plt.ylabel('Close price USD($)')
plt.plot(df['Close'])
plt.show()
Apple 股市走势

我们将 Apple 近几年的股价波动以图形式显示出来,我们之前在时序问题中已经了解到无论时序多么多变我们都可以将其进行因素分解分解为

df = df[['Close']]
df.head()

我们只关心 Close(收盘)这列数据,所以仅保留 Close 这列数据。

future_days = 25
df['Prediction'] = df[['Close']].shift(-future_days)

然后调用 shift 将 Close 数据向上移动 future_days 位置,这样在数据末尾就留出 future_days 个空位,用 NaN 进行站位的数据。

X = np.array(df.drop(['Prediction'],1))[:-future_days]

接下来工作就是,提取标签和数据,然后将数据进行分离为训练数据集和测试数据集。

y = np.array(df['Prediction'])[:-future_days]
x_train,x_test,y_train,y_test = train_test_split(X,y,test_size=0.25)

创建模型,这里创建树预测模型和线性回归模型

tree = DecisionTreeRegressor().fit(x_train,y_train)
lr = LinearRegression().fit(x_train,y_train)
x_future = df.drop(['Prediction'],1)[:-future_days]
x_future = x_future.tail(future_days)
x_future = np.array(x_future)
tree_prediction = tree.predict(x_future)
lr_prediction = lr.predict(x_future)
predictions = tree_prediction
valid = df[X.shape[0]:]

valid['Prediction'] = predictions
plt.figure(figsize=(16,8))
print(valid)
plt.title('Model')
plt.xlabel('Days')
plt.ylabel('Close Price USD($)')
plt.plot(df['Close'])
plt.plot(valid[['Close','Prediction']])
plt.legend(['Orig','Val','Pred'])

通过对 predictions 进行给 lr_prediction 或 tree_prediction 不同值来观察预测效果。

上一篇 下一篇

猜你喜欢

热点阅读