def initialize(context): 
    psw = paired_switching(context)
    
    context.instrument = {'equity':symbol('SPY'), 'treasury':symbol('TLT')} 
    context.nbSwitch = 0
       
    context.lookback = 3*21 # 4 months period, 21 trading days per month
    
    context.Periodicity = 1 # every x period ; 1 means every period
    context.periodCount = 0
    
    context.cagr_period = 0
    context.global_fund_managed = 0.9
    
    context.max_priceslippage = (float(0.5)/100)     
    
    '''
    get_environment(field='platform')
    Returns information about the environment in which the backtest or live algorithm is running.
    If no parameter is passed, the platform value is returned. Pass * to get all the values returned in a dictionary.
    To use this method when running Zipline standalone, import get_environment from the zipline.api library.

    Parameters
    arena: Returns IB, live (paper trading), or backtest.
    data_frequency: Returns minute or daily.
    start: Returns the UTC datetime for start of backtest. In IB and live arenas, this is when the live algorithm was deployed.
    end: Returns the UTC datetime for end of backtest. In IB and live arenas, this is the trading day's close datetime.
    capital_base: Returns the float of the original capital in USD.
    platform: Returns the platform running the algorithm: quantopian or zipline.   
    '''    
    context.env = get_environment('platform')    
    if context.env is 'quantopian' or get_environment('arena') == 'live' or get_environment('arena') == 'IB': 

    	set_commission(commission.PerTrade(cost=4.0))
    	set_slippage(slippage.FixedSlippage(spread=0.00))
    	schedule_function(psw.ordering_logic,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(hours=1, minutes=0))
                      
	schedule_function(get_cagr,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(hours=5, minutes=0))
                      
    elif context.env == 'zipline':
        
    	context.set_commission(commission.PerTrade(cost=4.0))
    	context.set_slippage(slippage.FixedSlippage(spread=0.00))
     
    	context.schedule_function(psw.ordering_logic,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(hours=1, minutes=0))
                      
	context.schedule_function(get_cagr,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(hours=5, minutes=0))
                      
        context.startDate = datetime(2004, 1, 1, 0, 0, 0, 0, pytz.utc)
        context.endDate = datetime(2015, 1, 1, 0, 0, 0, 0, pytz.utc)
    
    return
Ejemplo n.º 2
0
def before_trading_start(context, data):
    """
    Called every day before market open. Gathers today's pipeline
    output and initiates real-time data collection (in live trading).
    """
    context.candidates = algo.pipeline_output('pipeline')
    context.assets_to_short = []
    context.target_value_per_position = -50e3

    # Start real-time data collection if we are in live trading
    if algo.get_environment("arena") == "trade":

        # start real-time tick data collection for our candidates...
        sids = [asset.real_sid for asset in context.candidates.index]

        if sids:

            # collect the trade/volume data
            collect_market_data("us-stk-realtime",
                                sids=sids,
                                until="09:32:00 America/New_York")

            # ...and point Zipline to the derived aggregate db
            # For Interactive Brokers databases:
            algo.set_realtime_db("us-stk-realtime-1min",
                                 fields={
                                     "close": "LastPriceClose",
                                     "open": "LastPriceOpen",
                                     "high": "LastPriceHigh",
                                     "low": "LastPriceLow",
                                     "volume": "LastSizeSum"
                                 })
Ejemplo n.º 3
0
    def __init__(self, context, strategies=[], allocation_model=None, regime=None):

        if get_environment('platform') == 'zipline':
            self.day_no = 0

        self.ID = 'algo'

        self.strategies = strategies
        self.allocation_model = allocation_model
        self.regime = regime

        context.strategies = self.strategies
        self.weights = [0. for s in self.strategies]
        context.strategy_weights = self.weights
        self.strategy_IDs = [s.ID for s in self.strategies]
        self.active = [s.ID for s in self.strategies] + [p.ID for s in self.strategies for p in s.portfolios]

        if self.allocation_model == None:
            raise ValueError('\n *** FATAL ERROR : ALGO ALLOCATION MODEL CANNOT BE NONE ***\n')

        context.metrics = Metrics(context)

        self.all_assets = self._set_all_assets()

        print('ALL ASSETS = {}'.format([s.symbol for s in self.all_assets]))

        self.allocations = pd.Series(0, index=self.all_assets)
        self.previous_allocations = pd.Series(0, index=self.all_assets)

        self.data = Data(self.all_assets)
        context.algo_data = self.data

        set_symbol_lookup_date('2016-01-01')

        self._instantiate_rules(context)

        context.securities = []  # placeholder securities in portfolio

        if get_environment('platform') == 'zipline':
            context.count = context.max_lookback
        else:
            context.count = 0

        self.rebalance_count = 1  # default rebalance interval = 1
        self.first_time = True

        return
def initialize(context):
    
    context.global_fund_managed = 0.9
    
    weight1 = 0.5
    weight2 = 1-weight1
    start1_portf_allocation = weight1 *context.global_fund_managed
    start2_portf_allocation = weight2 *context.global_fund_managed
    
    context.s1 = strat1(context, start1_portf_allocation)
    context.s2 = strat2(context, start2_portf_allocation)
    
    context.instrument = context.s1.instrument
    context.instrument += context.s2.instrument
    
    context.cagr_period = 0
    
    context.env = get_environment('platform')    
    if context.env is 'quantopian' or get_environment('arena') == 'live' or get_environment('arena') == 'IB': 
    	set_commission(commission.PerTrade(cost=4.0))
    	set_slippage(slippage.FixedSlippage(spread=0.00))
    	schedule_function(rebalance,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(hours=1, minutes=0))
                      
	schedule_function(get_cagr,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(hours=5, minutes=0))
                      
    elif context.env == 'zipline':
        context.set_commission(commission.PerTrade(cost=4.0))
        context.set_slippage(slippage.FixedSlippage(spread=0.00))
        
        context.schedule_function(rebalance,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(hours=1, minutes=0))
        context.schedule_function(get_cagr,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(hours=5, minutes=0))
                      
        context.startDate = datetime(2004, 1, 1, 0, 0, 0, 0, pytz.utc)
        context.endDate = datetime(2015, 1, 1, 0, 0, 0, 0, pytz.utc)
    
    return
