Back to Community
Method to get historic values from fetcher data

When using fetcher, the History function currently doesn't return the values fetched from data. One is limited to using the standard price,mavg, etc. If you want more than that, you must collect the values yourself in an array, which means your have created a warm-up period for the algorithm. This can be tolerated for backtesting, but is a real problem for live algorithms.

Thanks to Seong Lee of the Quantopian engineering staff, who came up with this clever workaround which will allow me to relaunch my live algorithm this week, using a vix slope calculation.

The algorithm gets around the limitation of returning a single item per day, by stuffing all the values into a string and passing back that single string, and then splitting the string and converting it back to numeric values.

I've tested it live and in simulation.

Clone Algorithm
48
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: 543eb9538362450900f33f59
There was a runtime error.
36 responses

Richard,
Thanks for sharing, fetcher/history issues are something I've run into as well. I'm not 100% sure if this will apply to your specific case, but if you would like to do historical calculations on fetched data, there is one other option I have found.

If you add a pre_func argument to the fetch_csv function, you will have access to the entire dataframe while in that function. That means you can apply rolling calculations on the data and append the results as new columns. This example here adds a moving average and standard deviation field to the VIX data. You will have to be careful not to introduce look ahead bias though.

David

Clone Algorithm
37
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: 543f030018b9786a994a71b2
There was a runtime error.

David
Seong Lee suggested this to me first, but I wanted something a bit more generic, because I have a lot of code and I wanted the flexibility of having the array of values to manipulate. But it's good that you mentioned it, because for many people it's probably a better solution.

Rich

I just discovered the need for this, but I think I'll have to do the packed string method - I need to calculate historical spreads between various fetched time-series. Thanks, I look forward to a better way of doing this one day though!

Hi dAVid... what is the difference... between... te first chart and your chart...?? are you using... vix as buy and sell signal... or its already in the algo... that when the vix spikes... automatic buy some stocks... puzzled....

@David - Don't the mean and std seem to be going right to left in your chart? Have in mind that Yahoo historical data comes in reverse-chronological order.

Just realized fetch_csv does not work in live mode. I am stunned that the fetch_csv function was even introduced without proper support in live execution. Now my algo is stuck in backtest mode without this brittle hack.

It works for me, you just can't enter them into the contest. What is the issue you are seeing?

https://www.quantopian.com/posts/function-like-history-but-for-fetch-csv-data

This is the unpleasant hack I use to get access to some number of historical rows of data from fetch_csv, in a way that avoids look-ahead bias. It's been working well enough for a couple of months of live trading though.

EDIT: And all due credit to the above Richard Diehl and Seong Lee for the original idea!

Thank you Simon, I will have a look!

The main issue as I see with these workarounds is that they increase risk of bugs in live algorithms, where you'd least want increased risk. I'd be much happier Quantopian built a consistent API where the difference between live and backtesting was minimal.

Yeah I absolutely agree, but I think fetch_csv in general is something that Quantopian has less interest in supporting these days, so I think it's basically take-it-or-leave-it. Don't want to speak for them though.

Good motivation to keep alternative options on the back burner!

Yeah, the new pivot seems to be selling data so the motivation for providing methods for people to get their own is diminishing I guess!

@Klon - I'd be much happier Quantopian did not release tools that allow you to calculate moving averages based on future data; and when the bug was discovered (see July 25, 2015, above), admit and correct it, rather than just quietly disallowing it in the contest.

Yeah, fetch_csv can be tricky to use properly.

Hello,

Below is the simplified version of some of the code that others have shared here, as I just wanted to pull the VIX data each day. However, I have a couple of questions:

1) Is there a simple way to pull the prior day's VIX? For example for the code vix_data = data['vix'] successfully works to pull the most recent value, but I've tried something like vix_data['vix'][-1] in an attempt to pull the value for the day prior, but I receive errors when I try that approach. Does anyone know how I might go about tweaking this code in order to accomplish this?

2) I'm trying to understand why the print vix_data function at the end returns zipline._protocol.SidView object at 0x7f4047632890 in the log instead of the value of VIX that I'm pulling. The strange (or at least confusing part for me) is that the VIX data pulls and charts correctly based on the record() function.

