You are here:  Home » 量化交易与机器学习 » backtrader » 股票Screening- backtrader中文教程

股票Screening

Looking一些其他的事情我碰到一个问题一提出的一个StackOverlow家族网站:定量Finance又名定量StackExchange。问题:

  • 股票筛选和扫描开源软件使用的技术分析?

它被标记为Python,所以很有看头,如果backtrader是达task.

The分析itself

The问题似乎适用于一个简单的分析。虽然问题刚刚想要一上方均线,我们会继续像额外信息不符合条件的,个股以确保粮食实际上是被从chaff.

class Screener_SMA(bt.Analyzer):
    params = dict(period=10)

    def start(self):
        self.smas = {data: bt.indicators.SMA(data, period=self.p.period)
                     for data in self.datas}

    def stop(self):
        self.rets["over"] = list()
        self.rets["under"] = list()

        for data, sma in self.smas.items():
            node = data._name, data.close[0], sma[0]
            if data > sma:  # if data.close[0] > sma[0]
                self.rets["over"].append(node)
            else:
                self.rets["under"].append(node)

Note

Of当然,人们也需要分开import backtrader as bt

这几乎解决了这个问题。该Analyzer分析:

  • period作为一个参数有一个灵活analyzer
  • start method

    For每个data在系统做出Simple Moving AverageSMA),用于it.

  • stop method

    Look其中dataclose如果没有其他规定)高于其sma和存储在`关键list下的over回报(rets

    的构件rets是在标准analyzers和碰巧是collections.OrderedDict。创建由基class.

    Keep不符合项下的标准under

现在的问题的那些:得到分析并running.

Note

我们假设代码已被放在一个名为st-screener.py

方法1

backtrader包括文件,因为时间已近开始,自动运行的脚本运行所谓的btrun,它可以装载战略,指标,从分析仪Python模块,分析论证,当然plot.

Let我们做一个运行:

$ btrun --format yahoo --data YHOO --data IBM --data NVDA --data TSLA --data ORCL --data AAPL --fromdate 2016-07-15 --todate 2016-08-13 --analyzer st-screener:Screener_SMA --cerebro runonce=0 --writer --nostdstats
===============================================================================
Cerebro:
  -----------------------------------------------------------------------------
  - Datas:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    - Data0:
      - Name: YHOO
      - Timeframe: Days
      - Compression: 1
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    - Data1:
      - Name: IBM
      - Timeframe: Days
      - Compression: 1
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    - Data2:
      - Name: NVDA
      - Timeframe: Days
      - Compression: 1
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    - Data3:
      - Name: TSLA
      - Timeframe: Days
      - Compression: 1
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    - Data4:
      - Name: ORCL
      - Timeframe: Days
      - Compression: 1
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    - Data5:
      - Name: AAPL
      - Timeframe: Days
      - Compression: 1
  -----------------------------------------------------------------------------
  - Strategies:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    - Strategy:
      *************************************************************************
      - Params:
      *************************************************************************
      - Indicators:
        .......................................................................
        - SMA:
          - Lines: sma
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          - Params:
            - period: 10
      *************************************************************************
      - Observers:
      *************************************************************************
      - Analyzers:
        .......................................................................
        - Value:
          - Begin: 10000.0
          - End: 10000.0
        .......................................................................
        - Screener_SMA:
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          - Params:
            - period: 10
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          - Analysis:
            - over: ("ORCL", 41.09, 41.032), ("IBM", 161.95, 161.221), ("YHOO", 42.94, 39.629000000000005), ("AAPL", 108.18, 106.926), ("NVDA", 63.04, 58.327)
            - under: ("TSLA", 224.91, 228.423)

我们已经使用了一组众所周知的行情:

而这恰好是唯一一个是下10Simple Moving
Average
TSLA.

让我们尝试了50天左右。是的,这也可以控制btrun。运行(输出缩短):

$ btrun --format yahoo --data YHOO --data IBM --data NVDA --data TSLA --data ORCL --data AAPL --fromdate 2016-05-15 --todate 2016-08-13 --analyzer st-screener:Screener_SMA:period=50 --cerebro runonce=0 --writer --nostdstats
===============================================================================
Cerebro:
  -----------------------------------------------------------------------------
  - Datas:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    - Data0:
...
...
...
        - Screener_SMA:
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          - Params:
            - period: 50
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          - Analysis:
            - over: ("ORCL", 41.09, 40.339), ("IBM", 161.95, 155.0356), ("YHOO", 42.94, 37.9648), ("TSLA", 224.91, 220.4784), ("AAPL", 108.18, 98.9782), ("NVDA", 63.04, 51.4746)
            - under:

通知如何50天周期已在命令行中设定:

  • st-screener:Screener_SMA:period=50

    在前面的运行,这是st-screener:Screener_SMA并且默认10从代码为used.

We也需要调整fromdate,以确保有足够的酒吧考虑了Simple Moving Averages

在这种情况下,所有代号都是above50工作日移动average.

Approach 2

Craft一个小脚本(参见下面的完整代码)有更好的控制我们所做的。但结果是same.

其核心是相当小:

    cerebro = bt.Cerebro()
    for ticker in args.tickers.split(","):
        data = bt.feeds.YahooFinanceData(dataname=ticker,
                                         fromdate=fromdate, todate=todate)
        cerebro.adddata(data)

    cerebro.addanalyzer(Screener_SMA, period=args.period)
    cerebro.run(runonce=False, stdstats=False, writer=True)

约为参数解析其余mostly.

For10天(再次缩短输出):

$ ./st-screener.py
===============================================================================
Cerebro:
...
...
...
        - Screener_SMA:
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          - Params:
            - period: 10
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          - Analysis:
            - over: (u"NVDA", 63.04, 58.327), (u"AAPL", 108.18, 106.926), (u"YHOO", 42.94, 39.629000000000005), (u"IBM", 161.95, 161.221), (u"ORCL", 41.09, 41.032)
            - under: (u"TSLA", 224.91, 228.423)

相同的结果。因此,让我们避免重蹈它50days.

Concluding

Both的btrun`从Approach 1Approach 2使用小脚本一模一样的analyzer,因此提供相同results.

