-
In an attempt to see PnL in terms of pips when dealing with forex, I stumbled upon this thread: #8. In this thread @kernc suggested: class BaseStrategy(Strategy)
total_pips_gained = 0
# ......
def next(self):
super().next()
exit_portion = self.__exit_signal[-1]
print("Total pips gained: " ,self.total_pips_gained)
if exit_portion > 0:
for trade in self.trades:
if trade.is_long:
pnl_in_pips = self.position.pl / self.position.size / self.data.pip
self.total_pips_gained += pnl_in_pips
trade.close(exit_portion)
elif exit_portion < 0:
for trade in self.trades:
if trade.is_short:
pnl_in_pips = self.position.pl / self.position.size / self.data.pip
self.total_pips_gained += pnl_in_pips
trade.close(-exit_portion) With the idea that we'd want to calculate PnL of pips when we close our position. However, UPDATE: For shorts: it should be: Follow up question: I was not able to find Thank you! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 4 replies
-
Not sure it's related, but you likely should reset def init(self):
self.total_pips_gained = 0 Let me know if that does anything.
It's here: backtesting.py/backtesting/_util.py Lines 141 to 146 in 5e1accc |
Beta Was this translation helpful? Give feedback.
-
Let's extend the simple SmaCross strategy from the tests: backtesting.py/backtesting/test/_test.py Lines 54 to 69 in 73e1534 We override it such that from backtesting import Backtest, Strategy
from backtesting.test import GOOG
from backtesting.test._test import SmaCross
class S(SmaCross):
def init(self):
super().init()
self.total_pips = 0
# Patch self.position.close()
old_position_close = self.position.close
def new_position_close(*args, **kwargs):
if self.position:
pnl_in_pips = self.position.pl / self.data.pip
print(pnl_in_pips, self.trades[-1])
self.total_pips += pnl_in_pips
old_position_close(*args, **kwargs)
self.position.close = new_position_close
bt = Backtest(GOOG.iloc[:100], S, cash=10_000, trade_on_close=True)
stats = bt.run()
stats._strategy.total_pips
stats._trades
stats[['Equity Final [$]', 'Return [%]']] The numbers all add up. (There is one additional trade forcefully closed at the end of the backtest run, and that closing doesn't call our patched method, hence the missing output.) Notice the use of a result of the fact trades aren't closed instantly, but rather with the next bar's open. |
Beta Was this translation helpful? Give feedback.
-
Best just look in the source or in docs: backtesting.py/backtesting/backtesting.py Lines 600 to 604 in 73e1534
|
Beta Was this translation helpful? Give feedback.
Not sure it's related, but you likely should reset
total_pips_gained
ininit()
:Let me know if that does anything.
It's here:
backtesting.py/backtesting/_util.py
Lines 141 to 146 in 5e1accc