Back to Community
Calculating VXV/VIX ratio

Hello all,

I try to calculate the VXV/VIX ratio but algo returns an error.
Could somebody explain me what is wrong with my code please ?

I'm new with Python and programming language in general, some experience with Metatrader.

Regards,
Flo

import pandas

def rename_col(df):  
    df = df.rename(columns={'CLOSE': 'price'})  
    df = df.rename(columns={'VIX Close': 'price'})  
    df = df.rename(columns={'Equity Put Volume': 'price'})  
    df = df.fillna(method='ffill')  
    df = df[['price', 'sid']]  
    # Correct look-ahead bias in mapping data to times  
    df = df.tshift(1, freq='b')  
    log.info(' \n %s ' % df.head())  
    return df  
def initialize(context):  
    # import the external data

    fetch_csv('http://www.quandl.com/api/v1/datasets/CBOEFE/INDEX_VXV.csv?trim_start=2012-01-01',  
        date_column='Date',  
        symbol='VXV',  
        post_func=rename_col,  
        date_format='%d-%m-%Y')

    fetch_csv('http://www.quandl.com/api/v1/datasets/CBOEFE/INDEX_VIX.csv?trim_start=2012-01-01',  
        date_column='Date',  
        symbol='VIX',  
        post_func=rename_col,  
        date_format='%d-%m-%Y')  
    # SPX  
    context.stock = symbol('SPY')

def handle_data(context, data):

    if (data['VXV'].price / data['VIX'].price  > 1):  
       order_target_percent(context.stock, 1)  
    if (data['VXV'].price / data['VIX'].price  < 1):  
       order_target_percent(context.stock, 0)

    #record the variables  
    if 'price' in data['VIX']:  
       record(ratio = (data['VXV'].price / data['VIX'].price))

12 responses

How can I replace this portion of code with data coming from Quandl ? my understanding is that context.SPY and context.AAPL refer to symbols in Quantopian database and declared with :


context.SPY = symbol('SPY')  
context.AAPL = symbol('AAPL')  

In this code :


def handle_data(context, data):

    prices = history(30, '1d', 'price')  
    ratio = prices[context.SPY] / prices[context.AAPL]  
    ma = talib.MA(ratio, 14)[-1:]  
    record(MA_Of_Ratio=float(ma))  

How can I use VIX and VXV instead of AAPL and SPY ?

def initialize(context):

    fetch_csv('http://www.quandl.com/api/v1/datasets/CBOEFE/INDEX_VXV.csv?trim_start=2012-01-01',  
        date_column='Date',  
        symbol='VXV',  
        post_func=rename_col,  
        date_format='%d-%m-%Y')

    fetch_csv('http://www.quandl.com/api/v1/datasets/CBOEFE/INDEX_VIX.csv?trim_start=2012-01-01',  
        date_column='Date',  
        symbol='VIX',  
        post_func=rename_col,  
        date_format='%d-%m-%Y')  
    context.VIX = 'VIX'  
    context.VXV = 'VXV'  

context.VIX = 'VIX' returns error :(

Any idea why I have this error with the code bellow ?
I can plot VIX et VXV separately with .price attribute, it is not clear for me with there is such error.
Thank's!

AttributeError: 'SIDData' object has no attribute 'price'
USER ALGORITHM:39, in handle_data
ratio = (data['VXV'].price / data['VIX'].price)

import pandas

def rename_col(df):  
    df = df.rename(columns={'CLOSE': 'price'})  
    df = df.rename(columns={'VIX Close': 'price'})  
    df = df.rename(columns={'Equity Put Volume': 'price'})  
    df = df.fillna(method='ffill')  
    df = df[['price', 'sid']]  
    # Correct look-ahead bias in mapping data to times  
    df = df.tshift(1, freq='b')  
    log.info(' \n %s ' % df.head())  
    return df  
def initialize(context):  
    # import the external data  
    fetch_csv('http://www.quandl.com/api/v1/datasets/CBOE/EQUITY_PC.csv?trim_start=2012-01-01',  
        date_column='Date',  
        symbol='PutVolume',  
        post_func=rename_col,  
        date_format='%d-%m-%Y')

    fetch_csv('http://www.quandl.com/api/v1/datasets/CBOEFE/INDEX_VXV.csv?trim_start=2012-01-01',  
        date_column='Date',  
        symbol='VXV',  
        post_func=rename_col,  
        date_format='%d-%m-%Y')

    fetch_csv('http://www.quandl.com/api/v1/datasets/CBOEFE/INDEX_VIX.csv?trim_start=2012-01-01',  
        date_column='Date',  
        symbol='VIX',  
        post_func=rename_col,  
        date_format='%d-%m-%Y')  
    # SPX  
    context.SPY = symbol('SPY')

def handle_data(context, data):

    ratio = (data['VXV'].price / data['VIX'].price)  

get it

I'm having a similar error getting AttributeError: 'SIDData' object has no attribute 'price' - did you ever get it figured out?

This usually happens if you're trying to get the price of a stock in a minute that it didn't trade.

You can add this guard to check there is price data for the security: (or in this case, the instrument)

if 'VXV' and 'VIX' in data:  
     ratio = (data['VXV'].price / data['VIX'].price)  

If your code is structured in a different way (hard-coded list of stocks, using a fundamentals or set_universe screener) then you can do:

for stock in data:  #loop through your list of stocks  
    if stock in data:  # check there is price data in this bar  
        price = data[stock].price   # access the price  

You can also see more info here: https://www.quantopian.com/help#api-common-errors

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.

Vix is an index not an ETF

Thanks - what an odd piece of code to need though, as for stock in data: should iterate through all the stocks in data, making the beck unnecessary. I suppose it has to do with the way the underlying zipline objects are overloaded dict-like obejcts: perhaps overloading in for if stock in data compares a bunch of attributes, not just existence. Thanks!

@florent: what are reading/signalling with the PC ratio's? Any insights?

I cant manage to fetch the data. for some reason all entriesare empty, even though the CSV previous seems to show data. anyone can help ? this fetcher is hard to debug

Clone Algorithm
100
Loading...
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: 55ac05ddc2763a0c714865c0
There was a runtime error.

I have some magic for you: uncomment

#context.SPY = symbol('SPY')  

.... and it the data will be in DATA... not in history though... you have to merge the data into history if you really want it

yes it works ... very strange wonder why

Magic!

Each algo needs at least one declared symbol. One of the quirks of fetcher.