MachineLearning 第二个例程股票价格预测

1. 下载股票数据

地址:http://www.nasdaq.com/symbol/aapl/historical

2. 运行代码

import csv
import numpy as np
from sklearn.svm import SVR
import matplotlib.pyplot as plt
from sklearn import model_selection


dates = []
prices =[]

def get_data(filename):
    with open(filename,'r') as csvfile:
        csvFileReader = csv.reader(csvfile)
        next(csvFileReader)
        for row in csvFileReader:
            dates.append((row[0]))
            prices.append(float(row[1]))
    return

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.2)

    svr_lin.fit(dates, prices)
    svr_poly.fit(dates, prices)
    svr_rbf.fit(dates, prices)

    predict_svr_lin = svr_lin.predict(dates)
    predict_svr_poly = svr_poly.predict(dates)
    predict_svr_rbf = svr_rbf.predict(dates)

    error_lin = predict_svr_lin - prices
    error_poly = predict_svr_poly - prices
    error_rbf = predict_svr_rbf - prices

    plt.figure(1)
    plt.scatter(dates,error_lin)

    plt.figure(2)
    plt.scatter(dates, error_poly)

    plt.figure(3)
    plt.scatter(dates, error_rbf)

    plt.figure(4)
    plt.plot(dates, prices, 'ro-.' ,label='actual price')
    plt.plot(dates, predict_svr_rbf, 'b--',label = 'RBF model')
    ## the following prediction failed
    # plt.plot(dates, predict_svr_poly, color='green', label='polynomial model')
    # plt.plot(dates, predict_svr_lin, color='blue', label='linear model')

    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.title('support vector Regression')
    plt.legend()
    plt.show()

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

get_data('Apple_last_3months_stock_price.csv')

predict_prices(dates, prices, 29)

原文vedio: https://www.youtube.com/watch?v=SSu00IRRraY


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值