コード例 #1
0
 def __init__(self):
     super().__init__()
     # 取指数成分股实例
     self.index_member_obj = GetIndexMember()
     # 取K线数据实例
     self.data_class = GetKlineData()
     # 取指标实例
     self.indicator = SaveGetIndicator()
コード例 #2
0
    def __init__(self):
        super().__init__()
        # 取指数成分股实例
        self.index_member_obj = GetIndexMember()
        # 取K线数据实例
        self.data_class = GetKlineData()
        # 取指标实例
        self.indicator = SaveGetIndicator()

        # 取指标数据
        self.ma5 = self.indicator.get_indicator('ma5')
        self.ma10 = self.indicator.get_indicator('ma10')
        self.now = time.time()
コード例 #3
0
    def __init__(self, strategy_name='ma_strategy'):
        super().__init__()

        self.strategy_name = strategy_name
        # 取指数成分股实例
        self.index_member_obj = GetIndexMember()
        # 取K线数据实例
        self.data_class = GetKlineData()
        # 取指标实例
        self.indicator = SaveGetIndicator()

        # 取指标数据
        self.ma5 = self.indicator.get_indicator('ma5')
        self.ma10 = self.indicator.get_indicator('ma10')
        self.now = time.time()
        Environment.logger = Logger(strategy_name)
コード例 #4
0
class MaStrategy(StrategyBase):
    def __init__(self, strategy_name='ma_strategy'):
        """
        用户定义类变量
        取本地数据
        :param strategy_name:
        """
        super().__init__(strategy_name=strategy_name)

        # 取指数成分股实例
        self.index_member_obj = GetIndexMember()
        # 取K线数据实例
        self.data_class = GetKlineData()
        # 取指标实例
        self.indicator = SaveGetIndicator()

        # 取指标数据
        self.ma5 = self.indicator.get_indicator('ma5')
        self.ma10 = self.indicator.get_indicator('ma10')
        self.now = time.time()
        Environment.logger = Logger(strategy_name)

    def initialize(self):
        # 设置运行模式,回测或者交易
        self.run_mode = RunMode.BACKTESTING.value
        # 设置回测资金账号
        self.account = ['test0']
        # 设置回测资金账号资金量
        self.capital = {'test0': 2000000}
        # 设置回测基准
        self.benchmark = '000300.SH'
        # 设置复权方式
        self.rights_adjustment = RightsAdjustment.FROWARD.value
        # 设置回测起止时间
        self.start = datetime(2018, 1, 1)
        self.end = datetime(2019, 1, 1)
        # 设置运行周期
        self.period = 'daily'
        self.index_member_obj.get_all_index_members()
        _, index_members_all = self.index_member_obj.get_index_members(
            '000300.SH')
        self.universe = index_members_all

        # 设置在运行前是否缓存日线,分钟线等各个周期数据
        self.daily_data_cache = True
        Environment.logger.info(self.universe)

        # 回测滑点设置,按固定值0.01,20-0.01 = 19.99;百分比0.01,20*(1-0.01) = 19.98;平仓时用'+'
        self.set_slippage(stock_type=StockType.STOCK.value,
                          slippage_type=SlippageType.SLIPPAGE_FIX.value,
                          value=0.01)

        # 回测股票手续费和印花税,卖出印花税,千分之一;开仓手续费,万分之三;平仓手续费,万分之三,最低手续费,5元
        # 沪市,卖出有万分之二的过户费,加入到卖出手续费
        self.set_commission(stock_type=StockType.STOCK_SH.value,
                            tax=0.001,
                            open_commission=0.0003,
                            close_commission=0.00032,
                            close_today_commission=0,
                            min_commission=5)
        # 深市不加过户费
        self.set_commission(stock_type=StockType.STOCK_SZ.value,
                            tax=0.001,
                            open_commission=0.0003,
                            close_commission=0.0003,
                            close_today_commission=0,
                            min_commission=5)

    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:
                            Trade(self).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(
                        ):
                            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', 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()
コード例 #5
0
 def save_ma(self, num):
     save_get_indicator = SaveGetIndicator()
     ma5 = self.kline['close'].rolling(num).mean()
     save_get_indicator.save_indicator('ma' + str(num), ma5)
     pass
コード例 #6
0
            return fit_result.resid

        self.raw_data = self.raw_data.apply(cal_resid,
                                            args=(
                                                index_class_obj,
                                                share_data,
                                                method,
                                            ),
                                            axis=1)
        return self.raw_data


