import numpy as np
import pandas as pd
from pylab import plt
plt.style.use('seaborn')
%matplotlib inline
import pandas_datareader as pdr
start = '2015-01-01'
end = '2019-12-31'
data = pdr.get_data_yahoo('600001',start,end)
data
data_cp = data
data = data['Close']
data.columns = ['prices']
data = pd.DataFrame(data)
data
data.info
data.plot(figsize=(10, 6));
data['returns'] = np.log(data / data.shift(1))
data.head()
lags = 5
cols = []
for lag in range(1, lags+1):
col = 'ret_%d' % lag
data[col] = data['returns'].shift(lag)
cols.append(col)
data
data.dropna(inplace=True)
data.head()
# OLS regression
reg = np.linalg.lstsq(data[cols].values, np.sign(data['returns'].values))[0]
reg
pred = np.sign(np.dot(data[cols].values, reg))
pred
np.sign(data['returns'].values)
data['ols_pred'] = pred
c = np.sign(data['returns'] * data['ols_pred'])
c.value_counts()
c.value_counts()[1] / (c.value_counts().sum())
data['ols_returns'] = data['returns'] * data['ols_pred']
data[['returns', 'ols_returns']].cumsum().apply(np.exp).plot(figsize=(10, 6));
from sklearn import linear_model
lm = linear_model.LogisticRegression(C = 1e6)
lm.fit(data[cols], np.sign(data['returns']))
data['log_pred'] = lm.predict(data[cols])
data.head()
data['log_returns'] = data['returns'] * data['log_pred']
data[['returns', 'ols_returns', 'log_returns']].cumsum(
).apply(np.exp).plot(figsize=(10, 6));
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
mean = data['returns'].mean()
std = data['returns'].std()
print(mean, std)
fc = tf.contrib.layers.real_valued_column('returns', dimension=lags)
fcb = [tf.contrib.layers.bucketized_column(fc,
boundaries=[-0.0005, 0.0001, 0.0005])]
model = tf.contrib.learn.DNNClassifier(hidden_units=[50, 50],
feature_columns=fcb)
def get_data():
fc = {'returns': tf.constant(data[cols].values)}
la = tf.constant((data['returns'] > 0).astype(int).values,
shape=[len(data), 1])
return fc, la
model.fit(input_fn=get_data, steps=100)
model.evaluate(input_fn=get_data, steps=1)
data['dnn_pred'] = list(model.predict(input_fn=get_data))
data['dnn_pred'] = np.where(data['dnn_pred'] > 0, 1.0, -1.0)
data['dnn_pred']
data['dnn_returns'] = data['returns'] * data['dnn_pred']
data[['returns', 'ols_returns', 'log_returns', 'dnn_returns']].cumsum(
).apply(np.exp).plot(figsize=(10, 6));
问题:
读取AMZN股票的历史收盘价数据,训练神经网络或者其他机器学习模型,
以延迟特征(日收益率)为输入进行涨跌预测。
并将模型预测结果转化为策略,应用与历史交易(可以是训练数据也可以是其他时间段)
计算算法交易策略下的回报是如何