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

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

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

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

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

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

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

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

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

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

1、Data Exploration

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

# Research environment functionsfrom quantopian.research import returns, symbols# Select a time range to inspectperiod_start = '2014-01-01'period_end = '2014-12-31'# Query returns data for AAPL# over the selected time rangeaapl_returns = returns(assets=symbols('AAPL'),start=period_start,end=period_end,)# Display first 10 rowsaapl_returns.head(10)

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

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

# Import Pipeline class and datasetsfrom quantopian.pipeline import Pipelinefrom quantopian.pipeline.data import USEquityPricingfrom quantopian.pipeline.data.psychsignal import stocktwits# Import built-in moving average calculationfrom quantopian.pipeline.factors import SimpleMovingAveragedef make_pipeline():# Get latest closing priceclose_price = USEquityPricing.close.latest# Calculate 3 day average of bull_minus_bear scoressentiment_score = SimpleMovingAverage(inputs=[stocktwits.bull_minus_bear],window_length=3,)# Return Pipeline containing close_price# and sentiment_scorereturn Pipeline(columns={'close_price': close_price,'sentiment_score': sentiment_score,})

3、投资组合优化算法

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

import quantopian.optimize as optobjective = 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_outputfrom quantopian.pipeline import Pipelinefrom 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 Pipelinefrom quantopian.pipeline.data.builtin import USEquityPricingfrom quantopian.pipeline.filters import QTradableStocksUS# Import Optimize API moduleimport 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 parameterscontext.max_leverage = 1.0context.max_pos_size = 0.015context.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). Documentationon pipeline can be found here:https://www.quantopian.com/help#pipeline-title"""# Base universe set to the QTradableStocksUSbase_universe = QTradableStocksUS()# Factor of yesterday's close price.yesterday_close = USEquityPricing.close.latestpipe = 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.indexdef compute_weights(context, data):#计算10日与30日均值hist = data.history(context.security_list, 'price', 30, '1d')prices_10 = hist[-5:]prices_30 = histsma_10 = prices_10.mean()sma_30 = prices_30.mean()# 加权计算raw_weights = (sma_30 - sma_10) / sma_30normalized_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 outputalpha = 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学习的笔记(一)相关推荐

  1. 面向交易的日内高频量化交易平台笔记

    1. 本次讲座介绍. 长江证券金融工程部邀请了北京知象科技创始人,对其量化交易系统(股票.期货)进行了简单的介绍以及推广. 2.本次讲座主要设计的内容. 针对股票日内高频量化交易平台.本次讲座只cov ...

  2. 旷世轻量化网络ShuffulNetV2学习笔记

    旷世轻量化网络ShuffulNetV2学习笔记 ShuffleNet V2: Practical Guidelines for Efficient CNN Architecture Design Ab ...

  3. 《学习期货策略的筒子收藏了》国内量化交易平台

    为什么80%的码农都做不了架构师?>>>    中低端平台适合投资者进行趋势.反趋势等对行情和交易逻辑要求不高的策略,高端交易平台适合机构投资者进行趋势.套利.对冲.高频等对行情和交 ...

  4. 深度学习-最优化笔记

    深度学习-最优化笔记 作者:杜客 链接:https://zhuanlan.zhihu.com/p/21360434 来源:知乎 著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处. 译 ...

  5. [转载]Python量化交易平台开发教程系列0-引言

    原文出处:http://vnpy.org/2015/03/04/20150304_Python%E9%87%8F%E5%8C%96%E4%BA%A4%E6%98%93%E5%B9%B3%E5%8F%B ...

  6. 量化投资必备手册:史上超全量化交易平台汇总

    量化投资必备手册,分享30个量化交易平台给你们,转需,不用谢! 1. 国泰君安量化交易系统 量化交易系统网址:https://quant.gtja.com/ 2. 量化云 量化回测平台:https:/ ...

  7. Python量化交易平台:JQData | API使用文档(转)

    Python量化交易平台:JQData | API使用文档(转) #原文地址:https://www.joinquant.com/help/api/help?name=JQData JQData说明书 ...

  8. Python量化交易平台开发教程系列0-引言

    原创文章,转载请注明出处:用Python的交易员 为什么用Python来开发量化交易平台 目前本人所在的公司一共有三款平台,分别基于C++, C#和Python.其中C#和Python平台都是由交易员 ...

  9. 量化投资 | 量化交易平台工具汇总

    量化投资必备手册,分享30个量化交易平台给你们,转需,不用谢! 1. 掘金量化  量化交易系统官方网址:https://www.myquant.cn/ 2.国泰君安量化交易系统 量化交易系统网址:ht ...

最新文章

  1. 通过apt自动生成建造者模式单线程版代码(一)
  2. 在.net中如何禁用或启用DropDownList的Items
  3. OSM OpenStreetMap 获取城市路网数据及转为ESRI shp数据的方法
  4. 首发福利!全球第一开源ERP Odoo系统架构部署指南 电子书分享
  5. 【深度学习】深入理解卷积神经网络(CNN)
  6. spring-data-jpa 二、多对一结构、Repository
  7. 面试前准备这些,成功率会大大提升!(Java篇)
  8. python从零开始学习网站-7天从零开始学Python
  9. 严格模式与混杂模式如何区分_品牌商如何规划合伙人模式
  10. c语言中字符名词解释,C语言名词解释哪里有名词的解释 比如 什么型 什么型的...
  11. ARKit何以从同类技术中胜出?
  12. vue实例中使用swiper
  13. Action以外的类中来获得Spring所管理的Service对象
  14. 「PMP答题卡」真实模拟PMP考试
  15. 联想u盘启动linux,联想ThinkPad L540笔记本BIOS设置u盘启动教程
  16. 选择小程序的8大理由,让你拒绝说No
  17. 秒杀疯狂猜成语3 花花的3300个成语 包括C#源代码 交流
  18. 金蝶计算机快捷键,金蝶kis系列软件常用快捷键汇总
  19. 网站文章如何被快速收录,网站文章快速收录的方法!
  20. 算法 洗扑克牌(乱数排列)

热门文章

  1. 神舟笔记本(战神)摄像头或者相机不能使用的解决方法
  2. 目标检测算法DSSD的原理详解
  3. html中切角文本框,css实现切角效果
  4. mov和mp4格式哪个好_如何快速做视频格式的转换
  5. 淘宝理财 中证500 中证300 基金收益计算
  6. 打开软件显示乱码的解决方法
  7. matlab 双y轴对数坐标 误差线,matlab双y轴添加误差棒(转载)
  8. 倒计时不到1天!iPhone 11系列起售价预测,或将成为新的“真香机”
  9. 【NLP】第8章 将 Transformer 应用于法律和财务文件以进行 AI 文本摘要
  10. qq发消息时键盘挡住了_键盘挡住输入框解决办法