# 机器学习股票价格预测初级实战

OK，下面我就把关注点集中在价格预测这件事上。我们都知道，不论用机器学习做什么，首先我们得需要一些数据源，并且还需要有一些途径来进行回测。那么像股票或者其他金融盘口的数据是有很多途径可以获取的，我今天给大家介绍一个我平时经常用的平台：RiceQuant米筐量化交易平台(非广告)。

image

``df = get_price('CSI300.INDX','2005-01-05','2015-01-01').reset_index()[['open','close']] ``

``>>> up_and_down=df['close']-df['open'] > 0 # 获取涨跌情况 >>> rate_of_return = (df['close']-df['open'])/df['open'] # 获取涨跌幅 >>> up_and_down_statistic = up_and_down.value_counts() # 获取涨跌天数 ``

image

``rate_of_return.plot(kind='line', style='k--', figsize=(15, 10), title='Daily Yield Changes Over Time Series') ``

image

``import pandas as pd import numpy as np from __future__ import division   from sklearn import svm from collections import deque import matplotlib.pyplot as plt  window = 2 # 米筐获取某一品种历史数据的DataFrame,注意得从2005-01-04开始 df = get_price('CSI300.INDX', '2005-01-05', '2015-07-25').reset_index()[['open', 'close']] up_and_down = df['close'] - df['open'] > 0 print(len(up_and_down)) X = deque() y = deque() clf = svm.LinearSVC() # SVM prediction = 0 test_num = 0 # 测试总数 win_num = 0 # 正确预测数  current_index = 400 # 起始位置  for current_index in range(current_index, len(up_and_down)-1, 1):  fact = up_and_down[current_index+1]          X.append(list(up_and_down[(current_index-window): current_index]))  y.append(up_and_down[current_index])  if len(y) > 100 and len(y) % 50 == 0:    test_num += 1    clf.fit(X, y)        prediction = clf.predict(list(up_and_down[(current_index-window+1): current_index+1]))            if prediction[0] == fact:      win_num += 1      print(win_num)       print("预测准确率为",win_num/test_num) ``

``# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。 def init(context):    context.s1 = "000001.XSHE"    # 是否已发送了order    context.fired = False  # 你选择的证券的数据更新将会触发此段逻辑，例如日或分钟历史数据切片或者是实时数据切片更新 def handle_bar(context, bar_dict):    # 开始编写你的主要的算法逻辑     # bar_dict[order_book_id] 可以拿到某个证券的bar信息    # context.portfolio 可以拿到现在的投资组合状态信息     # 使用order_shares(id_or_ins, amount)方法进行落单     # TODO: 开始编写你的算法吧！    if not context.fired:        # order_percent并且传入1代表买入该股票并且使其占有投资组合的100%        order_percent(context.s1, 1)        context.fired = True ``