Ejemplo n.º 1
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """

    c = context

    c.etf_universe = StaticAssets(
        symbols('XLY', 'XLP', 'XLE', 'XLF', 'XLV', 'XLI', 'XLB', 'XLK', 'XLU'))
    c.alphas = pd.DataFrame()

    # Rebalance every day, 1 hour after market open.
    schedule_function(
        rebalance,
        date_rules.every_day(),
        time_rules.market_open(hours=1),
    )

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

    # Create our dynamic stock selector.
    attach_pipeline(make_pipeline(context), 'pipeline')
    attach_pipeline(make_pipeinit(context), 'pipeinit')

    c.first_trading_day = True
    c.factor_name_list = make_factor().keys()
Ejemplo n.º 2
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    feature_num = 11
    context.orders_submitted = False
    large_num = 9999999
    least_num = 0
    context.n_components = feature_num
    context.security = symbol(SYMBOL)  # Trade SPY
    set_benchmark(symbol(SYMBOL))  # Set benchmarks
    context.model = SVC(kernel='rbf', tol=1e-3, random_state=0, gamma=0.2, C=10.0, verbose=True)  # 8.05 for SVM model
    context.lookback = 350  # Look back 62 days
    context.history_range = 350  # Only consider the past 400 days' history
    context.threshold = 4.05
    context.longprices = large_num
    context.shortprices = least_num
    set_long_only()
    # Generate a new model every week
    schedule_function(create_model, date_rules.week_end(), time_rules.market_close(minutes=10))
    """
    # Generate a new model every week
    schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10))
    """

    # Trade at the start of every day
    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open(minutes=1))
def initialize(context):
    """
        A function to define things to do at the start of the strategy
    """
    # set the account currency, only valid for backtests
    set_account_currency("USD")
    
    # universe selection
    context.short_dollar_basket = {
                               symbol('FXCM:AUD/USD'):1,
                               symbol('FXCM:EUR/USD'):1,
                               symbol('FXCM:GBP/USD'):1,
                               symbol('FXCM:NZD/USD'):1,
                               symbol('FXCM:USD/CAD'):-1,
                               symbol('FXCM:USD/CHF'):-1,
                               symbol('FXCM:USD/JPY'):-1,
                             }
    
    # Call rebalance function on the first trading day of each month after 2.5 hours from market open
    schedule_function(rebalance,
                    date_rules.month_start(days_offset=0),
                    time_rules.market_close(hours=2, minutes=30))
    
    # set trading cost and slippage to zero
    set_commission(fx=commission.PipsCost(cost=0.00))
    set_slippage(fx=slippage.FixedSlippage(0.00))
Ejemplo n.º 4
0
def initialize(context):
    """
    Called once at the start of a backtest, and once per day at
    the start of live trading. In live trading, the stored context
    will be loaded *after* this function is called.
    """
    # Rebalance every day, 1 hour after market open.
    algo.schedule_function(
        rebalance,
        algo.date_rules.month_start(),
        algo.time_rules.market_open(hours=1),
    )

    algo.schedule_function(
        bonds,
        algo.date_rules.month_start(days_offset=1),
        algo.time_rules.market_open(hours=1),
    )

    algo.set_benchmark(algo.sid("FIBBG000BDTBL9"))

    # Create a pipeline to select stocks each day.
    algo.attach_pipeline(make_pipeline(), 'pipeline')

    # algo.set_min_leverage(0, datetime.timedelta(30))
    # algo.set_max_leverage(1.2)

    context.trend_filter = False
Ejemplo n.º 5
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    feature_num = 11
    context.orders_submitted = False
    large_num = 9999999
    least_num = 0
    context.n_components = feature_num
    context.security = symbol(SYMBOL)  # Trade SPY
    set_benchmark(symbol(SYMBOL))  # Set benchmarks
    context.model = DecisionTreeClassifier(criterion='entropy',
                                           max_depth=feature_num,
                                           random_state=0)
    context.lookback = 350  # Look back 62 days
    context.history_range = 350  # Only consider the past 400 days' history
    context.threshold = 4.05
    context.longprices = large_num
    context.shortprices = least_num
    set_long_only()
    # Generate a new model every week
    schedule_function(create_model, date_rules.week_end(),
                      time_rules.market_close(minutes=10))
    """
    # Generate a new model every week
    schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10))
    """

    # Trade at the start of every day
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
Ejemplo n.º 6
0
def initialize(context):
    model = g_models[g_idx]
    print("hello world --- :",g_idx,model)
    attach_pipeline(make_pipeline(asset_finder=None,algo_mode=model), 'my_pipeline')
    schedule_function(rebalance, date_rules.week_start(days_offset=0), half_days=True)
    context.posset = {}
    context.rbcnt = 0
Ejemplo n.º 7
0
def initialize(context):

    # Schedule our rebalance function to run at the start of
    # each week, when the market opens.
    schedule_function(func=my_rebalance,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open())
Ejemplo n.º 8
0
def initialize(context):
    # Benchmark against the Dow Jones Industrial Average (DIA)
    api.set_benchmark(symbol('DIA'))

    # stop when trying to handle missing data
    api.set_nodata_policy(api.NoDataPolicy.EXCEPTION)

    # These are the default commission and slippage settings.  Change them to fit your
    # brokerage fees. These settings only matter for backtesting.  When you trade this
    # algorithm, they are moot - the brokerage and real market takes over.
    api.set_commission(api.commission.PerTrade(cost=0.03))
    api.set_slippage(api.slippage.VolumeShareSlippage(volume_limit=0.25, price_impact=0.1))

    # create an instance of the Dow30 class and set it within context
    context.dow30 = dow_constituents

    # next trade year
    context.year = 0

    # set to True to trigger a rebalance
    context.trade = False

    # for tracking max leverage
    context.mx_lvrg = 0

    # check for possible trades daily
    api.schedule_function(func=rebalance, date_rule=api.date_rules.every_day(), time_rule=api.time_rules.market_open(hours=1))
    def initialize(context):
        """ Called once at the start of the algorithm. """

        set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))
        set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.00))
        set_max_leverage(1.0)

        # Rebalance every day, 1 hour after market open.
        schedule_function(
            context.my_rebalance,
            date_rules.every_day(),
            time_rules.market_open(hours=1)
        )

        # Close all positions every day, 30 minutes before market close.
        schedule_function(
            context.close_positions,
            date_rules.every_day(),
            time_rules.market_close(minutes=30)
        )

        # Create risk manager
        context.risk_manager = RiskManager(context, daily_risk)

        # Create our dynamic stock selector.
        attach_pipeline(context.make_screener(), 'stock_screener')
Ejemplo n.º 10
0
def initialize(context):
    attach_pipeline(make_pipeline(), 'my_pipeline')

    # Rebalance each day.  In daily mode, this is equivalent to putting
    # `rebalance` in our handle_data, but in minute mode, it's equivalent to
    # running at the start of the day each day.
    schedule_function(rebalance, date_rules.every_day())
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())
Ejemplo n.º 12
0
def initialize(context):

    # Get continuous futures for Light Sweet Crude Oil...
    context.crude_oil = continuous_future('CL', roll='calendar')
    # ... and RBOB Gasoline
    context.gasoline = continuous_future('RB', roll='calendar')

    # If Zipline has trouble pulling the default benchmark, try setting the
    # benchmark to something already in your bundle
    set_benchmark(context.crude_oil)

    # Ignore commissions and slippage for now
    set_commission(us_futures=commission.PerTrade(cost=0))
    set_slippage(us_futures=slippage.FixedSlippage(spread=0.0))

    # Long and short moving average window lengths
    context.long_ma = 65
    context.short_ma = 5

    # True if we currently hold a long position on the spread
    context.currently_long_the_spread = False
    # True if we currently hold a short position on the spread
    context.currently_short_the_spread = False

    # Rebalance pairs every day, 30 minutes after market open
    schedule_function(func=rebalance_pairs,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(minutes=30))

    # Record Crude Oil and Gasoline Futures prices everyday
    schedule_function(record_price, date_rules.every_day(),
                      time_rules.market_open())
Ejemplo n.º 13
0
def initialize(context):
    """
    Initialization and trading logic
    """
    # Set comission and slippage
    if enable_commission:
        comm_model = PerDollar(cost=commission_pct)
    else:
        comm_model = PerDollar(cost=0.0)

    set_commission(comm_model)

    if enable_slippage:
        slippage_model = VolumeShareSlippage(
            volume_limit=slippage_volume_limit, price_impact=slippage_impact)
    else:
        slippage_model = FixedSlippage(spread=0.0)

    # Used only for progress output
    context.last_month = initial_portfolio

    # Store index membership
    context.index_members = pd.read_csv('./data/sp500_members.csv',
                                        index_col=0,
                                        parse_dates=[0])

    # Schedule rebalance monthly
    schedule_function(func=rebalance,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open())
Ejemplo n.º 14
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    feature_num = 11
    context.orders_submitted = False
    large_num = 9999999
    least_num = 0
    context.n_components = 6
    context.security = symbol(SYMBOL)  # Trade SPY
    set_benchmark(symbol(SYMBOL))  # Set benchmarks
    context.model2 = SVC(kernel='rbf', tol=1e-3, random_state=0, gamma=0.2, C=10.0, verbose=True)  # 8.05 for SVM model
    context.model3 = KNeighborsClassifier(n_neighbors=feature_num, p=3, metric='minkowski')  # 7.05 for  model
    context.model = DecisionTreeClassifier(criterion='entropy', max_depth=feature_num, random_state=0)
    context.model4 = RandomForestClassifier(criterion='entropy', n_estimators=feature_num, random_state=1,
                                            n_jobs=2)  # 5.2 for randomforest
    context.model1 = LogisticRegression(random_state=0, solver='lbfgs', multi_class='multinomial')
    context.modellist = {'SVM':context.model2,'KNeighbors':context.model3,'DecisionTree':context.model,'RandomForest':context.model4,'LogisticRegression':context.model1}
    context.lookback = 350  # Look back 62 days
    context.history_range = 350  # Only consider the past 400 days' history
    context.threshold = 4.05
    context.longprices = large_num
    context.shortprices = least_num
    context.time_series = 0
    context.init = 0
    set_long_only()
    # Generate a new model every week
    #schedule_function(create_model, date_rules.week_end(), time_rules.market_close(minutes=10))
    """
    # Generate a new model every week
    schedule_function(create_model1, date_rules.week_end(), time_rules.market_close(minutes=10))
    """

    # Trade at the start of every day
    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open(minutes=1))
Ejemplo n.º 15
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()
        )
Ejemplo n.º 16
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """

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

    schedule_function(rebalance, TRADE_FREQ,
                      date_rules.every_day(),
                      time_rules.market_open(hours=1, minutes=30),
    )

    schedule_function(record_vars, date_rules.every_day(),
                      time_rules.market_close())

    ml_pipeline = make_ml_pipeline(universe,
                                   n_forward_days=N_FORWARD_DAYS,
                                   window_length=TRAINING_PERIOD)

    # Create our dynamic stock selector.
    attach_pipeline(ml_pipeline, 'ml_model')

    context.past_predictions = {}
    context.ic = 0
    context.rmse = 0
    context.mae = 0
    context.returns_spread_bps = 0
