Code Monkey home page Code Monkey logo

quantdigger's Introduction

QuantDigger 0.6.0

QuantDigger是一个基于python的量化回测框架。它借鉴了主流商业软件(比如TB, 金字塔)简洁的策略语法,同时 避免了它们内置编程语言的局限性,使用通用语言python做为策略开发工具。和 zipline , pyalgotrade 相比, QuantDigger的策略语法更接近策略开发人员的习惯。目前的功能包括:股票回测,期货回测。 支持选股,套利,择时, 组合策略。自带了一个基于matplotlib编写的简单的策略和k线显示界面,能满足广大量化爱好者 基本的回测需求。设计上也兼顾了实盘交易,未来如果有时间,也会加入交易接口。

由于个人时间和工作的关系,本项目不再维护。

文档

wiki文档

依赖库

  • matplotlib

  • numpy

  • logbook

  • pandas

  • progressbar2

  • zmq

  • BeautifulSoup4 (tushare需要)

  • lxml (tushare需要)

  • tushare (一个非常强大的股票信息抓取工具)

  • python-dateutil(可选)

  • IPython

  • TA-Lib

  • 可以用pip安装依赖库:
    >>> pip install -r requirements/requirements.txt
  • 如果出现pypi源超时情况:
    >>> pip install -r requirements/requirements.txt -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
  • TA-Lib 通过pip直接安装可能会出错,
  • finance依赖

策略组合DEMO

源码

from quantdigger import (
   Strategy,
   MA,
   DateTimeSeries,
   NumberSeries,
   set_config,
   add_strategies,
   Profile
)


class DemoStrategy(Strategy):
   """ 策略A1 """

   def on_init(self, ctx):
      """初始化数据"""
      ctx.ma10 = MA(ctx.close, 10, 'ma10', 'y', 1)
      ctx.ma20 = MA(ctx.close, 20, 'ma20', 'b', 1)
      ctx.dt = DateTimeSeries()
      ctx.month_price = NumberSeries()

   def on_bar(self, ctx):
      ctx.dt.update(ctx.datetime)
      if ctx.dt[1].month != ctx.dt[0].month:
            ctx.month_price.update(ctx.close)
      if ctx.curbar > 20:
            if ctx.pos() == 0 and ctx.ma10[2] < ctx.ma20[2] and ctx.ma10[1] > ctx.ma20[1]:
               ctx.buy(ctx.close, 1)
               ctx.plot_text("buy", 1, ctx.curbar, ctx.close, "buy", 'black', 15)
            elif ctx.pos() > 0 and ctx.ma10[2] > ctx.ma20[2] and \
                  ctx.ma10[1] < ctx.ma20[1]:
               ctx.plot_text("sell", 1, ctx.curbar, ctx.close, "sell", 'blue', 15)
               ctx.sell(ctx.close, ctx.pos())
      ctx.plot_line("month_price", 1, ctx.curbar, ctx.month_price, 'y--', lw=2)
      return

   def on_exit(self, ctx):
      return


class DemoStrategy2(Strategy):
   """ 策略A2 """

   def on_init(self, ctx):
      """初始化数据"""
      ctx.ma50 = MA(ctx.close, 50, 'ma50', 'y', 2)
      ctx.ma100 = MA(ctx.close, 100, 'ma100', 'black', 2)

   def on_symbol(self, ctx):
      pass

   def on_bar(self, ctx):
      if ctx.curbar > 100:
            if ctx.pos() == 0 and ctx.ma50[2] < ctx.ma100[2] and ctx.ma50[1] > ctx.ma100[1]:
               ctx.buy(ctx.close, 1)
            elif ctx.pos() > 0 and ctx.ma50[2] > ctx.ma100[2] and \
                  ctx.ma50[1] < ctx.ma100[1]:
               ctx.sell(ctx.close, ctx.pos())

      return

   def on_exit(self, ctx):
      return


