Back

How to get 15min bar for universe stock selection

Hi folks,

I am a newbie of this paltform and start moving some steps.

I am trying to implement a simple - not for me - trading rule that:

  1. select from Universe only stocks (S&P500) with previous day DollarVolume greater than XX $ and a volatility measure
  2. Using the selected stocks from Universe, at market open, evaluate first 15 minutes candle and check if it is greater than previous day high and go Long
  3. Check for open positions if there is a los/profit liquidating position
 This is the code I have assembled for point 1 (it's not very fast...) import numpy as np

### <summary>
### Basic template algorithm simply initializes the date range and cash. This is a skeleton
### framework you can use for designing an algorithm.
### </summary>
class BasicTemplateAlgorithm(QCAlgorithm):
'''Basic template algorithm simply initializes the date range and cash'''

def Initialize(self):
'''Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized.'''

self.SetStartDate(2018,5, 22) #Set Start Date
self.SetEndDate(2018,5,25) #Set End Date
self.SetCash(100000) #Set Strategy Cash
# Find more symbols here: http://quantconnect.com/data
self.UniverseSettings.Resolution = Resolution.Daily
self.AddUniverse(self.CoarseSelectionFunction)

self.Schedule.On(self.DateRules.EveryDay(), self.TimeRules.At(9, 45), self.EveryDayAfterMarketOpen)



# sort the data by daily dollar volume and take the top 'NumberOfSymbols'
def CoarseSelectionFunction(self, coarse):
# sort descending by daily dollar volume
#sortedByDollarVolume = sorted(coarse, key=lambda x: x.DollarVolume, reverse=True)

# return the symbol objects of the top entries from our sorted collection
#return [ x.Symbol for x in sortedByDollarVolume[:self.__numberOfSymbols] ]

self.Debug(str(self.Time) + " List:" + str(len(coarse)) )

'''select for all U.S. stocks '''
matchingSymbols = []
for cf in coarse:
#self.closeWindow = RollingWindow[decimal](4)

if cf.Symbol.SecurityType != SecurityType.Equity:
continue

#self.Debug(str(cf.Symbol.Value) )

df = self.History(cf.Symbol, 2, Resolution.Daily)

if df.empty:
continue

row = df.iloc[[0]] # get yesterday prices
time_bar = row.index.values[0][1]
close_price = row['close'].values[0]
high_price = row['high'].values[0]
low_price = row['low'].values[0]
open_price = row['open'].values[0]
volume = row['volume'].values[0]

#self.Log( "time: %s" % str( time_bar ) )
#self.Log( "close_price: %s" % str( close_price ) )
#self.Log( "high_price: %s" % str( high_price ) )
#self.Log( "low_price: %s" % str( low_price ) )
#self.Log( "open_price: %s" % str( open_price ) )


#self.Debug( "Time: %s" % str( df.index.values[0][1] ) )
#self.Debug( "Close: %s" % str( df['close']) ) # Index(['close', 'high', 'low', 'open', 'volume'], dtype='object')
#self.Debug( str(df.columns) )

volatility = ((high_price-low_price)*100)/((high_price+low_price)/2)

#self.Debug( "DollarVolume: %s - Volatility: %s " % ( cf.DollarVolume , volatility) )

if volume*close_price >= 100000000 and volatility < 1:
self.Debug("Matched symbol " + str(cf.Symbol.Value) )
matchingSymbols.append(cf.Symbol)
if len(matchingSymbols) ==5:
break

return matchingSymbols

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
'''
#if not self.Portfolio.Invested:
# self.SetHoldings("SPY", 1)
pass

def OnSecuritiesChanged(self, changes):
self.changes = changes
'''
for security in changes.RemovedSecurities:
# liquidate securities that have been removed
if security.Invested:
self.Liquidate(security.Symbol)
self.Log("Exit {0} at {1}".format(security.Symbol, security.Close))

for security in changes.AddedSecurities:
# enter short positions on new securities
if not security.Invested and security.Close != 0:
qty = self.CalculateOrderQuantity(security.Symbol, -0.25)
self.MarketOnOpenOrder(security.Symbol, qty)
self.Log("Enter {0} at {1}".format(security.Symbol, security.Close))
'''
#for security in changes.AddedSecurities:
# schedule an event to run every day at five minutes after our Symbol's market open
def EveryDayAfterMarketOpen(self):
self.Log("EveryDay.SPY 10 min after open: Fired at: {0}".format(self.Time))

 

Now I am trying to understand how "generate the 15minute bar for each stock in the selected universe. I have seen the "consolidation" stuff, but always attached to single stock. My idea is use the callback "EveryDayAfterMarketOpen" to get the 15min candle and there execute the relative buy. From documentation I dont understand how can I get the first 15 minute candle. Can you help me?

Thanks,

Alex

Update Backtest







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