I'm trying to get two functions to alternate their execution during market hours only. The premise is to update total portfolio values and compare them to the previous close total portfolio values and log that daily performance. I've attached the code.
import numpy as np
import pandas as pd
from datetime import datetime, timedelta
from System import *
from QuantConnect import *
from QuantConnect.Algorithm import *
from QuantConnect.Data.Market import TradeBar
class BasicTemplateAlgorithm(QCAlgorithm):
'''High beta strategy'''
def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialize.'''
#Initial investment and backtest period
self.SetStartDate(2019,2,25) #Set Start Date
self.SetEndDate(2019,2,27) #Set End Date
self.SetCash(10000) #Set Strategy Cash
#Capture initial investment for risk off purposes
self.ClosingPortValue = self.Portfolio.TotalPortfolioValue
self.CurrentPortValue = self.Portfolio.TotalPortfolioValue
self.CurrentHoldValue = self.Portfolio.TotalHoldingsValue
#Universe
self.AddEquity("SPY", Resolution.Daily)
'''Schedule Function Here'''
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.Every(TimeSpan.FromMinutes(6)), self.UpdatePortValues)
self.Schedule.On(self.DateRules.EveryDay("SPY"), self.TimeRules.Every(TimeSpan.FromMinutes(7)), self.CheckDailyLosses)
'''Set Warmup Here'''
self.SetWarmup(TimeSpan.FromDays(30))
#OnData
def OnData(self, data):
'''OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here.'''
'''Arguments:
data: Slice object keyed by symbol containing the stock data'''
#Verify all indicators have warmed up before anything happens
if self.IsWarmingUp: return
self.SetHoldings("SPY", 0.10)
#Update Portfolio Values
def UpdatePortValues(self):
self.marginRemaining = self.Portfolio.MarginRemaining
self.CurrentPortValue = self.Portfolio.TotalPortfolioValue
self.CurrentHoldValue = self.Portfolio.TotalHoldingsValue
self.Log("Portfolio Values Have Been Updated")
#CheckLosses
#Check intraday losses and run defensive function if a 5.6% drop is recognized
def CheckDailyLosses(self):
self.CurrentPerformance = round( ((float(self.CurrentPortValue)/float(self.ClosingPortValue))-1)*100,2)
if (self.CurrentPortValue <= self.ClosingPortValue*0.90):
if(self.IsMarketOpen("SPY")):
self.HighLosses()
else: self.Log("Current Performance: {0}%".format(self.CurrentPerformance))
return
However, when I check my logs what I see is portfolio values being updated after the warmup followed by sequential firing of the CheckDailyLosses() method. This is then followed by sequential firing of the UpdatePortValues() method and it repeats into infinity in this pattern.
When I apply this to a more sophisticated algorithm, what I want to see is this portfolio performance check happening sandwhiched in between my morning and closing scheduled events in an alternating sequence.
Can anyone shine light onto why this is performing in this manner? I've combed through the documentation and tutorials and to my knowledge my schduled events are saying, "Every day that SPY is trading run these methods every 6 and 7 minutes respectively". If possible, I would also only like these methods to fire during market hours.
Thank you in advance. I've also attached a copy of the backtest although it doesn't display the logs.
Stephen Hyer
Edit: Can control firing during market hours by using self.IsMarketOpen() method. Only problem is getting these to fire in alternating sequence during market hours.
Stephen Hyer
Edit: I was able to solve the problem with the use of for loops.
for x in range (6,390,6): self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen("SPY", x), self.UpdatePortValues) for y in range (7,390,7): self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.AfterMarketOpen("SPY", y), self.CheckDailyLosses)
Halldor Andersen
Hi Shyer.
Use minute data resolution in the AddEquity() when using Schedule.On() for intraday events:
self.AddEquity("SPY", Resolution.Minute)
Also, use Action() when calling functions from Schedule.On():
self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.Every(TimeSpan.FromMinutes(6)), Action(self.UpdatePortValues)) self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.Every(TimeSpan.FromMinutes(7)), Action(self.CheckDailyLosses))
To retrieve the portfolio value at the end of each day, use OnEndOfDay():
def OnEndOfDay(self): self.ClosingPortValue = self.Portfolio.TotalPortfolioValue
To make sure the functions ignite during market hours, use:
if not self.IsMarketOpen("SPY"): return
I've attached a backtest where I've made adjustments to your code according to the highlights above.
Stephen Hyer
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!