Beispiel #1
0
def get_head(context, bar_dict):
    prices = history_bars(bar_dict, context.period + 1, '1d', 'close')
    b_prices = history_bars('000002.XSHE', 6, '1d', 'close')
    volumes = history_bars('000002.XSHE', context.period + 1, '1d', 'volume')
    score = {}
    for stock in prices.columns:
        p = prices[stock]
        v = volumes[stock]
        temp = 0
        for i in list(range(1, context.period)):
            if p[i] > p[i - 1]:
                if v[i] > v[i - 1]:
                    temp = temp + 2
                else:
                    temp = temp + 1
            else:
                if v[i] < v[i - 1]:
                    temp = temp - 1
                else:
                    temp = temp - 2
        score[stock] = temp
    s = pd.Series(score, name='scores')
    s.sort(ascending=False)
    context.to_buy = s.index[0:context.number]
    if b_prices[0] / b_prices[4] <= 0.92:
        context.to_buy = []
Beispiel #2
0
def handle_bar(context, bar_dict):
    '''
    交易函数
    '''
    s1 = history_bars(context.stocks[0], 21, '1d', 'close')
    s2 = history_bars(context.stocks[1], 21, '1d', 'close')
    logger.debug('s1:' + str(s1))
    logger.debug('s2:' + str(s2))
    import pdb
    pdb.set_trace()
    s1delta = (s1[-1] - s1[0]) / s1[0]
    s2delta = (s2[-1] - s2[0]) / s2[0]
    log_str = '元和 ' + str(s1[0]) + '->' + str(s1[-1]) + ' 涨幅: ' + str(
        round(s1delta, 3)) + ' 债券 ' + str(s2[0]) + '->' + str(
            s2[-1]) + ' 涨幅: ' + str(round(s2delta, 3))
    trading = None
    if s1delta is not None and s2delta is not None:
        if s1delta < 0 and s2delta < 0:
            trading = 'cash'
        elif s1delta > s2delta:
            trading = context.stocks[0]
        else:
            trading = context.stocks[1]
    if trading is None or trading == context.hold:
        return
    if context.hold is not None and context.hold != 'cash':
        order_target_percent(context.hold, 0)
        log_str += ' sell ' + context.hold
    if trading != 'cash':
        order_target_percent(trading, 1)
        log_str += ' buy ' + trading
    context.hold = trading
    logger.info(log_str)
def calculate_if_A_stock_premium_rate(context,today):
    exchange_rate_row = context.exchange_rate_df[(context.exchange_rate_df.日期 <= today)].tail(1)
    exchange_rate = exchange_rate_row.loc[:,'收盘价(元)'].values[0]

    # inquiry H stock prices
    H_price = pd.DataFrame([])
    for H_code in context.A_H_stock_df.H_code:
        H_price_row = context.H_stock_price_all[(context.H_stock_price_all.Date <= today) &
                                                (context.H_stock_price_all.H_code == H_code)].tail(1)
        H_price = H_price.append(H_price_row)
    H_price.drop(['Open', 'High', 'Low', 'Volume', 'Adj Close'], inplace=True, axis=1, errors='ignore')
    H_price.rename(columns={'Close': 'H_price_HKD'}, inplace=True)
    H_price['H_price_RMB'] = H_price['H_price_HKD'].map(
        lambda x: x * exchange_rate)

    # inquiry A stock prices
    A_price = pd.DataFrame([])
    for A_code in context.A_H_stock_df.A_code:
        A_price_hist = history_bars(order_book_id=A_code,bar_count=1,frequency='1d',fields='close')
        A_price_row = pd.DataFrame(data={'A_code': A_code, 'A_price': A_price_hist[0]},index=np.arange(1))
        A_price = A_price.append(A_price_row)

    # join the A+H prices
    A_H_price_compare_result = pd.merge(context.A_H_stock_df,H_price,how='left',on=['H_code'])
    A_H_price_compare_result = pd.merge(A_H_price_compare_result,A_price,how='left',on=['A_code'])
    A_H_price_compare_result['A股溢价率'] = 100 * (A_H_price_compare_result['A_price'] -
                                               A_H_price_compare_result['H_price_RMB']) \
                                        / A_H_price_compare_result['H_price_RMB']
    A_H_price_compare_result = A_H_price_compare_result.sort_values(by='A股溢价率',ascending=1)

    context.A_H_price_compare_result = A_H_price_compare_result
    #logger.info(context.A_H_price_compare_result)
    return context
