Back to Community
Economic Cycle

Backtest of Economic Cycle using custom data.

Clone Algorithm
6
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
from quantopian.algorithm import order_optimal_portfolio
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline, CustomFilter
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.filters import QTradableStocksUS
import quantopian.optimize as opt
from quantopian.pipeline.data.user_579e958d14ae60349e00035f import model_01
import numpy as np

def initialize(context):
    #set the benchmark to S&P500
    set_benchmark(symbol('SPY'))
    context.spy = sid(8554) # s&p 500
    context.ief = sid(23870) # mid term bonds
    context.vug = sid(25910) # growth
    context.ijs = sid(21772) # small cap value
    #context.pdp = sid(33441) # momentum
    context.gld = sid(26807) # gold
    context.qqq = sid(19920) # nasdaq qqq
    
    #initialise state
    context.state = -1
    # state = 0 risk on (consider leveraged etf's in this state only)
    # state = 1 medium risk
    # state = 2 risk off
    
    #initialise cycle
    context.currentcycle = -1
    
    # Schedule our rebalance function to run at the start of
    # each day, 2 hours after the market opens.
    schedule_function(
        my_rebalance,
        date_rules.every_day(),
        time_rules.market_open(hours=2)
    )

    # Record variables at the end of each day.
    schedule_function(
        my_record_vars,
        date_rules.every_day(),
        time_rules.market_close()
    )

    # Create our pipeline and attach it to the algorithm.
    my_pipe = make_pipeline()
    attach_pipeline(my_pipe, 'my_pipeline')

def make_pipeline():
    """
    Create our pipeline.
    """
    #creat a filter on SPY as its the datafeed that has the model attached
    my_sid_filter = SidInList(
        sid_list = (
            symbol('SPY').sid, 
                )
            )
    return Pipeline(
        columns={
            'cycle': model_01.totalma.latest #model from imported from custom data
        },
        screen=(my_sid_filter),
    )

def before_trading_start(context, data):
    """
    Get pipeline results.
    """
    # Gets the pipeline output every day.
    context.pipe_results = pipeline_output('my_pipeline')
    
def my_rebalance(context, data):
    #get the current days cycle value from the model
    context.currentcycle = context.pipe_results['cycle'][0]
    #set the cycle to the current cycle
    cycle = context.currentcycle
    #log.info("current: " + str(cycle) + " - previous: " + str(context.prevcycle))
    if cycle < 1 and context.state != 0: #check if the cycle is risk on, and the algo is not already in this state
        #risk on
        #set target weights
        order_target_percent(context.ijs, .5)
        order_target_percent(context.spy, .25)
        order_target_percent(context.qqq, .25)
        if data.can_trade(context.gld):
            order_target_percent(context.gld, 0)
            order_target_percent(context.ief, 0)
        context.state = 0
        log.info('state == 0')
    elif cycle > 1 and cycle < 1.5 and context.state != 1:
        if context.state not in [2, -1]: #check to make sure state isn't coming from 2 as coming from 2 needs to go to 1 first before switchig down states
            # and is not in initialisation state
            order_target_percent(context.ijs, .2)
            order_target_percent(context.spy, .4)
            order_target_percent(context.qqq, .4)
            if data.can_trade(context.gld):
                order_target_percent(context.gld, 0)
                order_target_percent(context.ief, 0)
            else:
                order_target_percent(context.ief, 0)
            context.state = 1
            log.info('state == 1')
    elif cycle > 1.5 and context.state != 2:  
        order_target_percent(context.ijs, 0)
        order_target_percent(context.spy, 0)
        order_target_percent(context.qqq, 0)
        if data.can_trade(context.gld):
            order_target_percent(context.ief, .5)
            order_target_percent(context.gld, .5)
        else:
            order_target_percent(context.ief, 1)
        context.state = 2
        log.info('state == 2')
       
def my_record_vars(context, data):
    """
    Record variables at the end of each day.
    """
    # Record the leverage and cylce to plot
    record(
        leverage=context.account.leverage,
        cycle=context.currentcycle
    )

#custom filter to only get the data for defined symbols    
class SidInList(CustomFilter):
    """
    Filter returns True for any SID included in parameter tuple passed at creation.
    Usage: my_filter = SidInList(sid_list=(23911, 46631))
    """    
    inputs = []
    window_length = 1
    params = ('sid_list',)
 
    def compute(self, today, assets, out, sid_list):
        out[:] = np.in1d(assets, sid_list)
There was a runtime error.
1 response

Can you tell us about the custom data set being used?