コード例 #1
0
def initialize(context):
    schedule_function(func=trade,
                      date_rule=date_rules.every_day(),
                      time_rule=time_rules.market_open(),
                      half_days=True)
    schedule_function(func=cancel,
                      time_rule=time_rules.market_close(minutes=5),
                      date_rule=date_rules.every_day(),
                      half_days=True)
    schedule_function(func=reorder,
                      time_rule=time_rules.market_open(minutes=5),
                      date_rule=date_rules.every_day(),
                      half_days=True)
    context.asserts = symbols('SPY')
    context.bonds = symbol('SHY')
    context.rebalance_date = 0
    context.fired = False
    context.rebalance_inteval = 'D'  #'Q', #'D', #'M' #'Q' #'Y'
    context.top_n_by_momentum = pd.Series()
    #Choose X stocks out of portfolio of Y stocks- how many stocks to hold - top X by momentum
    context.stocks = 1
    #Lookback for momentum calculation
    context.momentum_days = 60
    #set at less than 1 to ensure no leverage
    context.leverage_buffer = 0.99
    #Set to 0 to reject any stocks with negative momentum, set to -1 to accept stocks with negative momentum
    context.trend = 0.0
    context.reorder_dict = {}
コード例 #2
0
    def initialize(context):

        ws.send(msg_placeholder % "Simulation Start")

        context.lookback = 252  # Period to calculate slope and drawdown
        context.max_leverage = 1.0  # Leverage
        context.profit_take = 1.96  # 95% of bollinger band
        context.minimum_return = 0.1  # Enter if and only if annualized slope exceeds this level
        context.max_drawdown = 0.10  # Avoid if too much drawdown
        context.market_impact = 0.2  # Max order is 10% of market trading volume

        context.weights = {}  # Slope at time of entry
        context.drawdown = {}  # Drawdown at time of entry
        context.shares = {}  # Daily target share

        schedule_function(func=stop_loss,
                          date_rule=date_rules.every_day(),
                          time_rule=time_rules.market_open(minutes=30))

        ws.send(
            msg_placeholder %
            "Execution of stop loss scheduled at 30 minutes after market open")

        schedule_function(func=regression,
                          date_rule=date_rules.every_day(),
                          time_rule=time_rules.market_open(minutes=50))

        ws.send(
            msg_placeholder %
            "Execution of regression computation scheduled at 50 minutes after market open"
        )

        schedule_function(func=trade,
                          date_rule=date_rules.every_day(),
                          time_rule=time_rules.market_open(minutes=100))

        ws.send(
            msg_placeholder %
            "Execution of transaction planner scheduled at 100 minutes after market open"
        )

        for thirty_minute_interval in range(30, 391, 30):
            schedule_function(
                execute_transactions, date_rules.every_day(),
                time_rules.market_open(minutes=thirty_minute_interval
                                       ))  # execute every 30 minutes

        ws.send(msg_placeholder %
                "Execution of transactions scheduled at every 30 minutes")

        attach_pipeline(create_high_dollar_volume_pipeline(),
                        'top_dollar_volume')

        ws.send(msg_placeholder %
                "High Dollar Volume pipeline filter attached")