Beispiel #4
0
 def handle_bar(context, bar_dict):
     context.order_count += 1
     if context.order_count == 1:
         update_universe(context.s2)
         his = history_bars(context.s2, 5, '1d', 'close')
         print(sorted(his.tolist()))
         print(sorted([24.1, 23.71, 23.82, 23.93, 23.66]))
         assert sorted(his.tolist()) == sorted([26.06, 26.13, 26.54, 26.6, 26.86])
 def handle_bar(context, bar_dict):
     context.order_count += 1
     if context.order_count == 1:
         update_universe(context.s2)
         his = history_bars(context.s2, 5, '1d', 'close')
         print(sorted(his.tolist()))
         print(sorted([24.1, 23.71, 23.82, 23.93, 23.66]))
         assert sorted(his.tolist()) == sorted([26.06, 26.13, 26.54, 26.6, 26.86])
Beispiel #6
0
 def _history_bars(self, order_book_id, bar_count, freq, dt):
     if self.fetch_data_by_api:
         bars = history_bars(
             order_book_id, bar_count, freq, fields=None)
     else:
         bars = self.rqalpha_env.data_proxy.history_bars(
             order_book_id, bar_count, freq, field=None,
             dt=dt)
     return bars
Beispiel #7
0
def handle_bar(context, bar_dict):
    """
        Description : 选择的证券的数据更新将会触发此段逻辑
        Arg :
        Returns :
        Raises	 :
    """
    # 需要买的股票列表
    _lst_buy_stock = []
    # 遍历所有的股票
    for _stock in context.stocks:
        # 首先取得前面多少日的收盘价
        _data = history_bars(_stock, context.N, '1d', "close")
        # 判断是否是前面几天啦
        if len(_data) < context.N:
            continue
        # 取得最小值和最大值
        _min = _data.min()
        _max = _data.max()
        _close = _data[-1]
        # 先判断是否达到卖出的条件,
        # 条件是,达到止损
        if _close < _max * (100 - context.loss)/100:
            # 然后判断是否有买入
            if _stock in context.portfolio.positions.keys():
                order_target_percent(_stock, 0)
                logger.info("清空股票:{}".format(_stock))
        # 判断是否满足买的条件
        if ((_close > _min * (100 + context.M)/100)
            and _close ==_max):
            logger.info("买入股票{}".format(_stock))
            _lst_buy_stock.append(_stock)

    # 输出有多少个股票买入
    # 因为有时候有很多股票需要买入,这里要判断最值得的。
    # 我只买10个股票。
    # 这里要判断要买那个股票
    _lst_buy_stock_2 = []   # 这个是最终要选择的股票
    if (len(_lst_buy_stock) > 10):
        # 按照ATX来购买。趋势高的就买喽。
        pass
    else:
        _lst_buy_stock_2 = _lst_buy_stock
    # 如果现在持有的股票不在这个最终要选择的股票里边,就卖了吧
    if _stock in context.portfolio.positions.keys():
        if _stock not in _lst_buy_stock_2:
            order_target_percent(_stock, 0)
            logger.info("清空股票:{}".format(_stock))

    # 然后购买最终持有的股票。
    for _stock in _lst_buy_stock_2:
        order_target_percent(_stock, 0.1)
        logger.info("购买股票:{}".format(_stock))
    logger.info("总共买入股票数量:{}".format(len(_lst_buy_stock)))
Beispiel #8
0
def handle_bar(context, bar_dict):
    #    pass
    #
    #def handle_bar_weekly(context, bar_dict):
    '''
    交易函数
    '''
    hist_s1 = history_bars(context.stocks[0], context.window_size + 1, '1d',
                           'close')
    hist_s2 = history_bars(context.stocks[1], context.window_size + 1, '1d',
                           'close')
    curr_s1 = bar_dict[context.stocks[0]].close
    curr_s2 = bar_dict[context.stocks[1]].close
    logger.debug('s1:' + str(hist_s1))
    logger.debug('s2:' + str(hist_s2))
    s1delta = (curr_s1 - hist_s1[0]) / hist_s1[0]
    s2delta = (curr_s2 - hist_s2[0]) / hist_s2[0]
    log_str = '[' + context.now.isoformat() + ']'
    log_str += '沪深300 ' + str(hist_s1[0]) + '->' + str(curr_s1)
    log_str += ' 涨幅: ' + str(round(s1delta, 3))
    log_str += ' 中证500 ' + str(hist_s2[0]) + '->' + str(curr_s2)
    log_str += ' 涨幅: ' + str(round(s2delta, 3))
    trading = None
    if s1delta is not None and s2delta is not None:
        if s1delta < 0 and s2delta < 0:
            trading = 'cash'
        elif s1delta > s2delta:
            trading = context.stocks[0]
        else:
            trading = context.stocks[1]
    if trading is None or trading == context.hold:
        return
    if context.hold != 'cash':
        order_target_percent(context.hold, 0)
        log_str += ' sell ' + context.hold
    if trading != 'cash':
        order_target_percent(trading, 0.99)
        log_str += ' buy ' + trading
    context.hold = trading
    logger.info(log_str)
