跳至正文
返回文库全部文档

比较TA-Lib 与内置抛物线SAR指标

代码 backtrader

总结

此示例策略在同一价格序列上初始化两个抛物线SAR指标:根据最高价和最低价数据计算的TA-Lib 的SAR,以及 Backtrader 内置的PSAR。策略从CSV数据源加载历史市场数据,可选设定起止日期,然后通过 Backtrader 引擎运行。示例还提供逐步执行选项和可选的蜡烛图绘制功能。

代码展示了指标设置方法,以及在回测框架内比较两种实现的基本工作流程。它没有定义入场或退出规则、执行交易、报告表现,也没有解释如何解读SAR信号。因此,这是一个简短的技术指标和回测示例,但不能证明任一指标或使用该指标的策略能够盈利。

核心观点

  • 该示例在相同价格数据上初始化TA-Lib SAR和 Backtrader PSAR。
  • 示例从CSV文件载入历史价格,并可选设定日期范围。
  • 回测可在批处理模式下运行,也可逐步处理数据。
  • 可选绘图功能会以蜡烛图显示数据,但示例未提供交易规则或结果。

标签

全文
# tablibsartest.py


```py
#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015-2023 Daniel Rodriguez
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
###############################################################################
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import argparse
import datetime

import backtrader as bt


class TALibStrategy(bt.Strategy):
    def __init__(self):
        bt.talib.SAR(self.data.high, self.data.low)
        bt.ind.PSAR()


def runstrat(args=None):
    args = parse_args(args)

    cerebro = bt.Cerebro()

    dkwargs = dict()
    if args.fromdate:
        fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
        dkwargs['fromdate'] = fromdate

    if args.todate:
        todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')
        dkwargs['todate'] = todate

    data0 = bt.feeds.YahooFinanceCSVData(dataname=args.data0, **dkwargs)
    cerebro.adddata(data0)

    cerebro.addstrategy(TALibStrategy)
    cerebro.run(runonce=not args.use_next, stdstats=False)
    if args.plot:
        pkwargs = dict(style='candle')
        if args.plot is not True:  # evals to True but is not True
            npkwargs = eval('dict(' + args.plot + ')')  # args were passed
            pkwargs.update(npkwargs)

        cerebro.plot(**pkwargs)


def parse_args(pargs=None):

    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description='Sample for sizer')

    parser.add_argument('--data0', required=False,
                        default='../../datas/yhoo-1996-2015.txt',
                        help='Data to be read in')

    parser.add_argument('--fromdate', required=False,
                        default='2005-01-01',
                        help='Starting date in YYYY-MM-DD format')

    parser.add_argument('--todate', required=False,
                        default='2006-12-31',
                        help='Ending date in YYYY-MM-DD format')

    parser.add_argument('--use-next', required=False, action='store_true',
                        help=('Use next (step by step) '
                              'instead of once (batch)'))

    # Plot options
    parser.add_argument('--plot', '-p', nargs='?', required=False,
                        metavar='kwargs', const=True,
                        help=('Plot the read data applying any kwargs passed\n'
                              '\n'
                              'For example (escape the quotes if needed):\n'
                              '\n'
                              '  --plot style="candle" (to plot candles)\n'))

    if pargs is not None:
        return parser.parse_args(pargs)

    return parser.parse_args()


if __name__ == '__main__':
    runstrat()

```

在遵守原作品许可的前提下,附作者信息全文展示。 许可协议: GPL-3.0

此摘要由 Stratmill 研究智能体根据原文撰写,并非原文副本。