量化交易平台Quantopian学习的笔记(一)

最近对量化感兴趣,每周末带孩子上辅导班等候时在星巴克记录的一些笔记,记录一下便于以后查阅,一并分享出来希望对大家有帮助。

Quantopian量化交易平台主要针对美股,国内也有几个针对A股的,对A股感兴趣的可以去网上找找;

这个平台牛逼的地方就是:

1、提供了一套封装好的库方便我们写量化的策略使用;

2、提供了需要的数据,都在网上不用自己去找;

3、策略的算法框架足够简单,几百行代码就可以写一个自己的策略,教程中有例子;

4、回测框架现成的,写好策略随时就可以进行回测看效果;

5、支持实盘交易,只要你策略回测OK,关联上账号就可以实盘操作了,兴奋不!

下面是我上上周折腾了一个策略效果:

量化交易平台Quantopian学习的笔记(一)_第1张图片

下面是记录的一些笔记,根据自己的思路记录的有些凌乱,还请见谅!

1、Data Exploration

提供了简单易用的数据接口或者函数;比我们一句句用pandas写简单一些;

# Research environment functions

from quantopian.research import returns, symbols

# Select a time range to inspect

period_start = '2014-01-01'

period_end = '2014-12-31'



# Query returns data for AAPL

# over the selected time range

aapl_returns = returns(

    assets=symbols('AAPL'),

    start=period_start,

    end=period_end,

)



# Display first 10 rows

aapl_returns.head(10)

2、Pipeline API 形象的来说就是各种数据通过管道进行统一的加工分析后输出我们想要的结果,是一个强大的交叉分析工具

这个是管道API,他提供了一些算法和一些通用的策略算法(比如SimpleMovingAverage),把汇合的数据进行分析处理返回给我们想要的结果;

# Import Pipeline class and datasets

from quantopian.pipeline import Pipeline

from quantopian.pipeline.data import USEquityPricing

from quantopian.pipeline.data.psychsignal import stocktwits



# Import built-in moving average calculation

from quantopian.pipeline.factors import SimpleMovingAverage





def make_pipeline():

    # Get latest closing price

    close_price = USEquityPricing.close.latest



    # Calculate 3 day average of bull_minus_bear scores

    sentiment_score = SimpleMovingAverage(

        inputs=[stocktwits.bull_minus_bear],

        window_length=3,

    )



    # Return Pipeline containing close_price

    # and sentiment_score

    return Pipeline(

        columns={

            'close_price': close_price,

            'sentiment_score': sentiment_score,

        }

    )

3、投资组合优化算法

      提供了一个比较方便使用的quantopian.optimize库,方便用户根据自己设定的限制条件去选择自己的投资组合,并计算出各个权重,方便后续策略中使用,例如根据不同的权重沟通等值比率的股票等。

import quantopian.optimize as opt



objective = opt.MaximizeAlpha(expected_returns)

constraints = [

    opt.MaxGrossExposure(W_max),      #限制条件

    opt.PositionConcentration(min_weights, max_weights),

]

optimal_weights = opt.calculate_optimal_portfolio(objective, constraints)

4、Dollar Volume 资金量,其实就是某个股票的流动性,如果这个股票流动性大交易频繁,就说明你买进卖出成交的速度就又保证,不至于在策略运行中因为下单没成功而错失良机造成损失。

下面时拉出30天内的各股票的流动量,过滤出头部百分之10的高流动性股票;

from quantopian.algorithm import attach_pipeline, pipeline_output

from quantopian.pipeline import Pipeline

from quantopian.pipeline.factors import AverageDollarVolume

...

def initialize(context):

    pipe = Pipeline()

    attach_pipeline(pipe, name='my_pipeline')



    # Construct an average dollar volume factor and add it to the pipeline.

    dollar_volume = AverageDollarVolume(window_length=30)

    pipe.add(dollar_volume, 'dollar_volume')



    # Define high dollar-volume filter to be the top 10% of securities by dollar volume.

    high_dollar_volume = dollar_volume.percentile_between(90, 100)



    # Filter to only the top dollar volume securities.

    pipe.set_screen(high_dollar_volume)

5、滑动模式:其实就是下单时的策略,因为你想买10000股不会一下就买定,你可以定制个策略一次买多少(滑动),如果不设置默认每次价格5个点浮动,每次下单量0.1 (1000*0.1 = 100股),如果要买220股,那就试分三批买入,100、100、20;自己也可以根据自己的策略来设定,比较灵活。

