def initialize(context):
    # Turn off the slippage model
    set_slippage(slippage.FixedSlippage(spread=0.0))
    # Set the commission model
    set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.0))
    context.day = -1 # using zero-based counter for days
    context.set_benchmark(symbol('DIA'))
    context.assets = []
    print('Setup investable assets...')
    for ticker in asset_tickers:
        #print(ticker)
        context.assets.append(symbol(ticker))
    context.n_asset = len(context.assets)
    context.n_portfolio = 40 # num mean-variance efficient portfolios to compute
    context.today = None
    context.tau = None
    context.min_data_window = 756 # min of 3 yrs data for calculations
    context.first_rebal_date = None
    context.first_rebal_idx = None
    context.weights = None
    # Schedule dynamic allocation calcs to occur 1 day before month end - note that
    # actual trading will occur on the close on the last trading day of the month
    schedule_function(rebalance,
                  date_rule=date_rules.month_end(days_offset=1),
                  time_rule=time_rules.market_close())
    # Record some stuff every day
    schedule_function(record_vars,
                  date_rule=date_rules.every_day(),
                  time_rule=time_rules.market_close())
Пример #2
0
    def initialize(self, context):
        if self.verbose: print("Starting the robo advisor")

        # Populate Portfolios
        self.all_portfolios = initialize_portfolio(self.verbose)

        # Set Commission model
        self.initialize_commission(country=self.country, platform=self.trading_platform)

        # Set Slippage model
        set_slippage(slippage.FixedSlippage(spread=0.0))  # assume spread of 0

        # Schedule Rebalancing check
        rebalance_check_freq = date_rules.month_end()
        if (self.rebalance_freq == 'daily'): rebalance_check_freq = date_rules.every_day()
        elif (self.rebalance_freq == 'weekly'): rebalance_check_freq = date_rules.week_end()

        if self.verbose: print('Rebalance checks will be done %s' % self.rebalance_freq)
        schedule_function(
            func=self.before_trading_starts,
            date_rule=rebalance_check_freq,
            time_rule=time_rules.market_open(hours=1))

        # record daily weights at the end of each day
        schedule_function(
            func=record_current_weights,
            date_rule=date_rules.every_day(),
            time_rule=time_rules.market_close()
        )
def initialize(context):
    attach_pipeline(make_pipeline(), 'pipeline')
    #Schedule Functions
    if not IS_LIVE:
        schedule_function(
            trade,
            #date_rules.every_day(),
            #date_rules.week_end(days_offset=1),#0=Fri 1= Thurs
            date_rules.month_end(days_offset=3),
            time_rules.market_close(minutes=30)
        )
        schedule_function(record_vars, date_rules.every_day(), time_rules.market_close())
        schedule_function(cancel_open_orders, date_rules.week_end(days_offset=2), time_rules.market_close())
    
    context.spy = symbol('SPY')  #sid(8554) #SPY
    context.TF_filter = False
    #context.TF_lookback = 60
    #Set number of securities to buy and bonds fund (when we are out of stocks)
    context.Target_securities_to_buy = 15 #10 #15 #2 #1 #5 #10 #5
    
    context.bonds = symbol('IEF') #sid(23870)  #IEF
    context.relative_momentum_lookback = 44 #66 #22 #4 #22 #22 #22 #126 #Momentum lookback
    context.momentum_skip_days = 1
    context.top_n_relative_momentum_to_buy = 10 #15 #10 #15 #1 #5 #5 #10 #5 #Number to buy
    context.stock_weights = pd.Series()
    context.bond_weights = pd.Series()

    context.auto_close = {} #Initialize portfolio auto_close list.
    context.TRACK_ORDERS_ON = False
Пример #4
0
def initialize(context):
    # This code runs once, when the sim starts up
    log.debug('scheduling rebalance and recording')

    set_slippage(slippage.FixedSlippage(spread=0.0))
    set_commission(commission.PerShare(cost=0, min_trade_cost=0))

    schedule_function(func=rebalance,
                      date_rule=date_rules.month_end(),
                      time_rule=time_rules.market_close(minutes=15))

    schedule_function(func=record_daily,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close())
