コード例 #1
0
def initialize(context):
    ''' Initialize global vars'''
    context.long_leverage = 0.1
    context.short_leverage = -0.9
    context.returns_lookback = 16
    context.pct_per_stock = 0.5
    
    context.fastperiod = 12
    context.slowperiod = 26
    context.signalperiod = 9
    context.bar_count = 90

    set_commission(commission.PerShare(cost=0.0014, min_trade_cost=1))
    
    # Rebalance on the first trading day of each week at 12AM.
    schedule_function(rebalance, date_rules.week_start(days_offset=0),time_rules.market_open(hours=0.5))
    
    # Rebalance mid-week
    schedule_function(cut_losses, date_rules.week_start(days_offset=2),time_rules.market_open(hours=0.5))

    # Record tracking variables at the end of each day.
    schedule_function(record, date_rules.every_day(),time_rules.market_open(minutes=1))


    # Create and attach our pipeline (dynamic stock selector), defined below.
    attach_pipeline(make_pipeline(context),
                    'mean_reversion_macd_learning')
コード例 #2
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())
コード例 #3
0
def initialize(context):
    """
        API function to define things to do at the start of the strategy.
    """
    # set strategy parameters
    context.lookback_data = 60
    context.lookback_long = 20
    context.leverage = 2.0
    context.profit_target = 1.0

    # reset everything at start
    daily_reset(context)

    # create our universe
    create_universe(context)

    # schedule calculation at the end of opening range (30 minutes)
    schedule_function(calculate_trading_metrics, date_rules.every_day(),
                      time_rules.market_open(hours=0, minutes=30))

    # schedule entry rules
    schedule_function(no_more_entry, date_rules.every_day(),
                      time_rules.market_open(hours=1, minutes=30))

    # schedule exit rules
    schedule_function(unwind, date_rules.every_day(),
                      time_rules.market_close(hours=0, minutes=30))

    # set trading costs
    set_commission(commission.PerShare(cost=0.005, min_trade_cost=0.0))
    set_slippage(slippage.FixedSlippage(0.00))
コード例 #4
0
def rebalance_scheduler(context):
    '''
        function to schedule a rebalancing trade. 
        The rebalancing is done based on the weights determined in the strategy core
        for each of the instruments defined in the trading universe.
    '''
    context.use_handle_data = False
    rebalance_freq = context.params.get('rebalance_freq',None)

    if rebalance_freq is None:
        return
    
    if context.params['verbose']:
        print('setting up {} scheduler'.format(rebalance_freq))
    
    if rebalance_freq == 'monthly':
        schedule_function(rebalance,
                    date_rules.month_start(days_offset=0),
                    time_rules.market_open(hours=5, minutes=30))
    elif rebalance_freq == 'weekly':
        schedule_function(rebalance,
                    date_rules.week_start(days_offset=0),
                    time_rules.market_open(hours=5, minutes=30))
    elif rebalance_freq == 'daily':
        schedule_function(rebalance,
                    date_rules.every_day(),
                    time_rules.market_open(hours=5, minutes=30))
    elif rebalance_freq.endswith('m'):
        try:
            context.trade_freq = int(rebalance_freq.split('m')[0])
            print('trade freq {}'.format(context.trade_freq))
            context.bar_count = 0
            context.use_handle_data = True
        except:
            raise ValueError('Invalid minute frequency')
    elif rebalance_freq.endswith('h'):
        try:
            context.trade_freq = int(rebalance_freq.split('h')[0])*60
            print('trade freq {}'.format(context.trade_freq))
            context.bar_count = 0
            context.use_handle_data = True
        except:
            raise ValueError('Invalid hourly frequency')
    else:
        raise ValueError('Un-recognized rebalancing frequency')

    if context.params['no_overnight_position']:
        schedule_function(square_off,
                    date_rules.every_day(),
                    time_rules.market_close(hours=3, minutes=30))
コード例 #5
0
ファイル: svm.py プロジェクト: drgee1000/stock_trading
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))
コード例 #6
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
コード例 #7
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')
コード例 #8
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())
コード例 #9
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))
コード例 #10
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()
        )
コード例 #11
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))
コード例 #12
0
ファイル: tradeNFLX.py プロジェクト: TheJCBand/stockTrading
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())
コード例 #13
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())
コード例 #14
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,
    )
コード例 #15
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())
    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')
コード例 #17
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
コード例 #18
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')
コード例 #19
0
def initialize(context):
    schedule_function(func=trade,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(),
                      half_days=True)
    context.asserts = symbols('SPY', 'SHY', 'TLT', 'GLD')
    context.asserts_position = [0.25, 0.25, 0.25, 0.25]
    context.rebalance_inteval = 'Q'  #'Q', #'D', #'M' #'Q' #'Y'
    context.rebalance_date = 0
    context.fired = False
