コード例 #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):
    """
        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))
def initialize(context):
    """
        A function to define things to do at the start of the strategy
    """
    # universe selection
    context.securities = [symbol('NIFTY-I'), symbol('BANKNIFTY-I')]

    # define strategy parameters
    context.params = {
        'indicator_lookback': 375,
        'indicator_freq': '1m',
        'buy_signal_threshold': 0.5,
        'sell_signal_threshold': -0.5,
        'ROC_period_short': 30,
        'ROC_period_long': 120,
        'BBands_period': 300,
        'trade_freq': 5,
        'leverage': 2
    }

    # variable to control trading frequency
    context.bar_count = 0

    # variables to track signals and target portfolio
    context.signals = dict((security, 0) for security in context.securities)
    context.target_position = dict(
        (security, 0) for security in context.securities)

    # set trading cost and slippage to zero
    set_commission(commission.PerShare(cost=0.0, min_trade_cost=0.0))
    set_slippage(slippage.FixedSlippage(0.00))
コード例 #4
0
def initialize(context):
    """
    Called once at the start of a backtest, and once per day at
    the start of live trading.
    """
    # Attach the pipeline to the algo
    algo.attach_pipeline(make_pipeline(), 'pipeline')

    # Set SPY as benchmark
    algo.set_benchmark(algo.sid("FIBBG000BDTBL9"))

    # identify down gaps immediately after the opening
    algo.schedule_function(
        find_down_gaps,
        algo.date_rules.every_day(),
        algo.time_rules.market_open(minutes=1),
    )

    # at 9:40, short stocks that gapped down
    algo.schedule_function(
        short_down_gaps,
        algo.date_rules.every_day(),
        algo.time_rules.market_open(minutes=10),
    )

    # close positions 5 minutes before the close
    algo.schedule_function(
        close_positions,
        algo.date_rules.every_day(),
        algo.time_rules.market_close(minutes=5),
    )

    # Set commissions and slippage
    algo.set_commission(commission.PerShare(cost=0.0))
    algo.set_slippage(slippage.FixedBasisPointsSlippage(basis_points=3.0))
    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')
コード例 #6
0
def initialize(context):
    '''
        A function to define things to do at the start of the strategy
    '''
    # universe selection
    context.universe = [symbol('NIFTY-I'),symbol('BANKNIFTY-I')]
    
    # define strategy parameters
    context.params = {'indicator_lookback':375,
                      'indicator_freq':'1m',
                      'buy_signal_threshold':0.5,
                      'sell_signal_threshold':-0.5,
                      'SMA_period_short':15,
                      'SMA_period_long':60,
                      'RSI_period':300,
                      'BBands_period':300,
                      'ADX_period':120,
                      'trade_freq':15,
                      'leverage':1}
    
    # variable to control trading frequency
    context.bar_count = 0

    # variables to track target portfolio
    context.weights = dict((security,0.0) for security in context.universe)

    # set trading cost and slippage to zero
    set_commission(commission.PerShare(cost=0.0, min_trade_cost=0.0))
    set_slippage(slippage.FixedSlippage(0.00))

    # create the list of experts as well as the agent controlling them
    context.advisor = Advisor('bbands_ea',expert_advisor, context.universe)

    # schedule agent weights updates
    pass
コード例 #7
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())
コード例 #8
0
    def initialize(context):
        context.start_date = trading_start
        context.agent = agent
        context.num_trials = 0
        context.action = ACTION
        context.values = deque(maxlen=21)
        set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.00))
        set_slippage(slippage.FixedSlippage(0.00))
        context.universe = universe_transform('2018-01-01')

        schedule_function(rebalance_portfolio,
                          date_rules.week_start(days_offset=trading_day),
                          time_rules.market_open(hours=1))

        #schedule_function(cancel_open_orders, date_rules.every_day(), time_rules.market_open())

        schedule_function(prime_pipeline,
                          date_rules.week_start(days_offset=trading_day - 1),
                          time_rules.market_close())

        context.Factor_weights = ENV.current_node.weights
        context.weights = None
        context.run_pipeline = True  #We want to run stock selector immediately
        context.weeks_since_rebalance = -1

        attach_pipeline(make_pipeline(context), 'my_pipeline')
コード例 #9
0
 def initialize(context):
     context.time = 0
     context.asset = symbol('SPY')
     context.set_commission(
         commission.PerShare(cost=0.001, min_trade_cost=0))
     context.strategy_params_1 = ta_params
     set_benchmark(symbol("SPY"))
    def initialize(self):
        """
        Called once at the start of the algorithm.
        The initialize function is the place to set your tradable universe and define any parameters
        """
        self.securities = tickers

        self.sids = [self.symbol(security) for security in self.securities]

        # there needs to be enough data points to make a good model
        self.data_points = 100

        # amount of prior bars to study
        self.window_length = 50

        # Use a random forest regressor
        self.mdl = RandomForestRegressor()

        # stores recent prices
        self.recent_prices = OrderedDict()

        for security in self.securities:
            self.recent_prices[security] = []

        # initialise the model
        self.imp = Imputer(missing_values='NaN', strategy='mean', axis=0)

        self.set_commission(commission.PerShare(cost=0.013, min_trade_cost=1.3))
コード例 #11
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')
コード例 #12
0
ファイル: buyapple.py プロジェクト: xujun05/nzl
def initialize(context):
    context.asset = symbol('510050')

    # 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))
コード例 #13
0
def initialize(context):
    context.asset = symbol("AAPL")

    # 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=0.0075, min_trade_cost=1.0))
    context.set_slippage(slippage.VolumeShareSlippage())
コード例 #14
0
        def initialize(context):
            context.asset = symbol(asset_symbol)

            # To keep track of whether we invested in the stock or not
            context.invested = False

            # Explicitly set the commission/slippage to the "old" value until we can
            context.set_commission(commission.PerShare(**commission_cost))
            context.set_slippage(slippage.VolumeShareSlippage())
            context.params = params_list
コード例 #15
0
def initialize(context):
    attach_pipeline(make_pipeline(), 'my_pipeline')

    # If Zipline has trouble pulling the default benchmark, try setting the
    # benchmark to something already in your bundle
    #    set_benchmark(symbol("change this to a symbol in your data"))

    # Rebalance periodically
    schedule_function(rebalance, REBALANCE_INTERVAL)

    context.set_commission(commission.PerShare(cost=.005, min_trade_cost=0))
コード例 #16
0
def initialize(context):
    attach_pipeline(make_pipeline(), 'my_pipeline')

    # 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(VolumeShareSlippage())

    schedule_function(rebalance2, date_rules.every_day())
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))
コード例 #18
0
    def initialize(self, context):

        comm = commission.PerShare(cost=self.cost,
                                   min_trade_cost=self.min_trade_cost)
        set_commission(comm)

        # schedule train and review functions

        schedule_function(self.train_agent, self.train_date, self.train_time)
        schedule_function(self.review_performance, self.review_date,
                          self.review_time)
コード例 #19
0
ファイル: dual_ema_talib.py プロジェクト: zhengfaner/zipline
def initialize(context):
    context.asset = symbol('AAPL')

    # To keep track of whether we invested in the stock or not
    context.invested = False

    # 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))
コード例 #20
0
ファイル: olmar.py プロジェクト: gontse00/capfoliopro
    def initialize(algo, eps=1, window_length=5):
        algo.stocks = STOCKS
        algo.tickers = [symbol(ticker) for ticker in algo.stocks]
        algo.m = len(algo.stocks)
        algo.price = {}
        algo.b_t = np.ones(algo.m) / algo.m
        algo.eps = eps
        algo.window_length = window_length

        algo.set_commission(commission.PerShare(cost=0))
        algo.set_slippage(slippage.FixedSlippage(spread=0))
コード例 #21
0
        def initialize(context, asset):
            context.set_commission(commission.PerShare(cost=0, min_trade_cost=0))
            context.set_slippage(slippage.FixedSlippage(spread=0.0))

            context.start_date = context.get_datetime()
            context.asset = context.sid(asset)
            context.counter = count()
            # buy 1 first 4 days, close out all last day

            context.order_amounts = np.repeat(0, len(self.equity_daily_bar_days))
            context.order_amounts[0] = 2  # buy 2 lot on first day
            context.order_amounts[69] = -1  # sell 1 lot on 69th day
            context.order_amounts[-30] = -1  # close out final lot
コード例 #22
0
ファイル: olmar.py プロジェクト: yun-li/zipline
def initialize(algo, eps=1, window_length=5):
    algo.stocks = STOCKS
    algo.sids = [algo.symbol(symbol) for symbol in algo.stocks]
    algo.m = len(algo.stocks)
    algo.price = {}
    algo.b_t = np.ones(algo.m) / algo.m
    algo.last_desired_port = np.ones(algo.m) / algo.m
    algo.eps = eps
    algo.init = True
    algo.days = 0
    algo.window_length = window_length

    algo.set_commission(commission.PerShare(cost=0))
コード例 #23
0
ファイル: olmar.py プロジェクト: zhenxinlei/zipline
def initialize(algo, eps=1, window_length=5):
    algo.stocks = STOCKS
    algo.m = len(algo.stocks)
    algo.price = {}
    algo.b_t = np.ones(algo.m) / algo.m
    algo.last_desired_port = np.ones(algo.m) / algo.m
    algo.eps = eps
    algo.init = True
    algo.days = 0
    algo.window_length = window_length
    algo.add_transform('mavg', 5)

    algo.set_commission(commission.PerShare(cost=0))
コード例 #24
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))
コード例 #25
0
def initialize(context, eps=1, window_length=5):
    context.stocks = STOCKS
    context.sids = [context.symbol(symbol) for symbol in context.stocks]
    context.m = len(context.stocks)
    context.price = {}
    context.b_t = np.ones(context.m) / context.m
    context.last_desired_port = np.ones(context.m) / context.m
    context.eps = eps
    context.init = True
    context.days = 0
    context.window_length = window_length

    context.set_commission(commission.PerShare(cost=0, min_trade_cost=1.0))
コード例 #26
0
    def initialize(self):
        self.stocks = STOCKS
        self.set_commission(commission.PerShare(cost=0))

        self.days = 0
        self.short_window = 10
        self.long_window = 30
        self.price_history = deque(maxlen=self.long_window)

        #Exponential Moving Average
        self.last_ema_test = None
        self.short_ema_trans = EMA(timeperiod=self.short_window)
        self.long_ema_trans = EMA(timeperiod=self.long_window)
コード例 #27
0
ファイル: olmar.py プロジェクト: mikimaus78/myIbPy
    def initialize(self, eps=1, window_length=5):
        self.stocks = STOCKS
        self.m = len(self.stocks)
        self.price = {}
        self.b_t = np.ones(self.m) / self.m
        self.last_desired_port = np.ones(self.m) / self.m
        self.eps = eps
        self.init = True
        self.days = 0
        self.window_length = window_length
        self.add_transform(MovingAverage, 'mavg', ['price'],
                           window_length=window_length)

        self.set_commission(commission.PerShare(cost=0))
コード例 #28
0
def initialize(algo, eps=1, window_length=5):
    algo.stocks = ['AMD', 'CERN', 'COST', 'DELL', 'GPS', 'INTC', 'MMM']
    algo.sids = [algo.symbol(symbol) for symbol in algo.stocks]
    algo.m = len(algo.stocks)
    algo.price = {}
    algo.b_t = np.ones(algo.m) / algo.m
    algo.last_desired_port = np.ones(algo.m) / algo.m
    algo.eps = eps
    algo.init = True
    algo.days = 0
    algo.window_length = window_length

    algo.set_commission(commission.PerShare(cost=0, min_trade_cost=1.0))
    algo.set_slippage(slippage.VolumeShareSlippage())
コード例 #29
0
def initialize(context):
    #     set_benchmark(symbol('SPY'))
    model.init_model()
    context.i = 0
    context.asset1 = symbol('EBAY')
    context.asset2 = symbol('KLAC')
    context.model_fee= 1e-3
    context.previous_predict_reward=0
    context.previous_action=0
    context.set_commission(commission.PerShare(cost=0.005, min_trade_cost=1.0))
    context.set_slippage(slippage.VolumeShareSlippage())
    context.sequence_length=300
    context.tb_log_dir='./log/backtest'
    context.tensorboard=TensorBoard(log_dir=context.tb_log_dir)
コード例 #30
0
def initialize(context):
    # 记录股票代码,通过股票代码获取股票对象
    context.asset = symbol('AAPL')

    # 定义是否买入股票的标记
    context.invested = False

    # 设置交易的手续费,股票成交时,手续费按成交金额一定比例收取
    # 设置手续费率和最低费用
    context.set_commission(commission.PerShare(cost=.0075, min_trade_cost=1.0))

    # 设置模拟真实交易的滑价,当实际下单交易时,下单订单将影响市场。买单驱使价格上涨,卖单驱使价格下滑;
    # 这通常被称为交易的“价格影响”。价格影响的大小取决于订单与当前交易量相比有多大。
    context.set_slippage(slippage.VolumeShareSlippage(volume_limit=0.025, price_impact=0.1))