Beispiel #9
0
 def _history_bars(self, order_book_id, bar_count, freq, dt):
     if self.fetch_data_by_api and ExecutionContext.phase() in (
             EXECUTION_PHASE.BEFORE_TRADING,
             EXECUTION_PHASE.ON_BAR,
             EXECUTION_PHASE.ON_TICK,
             EXECUTION_PHASE.AFTER_TRADING,
             EXECUTION_PHASE.SCHEDULED):
             bars = history_bars(
                 order_book_id, bar_count, freq, fields=None)
     else:
         bars = self.rqalpha_env.data_proxy.history_bars(
             order_book_id, bar_count, freq,
             field=["datetime", "open", "high", "low", "close", "volume"],
             dt=dt)
     return bars
Beispiel #10
0
 def _history_bars(self, order_book_id, bar_count, freq, dt):
     if self.fetch_data_by_api and ExecutionContext.phase() in (
             EXECUTION_PHASE.BEFORE_TRADING,
             EXECUTION_PHASE.ON_BAR,
             EXECUTION_PHASE.ON_TICK,
             EXECUTION_PHASE.AFTER_TRADING,
             EXECUTION_PHASE.SCHEDULED):
             bars = history_bars(
                 order_book_id, bar_count, freq, fields=None)
     else:
         bars = self.rqalpha_env.data_proxy.history_bars(
             order_book_id, bar_count, freq,
             field=["datetime", "open", "high", "low", "close", "volume"],
             dt=dt)
     return bars
Beispiel #11
0
def handle_bar(context, bar_dict):
    """
        Description : 选择的证券的数据更新将会触发此段逻辑
        Arg :
        Returns :
        Raises	 :
    """
    # 需要买的股票列表
    _lst_buy_stock = []
    # 遍历所有的股票
    for _stock in context.stocks:
        # 首先取得前面多少日的收盘价
        _data = history_bars(_stock, context.N + 1, '1d', "close")
        # 判断是否是前面几天啦
        if len(_data) < context.N + 1:
            continue
        # 取得最小值和最大值
        _data_2 = _data[0:context.N]
        _min = _data_2.min()
        _max = _data_2.max()
        _close_1 = _data_2[-1]
        _close_2 = _data[-1]
        # 先判断是否达到卖出的条件,
        # 条件是,达到止损
        if _close_2 < _close_1 * (100 + context.min_up):
            # 然后判断是否有买入
            if _stock in context.portfolio.positions.keys():
                order_target_percent(_stock, 0)
                # logger.info("清空股票:{}".format(_stock))
        # 判断是否是有仓位
        if _stock in context.portfolio.positions.keys():
            # 如果是有降低,就清仓啦
            if _close_2 < _close_1:
                order_target_percent(_stock, 0)
                # logger.info("清空股票:{}".format(_stock))
        # 判断是否满足买的条件
        if ((_close_1 > _min * (100 + context.M) / 100) and _close_1 == _max
                and (_close_2 - _close_1) / _close_1 * 100 > context.min_up):
            # logger.info("买入股票{}".format(_stock))
            # order_target_percent(_stock, 0.1)
            _lst_buy_stock.append(_stock)

    logger.info("{}".format(len(_lst_buy_stock)))
Beispiel #12
0
 def handle_bar(context, bar_dict):
     return_list = history_bars(context.s1, 5, '1d', 'close')
     if str(context.now.date()) == '2016-12-29':
         assert return_list.tolist() == [9.08, 9.1199, 9.08, 9.06, 9.08]
Beispiel #13
0
 def handle_bar(context, bar_dict):
     return_list = history_bars(context.s1, 5, '1d', 'close')
     if str(context.now.date()) == '2016-12-29':
         assert return_list.tolist() == [9.08, 9.12, 9.08, 9.06, 9.08]