def handle_bar(self, event):
        Environment.logger.info('self.time_tag', self.time_tag, datetime.now())
        # Environment.logger.debug(len(Environment.bar_position_data_list))
        if self.time_tag not in self.group_hold_index:
            return

        # 取当前bar的持仓情况
        available_position_dict = {}
        for position in Environment.bar_position_data_list:
            if position.account_id == self.account[0]:
                available_position_dict[position.instrument + '.' + position.exchange] = position.position - position.frozen

        # 因子选股的持仓股票
        current_group_hold_list = self.group_hold.loc[self.time_tag].dropna().index.values
        # 当前资金账户的持仓股票
        position_stock_list = list(available_position_dict.keys())
        # 需要买入调仓的股票
        buy_stock_list = np.setdiff1d(current_group_hold_list, position_stock_list)
        # 需要卖出调仓的股票
        sell_stock_list = np.setdiff1d(position_stock_list, current_group_hold_list)
        # 需要调仓的股票,取这些票的收盘价
        buy_sell_stock_list = np.union1d(buy_stock_list, sell_stock_list)
        close_price_all = self.data_class.get_market_data(Environment.daily_data, stock_code=buy_sell_stock_list,
                                                          field=['close'],
                                                          start=self.time_tag, end=self.time_tag)

        Environment.logger.info(len(current_group_hold_list), len(position_stock_list), len(buy_stock_list),
                                len(sell_stock_list))

        print(Environment.bar_account_data_list[0].available)
        # 循环遍历股票池
        for stock in sell_stock_list:
            # 取当前股票的收盘价
            close_price = close_price_all['close'][stock]
            if np.isnan(close_price):
                continue
            Trade(self).order_shares(stock_code=stock, shares=-available_position_dict[stock], price_type='fix',
                                     order_price=close_price, account_id=self.account[0])
            Environment.logger.info(self.time_tag, 'sell', stock, available_position_dict[stock],
                                    'fix', close_price, self.account[0])

        print(Environment.bar_account_data_list[0].available, Environment.bar_account_data_list[0].account_id)
        # print(position_stock_list)
        if position_stock_list:
            self.single_stock_value = (Environment.bar_account_data_list[0].available -
                                       Environment.bar_account_data_list[0].total_balance * (1 - self.hold_ratio)) / \
                                      len(buy_stock_list)
            self.single_stock_value = max(self.single_stock_value, 0)
            print(self.single_stock_value)

        if self.single_stock_value > 0:
            for stock in buy_stock_list:
                # 取当前股票的收盘价
                close_price = close_price_all['close'][stock]
                if np.isnan(close_price):
                    continue
                buy_share = int(self.single_stock_value / close_price / 100) * 100
                Trade(self).order_shares(stock_code=stock, shares=buy_share, price_type='fix', order_price=close_price,
                                         account_id=self.account[0])
                Environment.logger.info(self.time_tag, 'buy', stock, buy_share, 'fix', close_price, self.account[0])
    def on_bar(self, event):
        Environment.logger.info('self.time_tag', self.time_tag, datetime.now(),
                                (time.time() - self.now) * 1000)
        Environment.logger.debug(len(Environment.bar_position_data_list))
        # 取当前bar的持仓情况
        with Timer(True):
            available_position_dict = {}
            for position in Environment.bar_position_data_list:
                available_position_dict[
                    position.instrument + '.' +
                    position.exchange] = position.position - position.frozen
            index_member_list = self.index_member_obj.get_index_member_in_date(
                self.time_tag)

            close_price_all = self.data_class.get_market_data(
                Environment.daily_data,
                stock_code=index_member_list,
                field=['close'],
                start=self.time_tag,
                end=self.time_tag)
            # 循环遍历股票池
            for stock in index_member_list:
                # 取当前股票的收盘价
                close_price = close_price_all['close'][stock]
                if close_price:
                    ma5 = self.ma5[stock][self.time_tag]
                    ma20 = self.ma10[stock][self.time_tag]
                    if ma5 and ma20:
                        # 如果5日均线突破20日均线,并且没有持仓,则买入这只股票100股,以收盘价为指定价交易
                        if ma5 > ma20 and stock not in available_position_dict.keys(
                        ) and stock in index_member_list:
                            Trade(self).order_shares(stock_code=stock,
                                                     shares=100,
                                                     price_type='fix',
                                                     order_price=close_price,
                                                     account=self.account[0])
                            Environment.logger.info('buy', stock, -1, 'fix',
                                                    close_price, self.account)
                        # 如果20日均线突破5日均线,并且有持仓,则卖出这只股票100股,以收盘价为指定价交易
                        elif ma5 < ma20 and stock in available_position_dict.keys(
                        ):
                            Trade(self).order_shares(stock_code=stock,
                                                     shares=-100,
                                                     price_type='fix',
                                                     order_price=close_price,
                                                     account=self.account[0])
                            Environment.logger.info('sell', stock, -1, 'fix',
                                                    close_price, self.account)
            for stock in available_position_dict.keys():
                if stock not in index_member_list:
                    Trade(self).order_shares(stock_code=stock,
                                             shares=-100,
                                             price_type='fix',
                                             order_price=close_price,
                                             account=self.account[0])
                    Environment.logger.info('sell not in index_member_list',
                                            stock, -1, 'fix', close_price,
                                            self.account)
        self.now = time.time()