Andbacktrader已经能够承受另一个小challenge

Two最后说明:

  • 这两种方法都使用内置的writer功能交付output.
    • As参数btrun--writer
    • 作为参数传递给cerebro.runwriter=True
  • 在这两种情况下runonce已停用。这是为了确保在线数据同步不断,因为结果可能有不同长度(股票的人能少买卖)

脚本usage

$ ./st-screener.py --help
usage: st-screener.py [-h] [--tickers TICKERS] [--period PERIOD]

SMA Stock Screener

optional arguments:
  -h, --help         show this help message and exit
  --tickers TICKERS  Yahoo Tickers to consider, COMMA separated (default:
                     YHOO,IBM,AAPL,TSLA,ORCL,NVDA)
  --period PERIOD    SMA period (default: 10)

The全script

#!/usr/bin/env python
# -*- coding: utf-8; py-indent-offset:4 -*-
###############################################################################
#
# Copyright (C) 2015, 2016 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 Screener_SMA(bt.Analyzer):
    params = dict(period=10)

    def start(self):
        self.smas = {data: bt.indicators.SMA(data, period=self.p.period)
                     for data in self.datas}

    def stop(self):
        self.rets["over"] = list()
        self.rets["under"] = list()

        for data, sma in self.smas.items():
            node = data._name, data.close[0], sma[0]
            if data > sma:  # if data.close[0] > sma[0]
                self.rets["over"].append(node)
            else:
                self.rets["under"].append(node)


DEFAULTTICKERS = ["YHOO", "IBM", "AAPL", "TSLA", "ORCL", "NVDA"]


def run(args=None):
    args = parse_args(args)
    todate = datetime.date.today()
    # Get from date from period +X% for weekeends/bank/holidays: let"s double
    fromdate = todate - datetime.timedelta(days=args.period * 2)

    cerebro = bt.Cerebro()
    for ticker in args.tickers.split(","):
        data = bt.feeds.YahooFinanceData(dataname=ticker,
                                         fromdate=fromdate, todate=todate)
        cerebro.adddata(data)

    cerebro.addanalyzer(Screener_SMA, period=args.period)
    cerebro.run(runonce=False, stdstats=False, writer=True)


def parse_args(pargs=None):

    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description="SMA Stock Screener")

    parser.add_argument("--tickers", required=False, action="store",
                        default=",".join(DEFAULTTICKERS),
                        help="Yahoo Tickers to consider, COMMA separated")

    parser.add_argument("--period", required=False, action="store",
                        type=int, default=10,
                        help=("SMA period"))

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

    return parser.parse_args()


if __name__ == "__main__":
    run()

评论被关闭。