コード例 #1
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)
コード例 #2
0
ファイル: mini_cap_v1.py プロジェクト: ccliuyang/quantest
def handle_bar(context, bar_dict):
    #count = context.buyStkCount
    context.today = context.now.date()
    context.today = str(context.today)
    #context.prev_calendar_date = get_prev_trade_date(context,context.today)

    for stk in context.portfolio.positions:
        percentage_today = get_percentage(context, context.today, stk)
        if percentage_today >= 0.099 or percentage_today <= -0.03:
            if stk in context.universe:
                context.universe.remove(stk)
        if stk not in context.universe:
            if (bar_dict[stk].close == bar_dict[stk].open == bar_dict[stk].high == bar_dict[stk].low) and \
                            percentage_today <= - 0.099:
                logger.info('跌停无法卖出:' + stk)
            else:
                order_target_percent(stk, 0)
                logger.info('sell:' + str(stk) + ' percent today: %.2f%%' %
                            (percentage_today * 100))
        # 买入新股
    for stk in context.universe:
        if stk not in context.portfolio.positions:
            percentage_today = get_percentage(context, context.today, stk)
            if (bar_dict[stk].close == bar_dict[stk].open == bar_dict[stk].high == bar_dict[stk].low) and \
                            percentage_today >= 0.099:
                logger.info('涨停无法买入:' + stk)
            else:
                if len(context.portfolio.positions) < context.buyStkCount:
                    percentage_today = get_percentage(context, context.today,
                                                      stk)
                    logger.info('buyin:' + str(stk) +
                                ' percent today: %.2f%%' %
                                (percentage_today * 100))
                    order_shares(stk, 500)
コード例 #3
0
def handle_bar(context, bar_dict):
    # 根据前一交易日的股票池入市买卖
    for order_book_id in context.portfolio.positions:
        if order_book_id not in context.universe:
            order_target_percent(order_book_id, 0)
    for order_book_id in context.universe:
        if order_book_id not in context.portfolio.positions:
            order_target_percent(order_book_id, 1)
コード例 #4
0
ファイル: test_api_stock.py プロジェクト: kknet/rqalpha
 def handle_bar(context, bar_dict):
     order_id = order_target_percent(context.s1, 0.02, style=LimitOrder(context.limitprice))
     print("after: ", context.portfolio.cash)
     order = get_order(order_id)
     order_side = SIDE.BUY if order.quantity > 0 else SIDE.SELL
     assert order.side == order_side
     assert order.order_book_id == context.s1
     assert order.price == context.limitprice
コード例 #5
0
 def handle_bar(context, bar_dict):
     order_id = order_target_percent(context.s1, 0.02, style=LimitOrder(context.limitprice))
     print("after: ", context.portfolio.cash)
     order = get_order(order_id)
     order_side = SIDE.BUY if order.quantity > 0 else SIDE.SELL
     assert order.side == order_side
     assert order.order_book_id == context.s1
     assert order.price == context.limitprice
コード例 #6
0
ファイル: sector_head_v1.py プロジェクト: dxcv/quantest
def position(context, bar_dict):
    stocks = set(context.to_buy)
    holdings = set(get_holdings(context))
    to_buy = stocks - holdings
    holdings = set(get_holdings(context))
    to_sell = holdings - stocks
    for stock in to_sell:
        if bar_dict[stock].is_trading:
            order_target_percent(stock, 0)
    to_buy = get_trading_stocks(to_buy, context, bar_dict)
    cash = context.portfolio.cash
    average_value = 0
    if len(to_buy) > 0:
        average_value = 0.98 * cash / len(to_buy)
    for stock in to_buy:
        if bar_dict[stock].is_trading:
            order_value(stock, average_value)
    context.marketval = context.portfolio.market_value
コード例 #7
0
ファイル: zip_2.py プロジェクト: johndpope/PythonFinance-1
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)))
コード例 #8
0
ファイル: mini_cap_v1.1.py プロジェクト: dxcv/quantest
def handle_bar(context, bar_dict):
    #count = context.buyStkCount
    context.today = context.now.date()
    context.today = str(context.today)
    #context.prev_calendar_date = get_prev_trade_date(context,context.today)

    for stk in context.portfolio.positions:
        percentage_today = get_percentage(context, context.today, stk)
        # 去除涨幅大于100%并且跌幅大于5%的股票
        for stk in context.portfolio.positions:
            position_percent = (
                context.portfolio.positions[stk].market_value -
                context.portfolio.positions[stk].bought_value
            ) / context.portfolio.positions[stk].bought_value
            if position_percent >= 1 or position_percent <= -0.05:
                if stk in context.universe:
                    context.universe.remove(stk)
        if stk not in context.universe:
            if (bar_dict[stk].close == bar_dict[stk].open == bar_dict[stk].high == bar_dict[stk].low) and \
                            percentage_today <= - 0.099:
                logger.info('跌停无法卖出:' + stk)
            else:
                order_target_percent(stk, 0)
                logger.info('sell:' + str(stk) + ' percent today: %.2f%%' %
                            (percentage_today * 100))
        # 买入新股
    for stk in context.universe:
        if stk not in context.portfolio.positions:
            percentage_today = get_percentage(context, context.today, stk)
            if (bar_dict[stk].close == bar_dict[stk].open == bar_dict[stk].high == bar_dict[stk].low) and \
                            percentage_today >= 0.099:
                logger.info('涨停无法买入:' + stk)
            else:
                if len(context.portfolio.positions) < context.buyStkCount:
                    percentage_today = get_percentage(context, context.today,
                                                      stk)
                    logger.info('buyin:' + str(stk) +
                                ' percent today: %.2f%%' %
                                (percentage_today * 100))
                    order_target_percent(stk, 0.2)
    logger.info('portfolio.positions: ' + str(context.portfolio.positions))
コード例 #9
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)
コード例 #10
0
def handle_bar(context, bar_dict):
    #count = context.buyStkCount
    #context.today = context.now.date()
    #context.today = str(context.today)
    #context.prev_calendar_date = get_prev_trade_date(context,context.today)
    #for stk in context.A_H_price_compare_result.A_code:
    #    df = context.A_H_price_compare_result[(context.A_H_price_compare_result.A_code == stk)]
    #    plot(stk, df.iloc[0,7])
    df = context.A_H_price_compare_result[(context.A_H_price_compare_result.A_code == '000002.XSHE')]
    plot('000002.XSHE', df.iloc[0,8])


        # 买入新股
    A_stk = '000002.XSHE'
    H_stk = ''
    if not context.holding_A:
        order_target_percent('000002.XSHE', 1)
        context.holding_A = True
    if bar_dict[A_stk].is_trading:
        if df.iloc[0,8] <= -10:
            order_value('000002.XSHE', 20000)
        if df.iloc[0,8] >= -5 and A_stk in context.portfolio.positions:
            order_value('000002.XSHE', -20000)
コード例 #11
0
ファイル: zip_1.py プロジェクト: johndpope/PythonFinance-1
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)))