欢迎大家来到IT世界,在知识的湖畔探索吧!
一、The Sample
backtrader尝试为每种新功能提供一个样本,这也不例外。 没有钟声和吹口哨,只是测试结果的结果是预期的。 这是在目录中的order_target下样本。
样本中的逻辑相当笨拙,仅可用于测试:
1.这模仿了一个不断增加的目标:
在奇数月(1月,3月,...)中,将日期用作目标(对于order_target_value而言,一天乘以1000)
欢迎大家来到IT世界,在知识的湖畔探索吧!
2.这模仿了一个减少的目标:
欢迎大家来到IT世界,在知识的湖畔探索吧!在偶数月份(2月,4月,...)中,将31天作为目标
二、order_target_size:
让我们看看一月和二月会发生什么:
$ ./order_target.py --target-size -- plot
0001 - 2005-01-03 - Position Size: 00 - Value 1000000.00
0001 - 2005-01-03 - Order Target Size: 03
0002 - 2005-01-04 - Position Size: 03 - Value 999994.39
0002 - 2005-01-04 - Order Target Size: 04
0003 - 2005-01-05 - Position Size: 04 - Value 999992.48
0003 - 2005-01-05 - Order Target Size: 05
0004 - 2005-01-06 - Position Size: 05 - Value 999988.79
...
0020 - 2005-01-31 - Position Size: 28 - Value 999968.70
0020 - 2005-01-31 - Order Target Size: 31
0021 - 2005-02-01 - Position Size: 31 - Value 999954.68
0021 - 2005-02-01 - Order Target Size: 30
0022 - 2005-02-02 - Position Size: 30 - Value 999979.65
0022 - 2005-02-02 - Order Target Size: 29
0023 - 2005-02-03 - Position Size: 29 - Value 999966.33
0023 - 2005-02-03 - Order Target Size: 28
...
三、order_target_value
从目标值可以预期会有类似的行为:
欢迎大家来到IT世界,在知识的湖畔探索吧!$ ./order_target.py --target-value --plot
0001 - 2005-01-03 - Position Size: 00 - Value 1000000.00
0001 - 2005-01-03 - data value 0.00
0001 - 2005-01-03 - Order Target Value: 3000.00
0002 - 2005-01-04 - Position Size: 78 - Value 999854.14
0002 - 2005-01-04 - data value 2853.24
0002 - 2005-01-04 - Order Target Value: 4000.00
0003 - 2005-01-05 - Position Size: 109 - Value 999801.68
0003 - 2005-01-05 - data value 3938.17
0003 - 2005-01-05 - Order Target Value: 5000.00
0004 - 2005-01-06 - Position Size: 138 - Value 999699.57
...
0020 - 2005-01-31 - Position Size: 808 - Value 999206.37
0020 - 2005-01-31 - data value 28449.68
0020 - 2005-01-31 - Order Target Value: 31000.00
0021 - 2005-02-01 - Position Size: 880 - Value 998807.33
0021 - 2005-02-01 - data value 30580.00
0021 - 2005-02-01 - Order Target Value: 30000.00
0022 - 2005-02-02 - Position Size: 864 - Value 999510.21
0022 - 2005-02-02 - data value 30706.560022 - 2005-02-02 - Order Target Value: 29000.00
0023 - 2005-02-03 - Position Size: 816 - Value 999130.05
0023 - 2005-02-03 - data value 28633.44
0023 - 2005-02-03 - Order Target Value: 28000.00
...
还有一条额外的信息行,告诉您(组合中的)实际数据值是多少。 这有助于找出目标值是否已达到。
初始目标为3000.0,报告的初始值为2853.24。 这里的问题是这是否是足够近。
答案是肯定的
- 该示例在每日柱状图的末尾使用市场定单,最后使用的价格为计算满足目标值的目标大小
- 执行将使用第二天的开盘价,这不太可能是前一天的开盘价。
以任何其他方式进行操作将意味着有人在欺骗他/她自己。
下一个目标值和最终值更接近:4000和3938.17。
更改为Feb后,目标值开始从31000减小到30000和29000。 所以
数据值从`30580.00到30706.56,然后到28633.44。 等待:
- 30580 -> 30706.56 is a positive change
确实。 在这种情况下,目标值的计算得出的大小满足了开盘价,而开盘价超出了价值到30706.56
如何避免这种影响:
- 该示例对订单使用Market类型执行,无法避免这种影响
- 方法order_target_xxx允许指定执行类型和价格。
可以将Limit指定为执行订单,然后将价格设为收盘价(如果没有其他内容,则不提供)甚至提供具体的定价。
四、order_target_percen
在这种情况下,它只是当前投资组合价值的百分比。
$ ./order_target.py --target-percent --plot
0001 - 2005-01-03 - Position Size: 00 - Value 1000000.00
0001 - 2005-01-03 - data percent 0.00
0001 - 2005-01-03 - Order Target Percent: 0.03
0002 - 2005-01-04 - Position Size: 785 - Value 998532.05
0002 - 2005-01-04 - data percent 0.03
0002 - 2005-01-04 - Order Target Percent: 0.04
0003 - 2005-01-05 - Position Size: 1091 - Value 998007.44
0003 - 2005-01-05 - data percent 0.04
0003 - 2005-01-05 - Order Target Percent: 0.05
0004 - 2005-01-06 - Position Size: 1381 - Value 996985.64
...
0020 - 2005-01-31 - Position Size: 7985 - Value 991966.28
0020 - 2005-01-31 - data percent 0.28
0020 - 2005-01-31 - Order Target Percent: 0.31
0021 - 2005-02-01 - Position Size: 8733 - Value 988008.94
0021 - 2005-02-01 - data percent 0.31
0021 - 2005-02-01 - Order Target Percent: 0.30
0022 - 2005-02-02 - Position Size: 8530 - Value 995005.45
0022 - 2005-02-02 - data percent 0.30
0022 - 2005-02-02 - Order Target Percent: 0.29
0023 - 2005-02-03 - Position Size: 8120 - Value 991240.75
0023 - 2005-02-03 - data percent 0.29
0023 - 2005-02-03 - Order Target Percent: 0.28
...
并且信息已更改,可以查看数据在投资组合中所占的百分比。
五、Sample Usage
$ ./order_target.py --help
usage: order_target.py [-h] [--data DATA] [--fromdate FROMDATE]
[--todate TODATE] [--cash CASH]
(--target-size | --target-value | --target-percent)
[--plot [kwargs]]
Sample for Order Target
optional arguments:
-h, --help show this help message and exit
--data DATA Specific data to be read in (default:
../../datas/yhoo-1996-2015.txt)
--fromdate FROMDATE Starting date in YYYY-MM-DD format (default:
2005-01-01)
--todate TODATE Ending date in YYYY-MM-DD format (default: 2006-12-31)
--cash CASH Ending date in YYYY-MM-DD format (default: 1000000)
--target-size Use order_target_size (default: False)
--target-value Use order_target_value (default: False)--target-percent Use
order_target_percent (default: False)
--plot [kwargs], -p [kwargs]
Plot the read data applying any kwargs passed For
example: --plot style="candle" (to plot candles)
(default: None)
六、Sample Code
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
from datetime import datetime
import backtrader as bt
import pandas as pd
class TheStrategy(bt.Strategy):
'''
This strategy is loosely based on some of the examples from the Van
K. Tharp book: *Trade Your Way To Financial Freedom*. The logic:
- Enter the market if:
- The MACD.macd line crosses the MACD.signal line to the upside
- The Simple Moving Average has a negative direction in the last x
periods (actual value below value x periods ago)
- Set a stop price x times the ATR value away from the close
- If in the market:
- Check if the current close has gone below the stop price. If yes,
exit.
- If not, update the stop price if the new stop price would be higher
than the current
【此策略大致基于范的一些示例
K. Tharp的书:*以贸易方式实现财务自由*。 逻辑:
-在以下情况下进入市场:
-MACD.macd行穿过MACD.signal行向上
-简单移动平均线的最后x方向为负
周期(实际值低于值x周期前)
-设置止损价x收盘价乘以ATR值的倍数
-如果在市场上:
-检查当前收盘价是否已低于止损价。 如果是,
出口。
-否则,如果新的止损价会更高,则更新止损价
比目前】
'''
params = (
('use_target_size', False),
('use_target_value', False),
('use_target_percent', False),
)
def notify_order(self, order):
if order.status == order.Completed:
pass
if not order.alive():
self.order = None # indicate no order is pending
def start(self):
self.order = None # sentinel to avoid operrations on pending order
def next(self):
dt = self.data.datetime.date()
portfolio_value = self.broker.get_value()
print('%04d - %s - Position Size: %02d - Value %.2f' %
(len(self), dt.isoformat(), self.position.size, portfolio_value))
data_value = self.broker.get_value([self.data])
if self.p.use_target_value:
print('%04d - %s - data value %.2f' %
(len(self), dt.isoformat(), data_value))
elif self.p.use_target_percent:
port_perc = data_value / portfolio_value
print('%04d - %s - data percent %.2f' %
(len(self), dt.isoformat(), port_perc))
if self.order:
return # pending order execution
size = dt.day
if (dt.month % 2) == 0:
size = 31 - size
if self.p.use_target_size:
target = size
print('%04d - %s - Order Target Size: %02d' %
(len(self), dt.isoformat(), size))
self.order = self.order_target_size(target=size)
elif self.p.use_target_value:
value = size * 1000
print('%04d - %s - Order Target Value: %.2f' %
(len(self), dt.isoformat(), value))
self.order = self.order_target_value(target=value)
elif self.p.use_target_percent:
percent = size / 100.0
print('%04d - %s - Order Target Percent: %.2f' %
(len(self), dt.isoformat(), percent))
self.order = self.order_target_percent(target=percent)
def runstrat(args=None):
args = parse_args(args)
cerebro = bt.Cerebro()
cerebro.broker.setcash(args.cash)
dkwargs = dict()
if args.fromdate is not None:
dkwargs['fromdate'] = datetime.strptime(args.fromdate, '%Y-%m-%d')
if args.todate is not None:
dkwargs['todate'] = datetime.strptime(args.todate, '%Y-%m-%d')
# data
data = bt.feeds.YahooFinanceCSVData(dataname=args.data, **dkwargs)
cerebro.adddata(data)
# strategy
cerebro.addstrategy(TheStrategy,
use_target_size=args.target_size,
use_target_value=args.target_value,
use_target_percent=args.target_percent)
cerebro.run()
if args.plot:
pkwargs = dict(style='bar')
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 Order Target')
parser.add_argument('--data0', default=r'E:\ml\Python_door_trader\backtrader_programma\stock600000.XSHG.csv',
required=False, help='Data to 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('--cash', required=False, action='store',
type=float, default=1000000,
help='Ending date in YYYY-MM-DD format')
pgroup = parser.add_mutually_exclusive_group(required=True)
pgroup.add_argument('--target-size', required=False, action='store_true',help=('Use order_target_size'))
pgroup.add_argument('--target-value', required=False, action='store_true',
help=('Use order_target_value'))
pgroup.add_argument('--target-percent', required=False,
action='store_true',
help=('Use order_target_percent'))
# 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:\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()
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/34165.html