Any help or guidance would be greatly appreciated.

def pre_func(df):  
    vix = df['Adj Close']  
    # dates = df['Date']  
    return df

def initialize(context):  
    # Stores yesterday's day in order to use in handle_data  
    context.yesterday = 0  
    yahoo_vix_url = "http://ichart.finance.yahoo.com/table.csv?s=%5EVIX&d=8&e=1&f=2016&g=d&a=0&b=1&c=2011&ignore=.csv" 

    context.target_notional = 1*pow(10,6)  
    context.init_amts = True  
    fetch_csv(yahoo_vix_url,  
              date_column='Date',  
              date_format='%Y-%m-%d',  
              symbol='vix',  
              usecols=['Adj Close'],  
              pre_func=pre_func)

def handle_data(context, data):  
    #get the vix data  
    vix_data = data['vix']

    #exit if the vix data was not fetched  
    if (vix_data is None) :  
        print("no vix data")  
        return  
    record(price=vix_data['Adj Close'])  
    print vix_data  

There is no simple way. To do it correctly, you must do it the complicated way.

Right. Okay. Any ideas about my second question then by any chance? I'm sorry but I'm new to Quantopian and I am not an experienced coder. Any help from the community would be greatly appreciated.

I'm trying to compare whether yesterday's vix > previous day > day before.

And I'm trying to understand why the print function in the code above would not generate an output value...

Perhaps try printing the specific value you are interested in, the same way you are recording it.

Oh, yes of course! Thank you, Simon! I think I had been staring at it too long...

On a related note, I wonder if you could help me with a "deprecated" error I'm getting with that code above, for the line vix_data = data['vix']. I've looked at the API materials but I'm not clear on how I would apply the new data.current format with this specific code for fetching data from a csv. Would you happen to have any suggestions?

data.current('vix', 'Adj Close')

First of all, thanks to everyone for the information and help in this thread! I'm working on a version of the algo shared by David above. And have been pleased to see that I can get previous day's VIX 'Adj Close' values.

Now I would like to understand how one would edit this code to also be able to pull in and save another column of data from the fetched file (i.e., right now the fetcher only pulls 'Adj Close' prices from that column). I would like to be able to add the Open, High, and Low columns of fetched data to this algo.

Ultimately, want to be able to 1) compare a trend in VIX for a sequence of 3-4 days, one day compared against the previous. And 2) Calculate the difference between the high and low VIX for a given day, and do a similar trend comparison over a period of 3-4 days.

From what I can tell, this seems feasible, but I'm not sure how to add or manipulate the code to achieve this. Could any of you with more advanced knowledge help me to revise this code a bit? I've been staring at it for a while now and trying different approaches, but honestly I don't really know how to move forward.. please help!

Clone Algorithm
3
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: 57d31b2653ade5103b5263e0
There was a runtime error.

I'm trying to develop some code here that uses fetcher to pull data from a .csv file, and takes the string of data, and creates a column of data which can then be used to analyze and manipulate multiple columns of historical VIX data. For example, this would enable one to use this algo to set signals/rules based on the VIX High, Low, Open or Close for a given day or days increasing/decreasing, etc. I've borrowed and edited some code that others have shared here which pulled and made available one single column of a fetched VIX .csv. I would like to extend this algo to be able to pull multiple columns of the same VIX file. I've tried to understand the algo and build on that logic to add the other columns of data and I'm getting closer, but I'm missing something... Please help!

Clone Algorithm
0
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: 57d55a2d9c8c8e10261d280c
There was a runtime error.

I've made some progress with regards to my quest to be able to pull historical data of the VIX using fetcher. However, I'd like to ask the community for help to better understand how I can use the arguments in the actual fetcher() function to call multiple columns. For example, the code I'm using right now is the following:

fetch_csv(yahoo_vix_url, date_column='Date', date_format='%Y-%m-%d', symbol='vix', usecols=['Adj Close'], post_func=post_func)  

How would I change or edit the usecols reference to point to multiple columns of the yahoo VIX data I'm trying to pull from: yahoo_vix_url = "http://ichart.finance.yahoo.com/table.csv?s=%5EVIX&d=0&e=1&f=2017&g=d&a=0&b=1&c=2010&ignore=.csv"?