Ejemplo n.º 5
0
    def update_data(self, context, data):

        if get_environment('platform') == 'zipline':
            # allow data buffer to fill in the ZIPLINE ENVIRONMENT
            if self.day_no <= context.max_lookback:
                self.day_no += 1
                return

        context.algo_data = self.data.update(context, data)

        # print ('ALGO_DATA = {}'.format(context.algo_data))

        return context.algo_data
def initialize(context):  
    context.stocks = [symbol('SPY'), symbol('TLT')]
    context.nbSwitch = 0
       
    context.lookback = 4*21 # 4 months period, 21 trading days per month
    
    context.Periodicity = 1 # every x period ; 1 means every period
    context.periodCount = 0
    
    context.cagr_period = 0
    context.portf_allocation = 0.9
    
    context.max_priceslippage = (float(0.5)/100)     
    context.limit_order = False 
    
    context.env = get_environment('platform')    
    if context.env is 'quantopian': 

    	set_commission(commission.PerTrade(cost=4.0))
    	set_slippage(slippage.FixedSlippage(spread=0.00))
    	schedule_function(ordering_logic,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(hours=1, minutes=0))
                      
	schedule_function(get_cagr,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(hours=5, minutes=0))
    elif context.env is 'zipline':
        
    	context.set_commission(commission.PerTrade(cost=4.0))
    	context.set_slippage(slippage.FixedSlippage(spread=0.00))
    	context.schedule_function(ordering_logic,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(hours=1, minutes=0))
                      
	context.schedule_function(get_cagr,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open(hours=5, minutes=0))
                      
        context.startDate = datetime(2008, 1, 1, 0, 0, 0, 0, pytz.utc)
        context.endDate = datetime(2014, 1, 1, 0, 0, 0, 0, pytz.utc)
        
    return
Ejemplo n.º 7
0
def initialize(context):
    context.stocks = [symbol('SPY'), symbol('TLT')]
    context.nbSwitch = 0

    context.lookback = return_window * 21  # 4 months period, 21 trading days per month

    context.Periodicity = 1  # every x period ; 1 means every period
    context.periodCount = 0

    context.cagr_period = 0
    context.portf_allocation = 0.9

    context.max_priceslippage = (float(0.5) / 100)

    context.env = get_environment('platform')
    if context.env == 'quantopian':

        set_commission(commission.PerTrade(cost=4.0))
        set_slippage(slippage.FixedSlippage(spread=0.00))
        schedule_function(ordering_logic,
                          date_rule=date_rules.month_start(),
                          time_rule=time_rules.market_open(hours=1, minutes=0))

        schedule_function(get_cagr,
                          date_rule=date_rules.month_start(),
                          time_rule=time_rules.market_open(hours=5, minutes=0))
    elif context.env == 'zipline':

        context.set_commission(commission.PerTrade(cost=4.0))
        context.set_slippage(slippage.FixedSlippage(spread=0.00))
        context.schedule_function(ordering_logic,
                                  date_rule=date_rules.month_start(),
                                  time_rule=time_rules.market_open(hours=1,
                                                                   minutes=0))

        context.schedule_function(get_cagr,
                                  date_rule=date_rules.month_start(),
                                  time_rule=time_rules.market_open(hours=5,
                                                                   minutes=0))

        context.startDate = datetime(2003, 1, 1, 0, 0, 0, 0, pytz.utc)
        context.endDate = datetime(2014, 1, 1, 0, 0, 0, 0, pytz.utc)
    '''
    get_environment(field='platform')
    Returns information about the environment in which the backtest or live algorithm is running.
    If no parameter is passed, the platform value is returned. Pass * to get all the values returned in a dictionary.
    To use this method when running Zipline standalone, import get_environment from the zipline.api library.

    Parameters
    arena: Returns IB, live (paper trading), or backtest.
    data_frequency: Returns minute or daily.
    start: Returns the UTC datetime for start of backtest. In IB and live arenas, this is when the live algorithm was deployed.
    end: Returns the UTC datetime for end of backtest. In IB and live arenas, this is the trading day's close datetime.
    capital_base: Returns the float of the original capital in USD.
    platform: Returns the platform running the algorithm: quantopian or zipline.   
    '''
    context.limit_order = None
    if get_environment('arena') == 'backtest':
        if get_environment('data_frequency') == 'daily':
            context.limit_order = False
        elif get_environment('data_frequency') == 'minute':
            context.limit_order = True
    else:
        context.limit_order = True


####################################
    context.yahoo = True
    ####################################

    back_year = '2005'
    today_year = str(datetime.today().year)
    url_start = 'http://ichart.finance.yahoo.com/table.csv?s='
    url_end = '&d=1&e=1&f=' + today_year + '&g=d&a=0&b=29&c=' + back_year + '&ignore=.csv'

    context.yinstrument = []

    for y_id in context.stocks:
        y_name = 'y_' + y_id.symbol
        context.yinstrument.append(y_name)
        url = url_start + y_id.symbol + url_end
        print(url)
        fetch_csv(url,
                  date_column='Date',
                  date_format='%Y-%m-%d',
                  symbol=y_name,
                  usecols=['Adj Close'],
                  post_func=rename_col)

    return