Exemple #3
0
 def handle_bar(self, event):
     # 取当前bar的持仓情况
     available_position_dict = {}
     for position in Environment.bar_position_data_list:
         available_position_dict[
             position.instrument + "." +
             position.exchange] = position.position - position.frozen
     # 当前bar的具体时间戳
     current_date = data_transfer.millisecond_to_date(
         millisecond=self.timetag, format="%Y-%m-%d")
     # 时间戳转换成int,方便后面取数据
     current_date_int = data_transfer.date_str_to_int(current_date)
     print(current_date)
     # 取数据实例
     data_class = GetData()
     # 循环遍历股票池
     for stock in self.universe:
         # 取当前股票的收盘价
         close_price = data_class.get_market_data(Environment.daily_data,
                                                  stock_code=[stock],
                                                  field=["close"],
                                                  end=current_date)
         # print(self.start, current_date)
         close_array = np.array(close_price)
         if len(close_array) > 0:
             # 利用talib计算MA
             ma5 = talib.MA(np.array(close_price), timeperiod=5)
             ma20 = talib.MA(np.array(close_price), timeperiod=20)
             # print(type(close_price.keys()))
             # 过滤因为停牌没有数据
             if current_date_int in close_price.keys():
                 # 如果5日均线突破20日均线,并且没有持仓,则买入这只股票100股,以收盘价为指定价交易
                 if ma5[-1] > ma20[
                         -1] and stock not in available_position_dict.keys(
                         ):
                     Trade(self).order_shares(
                         stock_code=stock,
                         shares=100,
                         price_type="fix",
                         order_price=close_price[current_date_int],
                         account=self.account[0])
                     print("buy", stock, 1, "fix",
                           close_price[current_date_int], self.account)
                 # 如果20日均线突破5日均线,并且有持仓,则卖出这只股票100股,以收盘价为指定价交易
                 elif ma5[-1] < ma20[
                         -1] and stock in available_position_dict.keys():
                     Trade(self).order_shares(
                         stock_code=stock,
                         shares=-100,
                         price_type="fix",
                         order_price=close_price[current_date_int],
                         account=self.account[0])
                     print("sell", stock, -1, "fix",
                           close_price[current_date_int], self.account)
 def __init__(self, strategy_name='strategy_base'):
     self._strategy_name = strategy_name
     self._run_mode = RunMode.BACKTESTING.value
     self._account = ['test_account']
     self._capital = {'test_account': 1000000}
     self._start = datetime(2017, 1, 1)
     self._end = datetime(2018, 1, 1)
     self._benchmark = '000300.SH'
     self._period = Period.DAILY.value  # 后续支持1min 3min 5min 等多周期
     self._universe = []
     self._rights_adjustment = RightsAdjustment.FROWARD.value
     self._time_tag = 0
     # 数据缓存开关
     self._daily_data_cache = False
     self._one_min_data_cache = False
     # 取数据
     self._get_data = GetKlineData()
     self.bar_index = 0
     # 初始化交易函数
     self.trade = Trade(self)
    def handle_bar(self, event):
        print('self.time_tag', self.time_tag, datetime.now(),
              (time.time() - self.now) * 1000)
        print(len(Environment.bar_position_data_list))
        # 取当前bar的持仓情况
        with Timer(True):
            available_position_dict = {}
            for position in Environment.bar_position_data_list:
                available_position_dict[
                    position.instrument + '.' +
                    position.exchange] = position.position - position.frozen
            index_member_list = self.index_member_obj.get_index_member_in_date(
                self.time_tag)

            close_price_all = self.data_class.get_market_data(
                Environment.daily_data,
                stock_code=index_member_list,
                field=['close'],
                start=self.time_tag,
                end=self.time_tag)
            # 循环遍历股票池
            for stock in index_member_list:
                # 取当前股票的收盘价
                close_price = close_price_all['close'][stock]
                # print(close_price, type(close_price))
                # close_array = np.array(close_price)
                if close_price:
                    # if len(close_array) > 0:
                    # # 利用talib计算MA
                    # try:
                    #     ma5 = talib.MA(close_array[-20:], timeperiod=5)
                    #     ma20 = talib.MA(close_array[-20:], timeperiod=20)
                    # except Exception as e:
                    #     continue

                    # print('ma5', ma5[-1], ma20[-1], ma5[-1] > ma20[-1], len(available_position_dict.keys()))

                    # 过滤因为停牌没有数据
                    # if self.time_tag in close_price.index:
                    #     print("qqqqqq", type(self.ma5), self.ma5)
                    ma5 = self.ma5[stock][self.time_tag]
                    ma20 = self.ma10[stock][self.time_tag]
                    if ma5 and ma20:
                        # 如果5日均线突破20日均线,并且没有持仓,则买入这只股票100股,以收盘价为指定价交易
                        if ma5 > ma20 and stock not in available_position_dict.keys(
                        ) and stock in index_member_list:
                            Trade(self).order_shares(stock_code=stock,
                                                     shares=100,
                                                     price_type='fix',
                                                     order_price=close_price,
                                                     account=self.account[0])
                            print('buy', stock, -1, 'fix', close_price,
                                  self.account)
                        # 如果20日均线突破5日均线,并且有持仓,则卖出这只股票100股,以收盘价为指定价交易
                        elif ma5 < ma20 and stock in available_position_dict.keys(
                        ):
                            Trade(self).order_shares(stock_code=stock,
                                                     shares=-100,
                                                     price_type='fix',
                                                     order_price=close_price,
                                                     account=self.account[0])
                            print('sell', stock, -1, 'fix', close_price,
                                  self.account)
            for stock in available_position_dict.keys():
                if stock not in index_member_list:
                    Trade(self).order_shares(stock_code=stock,
                                             shares=-100,
                                             price_type='fix',
                                             order_price=close_price,
                                             account=self.account[0])
                    print('sell not in index_member_list', stock, -1, 'fix',
                          close_price, self.account)
        self.now = time.time()