kernc / kernc/backtesting.py

close position with some note

Open
#1,303 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
Python
Stars
9k
Forks
1.5k
PR merge metrics
No merged PRs in 30d

Description

Discussed in https://github.com/kernc/backtesting.py/discussions/1298

Originally posted by silverwolf-x August 4, 2025
I want to add reasons for the end of certain trades, for example, how do I tag the ending order of the buy trade from 2013-02-26, indicating that I ended the trade due to reason R, and write R into this order and trade.

from datetime import date
from backtesting import Backtest, Strategy
from backtesting.lib import crossover

from backtesting.test import SMA, GOOG
class SmaCross(Strategy):
    n1 = 10
    n2 = 20

    def init(self):
        close = self.data.Close
        self.sma1 = self.I(SMA, close, self.n1)
        self.sma2 = self.I(SMA, close, self.n2)

    def next(self):
        if not self.data.index[-1].date() >= date(2013, 2, 1):
            if crossover(self.sma1, self.sma2):
                self.position.close()
                self.buy()
            elif crossover(self.sma2, self.sma1):
                self.position.close()
                self.sell()
        else:
            if self.data.index[-1].date() == date(2013, 2, 26):
                self.buy(size=1, tag="2013-02-26buy")
            if self.data.index[-1].date() == date(2013, 2, 27):
                self.position.close()
bt = Backtest(GOOG, SmaCross, cash=10000, commission=0.002)

stats = bt.run()

My Hope:

when calling either self.position.close(reason="R") or self.trade.close(reason="R"), I want to update the tag of any canceled order to "R". This makes sense because, at that point, the order looks like this:

{
 'is_contingent': False,
 'is_long': False,
 'is_short': True,
 'limit': None,
 'parent_trade': <Trade size=34 time=2146- price=801.1- pl=173 tag=2013-02-26buy>,
 'size': -34.0,
 'sl': None,
 'stop': None,
 'tag': '2013-02-26buy',
 'tp': None
}

Since the order already contains a parent_trade, updating the tag to "R" clearly indicates that the reason for closing the trade was "R".

Additionally, it would be useful if trades included a new property: close_reason (e.g.), which would display "R" in such cases.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the position and trade close entry points shown in the example (self.position.close() and self.trade.close()), then trace how the closing order and parent trade are represented. Define how a supplied reason should be retained in the order and trade data, including the requested close_reason; done means the example can record and expose the reason consistently.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.