コード例 #3
0
def initialize(context):
    c = context

    # Some Risk-On universes
    core_etf = symbols('QQQ', 'XLP', 'TLT', 'IEF')
    tact_etf = symbols('XLV', 'XLY', 'TLT', 'GLD')

    VAAG12 = symbols('SPY', 'IWM', 'QQQ', 'VGK', 'EWJ', 'VWO', 'VNQ', 'GSG',
                     'GLD', 'TLT', 'LQD', 'HYG')
    VAAG4 = symbols('SPY', 'VEA', 'VWO', 'BND')

    c.RISK = VAAG4  # Which Riskasset universe to use?

    alletf = symbols('QQQ', 'XLP', 'TLT', 'IEF', 'SPY', 'IWM', 'QQQ', 'VGK',
                     'EWJ', 'VWO', 'VNQ', 'GSG', 'GLD', 'TLT', 'LQD', 'HYG',
                     'XLV', 'XLY', 'GLD', 'VEA')  # 'TLO' repleced by 'TLT'
    # Some Risk Off (Cash) universes
    c.CASH = symbols('SHY', 'IEF', 'LQD')

    schedule_function(define_weights, date_rules.month_end(Month_Offset),
                      time_rules.market_open(minutes=64))
    log.info('define_weights for last trading day of the month')

    schedule_function(trade_sell, date_rules.month_end(Month_Offset),
                      time_rules.market_open(minutes=65))
    log.info('trade_sell for last trading day of the month')

    if TplusX > 0:
        schedule_function(
            trade_buy, date_rules.month_start(max(0,
                                                  TplusX - 1 - Month_Offset)),
            time_rules.market_open(minutes=66))
        log.info('trade_buy for month day ' +
                 str(max(0, TplusX - Month_Offset)))
    else:
        schedule_function(trade_buy, date_rules.month_end(Month_Offset),
                          time_rules.market_open(minutes=66))
        log.info('trade_buy last trading day of the month')

    stocks = core_etf + tact_etf
    context.sell = {}
    context.buy = {}

    for stock in stocks:
        context.sell[stock] = 0
        context.buy[stock] = 0

    context.difference_perc = 0.02

    context.stops = {}
    context.stoploss = 0.30
    context.stoppedout = []
コード例 #4
0
ファイル: helpers.py プロジェクト: CoderCoderCoder/QuantAI
def get_date_rules(freq):

    if freq == "day":

        start_rule = date_rules.every_day()
        end_rule = date_rules.every_day()

    elif freq == "week":

        start_rule = date_rules.week_start()
        end_rule = date_rules.week_end()

    elif freq == "month":

        start_rule = date_rules.month_start()
        end_rule = date_rules.month_end()

    else:

        start_rule = date_rules.every_day()
        end_rule = date_rules.every_day()

    date_rule = {"start": start_rule, "end": end_rule}
    time_rule = {
        "start": time_rules.market_open(),
        "end": time_rules.market_close()
    }

    return date_rule, time_rule
コード例 #5
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()
コード例 #6
0
def initialize(context):

    set_benchmark(symbol("SPY"))

    set_cancel_policy(EODCancel())
    # set_max_order_count(1)

    # set_max_leverage(1.0)

    context.longSpread = False
    context.shortSpread = False

    context.longStock = symbol('SH')
    context.shortStock = symbol('SPY')
    #
    # schedule_function(fnTripleMovingAverageCrossover,
    #                   date_rules.every_day(),
    #                   time_rules.market_open(minutes = 20))

    schedule_function(
        handle_data,
        date_rules.every_day(),
        # time_rules.market_close(minutes = 45))
        time_rules.market_open(minutes=45))

    # schedule_function(fnLiquidatePositions,
    #                   date_rules.every_day())
    #                   time_rules.market_open(minutes = 1))

    schedule_function(recordVars, date_rules.every_day())
コード例 #7
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())
コード例 #8
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())
コード例 #9
0
ファイル: ADX策略.py プロジェクト: zhaofeng555/QuantStudy
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())
コード例 #10
0
ファイル: ADOSC策略.py プロジェクト: zhaofeng555/QuantStudy
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())
コード例 #11
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())
コード例 #12
0
def initialize(context):
    print("init")
    context.asset = symbol('IBM')
    context.bar_count = 60
    context.short_window = 5
    context.long_window = 20
    context.ama_window = 10
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())
コード例 #13
0
 def initialize_testing_algo(self, context):
     set_commission(PerShare())
     set_slippage(VolumeShareSlippage())
     if self.syms is None:
         self.syms = self.__validate_symbols__(self.ticker_syms)
     self.portfolio_memory = PortfolioMemory(len(self.syms),
                                             self.config.n_history)
     schedule_function(self.testing_rebalance,
                       date_rule=date_rules.month_start(),
                       time_rule=time_rules.market_open(minutes=1))
