@Channelchan
2017-03-08T11:26:42.000000Z
字数 1218
阅读 25861
未分类
Linear Regression
计算000001的斜率与截距
import numpy as np
from statsmodels import regression
import statsmodels.api as sm
import matplotlib.pyplot as plt
import tushare as ts
import pandas as pd
import math
def linreg(X,Y):
# Running the linear regression
X = sm.add_constant(X)
model = regression.linear_model.OLS(Y, X).fit()
# print(model.params)
a = model.params[0]
b = model.params[1]
X = X[:, 1]
# Return summary of the regression and plot results
X2 = np.linspace(X.min(), X.max(), 100)
Y_hat = X2 * b + a
plt.scatter(X, Y, alpha=0.3) # Plot the raw data
plt.plot(X2, Y_hat, 'r', alpha=0.9) # Add the regression line, colored in red
plt.xlabel('X Value')
plt.ylabel('Y Value')
plt.show()
return model.summary()
asset = ts.get_k_data('000001', start='2016-01-01', end='2016-12-31', ktype='D',autype='qfq')
asset.index = pd.to_datetime(asset['date'], format='%Y-%m-%d')
asset = asset['close']
benchmark = ts.get_hist_data('sz', start='2016-01-01', end='2016-12-31', ktype='D')[::-1]
benchmark = benchmark['close']
new = pd.concat([asset, benchmark],join='inner', axis=1)
new.columns = ['asset', 'benchmark']
# print(new)
# We have to take the percent changes to get to returns
# Get rid of the first (0th) element because it is NAN
r_a = new['asset'].pct_change()[1:]
r_b = new['benchmark'].pct_change()[1:]
linreg(r_b.values, r_a.values)
MA策略与ChannelBreakOut策略的一元回归