if __name__ == '__main__':
    indicator_name = 'ma5'
    factor_name = 'factor_' + indicator_name
    indicator_data = SaveGetIndicator().get_indicator(indicator_name)

    factor_pre_obj = FactorPreProcessing(indicator_data)
    # 可根据时间和股票list过滤数据
    data_filter = factor_pre_obj.data_filter()
    # 去极值方法,四种
    extreme_data = factor_pre_obj.extreme_processing(
        dict(std={'sigma_multiple': 3}))
    # extreme_data = factor_pre_obj.extreme_processing(dict(mad={'median_multiple': 1.483}))
    # extreme_data = factor_pre_obj.extreme_processing(dict(quantile={'quantile_min': 0.025, 'quantile_max': 0.975}))
    # extreme_data = factor_pre_obj.extreme_processing(dict(box_plot={'median_multiple': 3}))

    # 中性化方法,可选择行业和流通市值中性
    neutralize_data = factor_pre_obj.neutralize_processing(
        dict(neutralize_method=[
            NeutralizeMethod.INDUSTRY.value,
コード例 #7
0
            fit_result = model.fit()
            # 残差作为中性化后的数据
            return fit_result.resid

        self.raw_data = self.raw_data.apply(cal_resid,
                                            args=(
                                                index_class_obj,
                                                share_data,
                                                method,
                                            ),
                                            axis=1)
        return self.raw_data


if __name__ == '__main__':
    indicator_data = SaveGetIndicator().get_indicator('ma10')

    factor_pre_obj = FactorPreProcessing(indicator_data)
    # 可根据时间和股票list过滤数据
    data_filter = factor_pre_obj.data_filter()
    # 去极值方法,四种
    extreme_data = factor_pre_obj.extreme_processing(
        dict(std={'sigma_multiple': 3}))
    # extreme_data = factor_pre_obj.extreme_processing(dict(mad={'median_multiple': 1.483}))
    # extreme_data = factor_pre_obj.extreme_processing(dict(quantile={'quantile_min': 0.025, 'quantile_max': 0.975}))
    # extreme_data = factor_pre_obj.extreme_processing(dict(box_plot={'median_multiple': 3}))

    # 中性化方法,可选择行业和流通市值中性
    neutralize_data = factor_pre_obj.neutralize_processing(
        dict(neutralize_method=[
            NeutralizeMethod.INDUSTRY.value,
コード例 #8
0
class MaStrategy(StrategyBase):
    def __init__(self):
        super().__init__()
        # 取指数成分股实例
        self.index_member_obj = GetIndexMember()
        # 取K线数据实例
        self.data_class = GetKlineData()
        # 取指标实例
        self.indicator = SaveGetIndicator()

    def initialize(self):
        # 设置运行模式,回测或者交易
        self.run_mode = RunMode.BACKTESTING.value
        # 设置回测资金账号
        self.account = ['test0', 'test1']
        # 设置回测资金账号资金量
        self.capital = {'test0': 2000000, 'test1': 1000}
        # 设置回测基准
        self.benchmark = '000300.SH'
        # 设置复权方式
        self.rights_adjustment = RightsAdjustment.NONE.value
        # 设置回测起止时间
        self.start = datetime(2018, 1, 1)
        self.end = datetime(2019, 1, 1)
        # 设置运行周期
        self.period = 'daily'
        _, index_members_all = self.index_member_obj.get_index_members(
            '000300.SH')
        self.universe = index_members_all

        # 设置在运行前是否缓存日线,分钟线等各个周期数据
        self.daily_data_cache = True
        print(self.universe)

        # 回测滑点设置,按固定值0.01,20-0.01 = 19.99;百分比0.01,20*(1-0.01) = 19.98;平仓时用'+'
        self.set_slippage(stock_type=StockType.STOCK.value,
                          slippage_type=SlippageType.SLIPPAGE_FIX.value,
                          value=0.01)

        # 回测股票手续费和印花税,卖出印花税,千分之一;开仓手续费,万分之三;平仓手续费,万分之三,最低手续费,5元
        # 沪市,卖出有万分之二的过户费,加入到卖出手续费
        self.set_commission(stock_type=StockType.STOCK_SH.value,
                            tax=0.001,
                            open_commission=0.0003,
                            close_commission=0.0003,
                            close_today_commission=0,
                            min_commission=5)
        # 深市不加过户费
        self.set_commission(stock_type=StockType.STOCK_SZ.value,
                            tax=0.001,
                            open_commission=0.0003,
                            close_commission=0.0005,
                            close_today_commission=0,
                            min_commission=5)

        # 取指标数据
        self.ma5 = self.indicator.get_indicator('ma5')
        self.ma10 = self.indicator.get_indicator('ma10')
        self.now = time.time()

    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()