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

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')
  • numpy 是数据统计和机器学习中都少不了 numpy
  • pandas 是我们加载数据和处理数据好帮手
  • matplotlib 数据可视化的工具,绘制各种线图、柱状图和饼图
  • sklearn 提供的 DecisionTreeRegressor 和 LinearRegression 决策树和线性回归模型

准备数据

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

  • 趋势图
  • 季节性
  • 循环性
  • 随机性
    我们今天要用回归模型对 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 不同值来观察预测效果。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。