コード例 #20
0
def initialize(context):

    context.security = symbol(SYMBOL)  # Trade
    set_benchmark(symbol(SYMBOL))  # Set benchmarks
    #print(context.security)
    context.start = True
    set_long_only()
    schedule_function(market_open, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
    context.orders_submitted = False
def initialize(context):
    """Setup: register pipeline, schedule rebalancing,
        and set trading params"""
    attach_pipeline(compute_factors(), 'factor_pipeline')
    schedule_function(rebalance,
                      date_rules.week_start(),
                      time_rules.market_open(),
                      calendar=calendars.US_EQUITIES)

    set_commission(us_equities=commission.PerShare(cost=0.00075, min_trade_cost=.01))
    set_slippage(us_equities=slippage.VolumeShareSlippage(volume_limit=0.0025, price_impact=0.01))
コード例 #22
0
def initialize(context):

    #set_benchmark(symbol("SPY"))
    
    # 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()
    )

    # Record variables at the end of each day.
    schedule_function(
        func=my_record_vars,
        date_rule=date_rules.every_day(),
        time_rule=time_rules.market_open()
    )

    # Create our pipeline and attach it to our algorithm.
    my_pipe = make_pipeline()
    attach_pipeline(pipeline=my_pipe, name='my_pipeline')
コード例 #23
0
def initialize(context):
    # Define Symbol
    context.security = symbol('MSFT')
    # Define standard devation threshold
    context.std_dev_threshold = 0.6

    schedule_function(enter_position,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open())

    schedule_function(square_off,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_close(minutes=1))
コード例 #24
0
ファイル: bpj.py プロジェクト: phanirajl/algoTrading
def initialize(context):
    set_slippage(VolumeShareSlippage(volume_limit=0.025,price_impact=0.1))
    tickers = ['AYI','APA','AMZN','LNT','CTL','ALB','ABBV','AMT','ADM','AON','ORCL']
    context.tick_list = tickers
    context.tickers = [ symbol(x) for x in tickers ]
    context.long= False
    context.short= False
    start = datetime.datetime(2013,1,3)
    end = datetime.datetime(2017,8,1)
    sec_list = SecurityList(tickers=tickers)
    sec_list.downloadQuandl(start,end)
    ts = sec_list.genTimeSeries()
    context.adjDiv = sec_list.adjDividends()
    context.adjHedge = sec_list.adjSplits()
    context.divFactors = sec_list.getAdjFactors()
    context.splits = sec_list.getSplits()
    context.avg = ts.mean()
    context.std = ts.std()
    context.leverage = 1
    context.share_num = 0
    context.diff_thresh = 100
    schedule_function(adjust_splits_dividends, date_rules.every_day(), time_rules.market_open())
    schedule_function(place_orders, date_rules.every_day(), time_rules.market_open(hours=1, minutes=30))
コード例 #25
0
def initialize(context):
    context.i = int(input("Start index?:  "))

    # Explicitly set the commission/slippage 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=.005, min_trade_cost=1.0))
    context.set_slippage(slippage.VolumeShareSlippage())
    context.schedule_function(func=run,
                              date_rule=date_rules.month_start(),
                              time_rule=time_rules.market_open(),
                              half_days=True,
                              calendar=None)
コード例 #26
0
def initialize(context):
    context.security = sid(8554)  # Trade SPY
    context.model = RandomForestRegressor()

    context.lookback = 3  # Look back 3 days
    context.history_range = 400  # Only consider the past 400 days' history

    # Generate a new model every week
    schedule_function(create_model, date_rules.week_end(),
                      time_rules.market_close(minutes=10))

    # Trade at the start of every day
    schedule_function(trade, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
コード例 #27
0
def initialize(context):
    context.asset = symbol('000001.SZ')

    # Explicitly set the commission/slippage 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))
    context.set_slippage(slippage.VolumeShareSlippage())

    schedule_function(
        my_func,
        date_rules.every_day(),
        time_rules.market_open(minutes=15)
    )
コード例 #28
0
def initialize(context):
    # ETFs and target weights for a balanced and hedged portfolio
    context.securities = {
        'SPY': 0.25,
        'TLT': 0.3,
        'IEF': 0.3,
        'GLD': 0.075,
        'DBC': 0.075
    }

    # Schedule rebalance for once a month
    schedule_function(rebalance, date_rules.month_start(),
                      time_rules.market_open())

    # Set up a benchmark to measure against
    context.set_benchmark(symbol('SPY'))
コード例 #29
0
def initialize(context):

    # slippage model
    set_slippage(slippage.FixedSlippage(spread=0))

    # stock universe - list of tickers
    securities = ['AAPL', 'ADBE', 'AIG', 'AMGN', 'BA']
    # change string list of tickers into asset list using symbol function
    context.sec_symbols = [symbol(s) for s in securities]
    print(len(context.sec_symbols))

    # schedule functions
    schedule_function(trade_market_open, date_rules.every_day(),
                      time_rules.market_open())
    schedule_function(cancel_open, date_rules.every_day(),
                      time_rules.market_close())
def initialize(context):
    schedule_function(func=trade, date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(),half_days=True)
    context.asserts = symbols('SPY','IEF')

    context.rebalance_date = 0
    context.fired = False
    context.rebalance_inteval = 'M'#'Q', #'D', #'M' #'Q' #'Y'

    context.asserts_position = [0.5, 0.5]
    context.volatility_policy = True
    #unused if volatility_policy is false
    context.volatility_days = 252
    context.volatility_price_history = 66
    #set at less than 1 to ensure no leverage
    context.leverage_buffer=0.90