kernc / backtesting.py

:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.
https://kernc.github.io/backtesting.py/
GNU Affero General Public License v3.0
5.04k stars 987 forks source link

allow open trades at end of backtest. #1102

Open themantalope opened 6 months ago

themantalope commented 6 months ago

Added option to leave trades open at the end of a backtest. Allows users to check if they have open trades at the end of a backtest as an easy way to use the strategy in a "live" manner.

LorenzoPietroBonatti commented 5 months ago

Hey, could you please show me how is it working for you? I tried to fork your branch and use it, but the trades doesn't remained open. Even if my strategy should be bought in the past candles and should not have sold all my position. Appreciate the help.

themantalope commented 5 months ago

Sure, here is a quick example:

from other_module import AmazingStrategy
from backtesting import Backtest
import pandas as pd

data = pd.read_csv("filewith_olhc.csv")
bt = Bactest(data, AmazingStrategy, cash=10000, leave_orders_open=True)
results = bt.run()
# now get the strategy object from results
strat_res = results._strategy
open_trades = strat_res.trades

Typically, all trades are closed at the end of the Backtest.run (see here). I wanted to be able to take a strategy with updated daily data and see if there are any "open" trades/positions (not sure which is the better term to use). If there is a less clunky way to do so please let me know.