分享

经典量化交易策略系列——线性回归的趋势跟踪系统

 havruta 2016-09-13

   本篇通过各个收盘的波峰波谷做简单线性回归拟合出类似的趋势线,然后结合股价以及预测值来跟踪趋势。思路:上升趋势线用波谷拟合,用波峰的值和拟合预测值做比较;下降趋势线用波峰拟合,用波谷的值和拟合预测值做比较。


    注:这种拟合的方式也许信号发出的不一定准确,后续可以加上拟合度置信区间来提高信号的准确性。


收益与风险


源码:


from datetime import datetime, timedelta

import numpy as np

import pandas as pd

from sklearn import datasets, linear_model


# 定义一个全局变量, 保存要操作的证券

security = '510180.XSHG'

# 初始化此策略

# 设置我们要操作的股票池, 这里我们只操作一支股票

set_universe([security])


arraySplitNum = 5


def initialize(context):

    g.fixedStartDate = datetime(2000,1,1)

    g.peakPrice = pd.DataFrame(columns=['xDays', 'yPrice', 'tDate'])

    g.throughPrice = pd.DataFrame(columns=['xDays', 'yPrice', 'tDate'])

    g.priceBuy = 0.0

    

# 每个单位时间(如果按天回测,则每天调用一次,如果按分钟,则每分钟调用一次)调用一次

def handle_data(context, data):

    hData = history(3, '1d', 'close', [security])

    hData.columns = ['close']

    

    pLen = len(g.peakPrice)

    tLen = len(g.throughPrice)

    

    # 计算相对时间变量

    xDays = (context.current_dt - g.fixedStartDate).days - 1

    

    if hData.iloc[-2].close >= hData.iloc[-3].close \

    and hData.iloc[-1].close <=>

        # 这是波峰

        g.peakPrice.loc[pLen] = [xDays, hData.iloc[-2].close, context.current_dt + timedelta(days=-1)]

    elif hData.iloc[-2].close <= hdata.iloc[-3].close="">

    and hData.iloc[-1].close >= hData.iloc[-2].close:

        # 这是波谷

        g.throughPrice.loc[tLen] = [xDays, hData.iloc[-2].close, context.current_dt + timedelta(days=-1)]


    pricePredictP = data[security].pre_close

    

    pricePredictT = data[security].pre_close

    

    lastPePrice = pricePredictP

    lastThPrice = pricePredictT

    

    pLen = len(g.peakPrice)

    tLen = len(g.throughPrice)

    if  pLen > 1 :

        # Create linear regression object

        regrP = linear_model.LinearRegression()

        

        # Train the model using the training sets

        regrP.fit(np.reshape(g.peakPrice.xDays.values, pLen).reshape(pLen,1), g.peakPrice.yPrice.values)

        

        pricePredictP = regrP.predict(xDays)

        

        lastPePrice = g.peakPrice.ix[pLen - 1].yPrice

        

    if  tLen > 1 :

        # Create linear regression object

        regrT = linear_model.LinearRegression()

        

        # Train the model using the training sets

        regrT.fit(np.reshape(g.throughPrice.xDays.values, tLen).reshape(tLen,1), g.throughPrice.yPrice.values)

        

        pricePredictT = regrT.predict(xDays)

        lastThPrice = g.throughPrice.ix[tLen - 1].yPrice


    bsFlag = ''

    lastClosePrice = data[security].pre_close

    if lastClosePrice > pricePredictP or lastThPrice > pricePredictP:

        bsFlag = '+'

    elif lastClosePrice < pricepredictt="" or="" lastpeprice=""><>

        bsFlag = '-'

    

    # 取得当前价格

    current_price = data[security].open

    # 取得当前的现金

    cash = context.portfolio.cash

    

    if bsFlag == '+' and g.priceBuy == 0 :

        # 全仓买入

        # 计算可以买多少只股票

        number_of_shares = int(cash/current_price)

        # 购买量大于0时,下单

        if number_of_shares > 0:

            # 买入股票

            order(security, +number_of_shares)

            g.priceBuy = current_price

            # 记录这次买入

            log.info(str(context.current_dt) + ' Buying %s' % (security))

        #g.peakPrice = pd.DataFrame(columns=['xDays', 'yPrice', 'tDate'])

    elif bsFlag == '-' and g.priceBuy > 0 :

        # 清仓卖出

        # 卖出所有股票,使这只股票的最终持有量为0

        order_target(security, 0)

        g.priceBuy = 0.0

        g.throughPrice = pd.DataFrame(columns=['xDays', 'yPrice', 'tDate'])

        # 记录这次卖出

        log.info(str(context.current_dt) + ' Selling %s' % (security))

    

    #record(closeP=data[security].close)

    record(peakP=pricePredictP)

    record(throughP=pricePredictT)

    #record(lastThP=lastThPrice)

    #record(peakP=pricePredictP)


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多