コード例 #14
0
def initialize(context):
    print("init")
    context.asset = symbol('IBM')

    context.T = 10

    # 自定义的初始化函数
    init_local_context(context)

    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())
コード例 #15
0
def initialize(context):
    print("init")
    context.asset = symbol('IBM')
    context.bar_count = 60
    context.period = 26
    # 设定AR的超卖线,低于它则买入
    context.over_sell = 80
    # 设定AR的超买线,高于它则卖出
    context.over_buy = 150
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())
コード例 #16
0
    def initialize(self, context):
        # Schedule our rebalance function to run every day, after a 1 hour, when the market opens.
        schedule_function(self.rebalance, date_rules.every_day(),
                          time_rules.market_open(hours=1, minutes=0))

        # max_minute = 6 * 60 + 30
        #
        # for minute in range(30, max_minute, 60):
        #     schedule_function(self.rebalance, date_rules.every_day(), time_rules.market_open(minutes=minute))

        my_pipe = self.make_pipeline()
        attach_pipeline(my_pipe, "my_pipeline")
コード例 #17
0
def initialize(context):
    print("init")
    context.asset = symbol('JD')
    context.bar_count = 20
    context.atr_period = 5
    context.pre_period = 1
    # 多头ATR的倍数
    context.long_multi = 1.5
    # 空头ATR的倍数
    context.short_multi = 2.0
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())
コード例 #18
0
def initialize(context):
    print('初始化策略')
    context.asset = symbol('IBM')
    # 止损线
    context.portfolio_stop_loss = 0.95
    # 止盈线
    context.portfolio_stop_win = 1.05
    # 是否已经触发止损
    context.stop_loss_triggered = False
    # 是否已经触发止盈
    context.stop_win_triggered = False

    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())
コード例 #19
0
def initialize(context):
    print("init")
    context.asset = symbol('AAPL')
    context.ema_fast_window = 5
    context.ema_slow_window = 20
    context.stop_loss_line = 5
    context.stop_win_line = 5
    # 记录净值的最大值,用于计算持仓的止损回撤
    context.max_up_to_now = None
    # 记录净值的最大值,用于计算持仓的止盈回撤
    context.min_up_to_now = None

    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())
コード例 #20
0
    def initialize(context):
        ws.send(msg_placeholder % "Simulation Start")
        context.security = symbol(ticker)
        context.model = RandomForestRegressor()
        context.trained = False

        context.lookback = 3
        context.history_range = 400

        schedule_function(create_model, date_rules.week_end(), time_rules.market_close(minutes=10))

        schedule_function(trade, date_rules.every_day(), time_rules.market_open(minutes=minutes))

        ws.send(msg_placeholder % "Execution of Training and Trading functions scheduled")
コード例 #21
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    context.assets = [
        (symbol('IEF'), 0.40),  # bond etf
        (symbol('QQQ'), 0.60)
    ]  # Nasdaq etf

    context.first_rebalance = 0

    set_commission(commission.PerShare(cost=0.005, min_trade_cost=1))
    # Rebalance every month, at market open.
    schedule_function(my_rebalance, date_rules.month_end(days_offset=0),
                      time_rules.market_open(minutes=1))
コード例 #22
0
def initialize(context):
    """
    Called once at the start of the algorithm.
    """
    # Rebalance every day, 1 hour after market open.
    schedule_function(rebalance, date_rules.month_end(),
                      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.
    print('ATTACH PIPELINE')
    attach_pipeline(make_pipeline(), 'pipeline')
    print('PIPELINE ATTACHED')
コード例 #23
0
def initialize(context):
    print("init")
    context.asset = symbol('IBM')

    # 历史窗口大小
    context.window_size = 10
    # 用户自定义的变量,可以被handle_data使用,触发空头的range.当K1<K2时,多头相对容易被触发,当K1>K2时,空头相对容易被触发
    context.K1 = 0.5
    context.K2 = 0.3
    # 止损线
    context.portfolio_stop_loss = 0.95
    # 止盈线
    context.portfolio_stop_win = 1.05
    # 是否已经触发止损
    context.stop_loss_triggered = False
    # 是否已经触发止盈
    context.stop_win_triggered = False

    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())