Ejemplo n.º 17
0
def initialize(context):
    context.set_commission(commission.PerShare(cost=0.0, min_trade_cost=0))
    set_benchmark(symbol('SPY'))
    context.asset = symbol('AAPL')
    context.has_ordered = False

    schedule_function(place_order, None, time_rules.market_open())
Ejemplo n.º 18
0
def initialize(context):
    # Set benchmark to short-term Treasury note ETF (SHY) since strategy is dollar neutral
    set_benchmark(symbol('AAPL'))

    # Schedule our rebalance function to run at the end of each day.
    # Modified the timing to 5 mins earlier than the market close to reduce the fail to book warnings
    # schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_close(minutes=5))
    # Try to change it to open and see what happened -- HY
    schedule_function(my_rebalance, date_rules.every_day(),
                      time_rules.market_open(minutes=5))

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

    # Get intraday prices today before the close if you are not skipping the most recent data
    # schedule_function(get_prices,date_rules.every_day(), time_rules.market_close(minutes=10))
    # Try to get the price data when the market is opening -- HY
    # schedule_function(get_prices, date_rules.every_day(), time_rules.market_open(minutes=1))

    # Set commissions and slippage to 0 to determine pure alpha
    set_commission(commission.PerShare(cost=0, min_trade_cost=0))
    set_slippage(slippage.FixedSlippage(spread=0))

    # Number of quantiles for sorting returns for mean reversion
    context.nq = 5

    # Number of quantiles for sorting volatility over five-day mean reversion period
    context.nq_vol = 3

    # Create our pipeline and attach it to our algorithm.
    my_pipe = make_pipeline()
    attach_pipeline(my_pipe, 'my_pipeline')
