克隆策略

在本文,我们仅有50Python代码开发一个股价预测模型,利用scikit-learn

基于历史数据,我们是否能够预测股价呢?可以!利用机器学习即可。 这听起来只是一个科学问题,由于市场有效性,股票市场充满随机与不确定性。

我们将开发三种不同的预测模型来预测立讯精密的股价,然后画图比较结果。

步骤: 1.安装库文件

In [1]:
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt

import pandas as pd # 首先导入库
df = D.history_data(instruments = ['002475.SZA'],
                    start_date = '2010-09-15',
                    end_date = '2017-08-18',
                    fields = ['close']
                    ) # 以立讯精密为例,导入某一时间段历史数据
df = df[['date','close']] # 运行结果根据需要进行列调整
dates = df['date'].map(lambda x:x.day)
prices = df['close']
assert len(dates) == len(prices)
In [2]:
dates = [i for i in dates]
prices = [p for p in prices]
In [3]:
def predict_prices(dates, prices, x):
    dates = np.reshape(dates, (len(dates), 1))
    
    svr_lin = SVR(kernel= 'linear', C=1e3)
    svr_poly = SVR(kernel= 'poly', C=1e3, degree= 2)
    svr_rbf = SVR(kernel= 'rbf', C=1e3, gamma=0.1)

    svr_lin.fit(dates, prices)
    svr_poly.fit(dates, prices)
    svr_rbf.fit(dates, prices)
    
    plt.scatter(dates,
                prices,
                color="black",
                label="Data")
    plt.plot(dates,
             svr_rbf.predict(dates),
             color="red",
             label="RBF Model")

    plt.plot(dates,
             svr_lin.predict(dates),
             color="green",
             label='linear Model')

    plt.plot(dates,
             svr_poly.predict(dates),
             color="blue",
             label="Ploynomial Model")

    plt.xlabel('Dates')
    plt.ylabel('Price')
    plt.title('Support Vector Reg')
    plt.legend()
    plt.show()

    return svr_rbf.predict(x)[0], svr_lin.predict(x)[0], svr_poly.predict(x)[0]

predicted_prices = predict_prices(dates, prices, 29)

print(predicted_prices)
(112.99800716428085, 114.85525898404195, 112.83762276437133)