欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

时间序列(五)股票分析

程序员文章站 2024-01-28 09:35:10
...

首先导入相关模块

import pandas as pd
import pandas_datareader
import datetime
import matplotlib.pylab as plt
import seaborn as sns
from matplotlib.pylab import style
from statsmodels.tsa.arima_model import ARIMA
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf

设置样式

style.use('ggplot')    
plt.rcParams['font.sans-serif'] = ['SimHei'] 
plt.rcParams['axes.unicode_minus'] = False  

读入数据

stockFile = 'data/T10yr.csv'
stock = pd.read_csv(stockFile, index_col=0, parse_dates=[0])
stock.head(10)

时间序列(五)股票分析

重采样

stock_week = stock['Close'].resample('W-MON').mean()
stock_train = stock_week['2000':'2015']

画图

stock_train.plot(figsize=(12,8))
plt.legend(bbox_to_anchor=(1.25, 0.5))
plt.title("Stock Close")
sns.despine()
plt.show()

时间序列(五)股票分析

发现波动太大,于是做一阶差分

stock_diff = stock_train.diff()
stock_diff = stock_diff.dropna()

plt.figure()
plt.plot(stock_diff)
plt.title('一阶差分')
plt.show()

时间序列(五)股票分析

接下来通过acf,pacf确定模型的p值以及q值

fig=plt.figure()
ax1=fig.add_subplot(211)
ax2=fig.add_subplot(212)
acf = plot_acf(stock_diff, lags=20,ax=ax1,title="ACF")
pacf = plot_pacf(stock_diff, lags=20,ax=ax2,title="PACF")
plt.show()

时间序列(五)股票分析

可以看出p,q分别取1就可以了

训练

model = ARIMA(stock_train, order=(1, 1, 1),freq='W-MON')
result = model.fit()

预测

pred = result.predict('20140609', '20160701',dynamic=True, typ='levels')
print (pred)

预测结果
2014-06-09 2.463559
2014-06-16 2.455539
2014-06-23 2.449569
2014-06-30 2.444183
2014-07-07 2.438962
2014-07-14 2.433788
2014-07-21 2.428627
2014-07-28 2.423470
2014-08-04 2.418315
2014-08-11 2.413159
2014-08-18 2.408004
2014-08-25 2.402849
2014-09-01 2.397693
2014-09-08 2.392538
2014-09-15 2.387383
2014-09-22 2.382227
2014-09-29 2.377072
2014-10-06 2.371917
2014-10-13 2.366761
2014-10-20 2.361606
2014-10-27 2.356451
2014-11-03 2.351296
2014-11-10 2.346140
2014-11-17 2.340985
2014-11-24 2.335830
2014-12-01 2.330674
2014-12-08 2.325519
2014-12-15 2.320364
2014-12-22 2.315208
2014-12-29 2.310053

2015-12-07 2.057443
2015-12-14 2.052288
2015-12-21 2.047132
2015-12-28 2.041977
2016-01-04 2.036822
2016-01-11 2.031666
2016-01-18 2.026511
2016-01-25 2.021356
2016-02-01 2.016200
2016-02-08 2.011045
2016-02-15 2.005890
2016-02-22 2.000735
2016-02-29 1.995579
2016-03-07 1.990424
2016-03-14 1.985269
2016-03-21 1.980113
2016-03-28 1.974958
2016-04-04 1.969803
2016-04-11 1.964647
2016-04-18 1.959492
2016-04-25 1.954337
2016-05-02 1.949181
2016-05-09 1.944026
2016-05-16 1.938871
2016-05-23 1.933716
2016-05-30 1.928560
2016-06-06 1.923405
2016-06-13 1.918250
2016-06-20 1.913094
2016-06-27 1.907939
Freq: W-MON, Length: 108, dtype: float64

图像展示结果

plt.figure(figsize=(6, 6))
plt.xticks(rotation=45)
plt.plot(pred)
plt.plot(stock_train)
plt.show()

时间序列(五)股票分析

相关标签: 股票 pd sns

上一篇: wpf listview images

下一篇: 边缘检测