Back

Trailing Stop Loss

I'm already aware of how to impliment a stop loss in Quanconnect. But i'd like a better way to impliment a trailing stop loss. 

One way I did it, which I don't prefer is having a function that counts the number of days a security is in my holdings and then using that number to decide how many days to look back in history I want to check to compare if the price has dropped x % less than the maximum price in history. 

 

For example:

 

The fucntion below keeps track of number of days in portfolio.

def position_check(self):
        for stock in self.symbols:
            shares_held = float(self.Portfolio[stock].Quantity)
            if shares_held:
                self.days_in_portfolio[stock]+=1
            else:
                self.days_in_portfolio[stock]=0

 

The funtion below checks to see if the current price is x % less than the price since I bought the security:

 

def stop_loss(self,stock):
        hist = self.History([stock],self.days_in_portfolio[stock],Resolution.Daily)
        curr_price = float(self.Portfolio[stock].Price)
        if 'close' not in hist:
            return 0
        prev_max =hist['close'].max()

trail_stop= ((curr_price - prev_max) /prev_max) <= -self.stop_loss_value

return trail_stop

 

Thanks for any help in advance. :)

Update Backtest








Maybe something like:

def Initialize(self):

self.max_loss_frac = 0.03
self.asset_best_price = {}

def OnData(self, data):

# risk managment to limit per position loss to n%
map(self.RiskManagement, self.universe)

def RiskManagement(self, symbol):
# https://github.com/QuantConnect/Lean/blob/24fcd239a702c391c26854601a99c514136eba7c/Common/Securities/SecurityHolding.cs#L79https://github.com/QuantConnect/Lean/blob/24fcd239a702c391c26854601a99c514136eba7c/Common/Securities/SecurityHolding.cs#L79
if self.Portfolio[symbol].HoldStock:

# init the avg price as our current best price for the asset
if symbol not in self.asset_best_price:
self.asset_best_price[symbol] = float(self.Portfolio[symbol].AveragePrice)

# For long positions
if self.Portfolio[symbol].Quantity > 0:
# update best price
self.asset_best_price[symbol] = np.maximum(self.asset_best_price[symbol], float(self.Securities[symbol].Price))
# have we exceeded the target limits?
if (float(self.Securities[symbol].Price)-self.asset_best_price[symbol])/self.asset_best_price[symbol] < -self.max_loss_frac:
# cover the position
self.Log("RM Exit of Long pos: %s"%symbol)
self.Liquidate(symbol, tag="RM Long Cover")
del self.asset_best_price[symbol]

# For Short positions
elif self.Portfolio[symbol].Quantity < 0:
# update best price
self.asset_best_price[symbol] = np.minimum(self.asset_best_price[symbol], float(self.Securities[symbol].Price))
# have we exceeded the target limits?
if (float(self.Securities[symbol].Price)-self.asset_best_price[symbol])/self.asset_best_price[symbol] > self.max_loss_frac:
# cover the position
self.Log("RM Exit of Short pos: %s"%symbol)
self.Liquidate(symbol, tag="RM Short Cover")
del self.asset_best_price[symbol]
1

Thanks :). I think this is probably something that I should submit a feature request for as I bet many community members want trailing stop orders as a built in order type. 

0

Update Backtest





0

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.


Loading...

This discussion is closed