Ejemplo n.º 19
0
def initialize(context):
    # Ethereum contract
    #context.contract = ContractHandler()
    # Get blacklist of sectors which returns a list of codes
    #context.blacklist = context.contract.getBlacklist()
    # for testing purpose without Ethereum exclude Defense, Beer & Alcohol, Tabacco and Coal
    context.blacklist = [26.0, 4.0, 5.0, 29.0]

    # Only run get_fundamentals when necessary based on the rebalance function
    context.initial = True
    # Dictionary of stocks and their respective weights
    context.stock_weights = {}
    # Count of days before rebalancing
    context.days = 0
    # Number of sectors to go long in
    context.sect_numb = 2
    # Sector mappings
    context.sector_mappings = get_sectors(key='code')
    context.ticker_sector_dict = get_sector_code()

    # TODO: Update this accordingly (weekly?)
    # Rebalance monthly on the first day of the month at market open
    schedule_function(rebalance,
                      date_rule=date_rules.month_start(),
                      time_rule=time_rules.market_open())
Ejemplo n.º 20
0
def initialize(context):
    # Dictionary of stocks and their respective weights
    context.stock_weights = {}
    # Count of days before rebalancing
    context.days = 0
    # Number of sectors to go long in
    context.sect_numb = 2

    # Sector mappings
    context.sector_mappings = {
        101.0: "Basic Materials",
        102.0: "Consumer Cyclical",
        103.0: "Financial Services",
        104.0: "Real Estate",
        205.0: "Consumer Defensive",
        206.0: "Healthcare",
        207.0: "Utilites",
        308.0: "Communication Services",
        309.0: "Energy",
        310.0: "Industrials",
        311.0: "Technology",
    }

    # Rebalance monthly on the first day of the month at market open
    schedule_function(rebalance, date_rule=date_rules.month_start(), time_rule=time_rules.market_open())
