Getting sid programmatically

Hi all,

I am trying to implement a simple algorithm that buys/sells a random security based on a coin flip (aka Cramer's algorithm). How can I select a stock at random? The following code does not work, and errors out saying sid takes only one parameter.

import random

# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
pass

# 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.
# data.portfolio holds the current portfolio state.

# Place orders with the order(SID, amount) method.
thestock = int(random.randint(1,200))
stock = sid(thestock)
coin = random.random()
if (coin < 0.5):
order(stock, 1)
else:
order(stock, -1)


10 responses

Hi,

This is a fun idea!

The sid function is a common pitfall - it is really only intended for explicitly identifying a security at development time. We actually pre-parse the script to find all the sid calls, and use that information to configure the data sent to your algorithm. As a result, we don't allow variables to be passed into the function. Luckily, we provide an alternative to select a universe of stocks without explicitly identifying any of them. You make the selection using a builtin called set_universe. In the attached backtest, I select a random universe of stocks based on the DollarVolume traded. Then, I choose a random security from that universe in the handle_data method, and use your coin flip code to decide on buying or selling it.

thanks,
fawce

68
Backtest from to with initial capital
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
# Backtest ID: 5167532c7a4cc4068beb3be9
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.
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 a lot for the quick reply and the sample code.

Also...3735% return based on randomness?? Wow.

Well, I didn't add any position limits, so it builds a pretty massive amount of leverage. I ran a bunch of samples and the returns are... random.

Hi Fawce,

Can the parameters 'bottom' & 'top' in set_universe vary within a program?

set_universe(universe.DollarVolumeUniverse(bottom, top))


In other words, for example, could I get access to different chunks of the universe for each tic?

Grant

Grant,

Sorry, that's not possible. set_universe is in initialize, and only callable once.

The real fix for this is to let you call the whole universe rather than just part of it. We'll get there.

Dan

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.

Dan,

No problem...I can try my algorithm with just a chunk of the universe. If I get it working, I'll post it. Basically looking to use a time series pattern matching algorithm that I developed to sort securities from most similar to least.

Grant

Very interesting experiment :) As I was thinking about it, if we simply choose one stock and randomly buy/sell it, why don't we try randomly picking two stocks and buy the one with lower price and sell the one with the higher price? It sounds like a very primitive version of pair trading, and I was hoping to get on average a better return. It did. Next step would be to make it more stable - a practical way of doing it is to run this algo a couple times using smaller amount of investments for each. Say you have $100, and you can split it into ten$10 trials of this algo and I believe since you have a positive expected return you can make money from this. Any ideas?

76
Backtest from to with initial capital
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
# Backtest ID: 5168770414359d067a30b596
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.

The returns probably need to be averaged over many (> 1000) random seeds...maybe the sequence of random nums led to 3000 and 4000% returns. I am guessing such a strategy has returns with zero mean and high variance (with another random seed I lost 4000%).

EDIT: Can I embed images here??? http://i.imgur.com/gtvZTbL.png

Hey Ha, good point here. But I still think the expected value seems to be higher than zero since you are after all buying at a lower price and selling at a higher one - intuitively. I definitely agree that we need to have some sort of average over a larger set of randomized data.

The algos look fantastic but how do you get such volatility using just equities?