Пример #5
0
def initialize(context):
    """
    use our factors to add our pipes and screens.
    """
    pipe = Pipeline()
    mkt_cap = MarketEquity()
    pipe.add(mkt_cap, 'market_cap')

    book_equity = BookEquity()
    # book equity over market equity
    be_me = book_equity / mkt_cap
    pipe.add(be_me, 'be_me')

    returns = Returns()
    pipe.add(returns, 'returns')

    attach_pipeline(pipe, 'ff_example')
    schedule_function(
        func=myfunc,
        date_rule=date_rules.month_end())
Пример #6
0
def initialize(context):
    # these must ALWAYS be present!
    context.transforms = []
    context.algo_rules = []
    context.max_lookback = 63
    context.outstanding = {}  # orders which span multiple days

    context.raw_data = {}

    #############################################################
    # set the following parameters as required

    context.show_positions = True
    # select records to show in algo.show_records()
    context.show_records = True

    # replace cash_proxy with risk_free if cantec.allow_cash_proxY_replacement is True
    # and cash_proxy price is <= average cash_proxy price over last context.cash_proxy_lookback days
    context.allow_cash_proxy_replacement = False
    context.cash_proxy_lookback = 43  # must be <= context.max_lookback

    context.update_metrics = False
    # to calculate Sharpe ratio
    context.calculate_SR = False
    context.SR_lookback = 63  # must be <= context.max_lookback
    context.SD_factor = 0

    # position only changed if percentage change > threshold
    context.threshold = 0.01

    # the following can be changed
    context.market_proxy = symbols('VFINX')[0]
    context.risk_free = symbols('VFISX')[0]
    # context.market_proxy = symbols('SPY')[0]
    # context.risk_free = symbols('SHY')[0]

    set_commission(commission.PerTrade(cost=10.0))
    context.leverage = 1.0
    #################################################################
    # configure strategies

    context.rebalance_interval = 3  # set interval to n = no of periods (default: months)
    # if you want to change default period, change schedule reallocate below

    # Strategy 1

    rs0003 = StrategyParameters(
        context,
        name='rs0003',
        portfolios=[symbols('NHMAX', 'FAGIX', 'VFIIX')],
        # portfolios=[symbols('HYD','HYD','MBB')],
        portfolio_allocation_modes=['EW'],
        portfolio_allocation_kwargs=[{}],
        security_weights=[None],
        portfolio_allocation_formulas=[None],
        scoring_methods=['RS'],
        scoring_factors=[{
            '+momentum': 1.0
        }],
        n_tops=[1],
        protection_modes=['BY_RULE'],
        protection_rules=['smma_rule'],
        protection_formulas=[None],
        cash_proxies=[symbol('VFISX')],
        # cash_proxies=[symbol('SHY')],
        strategy_allocation_mode='FIXED',
        portfolio_weights=[1.0],
        strategy_allocation_formula=None,
        strategy_allocation_rule=None)

    Configurator(context, define_transforms, define_rules, strategies=[rs0003])

    ############################
    # configure algorithm

    algo = Algo(context,
                strategies=[rs0003.strategy],
                allocation_model=AllocationModel(context,
                                                 mode='EW',
                                                 weights=None,
                                                 formula=None),
                regime=None)
    ###########################################################################################################
    # generate algo data every day at close
    schedule_function(algo.update_data, date_rules.every_day(),
                      time_rules.market_close())

    # daily functions to handle GTC orders
    schedule_function(algo.check_for_unfilled_orders, date_rules.every_day(),
                      time_rules.market_close())
    schedule_function(algo.fill_outstanding_orders, date_rules.every_day(),
                      time_rules.market_open())

    if context.update_metrics:
        # calculate metrics every day
        schedule_function(algo.update_metrics, date_rules.every_day(),
                          time_rules.market_close())

    if context.show_positions:
        schedule_function(algo.show_positions,
                          date_rules.month_start(days_offset=0),
                          time_rules.market_open())

    if context.show_records:
        # show records every day
        # edit the show_records function to include records required
        schedule_function(algo.show_records, date_rules.every_day(),
                          time_rules.market_close())

    schedule_function(algo.rebalance, date_rules.month_end(days_offset=2),
                      time_rules.market_open())