Ejemplo n.º 21
0
def initialize(context):
    set_commission(commission.PerDollar(cost=0.0055))
    # context.strategy_name = "FOF_{mdd}"
    context.mdd = context.namespace["mdd"]
    context.fof_code = context.namespace["fof_code"]
    context.save2mysql = context.namespace.get("save_method", 0)
    context.i = 0
    schedule_function(scheduled_rebalance,
                      date_rules.month_start(days_offset=0),
                      time_rules.market_open())
    context.init_value = pd.Series()  # 记录自最近一次调仓以来,组合内各基金所达到的最大净值
    context.adjust_date = 0  # 记录距离最近一次季调的时间
    context.stop_date = 0  # 记录距离最近一次止损的时间
    # 基金池
    stock = [
        '000478.OF', '050002.OF', '110006.OF', '161120.OF', '000217.OF',
        "501018.OF", '000071.OF', '070031.OF', '000342.OF', 'B00.IPE',
        "HSCI.HI", '037.CS', "em_bond", "reit", "SPTAUUSDOZ.IDC", '096001.OF',
        'SPX.GI', '000905.SH'
    ]
    context.stocks = []
    for sym in stock:
        context.stocks.append(symbol(sym))
    #  指数与基金的对应关系 fixed
    index = [
        "HSCI.HI", '037.CS', "EM_BOND", "REIT", "SPTAUUSDOZ.IDC", "000905.SH",
        "B00.IPE", "NDX.GI", 'SPX.GI'
    ]
    index_etf = ["000071.OF","161120.OF","000342.OF",\
                 "070031.OF","000217.OF","000478.OF",\
                 "501018.OF","160213.OF",'096001.OF']
    context.df_index = pd.DataFrame(
        data=index_etf,
        index=index,
    )
Ejemplo n.º 22
0
def initialize(context):
    print("{}:inside initialize".format(get_datetime()))

    schedule_function(rebalance, date_rule=date_rules.month_start(),
                        time_rule=time_rules.market_open())

    context.frequency = 120
    context.loop_count = 0
Ejemplo n.º 23
0
def initialize(context):
    print("init")
    context.asset = symbol('IBM')
    context.cmo_window = 30
    context.over_sell = -10
    context.over_buy = 10
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())
Ejemplo n.º 24
0
def initialize(context):
    print("init")
    context.asset = symbol('IBM')
    context.natr_period = 10
    context.long_multi = 0.2
    context.short_multi = 0.2
    context.pre_period = 1
    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())
