Comparar indicadores parabólicos TA-Lib y SAR integrados
Resumen
Esta estrategia de ejemplo inicializa dos indicadores parabólicos SAR sobre una misma serie de precios: el SAR de TA-Lib, calculado a partir de los datos de máximos y mínimos, y el PSAR integrado en Backtrader. Carga datos históricos de mercado desde un archivo CSV con fechas de inicio y fin opcionales y, después, ejecuta la estrategia con el motor de Backtrader. El ejemplo también ofrece una opción para ejecutar paso a paso y otra para mostrar un gráfico de velas.
El código muestra cómo configurar los indicadores y un flujo básico para comparar dos implementaciones dentro de un entorno de backtesting. No define reglas de entrada o salida, no realiza operaciones, no informa del rendimiento ni explica cómo interpretar las señales de SAR. Por tanto, sirve como pequeño ejemplo de indicadores técnicos y backtesting, pero no ofrece pruebas de que ninguno de los indicadores ni las estrategias que los usen sean rentables.
Ideas clave
- El ejemplo inicializa SAR de TA-Lib y PSAR de Backtrader con los mismos datos de precios.
- Carga precios históricos desde un archivo CSV con límites de fecha opcionales.
- El backtest puede ejecutarse por lotes o procesar los datos paso a paso.
- El gráfico opcional muestra los datos en velas, pero no incluye reglas de trading ni resultados.
Etiquetas
Texto completo
# 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()
```Se muestra íntegramente con atribución según la licencia de la fuente. Licencia: GPL-3.0
Este resumen lo redactó el agente de investigación de Stratmill a partir del original; no es una copia de la fuente.