Hello.
I've been trying to write this algo but I'm stuck. It's intended to be a long/short equity strategy based on a few fundamentals but I'm not sure how to fire the trades and write the monthly rebalancing function. It doesn't result in equal numbers of long and short equities, but the weight is supposed to be 0.45 if the len(self.longs) > 2, otherwise SetHoldings(self.longs, 0). For the shorts it's the same but the weight is -0.45.
Any help is much appreciated.
from AlgorithmImports import *
from datetime import timedelta
from QuantConnect.Data.UniverseSelection import *
from Selection.FundamentalUniverseSelectionModel import FundamentalUniverseSelectionModel
class LongShortPF(QCAlgorithm):
def Initialize(self):
self.UniverseSettings.Resolution = Resolution.Daily
self.SetStartDate(2015, 1, 1)
self.SetEndDate(2022, 1, 1)
self.SetCash(1000000)
self._changes = None
self.numb_stocks = 50
self.AddUniverse(self.CoarseSelection, self.FineSelection)
self.UniverseSettings.DataNormalizationMode = DataNormalizationMode.Raw
#self.SetBrokerageModel(BrokerageName.InteractiveBrokersBrokerage, AccountType.Cash)
#self.SetTimeZone(TimeZones.Chicago)
def CoarseSelection(self, coarse):
self.filteredStocks = [x.Symbol for x in coarse if x.HasFundamentalData \
and (float(x.Price)) > 10 \
and x.DollarVolume > 5000000]
return self.filteredStocks
def FineSelection(self,fine):
no_fin = [sec for sec in fine if \
sec.AssetClassification.MorningstarSectorCode != MorningstarSectorCode.FinancialServices]
tops = sorted(no_fin, key = lambda sec:sec.ValuationRatios.ForwardPERatio, reverse=True)[:self.numb_stocks]
bottoms = sorted(no_fin, key = lambda sec:sec.ValuationRatios.ForwardPERatio, reverse=True)[-self.numb_stocks:]
self.longs = [l.Symbol for l in tops if l.ValuationRatios.PEGRatio < 1]
self.shorts = [s.Symbol for s in bottoms if s.ValuationRatios.PEGRatio > 1]
return self.longs + self.shorts
def OnSecuritiesChanged(self, change):
pass
def OnData(self, data):
if not self.Portfolio.Invested:
if len(self.longs) < 2:
self.SetHoldings(self.longs, 0)
else:
self.SetHoldings(self.longs, 0.45 / len(self.longs))
if len(self.shorts) < 2:
self.SetHoldings(self.short, 0)
else:
self.SetHolding(self.shorts, -0.45 / len(self.shorts))
Vladimir
William Tait
It looks like the attached backtest works exactly as you requested. If you are satisfied with my answer, please accept it and don't forget to like it.
Vladimir
William Tait
Did you have a chance to try what I recommended?
Looking forward to your response.
William Tait
Hi Vladimir.
Thank you so much for your answer. It doesn't seem to be rebalancing every month as I ended up holding extremely large positions . By the way, how do I choose whether rebalancing should happen at the end or beginning of each month?
William Tait
Sorry. I've been looking incorrectly at the Asset Sales Volume as it was my holdings. My bad. But my rebalancing question remains. Thanks!!
Vladimir
William Tait
I was unable to reproduce both your statements.
It doesn't seem to be rebalancing every month
Rebalancing days from trades log
01/04/2021
02/01/2021
03/01/2021
04/01/2021
05/03/2021
06/01/2021
07/01/2021
08/02/2021
09/01/2021
10/01/2021
11/01/2021
12/01/2021
01/03/2022
02/01/2022
03/01/2022
04/01/2022
As a result, I held very large positions.
Did you have a chance to try what I recommended?
Does the algorithm I attached to this thread do what you intended?
be a long/short equity strategy based on a few fundamentals with monthly rebalancing?
If you are satisfied with my answer, please accept it and don't forget to like it.
William Tait
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.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!