Ejemplo n.º 25
0
def initialize(context):
    context.assets = {
        'a1': symbol('AAPL'),
        'a2': symbol('GE'),
        'a3': symbol('WMT')
    }

    schedule_function(cte_mix_handle, date_rules.every_day())
Ejemplo n.º 26
0
def initialize(context):
    print("init")
    context.asset = symbol('JD')
    context.bop_window = 20
    context.over_buy = 0.5
    context.over_sell = -0.5
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())
Ejemplo n.º 27
0
def initialize(context):
    context.begin = time.time()
    context.security = sid(118267)  # ISHARES RUSSELL 3000 ETF
    context.small = 30
    context.large = 70

    schedule_function(rebalance, date_rules.week_start(),
                      time_rules.market_open())
Ejemplo n.º 28
0
def initialize(context):
    print('初始化策略')
    context.asset = symbol('IBM')
    context.adx_buy_line = 40
    context.adx_sell_line = 20
    context.adx_window = 7

    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())
Ejemplo n.º 29
0
def initialize(context):
    print("init")
    context.asset = symbol('IBM')
    context.adosc_window = 14
    context.fast_period = 3
    context.slow_period = 10
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())
Ejemplo n.º 30
0
def initialize(context):

    __build_deeplearn_strategy(context)
    attach_pipeline(make_pipeline(context), 'my_pipeline')
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.every_minute())
    # record my portfolio variables at the end of day
    print("initialize over")
    pass
Ejemplo n.º 31
0
def initialize(context):
    context.params = {'lookback':12, 'min_volume':1E7
                      }
    
    schedule_function(strategy, date_rules.every_day(), 
            time_rules.market_open(minutes=30))

    attach_pipeline(make_strategy_pipeline(context), 
            name='strategy_pipeline')
Ejemplo n.º 32
0
def initialize(context):
    attach_pipeline(make_pipeline(), 'my_pipeline')

    # Rebalance each day.  In daily mode, this is equivalent to putting
    # `rebalance` in our handle_data, but in minute mode, it's equivalent to
    # running at the start of the day each day.
    schedule_function(rebalance, date_rules.every_day())

    # Explicitly set the commission to the "old" value until we can
    # rebuild example data.
    # github.com/quantopian/zipline/blob/master/tests/resources/
    # rebuild_example_data#L105
    context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0))
Ejemplo n.º 33
0
def initialize(context):
    context.has_ordered = False
    set_commission(commission.PerShare(cost=0.0, min_trade_cost=0.0))
    set_slippage(slippage.FixedSlippage(spread=0.0)) 
    schedule_function(func0, date_rules.week_end())