Or would I need to have four separate fetch_csv() functions to pull data from the same csv in order to get access to each column of data?

Thank you,
Winston

Clone Algorithm
0
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: 57dc9250c58520102bb94e25
There was a runtime error.

I posted a simple version of saving the data to an array:

https://www.quantopian.com/posts/fetcher-history-calculate-moving-average

Very good idea about adding a column of data...that really just skips the need to capture the array. Thinking about it now, I would just process the dataframe and then replace it with the values I need on a daily basis.

Thanks, Zippy. That's helpful, but I think I've got the code working when I want to just save one column of data from the csv and manipulate that. My question now is really more centered around how can I use fetch_csv() to reference and pull in multiple columns of data from the yahoo vix csv I'm pulling. For example, I need to be able to pull in today's open price, as well as yesterday's close and the high and low of yesterday (and access to high/low/close/open from several days ago). I've tried to build on some of the code examples from others here (many thanks all!) but have been somewhat stymied on this last important hurdle for my algo.

My code is below -- I would really appreciate some feedback on how I can get this code working. @Simon, I've been reading a lot on the forums for clues and noticed that you have a lot of experience in this area of the fetcher and have had great success in using complicated code around it for live trading so if you have any thoughts as well I'd really appreciate it!

Thanks,
Winston

# I'm trying to develop some code here that uses fetcher to pull data from a .csv file, and takes the string of data, and creates a column of data which can then be used to analyze and manipulate multiple columns of historical VIX data.  For example, this would enable one to use this algo to set signals/rules based on the VIX High, Low, Open or Close increasing/decreasing three days in a row, etc.  I've borrowed and edited some code that others have shared which pulled and made available one single column of a fetched VIX .csv.  I would like to extend this algo to be able to pull multiple columns of the same VIX file.  Please help!

from datetime import timedelta  
from pytz import timezone  
import statsmodels.api as sm  
import numpy as np  
import pandas as pd  
import talib

liveTrading = False

def custom_split(string_list):  
    """  
        Parses a string and returns it in list format, without the '[' ']' 

        :params string_list: a list that's been made into string e.g. "[ hello, hello2]"  
        :returns: a string that's been made into a list e.g. "[hello, hello2]" => [hello, hello2]  
    """  
    #: Remove the '[' and ']'  
    string_list = string_list[1:-1].split(',')  
    #: Convert to float  
    string_list = [float(s) for s in string_list]  
    return string_list

def get_day_delta(current_date):  
    """  
        Takes in the current date, checks it's day of week, and returns an appropriate date_delta  
        E.g. if it's a Monday, the previous date should be Friday, not Sunday

        :params current_date: Pandas TimeStamp  
        :returns: an int  
    """  
    if current_date.isoweekday() == 1:  
        return 3  
    else:  
        return 1  
def fill_func(df, row, num_dates):  
    """  
        Should be applied to every row of a dataframe. Reaches for the past thirty days of each dataframe,  
        appends the data to a string, returns the string which should be unpacked later on.

        :params df: The dataframe in it's totality  
        :params row: The row of each dataframe, passed through the lambda function of Dataframe.apply(lambda row: row)  
        :params num_dates: How many dates to go back (e.g. 30 = 30 days of past data)

        :returns: A list in the form of a string (containing past data) which should be unpacked later on  
    """  
    #: Instantiate variables  
    past_data_Adj_Close = []  
    past_data_High_Price = []  
    past_data_Low_Price = []  
    past_data_Open_Price = []  
    #: The current date is the name of the Series (row) being passed in  
    current_date = row.name  
    #: Iterate through the number of dates from 0->num_dates  
    for i in range(num_dates):  
        #: How many days to get back, calls get_day_delta for accurate delta assessment  
        #day_delta = get_day_delta(current_date)  #old code  
        #new code to fix the delay problem  
        if liveTrading and (i == 0):  
            day_delta = 0  
        else:  
            day_delta = get_day_delta(current_date)  
        #: Get the current_date and update the current_date to minus day_delta from the date  
        #: To get the appropriate past date  
        current_date = current_date - timedelta(days=day_delta)  
        try:  
            #: Get the price at the given current_date found by get_day_delta  
            data_Adj_Close = df.ix[current_date]['Adj_Close']  
            data_High_Price = df.ix[current_date]['High_Price']  
            data_Low_Price = df.ix[current_date]['Low_Price']  
            data_Open_Price = df.ix[current_date]['Open_Price']  

            past_data_Adj_Close.append(data_Adj_Close)  
            past_data_High_Price.append(data_High_Price)  
            past_data_Low_Price.append(data_Low_Price)  
            past_data_Open_Price.append(data_Open_Price)  
        except KeyError:  
            #: No data for this date, pass  
            pass  
    #: Return the list(s) made into a string  
    return str(past_data_Adj_Close), str(past_data_High_Price), str(past_data_Low_Price), str(past_data_Open_Price)