# Setting custom equity and futures slippage models.

def initialize(context):

    set_slippage(

        us_equities=slippage.FixedBasisPointsSlippage(basis_points=5, volume_limit=0.1),

        us_futures=slippage.FixedSlippage(spread=0)

    )

6、交易佣金的模式,默认的交易佣金时美股 0.0001美元,每个期权的交易时0.85美元,也可以自己设定,主要用于回测使用,具体根据实际的券商来设定。

# Setting custom equity and futures commission models.
def initialize(context):
    set_commission(
        us_equities=commission.PerShare(cost=0.001, min_trade_cost=0),
        us_futures=commission.PerContract(cost=1, exchange_fee=0.85, min_trade_cost=0)
    )

7、算法模版,整体设计的比较简单,按照模板填空即可,上手比较简单

"""

This is a template algorithm on Quantopian for you to adapt and fill in.

"""

import quantopian.algorithm as algo   #算法库

from quantopian.pipeline import Pipeline

from quantopian.pipeline.data.builtin import USEquityPricing

from quantopian.pipeline.filters import QTradableStocksUS

# Import Optimize API module

import quantopian.optimize as opt



#算法开始初始化

def initialize(context):

    """

    Called once at the start of the algorithm.

    """

    #初始化证券池sid(47740),sid(24), sid(42950)

    context.security_list = [ sid(39840)]

    

    

    # Constraint parameters

    context.max_leverage = 1.0

    context.max_pos_size = 0.015

    context.max_turnover = 0.95

    

   #任务函数,设置后会定期执行

    # Rebalance every day, 1 hour after market open.

    algo.schedule_function(

        rebalance,

        algo.date_rules.every_day(),

        algo.time_rules.market_open(hours=0.1),

    )



   #每天休市时执行这个任务

    # Record tracking variables at the end of each day.

    algo.schedule_function(

        record_vars,

        algo.date_rules.every_day(),

        algo.time_rules.market_close(),

    )



#这里设置一个数据管道

    # Create our dynamic stock selector.

    algo.attach_pipeline(make_pipeline(), 'pipeline')



# 数据处理管道,这里主要处理多处来源数据

def make_pipeline():

    """

    A function to create our dynamic stock selector (pipeline). Documentation

    on pipeline can be found here:

    https://www.quantopian.com/help#pipeline-title

    """



    # Base universe set to the QTradableStocksUS

    base_universe = QTradableStocksUS()



    # Factor of yesterday's close price.

    yesterday_close = USEquityPricing.close.latest



    pipe = Pipeline(

        columns={

            'close': yesterday_close,

        },

        screen=base_universe

    )

    return pipe



#交易开始前的处理函数

def before_trading_start(context, data):

    """

    Called every day before market open. 开盘数据处理

    """

    context.output = algo.pipeline_output('pipeline')



    # These are the securities that we are interested in trading each day.

    #context.security_list = context.output.index



def compute_weights(context, data):

    #计算10日与30日均值

    hist = data.history(context.security_list, 'price', 30, '1d')

    prices_10 = hist[-5:]

    prices_30 = hist

    sma_10 = prices_10.mean()

    sma_30 = prices_30.mean()

    # 加权计算

    raw_weights = (sma_30 - sma_10) / sma_30

    normalized_weights = raw_weights / raw_weights.abs().sum()

    return normalized_weights



#定期任务执行的函数,主要是写策略选股然后进行下单

def rebalance(context, data):

    """

    Execute orders according to our schedule_function() timing.

    """

    # Retrieve alpha from pipeline output

    alpha = context.output.close



    # 重置权重

    weights = compute_weights(context, data)

    # 组合重新分配

    for security in context.security_list:

        if data.can_trade(security):

            order_target_percent(security, weights[security])


#记录每天的操作

def record_vars(context, data):

    """

    Plot variables at the end of each day.

    """

    pass



#数据处理,每分钟被调用,主要分析实时数据

def handle_data(context, data):

    """

    Called every minute.

    """

    pass

   先写到这里,整体上来说比较简单,难的是后面的策略怎么搞,慢慢来,欢迎交流!

 

by 祝枝山          于2019.4.14

你可能感兴趣的:(Quantopian,量化)