if __name__ == '__main__':
   import timeit
   start = timeit.default_timer()
   set_config({'source': 'csv'})
   profiles = add_strategies(['BB.SHFE-1.Day'], [
      {
            'strategy': DemoStrategy('A1'),
            'capital': 50000.0 * 0.5,
      },
      {
            'strategy': DemoStrategy2('A2'),
            'capital': 50000.0 * 0.5,
      }
   ])
   stop = timeit.default_timer()
   print("运行耗时: %d秒" % ((stop - start)))

   # 绘制k线,交易信号线
   from quantdigger.digger import finance, plotting
   s = 0
   # 绘制策略A1, 策略A2, 组合的资金曲线
   curve0 = finance.create_equity_curve(profiles[0].all_holdings())
   curve1 = finance.create_equity_curve(profiles[1].all_holdings())
   curve = finance.create_equity_curve(Profile.all_holdings_sum(profiles))
   plotting.plot_strategy(profiles[0].data(), profiles[0].technicals(),
                           profiles[0].deals(), curve0.equity.values,
                           profiles[0].marks())
   # 绘制净值曲线
   plotting.plot_curves([curve.networth])
   # 打印统计信息
   print(finance.summary_stats(curve, 252))

策略结果

  • k线和信号线

k线显示使用了系统自带的一个联动窗口控件,由蓝色的滑块控制显示区域,可以通过鼠标拖拽改变显示区域。 上下方向键 来进行缩放。

doc/images/plot.png
  • 2个策略和组合的资金曲线。

    doc/images/figure_money.png
  • 组合的历史净值

    doc/images/figure_networth.png
  • 统计结果

>>> [('Total Return', '-0.99%'), ('Sharpe Ratio', '-5.10'), ('Max Drawdown', '1.72%'), ('Drawdown Duration', '3568')]

版本

0.6.0 版本 2019-05-28

  • 重构回测引擎,使其设计更合理和简洁。

0.5.1 版本 2017-07-13

  • 在原来0.5.0版的基础上改为支持Python3.6

0.5.0 版本 2017-01-08

  • 完善文档
  • 数据源可配置
  • 添加shell, 界面,回测引擎三则间的交互框架

0.3.0 版本 2015-12-09

  • 重新设计回测引擎, 支持组合回测,选股
  • 重构数据模块

0.2.0 版本 2015-08-18

  • 修复股票回测的破产bug
  • 修复回测权益计算bug
  • 交易信号对的计算从回测代码中分离
  • 把回测金融指标移到digger/finace
  • 添加部分数据结构,添加部分数据结构字段
  • 添加几个mongodb相关的函数

0.1.0 版本 2015-06-16

  • 夸品种的策略回测功能
  • 简单的交互
  • 指标,k线绘制

quantdigger's People

Contributors

honephy avatar leonardgithub avatar luwenxing avatar qink1986 avatar skabyy avatar wenwei-dev avatar wondereamer avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

quantdigger's Issues

本地数据?

很不错,但是看了一下源码,貌似没有维护本地数据的模块.对于大量细粒度数据的回测,没有本地数据很慢.比如要回测过去10年1分钟数据(更细的还有TICK...)
是不是应该弄一个HDF5文件,然后弄一个模块每天或实时维护它?

策略组合DEMO 的示例代码运行不了

File "/media/psf/Home/Documents/work-ubuntu/quant/quantdigger/tests/test.py", line 54, in
set_symbols(['BB.SHFE-1.Minute'], 0)
File "/media/psf/Home/Documents/work-ubuntu/quant/quantdigger/tests/quantdigger/engine/strategy.py", line 22, in set_symbols
_simulator = ExecuteUnit(pcontracts, dt_start, dt_end, n, spec_date)
File "/media/psf/Home/Documents/work-ubuntu/quant/quantdigger/tests/quantdigger/engine/execute_unit.py", line 43, in init
self._default_pcontract = self.pcontracts[0]
IndexError: list index out of range
Backend Qt4Agg is interactive backend. Turning interactive mode on.

demo都跑不起来,各种报错,无奈弃了 ,唉

