Sunday, January 31, 2016

Quantopian Tutorial, part 5

This part of the tutorial will cover more advanced topics that build upon our previous knowledge of constructing Python algorithms for trading.

First, let's go over the 'set)universe function.

def initialize(context)
     set_universe(universe.DollarVolumeUniverse(99.0, 100.0))

def handle_data(context, data):
     symbol('GOOG')
     for stock in data:
          print len(data)

So from this point on, any stocks or securities that you inquiry about using functions will be automatically included into our stocks universe.

Now, let's go over the 'fetch_csv()' function. This function allows us to import an external dataset in the CSV format.

fetch_csv("location of your csv file"
     pre_func=preview,
     date_column='data,
     universe_func=(my_universe))

context.target_weight = 0.01

def handle_data(context, data)

the fetch_csv("location of your csv file" will import your csv file full of securities, ticker symbols, dates, etc, into our algorithm. date_column='data' will locate and import the date column of your securities. And finally it will use the my_universe function to define our universe of securities.

What our algorithm is going to do is take our csv file and convert all of our securities into SID objects sids = set(financials['sid']) and then pass it through to our my_universe function defined as def my_universe(context, fetcher_data): and then that is going to grab all financial securities in our financials fetcher data financials = fetcher_data[fetcher_data['GICS Sector'] === 'Financials'], so it will grab all of the unique symbols of those securities, and then finally we are going to get the universe size so that we know how much weight to put into each security context.target_weight = 1.0/context.count and then we will return the set we got previously sids = set(financials['sid'] and return it via return sids.

So, the function financials = fetcher_data[fetcher_data['GICS Sector'] === 'Financials'] is describing all the securities listed in the S&P 500, which we will then grab their unique SIDs via the sids = set(financials['sid'] function, and then it will return that list return sids, and then we will use that as our daily universe for the stock. The pre_func=preview is a function that will allow us to preview the outcome of algorithm. The df['data'] = '11/1/15' function will allow us to pull those dates directly from our csv file or we can view them manually in Excel. The point of using the function is to tell our algorithm how to associate the SID object to the date that it belongs to.

We are then ordering that security with the context.target_weight which we found by calculating the number of securities in our universe and dividing that by 1 context.target_weight = 1.0/context.count .

**NOTE: this is all in daily mode, if you want it in minutely mode use the  schedule_function(func=rebalance, day_rule=day_rules.every_day(), time_rule=time_rules.market_open()) def rebalance(context, data): **

**NOTE: the maximum number of securities that you can import from a csv file into your universe is going to be around 200! 82 is the typical number of stocks in a 1% range of the dollar volume universe. You can also define your universe with a mix of fundamental factors.
Here is what our code will look like:

import datetime
import pandas as pd
import numpy as np

def preview(df):    
    log.info(' \n %s ' % df.head()) 
    df['data'] = '11/1/15'
    return df

# Function for returning a set of SIDs from fetcher_data
def my_universe(context, fetcher_data):
   
    # Grab just the SIDs for the Financials sector w/in the SP500:
    financials = fetcher_data[fetcher_data['GICS Sector'] == 'Financials']
     sids = set(financials['sid'])
   symbols = [s.symbol for s in sids if s != 0]
    context.count = len(symbols)
    print "total universe size: {c}".format(c=context.count)
   
    # Compute target equal-weight for each stock in the SP500 Financials 
universe
    context.target_weight = 1.0/context.count
    return sids

def initialize(context):
   
    # Fetch the SP500 constituents -- sourced from Quandl
    # https://s3.amazonaws.com/quandl-static-content/Ticker+CSV
%27s/Indicies/SP500.csv
    # static snapshot of the SP500 constituents as of 10/2013, along with 
GICS sectors
    # I'm grabbing the data from a file on my dropbox folder which I 
modified by adding
    # a date column, alternatively you could add the date inside of a 
more complicated
    # pre_func and use the csv file as is.
   
    fetch_csv(
       "https://dl.dropboxusercontent.com/u/169032081/SP500.csv",
        pre_func=preview,
        date_column='date',
        universe_func=(my_universe))

    context.target_weight = 0.01
    
    schedule_function(func=rebalance,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open())
    
def rebalance(context, data):
    # Loop over every stock in the Financials sector and make sure we have an equal-weight
    # exposure using the order_target_percent() method.
    for stock in data:
        # Guard for missing stock data
        if 'price' in data[stock]:
            order_target_percent(stock,context.target_weight)
        else:
            log.warn("No price for {s}".format(s=stock))
    
def handle_data(context,data):
    pass

No comments:

Post a Comment