def post_func(df):  
    df = df.rename(columns={'Adj Close': 'Adj_Close'})  
    df = df.rename(columns={'High': 'High_Price'})  
    df = df.rename(columns={'Low': 'Low_Price'})  
    df = df.rename(columns={'Open': 'Open_Price'})  
    #fix for time lag  

    df = df.fillna(method='ffill')  
    df_Adj_Close = df[['Adj_Close', 'sid']]  
    df_High_Price = df[['High_Price', 'sid']]  
    df_Low_Price = df[['Low_Price', 'sid']]  
    df_Open_Price = df[['Open_Price', 'sid']]  

    #: Creating a new column of past data using our own custom function per row  
    df['past_data_Adj_Close'] = df_Adj_Close.apply(lambda row: fill_func(df_Adj_Close, row, 32), axis=1)  
    df['past_data_High_Price'] = df_High_Price.apply(lambda row: fill_func(df_High_Price, row, 32), axis=1)  
    df['past_data_Low_Price'] = df_Low_Price(lambda row: fill_func(df_Low_Price, row, 32), axis=1)  
    df['past_data_Open_Price'] = df_Open_Price.apply(lambda row: fill_func(df_Open_Price, row, 32), axis=1)  
    return df  
# the other methods in your algorithm.

def initialize(context):  
    # Stores yesterday's day in order to use in handle_data  
    context.yesterday = 0  
    yahoo_vix_url = "http://ichart.finance.yahoo.com/table.csv?s=%5EVIX&d=0&e=1&f=2017&g=d&a=0&b=1&c=2010&ignore=.csv"


    context.target_notional = 1*pow(10,6)  
    context.init_amts = True  
    fetch_csv(yahoo_vix_url, date_column='Date', date_format='%Y-%m-%d', symbol='vix', usecols=['Adj Close','High','Low','Open'], post_func=post_func)  

    schedule_function(  
    myfunc,  
    date_rules.every_day(),  
    time_rules.market_open()  
    )  


def myfunc(context, data):

    #get the vix data  
    vix_data_Adj_Close = data_Adj_Close['vix']  
    vix_data_High_Price = data_High_Price['vix']  
    vix_data_Low_Price = data_Low_Price['vix']  
    vix_data_Open_Price = data_Open_Price['vix']  


    #exit if the vix data was not fetched  
    if (vix_data_Adj_Close is None) :  
        print("no vix data")  
        return


    ##################################################  
    #: Example of string unpacking  
    try:  
        #: Throws an error if you leave it without this except block (The initial error checker does, but it will return expected values once  
        #: handle_data is called for the first time)  
        vix_data_list_Adj_Close = custom_split(data['vix']['past_data_Adj_Close'])  
        vix_data_list_High_Price = custom_split(data['vix']['past_data_High_Price'])  
        vix_data_list_High_Price = custom_split(data['vix']['past_data_Low_Price'])  
        vix_data_list_Open_Price = custom_split(data['vix']['past_data_Open_Price'])  
    except:  
        return  
    #reverse the list(s) so it is in a standard quantopian order  
    vix_data_list_Adj_Close = vix_data_list_Adj_Close[::-1]  
    vix_data_list_High_Price = vix_data_list_High_Price[::-1]  
    vix_data_list_Low_Price = vix_data_list_Low_Price[::-1]  
    vix_data_list_Open_Price = vix_data_list_Open_Price[::-1]  

    ##################################################  
    record(VIX_Adj_Close = vix_data_list_Adj_Close)  
    log.info(vix_data_list_Adj_Close)  
    log.info(vix_data_list_High_Price)  
    log.info(vix_data_list_Low_Price)  
    log.info(vix_data_list_Open_Price)  

