使用样板策略假设买卖 1 股(仅限多头/每个买入订单都与卖出订单相结合)。
出于某种原因,当我卖出股票时,它会以与开仓时相同的金额记录交易价值(股票 * 价格),尽管股价不同。
输出:
2018-02-15 10:30:00, BUY ORDER PLACED, Price: 169.79, Cost: 0.00, Comm: 0.00
2018-02-15 10:30:00, BUY ORDER EXECUTED, Price: 172.06, Cost: 172.06, Comm: 0.17
2018-03-19 14:30:00, SELL ORDER PLACED, Price: 174.19, Cost: 0.00, Comm: 0.00
2018-03-19 14:30:00, SELL ORDER EXECUTED, Price: 174.88, Cost: 172.06, Comm: 0.17
上图我们可以看到买单在 172.06 执行(交易价值(即成本)在交易 1 股时是相同的),但是卖单以不同的价格执行(174.88)但仍然具有相同的交易价值和佣金?
示例代码:
class Test(bt.SignalStrategy):
def __init__(self):
self.sma1 = bt.ind.SMA(period=100)
self.dataclose= self.datas[0].close
self.order = None
self.buyprice = None
self.buycomm = None
self.sellprice = None
self.sellcomm = None
def log(self, txt, dt=None):
dt = dt or self.data.datetime.datetime(0)
print('%s, %s' % (dt, txt))
def notify_order(self, order):
# 1. If order is submitted/accepted, do nothing
if order.status in [order.Submitted, order.Accepted]:
return
# 2. If order is buy/sell executed, report price executed
if order.status in [order.Completed]:
if order.isbuy():
self.log('BUY ORDER PLACED, Price:{0:8.2f}, Cost:{1:8.2f}, Comm:{2:8.2f}'.format(order.created.price,order.created.value,order.created.comm))
self.log('BUY ORDER EXECUTED, Price:{0:8.2f}, Cost:{1:8.2f}, Comm:{2:8.2f}'.format(order.executed.price,order.executed.value,order.executed.comm))
self.buyprice = order.executed.price
self.buycomm = order.executed.comm
if order.issell():
self.log('SELL ORDER PLACED, Price:{0:8.2f}, Cost:{1:8.2f}, Comm:{2:8.2f}'.format(order.created.price,order.created.value,order.created.comm))
self.log('SELL ORDER EXECUTED, Price:{0:8.2f}, Cost:{1:8.2f}, Comm:{2:8.2f}'.format(order.executed.price, order.executed.value,order.executed.comm))
self.sellprice = order.executed.price
self.sellcomm = order.executed.comm
self.bar_executed = len(self) #when was trade executed
# 3. If order is canceled/margin/rejected, report order canceled
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log('Order Canceled/Margin/Rejected')
self.order = None
def next(self):
if self.order:
return
if self.getposition(data=self.data).size == 0:
if data.close[0] > self.sma1:
self.buy()
else:
if data.close[0] < self.sma1:
self.close()