Exemplo n.º 1
0
    def handle_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:
                            self.trade.order_shares(stock_code=stock,
                                                    shares=100,
                                                    price_type='fix',
                                                    order_price=close_price,
                                                    account_id=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(
                        ):
                            self.trade.order_shares(stock_code=stock,
                                                    shares=-100,
                                                    price_type='fix',
                                                    order_price=close_price,
                                                    account_id=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_id=self.account[0])
                    Environment.logger.info('sell not in index_member_list',
                                            stock, -1, 'fix', close_price,
                                            self.account)
        self.now = time.time()
            with switch_collection(Kline,
                                   security_code) as KlineDaily_security_code:
                doc_list = []
                for index, row in kline_daily_data.iterrows():
                    date_int = int(row['date'])
                    if not np.isnan(date_int):
                        date_int = str(date_int)
                        time_tag = datetime.strptime(date_int, "%Y%m%d")
                        doc = KlineDaily_security_code(
                            time_tag=time_tag,
                            pre_close=None,
                            open=int(row['open']),
                            high=int(row['high']),
                            low=int(row['low']),
                            close=int(row['close']),
                            volume=int(row['volume']),
                            amount=int(row['amount']),
                            match_items=None,
                            interest=None)
                        doc_list.append(doc)

                KlineDaily_security_code.objects.insert(doc_list)


if __name__ == '__main__':
    with Timer(True):
        save_index_kline_object = SaveIndexKlineDaily(
            '../../../../data/KLine_daily/KLine_index_daily/')
        save_index_kline_object.insert_security_code_list()
Exemplo n.º 3
0
                            ):
                        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)


if __name__ == "__main__":
    # 测试运行完整个策略所需时间
    from AmazingQuant.utils.performance_test import Timer

    time_test = Timer(True)
    with time_test:
        # 运行策略,设置是否保存委托,成交,资金,持仓
        MaStrategy().run(save_trade_record=True)
Exemplo n.º 4
0
    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()