Hi Winston ,

See if this works for you. Just make sure to spot check a few values to make sure my logic is right.

from collections import deque

def initialize(context):

    context.vix_fields = ['Adj Close', 'High', 'Low', 'Open']  
    context.vix = {}  
    for field in context.vix_fields:  
        context.vix[field] = deque([], 5)

    url = 'http://ichart.finance.yahoo.com/'  
    url += 'table.csv?s=%5EVIX&d=0&e=1&f=2017&g=d&a=0&b=1&c=2010&ignore=.csv"'  
    fetch_csv(url,  
              date_column='Date',  
              date_format='%Y-%m-%d',  
              symbol='vix',  
              usecols=context.vix_fields) 

def before_trading_start(context, data):

    for field in context.vix_fields:  
        val = data.current('vix', field)  
        context.vix[field].appendleft(val)

    # today's open  
    print 'open - %.2f' % context.vix['Open'][0]

    # yesterday's high/low (check that we have more than one day's data)  
    if len(context.vix['Open']) > 1:  
        print 'yesterday high/low - %.2f/%.2f' % (context.vix['High'][1], context.vix['Low'][1])  

Zippy -- thank you so very much for the quick response! Now I think I need to spend some time unpacking each line to make sure I understand how this code works and how everything fits together. But this looks like a much cleaner and more efficient way to do what I was attempting... brilliant!

Thanks!
Winston

Hi Winston and thanks :-)

Here, I will give you the cliff notes:

initialize:
- create array of csv fields at context.vix_fields
- create dictionary at context.vix
- initialize dictionary with deques (see https://docs.python.org/2/library/collections.html#deque-objects)
- make call for csv file

before_trading_starts:
- loop through field names, get data value for each field and add to context.vix dict

context.vix contains last five days of data. You can change deque([], 5) to some other number.

Zippy,

This may be a very obvious and basic mistake I'm making... but I'm just trying to incorporate some of the code and ideas you've so kindly shared in a basic algo of my own for learning and subsequent building. I'm getting an error and was wondering if you could point me in the right direction? I'm getting an IndexError: deque index out of range when I try to reference the previous day's Adj Close price. It ran fine when I run your code from above on a standalone basis, so I know it's something I've done wrong after adding a schedule function and a handle_data function... Here's my code:

from collections import deque

def initialize(context):  
    context.vix_fields = ['Adj Close','High','Low','Open']  
    context.vix = {}  
    for field in context.vix_fields:  
        context.vix[field] = deque([], 5)  
    url = 'http://ichart.finance.yahoo.com/'  
    url += 'table.csv?s=%5EVIX&d=0&e=1&f=2017&g=d&a=0&b=1&c=2010&ignore=.csv"'  
    fetch_csv(url,  
              date_column='Date',  
              date_format='%Y-%m-%d',  
              symbol='vix',  
              usecols=context.vix_fields)  
    schedule_function(  
    myfunc,  
    date_rules.every_day(),  
    time_rules.market_open()  
    )  
    context.asset1 = sid(8554)

def before_trading_start(context, data):  
    for field in context.vix_fields:  
        val = data.current('vix', field)  
        context.vix[field].appendleft(val)  
    # today's open  
    print 'open - %.2f' % context.vix['Open'][0]  
    if len(context.vix['Open']) > 1:  
        print 'high - %.2f' % context.vix['High'][1]  
        print 'low - %.2f' % context.vix['Low'][1]  
        print 'close - %.2f' % context.vix['Adj Close'][1]  
        # yesterday's high/low  
        print 'yesterday high/low - %.2f/%.2f' % (context.vix['High'][1], context.vix['Low'][1])

def myfunc(context, data):  
    vix_open = context.vix['Open'][0]  
    # why do I get runtime error?  IndexError: deque index out of range (line 47, in myfunc)??  I'm probably missing something basic here...?  
    vix_close_yesterday = context.vix['Adj Close'][1]  
    if vix_open > 14:  
        order_target_percent(context.asset1, 1.00)  
    else:  
        order_target_percent(context.asset1, 0.00)  

Hi Winston,

this works:

    if len(context.vix['Adj Close']) > 1:  
        vix_close_yesterday = context.vix['Adj Close'][1]  
        print vix_close_yesterday  

basically, what is happening is we are creating the data structure in the initialization function. The data structure looks like this:

context.vix = {  
    'Open': deque([], 5),  
    'High': deque([], 5),  
    'Low': deque([], 5),  
    'Adj Close': deque([], 5)  
}

For reference:
https://docs.python.org/2/tutorial/datastructures.html#dictionaries
https://docs.python.org/2/library/collections.html#deque-objects

The deque is initialized with an empty list as a container and will be max length of 5 elements. Then in the before_trading_start function, which is called everyday, we are filling in the data. We get an index error if we try to access an element before the data has been filled in. Once we get the five elements, going on older values are dropped and new values are added.

So, at the start of the backtest, if we want to access context.vix['High'][1] first we need to test that context.vix['High'] has a length greater than one (since lists are indexed starting at zero). To access context.vix['High'][2], test that the deque has a length greater than two, etc. up to context.vix['High'][4] which needs a length greater than four because we want the fifth element.

If you need more than five days, change the deque number in the initialization function.

Hope that helps...it is harder to explain than it is to code :-)

