使用Backtesting.py回溯测试交易策略

2024-06-14 11:19:37 发布

您现在位置:Python中文网/ 问答频道 /正文

I want to backtest a trading strategy. Its relatively simple. Just buy a stock at a start price. Immediately set a sell order at an exit difference above and a buy order at an entry difference below. I want it to continue till a max open lot number of times. I have managed to write code below. The orders are places but none execute. I am using the backtesting.py library https://kernc.github.io/backtesting.py/doc/backtesting/index.html Example: start = 125 orders should be placed at buy 124, sell 126..buy 125, sell 127..buy 126, sell 128 and so on. The next function runs for every new row of the data and it there that i am having trouble to set my current buy and sell prices. Help anyone please

from backtesting import Backtest, Strategy, Position
from backtesting.lib import crossover, SignalStrategy
from backtesting.test import SMA

class Scalp_buy(Strategy):

    start = 125
    lot_step = 5
    buy_criteria = 1
    sell_criteria = 1
    max_open = 10
    lot_size = 6000
    max_loss = 1000
    equity_list = []
    current_buy_order = []
    current_sell_order = []
    current_buy = start - buy_criteria
    current_sell = start + sell_criteria

    def init(self):
        super().init()
        self.current_buy = self.start - self.buy_criteria
        self.current_sell = self.start + self.sell_criteria
        self.buy(price = self.start, tp = self.current_sell)

    def next(self):
        super().next()
        for x in range(0,self.max_open): 
            self.orders.set_entry(price = self.current_buy)
            self.orders.set_tp(price = self.current_sell)
            self.current_buy  += self.buy_criteria
            self.current_sell  += self.sell_criteria

       # print(self.position.open_time,self.position.open_price,self.position.pl, self.position.pl_pct , self.position.size)


bt = Backtest(df, Scalp_buy, cash=10000, commission=.0014)

output = bt.run()
output```

Tags: andtoselfpositionorderbuyopencurrent
1条回答
网友
1楼 · 发布于 2024-06-14 11:19:37

根据文档[在此处输入链接说明][1]

如果交易在收盘时为真,则市场订单将根据当前酒吧的收盘价而不是下一个酒吧的开盘价填写

您应该在参数trade_on_close=True时使用Backtest

bt = Backtest(df, Scalp_buy, cash=10000, commission=.0014, trade_on_close=True)

相关问题 更多 >