How do I get price from a symbol? ( A variable )

I'm trying something like this:

ticker = 'AAPL'
today_s_data = data[ symbol( ticker ) ].price

And it gives me this error:

62 Error non-string argument given to symbol()

But clearly type( ticker ) is 'str'.

Why doesn't it recognize it as a string?

It only works with I type in symbol( 'AAPL' ). Weird.

18 responses

please code up an algo and add it as a backtest so we can interact with your code.

Okay here it is.

21
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
 Returns 1 Month 3 Month 6 Month 12 Month
 Alpha 1 Month 3 Month 6 Month 12 Month
 Beta 1 Month 3 Month 6 Month 12 Month
 Sharpe 1 Month 3 Month 6 Month 12 Month
 Sortino 1 Month 3 Month 6 Month 12 Month
 Volatility 1 Month 3 Month 6 Month 12 Month
 Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
import datetime
import pytz
import numpy as np

def initialize(context):

#log.info( context.stocks[ 2 ] )
context.ticker_string = [ 'ABT', 'ABBV', 'ACE', 'ACN' ]

# Will be called on every trade event for the securities you specify.
def handle_data( context , data ):
# Implement your algorithm logic here.

# data[sid(X)] holds the trade event data for that security.

today_s_data = np.zeros( ( 502 , ) , dtype = np.float32 )
for i in xrange( 502 ):
#ticker = str( context.ticker_string[ i ] )
ticker = 'AAPL'
if symbol( 'AAPL' ) in data:
today_s_data[ i ] = data[ symbol( 'AAPL' ) ].price
else:
today_s_data[ i ] = 0.

log.info( get_datetime().hour )
# context.portfolio holds the current portfolio state.

# Place orders with the order(SID, amount) method.

# TODO: implement your own logic here.
#order(sid(24), 50)

There was a runtime error.

Any idea why it doesn't work?

Seriously? No one had this problem before? Everybody here manually types in the symbols they want to get data for?

I find that hard to believe.


# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
import datetime
import pytz
import numpy as np

def initialize(context):
symbol('AAPL') # seed data dict
def handle_data( context , data ):
for tkr in data:
pricenow = data[tkr].price



Thank you Dan!

Let me try it.

Dan,

So just to clarify,

symbol('AAPL') # seed data dict

This part can't become:

symbol( some_tkr )

Is that right? Because that's what I'm trying to not have to type in manually.

Thanks!!


# Try this:
def initialize(context):
# I should declare my symbols here.
# Side effect: data-dict gets filled with prices and other data.
symbols('AAPL','IBM','SPY')
def handle_data( context , data ):
for tkr in data:
print(tkr.symbol)
print(data[tkr].price)



Dan, thanks for the repeated responses!

But I think you are not getting my question. I need to NOT type in the symbols manually into the 'symbol' or 'symbols' object, like you did in your answer. I need to pass them in as a parameter.

# like this:
def initialize( context ):
# generate a list of symbols here, then
symbols( this_tkr, that_tkr )
# but it gives me an error saying this_tkr is not a string argument, which it is.



What I need to do is look at the prices of multiple stocks, say, every day at the same time. How do you do this?

Hi Ning,

You can't have a string representing the symbol you want because all the symbols must be known before starting the backtest.

But you could have something like this:

def initialize(context):
context.stock1 = symbol('AAPL')
context.stock2 = symbol('IBM')
context.listOfStocks = symbols('GS','C','SPY')
def handle_data( context , data ):
for tkr in data:  # AAPL,IBM,GS,C,SPY
print(tkr.symbol)
print(data[tkr].price)


If you want a random bunch of stocks you can use set_universe() instead:

    set_universe(universe.DollarVolumeUniverse(98, 99))


Hope that helps

Thanks for the response James!

I'm not using a random selection of stocks.

The symbols() function can only take 255 arguments, that's the problem here. I wouldn't mind manually typing it in if I have to.

But that just seems odd that in a library for running trading algorithms it would be so hard to load more than a few stock prices.

There must be something I'm missing here, right?

If I'm doing more than 20 or so I just use a text editor with regular expression search/replace to build the symbols() list and paste it into the algo. I wasn't actually aware of the 255 cap. I think if you use set_universe() then the most you will ever get is about 400 (??) depending on how many stocks are listed on the exchange at that point in time. I think Quantopian's reason was due to the long running-time for algos using so many symbols. Perhaps someone from Q can confirm :)

Thanks James!

I think it makes sense.

I hope there is a way to look at over 400 stocks on every iteration with Quantopian. Maybe there is, and someone with the knowledge can help us out!

To chime in here,

1. The stocks need to explicitly called in the backtest - you can't pass a variable into "symbol". This is because we scan the algorithm for code errors and malicious intent before we run it on our servers.

2. You can trade up to 200 securities per bar of the backtest. This cap exists for performance reasons so that we can maintain a good backtesting experience - otherwise it's a lot of data! A couple months ago we increased the cap from 100 to 200 securities and I imagine as we continue to grow, we'll raise the cap again.

I hope this helps clear up any lingering confusion!

Disclaimer

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 Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian 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.

Thanks for the clarification Alisa!

So you said, you can trade 200 securities, but can I load the prices for more than 200?

After so many years, the bug still exists, quite disappointing

when it came to futures, you have to type all the symbols manually, very tired

As you noticed, the 'future_symbol' method works a bit different in the IDE vs the notebook environment. The symbol argument must be a string, and not a variable, in the IDE. This isn't really a bug. Just a difference. Not a way to work around this behavior.

Disclaimer

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 Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian 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.