Example #1
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())
Example #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 = 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))
Example #3
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))
Example #4
0
def initialize(context):

  # Stocks to trade
  stock_list = ['FB', 'AMZN', 'AAPL', 'NFLX', 'GOOGL']
  context.stocks = [symbol(stock) for stock in stock_list]

  # How much of the portfolio is invested in each stock (20% each)
  context.target_pct_per_stock = 1 / len(context.stocks)

  # Transaction costs
  #context.set_commission(commission.PerShare(cost=0.0, min_trade_cost=0))
  #context.set_commission(commission.PerDollar(cost=0.0015)) # default is 0.0015
  #context.set_commission(commission.PerTrade(cost=0.0))

  # Slippage
  #context.set_slippage(slippage.VolumeShareSlippage())

  # Upper and Lower bound for RSI trading signals
  context.low_rsi = 30
  context.high_rsi = 70

  # Moving average window
  #context.index_average_window = 100

  set_benchmark(False)
Example #5
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
Example #6
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')
Example #7
0
def initialize(context):

    # List of Major World Indices Yahoo tickers - https://finance.yahoo.com/world-indices
    with open('tickers.pickle', 'rb') as handle:
        indices_tickers = pickle.load(handle)  # load in tickers from pickle

    os.remove('tickers.pickle')  # delete tickers pickle file

    context.indices = [symbol(ticker) for ticker in indices_tickers
                       ]  # create list of ticker symbols
    context.days_of_correction = [
        0 for _ in indices_tickers
    ]  # create list of days since correction has begun
    set_benchmark(symbol('^GSPC'))
    set_commission(
        commission.PerTrade(cost=15.0)
    )  # commission for IBKR, UK for Stocks, ETF's & Warrants - https://www.interactivebrokers.co.uk/en/index.php?f=39753&p=stocks1
    '''-----------------------------PARAMETERS TO BE OPTIMISED--------------------------------'''
    context.correction_margin = 0.1  # the percentage drawdown considered a correction
    print('Drawdown percentage range from peak for correction: ' +
          str(round(context.correction_margin * 100)) + '%')
    context.upturn_coefficient = 0.24  # the ratio upturn from trough indicating end of correction - used in calculate_required_upturn function
    print('Upturn Coefficient: ' + str(round(context.upturn_coefficient, 4)))
    context.min_gain = 0.05  # the highest the price can be from peak and still be considered for ordering
    print('Mainimum potential gain from peak to be considered: ' +
          str(round(context.min_gain * 100, 0)) + '%')
    context.state_threshold = -10.0  # 0.0002 threshold between bull and bear markets
    print('Market state threshhold: ' +
          str(round(context.state_threshold, 4)) + '%')
Example #8
0
def initialize(context):

    # List of Major World Indices Yahoo tickers - https://finance.yahoo.com/world-indices
    with open('tickers.pickle', 'rb') as handle:
        indices_tickers = pickle.load(handle)  # load in tickers from pickle

    os.remove('tickers.pickle')  # delete tickers pickle file

    context.indices = [symbol(ticker) for ticker in indices_tickers
                       ]  # create list of ticker symbols
    context.days_of_correction = [
        0 for _ in indices_tickers
    ]  # create list of days since correction has begun
    set_benchmark(symbol('^GSPC'))
    '''-----------------------------PARAMETERS TO BE OPTIMISED--------------------------------'''
    context.correction_margin = 0.1  # the percentage drawdown considered a correction
    print('Drawdown percentage range from peak for correction: ' +
          str(round(context.correction_margin * 100)) + '%')
    context.upturn_coefficient = 0.22  # the ratio upturn from trough indicating end of correction - used in calculate_required_upturn function
    print('Upturn Coefficient: ' + str(round(context.upturn_coefficient, 2)))
    context.min_return = 0.26  # the minimum return required before changing positions
    print('Minimum return per trade: ' + str(round(context.min_return * 100)) +
          '%')
    context.min_gain = 0.07  # the highest the price can be from peak and still be considered for ordering
    print('Mainimum potential gain from peak to be considered: ' +
          str(round(context.min_gain * 100, 0)) + '%')
    context.stop_loss = 0.53  # lowest proportion of investment peak
    print('Stop loss for investments: ' + str(round(context.stop_loss * 100)) +
          '%')