(QA) E:\code\quantdigger>python demo.py
[I 210123 00:24:34 dsutil:17] register datasource: <class 'quantdigger.datasource.impl.csv_source.CsvSource'> => csv
[I 210123 00:24:34 dsutil:17] register datasource: <class 'quantdigger.datasource.impl.tushare_source.TuShareSource'> => tushare
[I 210123 00:24:34 dsutil:17] register datasource: <function CachedTuShareSource at 0x000001A5AB59A840> => cached-tushare
[I 210123 00:24:34 dsutil:17] register datasource: <class 'quantdigger.datasource.impl.mongodb_source.MongoDBSource'> => mongodb
[I 210123 00:24:34 dsutil:17] register datasource: <class 'quantdigger.datasource.impl.sqlite_source.SqliteSource'> => sqlite
Traceback (most recent call last):
File "demo.py", line 1, in
from quantdigger import *
File "E:\code\quantdigger\quantdigger_init_.py", line 3, in
from quantdigger.engine.strategy import *
File "E:\code\quantdigger\quantdigger\engine\strategy.py", line 2, in
from quantdigger.engine.execute_unit import ExecuteUnit
File "E:\code\quantdigger\quantdigger\engine\execute_unit.py", line 9, in
from quantdigger.engine.context import Context
File "E:\code\quantdigger\quantdigger\engine\context_init_.py", line 1, in
from .data_context import OriginalData
File "E:\code\quantdigger\quantdigger\engine\context\data_context.py", line 25
self.default_pcontract: str = None
^
SyntaxError: invalid syntax

(QA) E:\code\quantdigger>

talib的out of index错误

在策略运行完用matplotlib显示后,鼠标右移超过最右边的bar会显示该错误。可能talib的运行结果与
显示挂钩了。

一到画图就直接系统重启

MACOS配置的本地的csv数据源,调了很久终于可以跑起来了,结果一到plt.show()就系统直接重启了,,,,,一头雾水!

运行策略组合DEMO 源码 后报错,运行不了呢

运行策略组合DEMO 源码 后报错
File "pandas_libs\parsers.pyx", line 689, in pandas._libs.parsers.TextReader._setup_parser_source

FileNotFoundError: [Errno 2] File b'./data\CONTRACTS.csv' does not exist: b'./data\CONTRACTS.csv'

AttributeError: 'SourceWrapper' object has no attribute 'open'

    ConfigUtil.set(source='tushare')
    profiles = add_strategies(['000001.SH-1.DAY'], [
        {
            'strategy': DemoStrategy('A1'),
            'capital': 5000000.0,
        }
    ])

报错:

  File "C:\Users\***\AppData\Local\Programs\Python\Python37\lib\site-packages\quantdigger-0.6.0-py3.7.egg\quantdigger\engine\context\data_context.py", line 125, in __init__
    self.open = NumberSeries(raw_data.open.values, 'open')
AttributeError: 'SourceWrapper' object has no attribute 'open'

Atlas (http://math-atlas.sourceforge.net/) libraries not found.

No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
customize GnuFCompiler
Could not locate executable g77
Could not locate executable f77
customize IntelVisualFCompiler
Could not locate executable ifort
Could not locate executable ifl
customize AbsoftFCompiler
Could not locate executable f90
customize CompaqVisualFCompiler
Could not locate executable DF
customize IntelItaniumVisualFCompiler
Could not locate executable efl
customize Gnu95FCompiler
Could not locate executable gfortran
Could not locate executable f95
customize G95FCompiler
Could not locate executable g95
customize IntelEM64VisualFCompiler
customize IntelEM64TFCompiler

关于 max_drawdown(networth) 的疑问

在这个函数中,我注意到 duration[t] = 0 if drawdown[t] <= 0 else duration[t-1] + 1,这计算出来的是新高到下一个新高中的天数,而不是“最大回撤”的天数,不知是我理解有误还是特意为之?

def max_drawdown(networth):
    """ 统计最大回测和相应的回测周期。
    networth: 历史净值
    """
    hwm = [0]  # 历史最大值序列变量
    eq_idx = networth.index
    drawdown = pd.Series(index=eq_idx)
    duration = pd.Series(index=eq_idx)

    for t in range(1, len(eq_idx)):
        cur_hwm = max(hwm[t-1], networth[t])
        hwm.append(cur_hwm)
        drawdown[t] = hwm[t] - networth[t]
        # <=0 新高,计数0
        duration[t] = 0 if drawdown[t] <= 0 else duration[t-1] + 1
    return drawdown.max(), duration.max()

执行demo的时候,提示这个错

D:\worksoft\anaconda3\lib\site-packages\quantdigger-0.6.0-py3.6.egg\quantdigger\engine\execute_unit.py in _load_data(self, strpcons, dt_start, dt_end, n, spec_date)
216 dt_start = spec_date[strpcon][0]
217 dt_end = spec_date[strpcon][1]
--> 218 assert(dt_start < dt_end)
219 if n:
220 wrapper = self._data_manager.get_last_bars(strpcon, n)

TypeError: '<' not supported between instances of 'int' and 'str'

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.