股票量化分析(13)——直线拟合、曲线拟合、方差计算
这里直线拟合需要用到statsmodels这个库;曲线拟合需要用到np.polynomial.Chebyshev.fit()这个函数;方差计算需要用到sklearn这个库。首先来看直线拟合,这里拟合’600848’这只股票一年的收市的股价。import tushare as tsimport pandas as pdimport matplotlib.pyplot as pltimpo
·
这里直线拟合需要用到statsmodels这个库;
曲线拟合需要用到np.polynomial.Chebyshev.fit()这个函数;
方差计算需要用到sklearn这个库。
首先来看直线拟合,这里拟合’600848’这只股票一年的收市的股价。
import tushare as ts
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import talib
df=ts.get_hist_data('600848',start='2015-01-01',end='2015-12-31')
df=df.sort_index()
df.index=pd.to_datetime(df.index,format='%Y-%m-%d')
#收市股价
close= df.close
x=np.arange(0,len(close))
y=close.values
import statsmodels.api as sm
from statsmodels import regression
def regress_y(y):
x=np.arange(0,len(y))
x=sm.add_constant(x)
model=regression.linear_model.OLS(y,x).fit()
return model
model=regress_y(close)
b=model.params[0]
k=model.params[1]
y_fit=k*x+b
plt.plot(x,y)
plt.plot(x,y_fit,'r')
接着来看一下用sklearn计算偏差绝对值之和(MAE),偏差平方(MSE),偏差平方和开平方(RMSE)
from sklearn import metrics
MAE=metrics.mean_absolute_error(y,y_fit)
MSE=metrics.mean_squared_error(y,y_fit)
RMSE=np.sqrt(MSE)
最后来看一下多项式拟合,这里取得是9项:
#多项式拟合
p=np.polynomial.Chebyshev.fit(x,y,9)
y_fit_n=p(x)
plt.plot(x,y,'',x,y_fit_n,'r')
更多推荐

所有评论(0)