Back to Community
ROC in Quantopian?

Hi,

I just got into programming with python in Quantopian. I was looking to create a sector rotation algorithm based on ROC for every 14 days.

  1. Find ROC for 9 SPY sectors and sort them from lowest to highest
  2. Allocate 50% to sector for highest rank, 25% to second highest rank, and 25% to third highest rank every 14 days

I was wondering if anyone can help me out? Totally lost.

8 responses

Hello David,

What is your definition of ROC (presumably, "return on capital")? I figure you are wanting something along the lines of ROIC as described in http://en.wikipedia.org/wiki/Return_on_capital.

There's a bit of a learning curve to working with Pandas dataframes, but you might want to just take the dive and have a look at https://www.quantopian.com/posts/working-with-history-dataframes. My sense, at this point, is that you'll be able to create a dataframe of ROC values and then sort (e.g. http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.sort.html). Once you have the sorted dataframe, then you can use the built-in order_target_percent method to do the allocation.

Grant

Yes I am looking for some good examples on the use of rate of change ta.ROC in some other algorithms. It would be helpful for a new programmer like me. I think i'll take a look at the zScore one. If you have any other resource links, please let me know. Thanks!

O.K. Rate of change (ROC). Got it. There should be an example around of how to use the TA-LIB methods with a Pandas DataFrame as input. If not, tomorrow, I should have time to work something up. I'm curious how it'll work. --Grant

David,

Here's an example:

import zipline.transforms.ta as ztt

def initialize(context):  
    context.stocks = [ sid(19662),  # XLY Consumer Discrectionary SPDR Fund  
                       sid(19656),  # XLF Financial SPDR Fund  
                       sid(19658),  # XLK Technology SPDR Fund  
                       sid(19655),  # XLE Energy SPDR Fund  
                       sid(19661),  # XLV Health Care SPRD Fund  
                       sid(19657),  # XLI Industrial SPDR Fund  
                       sid(19659),  # XLP Consumer Staples SPDR Fund  
                       sid(19654),  # XLB Materials SPDR Fund  
                       sid(19660) ] # XLU Utilities SPRD Fund

def handle_data(context, data):  
    prices = history(30,'1d','price')  
    roc = prices.apply(ztt.talib.ROC, axis=0, raw=True, timeperiod=14)  
    print roc.tail(1)  

Is this what you need?

You may want to take a look at:

https://www.quantopian.com/posts/s-and-p-500-sector-fund-allocator

Grant

Clone Algorithm
65
Loading...
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
import zipline.transforms.ta as ztt

def initialize(context):
    
    context.stocks = [ sid(19662),  # XLY Consumer Discrectionary SPDR Fund
                       sid(19656),  # XLF Financial SPDR Fund
                       sid(19658),  # XLK Technology SPDR Fund
                       sid(19655),  # XLE Energy SPDR Fund
                       sid(19661),  # XLV Health Care SPRD Fund
                       sid(19657),  # XLI Industrial SPDR Fund
                       sid(19659),  # XLP Consumer Staples SPDR Fund
                       sid(19654),  # XLB Materials SPDR Fund
                       sid(19660) ] # XLU Utilities SPRD Fund

def handle_data(context, data):
    
    prices = history(30,'1d','price')
    
    roc = prices.apply(ztt.talib.ROC, axis=0, raw=True, timeperiod=14)
    
    print roc.tail(1)
    
    
There was a runtime error.

Here's a first crack at it. --Grant

Clone Algorithm
65
Loading...
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
import zipline.transforms.ta as ztt
import pandas as pd
from pytz import timezone
import numpy as np

trading_freq = 10 # trading frequency in elapsed full trading days

def initialize(context):
    
    context.stocks = [ sid(19662),  # XLY Consumer Discrectionary SPDR Fund
                       sid(19656),  # XLF Financial SPDR Fund
                       sid(19658),  # XLK Technology SPDR Fund
                       sid(19655),  # XLE Energy SPDR Fund
                       sid(19661),  # XLV Health Care SPRD Fund
                       sid(19657),  # XLI Industrial SPDR Fund
                       sid(19659),  # XLP Consumer Staples SPDR Fund
                       sid(19654),  # XLB Materials SPDR Fund
                       sid(19660) ] # XLU Utilities SPRD Fund
    
    context.stocks_dict = {}
    
    for stock in context.stocks:
        context.stocks_dict[stock.sid] = stock
    
    context.day_count = -1
 
def handle_data(context, data):
    
    # trading control
    ################################# 
    # Trade only once per day (skip days for which market closes early)
    loc_dt = get_datetime().astimezone(timezone('US/Eastern'))
    if loc_dt.hour == 16 and loc_dt.minute == 0:
        context.day_count += 1
        pass
    else:
        return
    
    # Limit trading frequency
    if context.day_count % trading_freq != 0.0:
        return  
    #################################

    # get bar data
    prices = history(30,'1d','price') # prices in a Pandas DataFrame
    
    # compute current rate of change (ROC) using TA-LIB
    roc = prices.apply(ztt.talib.ROC, axis=0, raw=True, timeperiod=10).tail(1).transpose()
    
    # sort ROC
    rocSorted = roc.apply(np.sort,axis=0)
    
    # set allocation
    allocation = rocSorted.copy()
    allocation.iloc[0:-3,0] = 0
    allocation.iloc[-3,0] = 0.25
    allocation.iloc[-2,0] = 0.25
    allocation.iloc[-1,0] = 0.5  
    allocation = allocation.transpose()
    
    # apply allocation
    for stock in allocation.columns:
        order_target_percent(context.stocks_dict[stock],allocation[stock])
There was a runtime error.

Okay thanks Grant! Will try to experiment with the code you provided. It's very helpful! Thanks!

Hello, dumb question, but I got about 0 experience with Python...how do I get actual value from this: "roc.tail(1)" ?
It outputs number I need, how do I assign it to variable?

Hello Stepan,

I don't know what your code looks like, but you could try this:

float(roc.tail(1).values)  

This assumes that roc.tail(1) is a Pandas DataFrame containing a single value.

Grant