Less fancy, which is sometimes better!

from collections import deque

def initialize(context):  
    context.vix = {  
        'Open': deque([], 5),  
        'High': deque([], 5),  
        'Low': deque([], 5),  
        'Adj Close': deque([], 5)  
    }  
    url = 'http://ichart.finance.yahoo.com/table.csv'  
    url += '?s=%5EVIX&d=0&e=1&f=2017&g=d&a=0&b=1&c=2010&ignore=.csv"'  
    fetch_csv(url, date_column='Date', symbol='vix')  

def before_trading_start(context, data):  
    for field in ['Open', 'High', 'Low', 'Adj Close']:  
        val = data.current('vix', field)  
        context.vix[field].appendleft(val)  

    print 'open - %.2f' % context.vix['Open'][0]  

    if len(context.vix['Open']) > 1:  
        print 'high - %.2f' % context.vix['High'][1]  
        print 'low - %.2f' % context.vix['Low'][1]  
        print 'close - %.2f' % context.vix['Adj Close'][1]  

Note that %.2f rounds the float. See:
https://docs.python.org/2/library/string.html#formatspec

Trouble with these methods is they take time to "warm up" in live trading. That becomes more tedious when you need 30+ days of history.

True, Simon. Winston only needs five days of data. Of course, if you need 30 days of data, you can do something like this:

def shift(df):  
    vals = df['Close'].shift(-30)  
    df['Last Month Close'] = vals  
    return df

def initialize(context):  
    url = 'http://ichart.finance.yahoo.com/table.csv'  
    url += '?s=%5EVIX&d=0&e=1&f=2017&g=d&a=0&b=1&c=2010&ignore=.csv"'  
    fetch_csv(url, date_column='Date', symbol='vix', pre_func=shift)  

def before_trading_start(context, data):  
    for field in ['Close', 'Last Month Close']:  
        val = data.current('vix', field)  
        print '%s - %.2f' % (field, val)  

There's more than one way to skin a cat :-)

Extend that to an arbitrary number of days in the past, and you might get a solution similar to the one I posted last year. :)

haha...I guess there is always someone reinventing the wheel :-)

Thank you very much for your help, Zippy! I really appreciate it. For my purposes I think this is exactly what I needed. It's an elegant and clean approach to accomplish this solution.

I had tried the previous approach posted here some time ago but was unable to get it to work for the multiple columns of data which I needed... (I may have missed something but I got tangled up in the complexity). In a way it is funny how they make this so difficult to do what should be a fairly simple exercise! If only the VIX index data was available as a ticker symbol like VXX!

Thanks all again!
Winston

Hey, thanks too, Winston...I also figured out a bunch of stuff working through this with you!