For code/output blocks: Use ``` (aka backtick or grave accent) in a single line before and after the block. See: http://commonmark.org/help/
Finding The Maximum Profit of a Position at A Point in Time
-
I am currently running a backtest of a wide range of stocks.
At any given time, the system I am backtesting holds multiple positions concurrently. I would like to track the maximum profit of each position from the point of it is taken to the "current" bar. Why? The maximum profit of each position is a key exit parameter.
To do this I created a list called "self.position_pnl_list". Here is how I integrated it into my code:
class BTStrategy(bt.Strategy): def __init__(self): pass def start(self): self.bought_bars={d:0 for d in self.getdatanames()} self.sold_bars={d:0 for d in self.getdatanames()} self.size = None self.initial_risk = None self.position_pnl_list = [] def next(self): for i, d in enumerate(self.getdatanames()): pos = self.getposition(data=self.getdatabyname(d)) comminfo = self.broker.getcommissioninfo(data=self.getdatabyname(d)) position_pnl = comminfo.profitandloss(pos.size, pos.price, self.getdatabyname(d).close[0]) risk_parity_size = int((self.broker.getvalue() * 0.01)/self.getdatabyname(d).atr[0]) self.trailing_stop = self.getdatabyname(d).trailing_stop self.position_pnl_list.append(position_pnl)
When I close each position, I delete the list values just to make sure that does not mix old position profit metrics with new ones: as follows:
if pos.size: if len(self.position_pnl_list) > 0: maximum_position_profit = max(self.position_pnl_list) if maximum_position_profit >= 1000: self.close(data=self.getdatabyname(d), size=self.size) del self.position_pnl_list[:]
Questions:
- Is this the correct approach?
- Is there a better way or an inbuilt Backtrader I could use to accomplish my goals?