Пример #7
0
def initialize(context, date_limits, verbose, symbols):
    print "in initialize"
    start_time_initialize = time.time()
    context.verbose = verbose
    # Define rebalance frequency
    context.scheduler = SCHEDULER
    if context.scheduler  == 'Daily':
        schedule_function(rebalance)
    if context.scheduler  == 'Weekly':
        schedule_function(rebalance, date_rules.week_end())
    elif context.scheduler  == 'Monthly':
        schedule_function(rebalance, date_rules.month_end())

    context.date_limits = date_limits

    # Set slippage model and commission model
    set_slippage(slippage.FixedSlippage(spread=SLIPPAGE_SPREAD))
    set_commission(commission.PerShare(cost=COMMISSION_COST_PER_SHARE, min_trade_cost=COMMISSION_MIN_TRADE_COST))

    context.symbols = symbols
    symbol_membership = utils.get_underlying(context.symbols, sep = ' / ')
    symbol_membership.index = context.symbols
    context.symbol_membership = symbol_membership
    if REFERENCE_GROUP_SYMBOL['Cash'] in context.symbol_membership.index:
        context.symbol_membership.loc[REFERENCE_GROUP_SYMBOL['Cash']] = 'Cash'
    
    asset_keys = utils.get_asset_keys_db()
    if RETS_READER is not None:
        returns = utils.get_returns_db(RETS_READER, context.symbols, asset_keys)

    else:
        returns = None
    if VOL_READER is not None and CORR_READER is not None:
        volatility = utils.get_volatilities_db(VOL_READER, context.symbols, asset_keys)
        correlations = utils.get_correlations_db(CORR_READER, context.symbols, asset_keys)

    else:
        volatility, correlations = [None]*2
    data_dict = {'returns': returns, 'volatility': volatility, 'correlations': correlations}
    context.data_dict = data_dict


    #print returns
    #print ''
    #print ''
    #print volatility
    #print ''
    #print ''
    #print correlations
    #print asfasfasf

    # Group
    group = "Top"
    if len(sys.argv) >= 3 and 'ASSETTYPE=' in sys.argv[2]:
        group = sys.argv[2].split('=')[-1]
    params_dict = {}
    params_dict.update(data_dict)
    params_dict.update(PARAMS['params'])

    ag_name = 'Top'
    if group == 'Equity':
        ag_name = PARAMS['params']['group']
    context.group = AbstractGroup(context.symbols, name = ag_name, start=START_DATE_BT_STR, end = END_DATE_BT_STR, verbose = verbose, strategy_id = ID, scheduler = SCHEDULER , **params_dict)
    #print "DEBUG [context.group.updated_symbols] : \n", context.group.updated_symbols
    context.round_weights = 4
    context.ref_group_df = pd.DataFrame(pd.Series({v:k for k,v in REFERENCE_GROUP_SYMBOL.items()}))
    context.active_orders = []

    if verbose:
        print "INFO: Initialize took %f s." % (time.time() - start_time_initialize)
Пример #8
0
from zipline.pipeline import CustomFactor
from zipline.pipeline.data import USEquityPricing
from zipline.pipeline.fundamentals import Fundamentals

from pandas._libs.tslib import normalize_date

#day = normalize_date()

# time frame on which we want to compute Fama-French
normal_days = 31
# approximate the number of trading days in that period
# this is the number of trading days we'll look back on,
# on every trading day.
business_days = int(0.69 * normal_days)

print(date_rules.month_end())

# 以下自定义因子选取期初数
class Returns(CustomFactor):
    """
    每个交易日每个股票窗口长度"business_days"期间收益率
    """
    window_length = business_days
    inputs = [USEquityPricing.close]

    def compute(self, today, assets, out, price):
        out[:] = (price[-1] - price[0]) / price[0] * 100


class MarketEquity(CustomFactor):
    """
Пример #9
0
def initialize(context):
    set_slippage(NoSlippage())
    schedule_function(func=rebalance,
                      date_rule=date_rules.month_end(),
                      time_rule=time_rules.market_close(minutes=15))