Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Put Call Ratio Help

Hi guys,

This website has been very helpful for me in learning about trading algorithms. I am attempting to write code that buys SPY when the put call ratio of SPX is < 1 and sells SPY when the ratio is >= 1 but am having some difficulties. Can someone please help to guide me in the right direction?

Best,
Joe

##Testing algos referencing put/call ratios##  
import numpy as np  
import datetime  
import pandas

def initialize(context):  
    # This is the search query we are using, this is tied to the csv file.  
    # User fetcher to get data. I uploaded this csv file manually, feel free to use.  
    context.query="SPX Put/Call Ratio"  
    url='https://dl.dropboxusercontent.com/s/4qaknmgfxbntz06/putcalltest.csv'  
    fetch_csv(url,  
               date_column = "Date",  
               date_format = "%m/%d/%Y",  
               symbol = context.query)  
    context.security = sid(8554) # S&P5000  

    # If the Put Call is below this value we buy. Otherwise we sell.  
    context.threshold = 1

def handle_data(context, data):  
    context.invested=False  
    #checks if put/call ratio is available for date  
    if context.query in data[context.query]:  
        indicator = (data[context.query][context.query])  

        if indicator < context.threshold:  
            order(context.security, 100)  
            context.invested = True  
            ##this ensures that there is no shorting.  
        elif indicator >= context.threshold:  
        #and context.portfolio.positions[sid(8554)].amount >= 100:  
            order(context.security, -100)  
            context.invested = False  
    #record(data[context.query][context.query])  
5 responses

To be specific, the backtest generates no results and when I uncomment record(data[context.query][context.query]) I get an error: Runtime exception: KeyError: 'SPX Put/Call Ratio'

Hey Joe,

I tried cloning your algorithm and got the same results. I think for some reason I can't access the dropbox url. I found (presumably) the same data at CBOE website (http://www.cboe.com/data/PutCallRatio.aspx). I uploaded the data to GitHub (https://gist.github.com/breeko/6210432/raw/)

I made a few other changes. I noticed context.invested is not a constraint so I made it one (if indicator < context.treshold and context.invested==False). To magnify the actual performance, I invested all the cash in your portfolio. Otherwise, you wouldn't be able to see much movement on the graph.

The result tracks the market very closely. Perhaps you can put in a larger threshold. So, for instance, if the ratio is below .8 buy and sell if above 1.2.

This is great stuff - great idea, and great assist. Thank you both for this thread!

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.

Yes, thanks for the help Branko I appreciate it!

It looks like the code uses end of day data to trade at the beginning of the day.

Let me know if I'm mistaken.

Thanks