Example #9
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())
Example #10
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))
Example #11
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"))
Example #12
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))
Example #13
0
    def initialize(self, context):

        set_benchmark(symbol(self.symbol))

        context.set_slippage(slippage.NoSlippage())

        context.scheduled_data = {}
Example #14
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))
Example #15
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
Example #16
0
def initialize(context):
    # attach_pipeline(make_pipeline(), 'my_pipeline')
    context.longStock = symbol('SPY2')
    context.shortStock = symbol('SH2')

    context.turnover_count = 0

    # etf stock
    context.shorting_on = True

    set_benchmark(symbol("SPY2"))
Example #17
0
    def initialize(self, context, stock_ids):
        super().initialize(context, stock_ids)

        context.portfolio_highest = {}
        context.price_highest = {}
        context.stock_shares = {}

        context.set_commission(
            commission.PerShare(cost=.0075, min_trade_cost=1.0))
        context.set_slippage(slippage.VolumeShareSlippage())
        set_benchmark(context.assets[0])

        for asset in context.assets:
            context.price_highest[asset] = 0.0
            context.portfolio_highest[asset] = 0.0
            context.stock_shares[asset] = 0
Example #18
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')

    algo.set_benchmark(algo.sid('FIBBG000BDTBL9'))

    # Rebalance every day, 30 minutes before market close.
    algo.schedule_function(
        rebalance,
        algo.date_rules.every_day(),
        algo.time_rules.market_close(minutes=30),
    )
Example #19
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("SPY"))

    # 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))
Example #20
0
def initialize(context):
    attach_pipeline(make_pipeline(), 'data_pipeline')

    context.technical_indicator_states = {}
    context.window_length = 7
    context.benchmark = deque(maxlen=context.window_length)
    context.benchmark_asset = symbol('SPY')
    context.benchmark_assets = symbols('QQQ', 'SPY')

    #context.classifier = RandomForestClassifier() # Use a random forest classifier
    context.classifier = DecisionTreeClassifier(max_depth=5, max_leaf_nodes=10)

    # Clasifier training data
    context.features = [
        'RSI', 'EMA', 'MACD', 'SMA_5', 'SMA_10', 'bb_lower', 'bb_middle',
        'bb_upper'
    ]
    context.response = ['Class']
    context.X = pd.DataFrame(
        columns=context.features)  # Independent, or input variables
    context.Y = pd.DataFrame(
        columns=context.response)  # Dependent, or output variable

    context.prediction = {}  # Stores most recent prediction

    context.tick = 0
    context.total_buy = 0
    context.positions = None
    context.position_adjustment_days = 5  # Number of days to wait before adjusting positions
    context.min_data_points = 500
    context.max_data_points = 1500

    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open(minutes=1))
    schedule_function(record_vars, date_rules.every_day(),
                      time_rules.market_close())
    set_benchmark(symbol('SPY'))
    # Turn off the slippage model
    set_slippage(slippage.FixedSlippage(spread=0.0))
    # Set the commission model (Interactive Brokers Commission)
    set_commission(commission.PerShare(cost=0.01, min_trade_cost=1.0))
Example #21
0
def initialize(context):
    set_benchmark(symbol("BTC"))
Example #22
0
def initialize(context):
	set_benchmark(symbol('MSFT'))
	context.i = 0
	context.asset = symbol('MSFT')
Example #23
0
def initialize(context):
    set_benchmark(symbol("PETR4"))
 def initialize(cls, context):
     context.i = 0
     context.asset = symbol('MSFT')
     context.assets = [symbol(asset) for asset in cls._portfolio.assets]
     set_benchmark(symbol('benchmark'))
Example #25
0
def intialize(context):
    context.stock = symbol('SPY')
    set_benchmark(context.stock)
def initialize(context):
    set_benchmark(symbol(stock))
    context.asset = symbol(stock)
    context.i = 0
Example #27
0
 def initialize(context):
     set_benchmark(symbol('SH00300'))
Example #28
0
def initialize(context):
    context.i = 0
    set_benchmark(symbol('AAPL'))
    context.asset = symbol('AAPL')