def initialize (context) :
   
    # Algorithm parameters are defined here
    if ENVIRONMENT == 'RESEARCH':    
        context.benchmark = symbols('SPY')
        context.risk_free = symbols('SHY')
        context.cash_proxy = symbols('SHY')
    elif ENVIRONMENT == 'ZIPLINE' or ENVIRONMENT == 'IDE':
        context.benchmark = symbol('SPY')
        context.risk_free = symbol('SHY')
        context.cash_proxy = symbol('SHY')

    context.algo_transforms = [(['price'], ROCP, ['mom_63'], 62), 
                               (['price'], ROCP, ['mom_21'], 20), 
                               (['price'], average_historic_volatility, ['hvol_20'], 63, 20),
                               (['price'], SMA, ['short_mavg'], 21),
                               (['price'], SMA, ['long_mavg'], 63)
                               ]
    
    if ENVIRONMENT == 'ZIPLINE' or ENVIRONMENT == 'IDE':
        context.strategies = {
                                'strategy1': {
                                    'strat_wt' : 1.0,
                                    'strat_type' : 'SIGNAL',
                                    'alloc_type' : 'EQWT',   
                                    'portfolios' : [
                                                    symbols('VHT', 'VGT', 'VCR', 'IBB', 'EDV', 'VB', 'VAW', 
                                                            'TLT')
                                                    ],
                                    'weights' : [1.0],
                                    'n_top' : [1],
                                    'zscore_data' : ['+mom_63', '+mom_21', '-hvol_20'],
                                    'zscore_weights' : [0.7, 0.0, 0.3],
    #                                 'filter' : [lambda x,y: (x > y) & (x > 0), 'mom_21', ('mom_21', context.risk_free)]
    #                                 'filter' : []
                                    'filter' : [lambda x,y: x > y, 'mom_63', ('mom_63', context.risk_free)],
                                    'buy_trigger' : [lambda x,y: (x > y) and (context.buy_flag==False), 
                                                     'short_mavg', 'long_mavg'], 
                                    'sell_trigger' : [lambda x,y : (x < y) and (context.buy_flag==True), 
                                                      'short_mavg', 'long_mavg']
                                    }
                                }
        
    elif ENVIRONMENT == 'RESEARCH':
        context.strategies = {
                                'strategy1': {
                                    'strat_wt' : 1.0,
                                    'strat_type' : 'SIGNAL',
                                    'alloc_type' : 'EQWT',
                                    'portfolios' : [
                                                    [symbols('VHT'), symbols('VGT'), symbols('VCR'), 
                                                     symbols('IBB'), symbols('EDV'), symbols('VB'), 
                                                     symbols('VAW'), symbols('TLT')]
                                                    ],
                                    'weights' : [1.0],
                                    'n_top' : [1],
                                    'zscore_data' : ['+mom_63', '+mom_21', '-hvol_20'],
                                    'zscore_weights' : [0.7, 0.0, 0.3],
                                    # 'filter' : [lambda x,y: (x > y) & (x > 0), 'mom_21', 
                                    #             ('mom_21', context.risk_free)]
    #                                 'filter' : []
                                    'filter' : [lambda x,y: x > y, 'mom_63', ('mom_63', context.risk_free)], 
                                    'buy_trigger' : [lambda x,y: (x > y) and (context.buy_flag==False), 
                                                     'short_mavg', 'long_mavg'],
                                    'sell_trigger' : [lambda x,y : (x < y) and (context.buy_flag==True), 
                                                      'short_mavg', 'long_mavg']
                                    }
                                }

    # have to set this manually 'til I figure how to generate it programmatically from above parameters
    context.max_lookback = 120        # need additional data for recursive indicators like EMA, historic_vol etc.
    
    # set the appropriate time_rule offsets (hours, minutes) for order processing
    context.order_time_rule = time_rules.market_close(hours=0, minutes=1)
    
    context.threshold = 0.0     # only BUY/SELL if asset QTY changes by threshold%
    
    set_commission(commission.PerTrade(cost=0.0))  
    set_slippage(slippage.FixedSlippage(spread=0))
    
    #######################################################################################
    # THE FOLLOWING MUST ALWAYS BE INCLUDED AND MUST PRECEDE ANY SCHEDULED FUNCTIONS!
    # include this check to make sure that the algo parameters are formatted as required
    check_algo_parameters (context)
    # create a set of all the symbols used by the algorithm
    create_symbol_list(context)
    initialize_strat_variables(context)
    if ENVIRONMENT != 'IDE':
        add_strat_history(context)  
    #######################################################################################
    
    schedule_function(generate_strat_data,  
                     # date_rule=date_rules.month_start(days_offset=0),
                     date_rule=date_rules.month_start(days_offset=0),
                     time_rule=time_rules.market_open(hours=0, minutes=1),
                     half_days=True) 

#     schedule_function_by_interval(context, test_signal,  
#                      date_rule=date_rules.every_day(), 
#                      time_rule=time_rules.market_open(hours=0, minutes=5),
#                      half_days=True,
#                      freq=1)    
    
    # the 'freq' parameter is added to the norma schedule_function routine
    # to enable intervals of 'freq' periods - 1,2,3,.....  months
    schedule_function_by_interval(context, rebalance,  
                     date_rule=date_rules.month_start(days_offset=0), 
                     time_rule=time_rules.market_open(hours=0, minutes=5),
                     half_days=True,
                     freq=1)
    
    schedule_function_by_interval(context, handle_orders,  
                     date_rule=date_rules.month_start(days_offset=0), 
                     time_rule=time_rules.market_close(hours=0, minutes=15),
                     half_days=True,
                     freq=1)
Ejemplo n.º 35
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)
Ejemplo n.º 36
0
def schedule_function_by_interval (context, func, date_rule, time_rule, half_days=True, freq=1):
    context.interval_counter[func] = {'freq':freq, 'count':freq, 'periods':freq}
#     print ('\n\nINTERVAL COUNTER\n{}'.format(context.interval_counter))
    schedule_function (func, date_rule, time_rule, half_days)
    return