コード例 #24
0
def initialize(context):
    print("init")
    context.asset = symbol('IBM')
    # 快线回看周期为9
    context.fastk_period = 9
    # 慢线回看周期为3
    context.slowk_period = 3
    context.slowd_period = 3
    # 使用简单平均
    context.slowk_matype = 0
    # 历史窗口
    context.kdj_window = 100
    # 超买信号线
    context.over_buy_signal = 80
    # 超卖信号线
    context.over_sell_signal = 20

    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())
コード例 #25
0
def initialize(context):
    print("init")
    context.asset = symbol('IBM')

    # 止损线
    context.portfolio_stop_loss = 0.9
    # 止盈线
    context.portfolio_stop_win = 1.1
    # 是否已经触发止损
    context.stop_loss_triggered = False
    # 是否已经触发止盈
    context.stop_win_triggered = False
    # 买入线
    context.lower_rsi = 30
    # 卖出线
    context.upper_rsi = 80
    # 历史长度
    context.rsi_window = 21

    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())
コード例 #26
0
    def initialize(context):

        ws.send(msg_placeholder % "Simulation Start")

        context.security = symbol(ticker)
        context.long_threshold = 0
        context.short_threshold = -0.06

        context.no_shorts = no_shorts

        if context.no_shorts:
            set_long_only()

        context.n_clusters = 9
        context.ret_windows = [30]
        context.window_lengths = [30, 90, 150, 210, 240]
        context.lookback = 8 * 250
        context.refresh_frequency = 30

        context.use_classifier = use_clf

        if context.use_classifier:
            context.ret_buckets = {
                "gen": [-0.04, 0, 0.04]
            }

        context.long_prob_lb = 0.5
        context.short_prob_ub = 0.3

        context.model = {}
        context.return_projections = {}
        context.price_projections = {}
        context.bucket_probs = {}

        context.days_traded = 0
        context.last_traded_date = 0

        schedule_function(rebalance, date_rule=date_rules.every_day(), time_rule=time_rules.market_open(hours=1))

        ws.send(msg_placeholder % "Execution of clustering scheduled at 1 hour after market open")
コード例 #27
0
def initialize(context):
    print("init")
    context.asset = symbol('IBM')
    # 底仓价格
    context.base_price = None
    # 计算移动均值所需的历史bar数目,用户自定义的变量,可以被handle_data使用
    context.sma_window_size = 24
    # 确定当前price可否作为base_price的依据就是当前price是否小于20日均线*price_to_sma_threshold
    context.price_to_sma_threshold = 1
    # 止损线,用户自定义的变量,可以被handle_data使用
    context.portfolio_stop_loss = 0.90
    # 用户自定义变量,记录下是否已经触发止损
    context.stop_loss_triggered = False
    # 止盈线,用户自定义的变量,可以被handle_data使用
    context.portfolio_stop_win = 1.10
    # 用户自定义变量,记录下是否已经触发止盈
    context.stop_win_triggered = False
    # 设置网格的4个档位的买入价格(相对于基础价的百分比)
    context.buy4, context.buy3, context.buy2, context.buy1 = 0.88, 0.91, 0.94, 0.97
    # 设置网格的4个档位的卖出价格(相对于基础价的百分比)
    context.sell4, context.sell3, context.sell2, context.sell1 = 1.8, 1.6, 1.4, 1.2

    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())
コード例 #28
0
def initialize(context):

    context.asset = symbol('IBM')
    SVM_train(context)

    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())
コード例 #29
0
def initialize(context):
    print("init")
    context.asset = symbol('IBM')
    context.tema_window = 60
    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())
コード例 #30
0
ファイル: test_api.py プロジェクト: zhaofeng555/QuantStudy
def initialize(context):
    context.asset = symbol('IBM')
    set_commission(commission.PerShare(cost=0.0001, min_trade_cost=0))

    schedule_function(rebalance, date_rules.every_day(),
                      time_rules.market_open())