Back

Access slice.Bars by symbol text

The docs for Handling Data include sample code like:

For example ibmBar = slice.Bars["IBM"]

When I try this I get the error message:

 Runtime Error: TypeError : unindexable object at OnData in main.py:line 96
 TypeError : unindexable object

My ondata code looks like this:

def OnData(self, slice):
#self.Debug('Begin OnData ' +' '+str(self.Time)+' '+str(slice.Bars.Count)+' '+str(self.curPositions))

if slice.Bars.Count == 0: return
#if self.changes == None: return

for tradeBar in slice.Bars.Values:
sym = tradeBar.Symbol.Value
self.Log('tradeBar Sym: '+ sym)


crmBar = slice.Bars["CRM"]
self.Log ('slice.count: '+str(slice.Bars.Count)+' crm: '+str(crmBar.Symbol.Value))

The universe is loaded by a custom list and the code properly logs the four symbols in the slice, including CRM, before failing at crmBar=slice.Bars['CRM'].

This is obviously test code, but related to my goal to evaluate the symbols in slice in the order they are loaded in the custom universe.  I want to evaluate potential trades in that order because the symbols loaded first have a better profit potential than the other symbols - if the trade is triggered.  

Thanks for some help, I've spent way too much time on this simple issue.

  
Update Backtest







Hi Hugh,

For equity, you could simply use slice["CRM"].  It is already a TradeBar. 

slice["CRM"].Open
slice["CRM"].Close
slice["CRM"].EndTime
slice["CRM"].Volume
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.


Jing Wu  Thanks for the suggestion, but unfortunately it does not work - when the symbols are added via the custom universe.  As a test I tried adding the same four symbols in initialize using AddEquity and your suggestion worked, but not with the custom universe.  The error message was different though.  Where it was generating an  "unindexable object" error using slice.Bars, it is now generating a "KeyNotFound" exception.

Below is my code using the custom universe logic.  It properly logs the four symbols in the slice, and then dies at the slice["CRM'] command.

import numpy as np
import decimal as d

class BasicTemplateAlgorithm(QCAlgorithm):

def Initialize(self):
self.SetStartDate(2018,4,6) #(2013,1,1)
self.SetEndDate(2018,4,10)

self.backtestSymbolsPerDay = {}
self.current_universe = []
self.cuDate = 'x'

self.UniverseSettings.Resolution = Resolution.Hour;
self.AddUniverse("my-dropbox-universe", self.universeGetter)

self.symDatas = {} # holds symbolData objects
self.curPositions = 0

def universeGetter(self, date):

# handle live mode file format
if self.LiveMode:
# work on this later
return self.current_universe

# backtest - first cache the entire file
#if len(self.backtestSymbolsPerDay) == 0:
# str = self.Download("https://www.dropbox.com/s/rmiiktz0ntpff3a/daily-stock-picker-backtest.csv?dl=1")
# for line in str.splitlines():
# data = line.split(',')
# self.backtestSymbolsPerDay[data[0]] = data[1:]
# Dummmy this up for now
if len(self.backtestSymbolsPerDay) == 0:
self.backtestSymbolsPerDay['20180406'] = ['ABMD', 'BZUN', 'CRM', 'NOW']
self.backtestSymbolsPerDay['20180413'] = ['PAYC', 'ULTI', 'CRM', 'ADBE']
self.backtestSymbolsPerDay['20180420'] = ['PAYC', 'ADBE', 'CRM', 'RHT']
self.backtestSymbolsPerDay['20180427'] = ['PAYC', 'CRM', 'RHT', 'BOOT']

index = date.strftime("%Y%m%d")
if index in self.backtestSymbolsPerDay:
self.cuDate = index
self.current_universe = self.backtestSymbolsPerDay.get(index, self.current_universe)

return self.current_universe

def OnData(self, slice):
#self.Debug('Begin OnData ' +' '+str(self.Time)+' '+str(slice.Bars.Count)+' '+str(self.curPositions))

if slice.Bars.Count == 0: return
#if self.changes == None: return

for tradeBar in slice.Bars.Values:
sym = tradeBar.Symbol.Value
self.Log('tradeBar Sym: '+ sym +' '+ str(tradeBar.Close))


crmBar = slice["CRM"]
self.Log('Close: for ' + crmBar.Symbol.Value +' is '+str(crmBar.Close))



# reset changes
self.changes = None

#self.Debug(str(self.Time) +' '+'end OnData')

def OnSecuritiesChanged(self, changes):
self.changes = changes


# remove symbolData for removed symbols
#for sec in self.changes.RemovedSecurities:
# self.symDatas.pop(sec.Symbol, None)

Thanks.  Any other ideas?

0

Let me go at this another way - if slice[symbol string] doesn't work but slice[symbol object] does work, how can I get symbol object from symbol string?

0

Like this

symbol = Symbol.Create("IBM", SecurityType.Equity, Market.USA)
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.


Jared Broad 

Thank you very much.  That works and let's me move forward.

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