Hello all,
As the title suggests I am having difficulty creating a boolean condition inside OnData to check if a current bar represents the beginning of a new year compared to the previous bar
def OnData(self, data):
if not self.Portfolio.Invested: #initialise holdings at backtest start
self.SetHoldings(self.vti, 0.3)
if ' ' ' boolean to compare current datetime with previous bar datetime' ' ' :
self.SetHoldings(self.vti, 0.3)
Has anyone got an example of how to check this?
Thank you in advance
Rahul Chowdhury
Hey Louis,
You can achieve annual rebalancing by keeping a pointer of the year when you last rebalanced. We can initialize this pointer to -1 when we start our algorithm so that it immediately rebalances.
def Initialize(self): self.SetStartDate(2015, 1, 1) # Set Start Date self.SetCash(100000) # Set Strategy Cash self.AddEquity("SPY", Resolution.Daily).Symbol self.lastYear = -1
and then in OnData we can rebalance when the year has changed.
def OnData(self, data): if self.Time.year == self.lastYear: return self.lastYear = self.Time.year self.SetHoldings("SPY", 0.5)
Louis Dwyer
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!