def sample_815(): """ 8.1.5 自定义仓位管理策略的实现 :return: """ metrics = sample_814(False) print('\nmetrics.gains_mean:{}, -metrics.losses_mean:{}'.format(metrics.gains_mean, -metrics.losses_mean)) from abupy import AbuKellyPosition # 42d使用AbuKellyPosition,60d仍然使用默认仓位管理类 buy_factors2 = [{'xd': 60, 'class': AbuFactorBuyBreak}, {'xd': 42, 'position': AbuKellyPosition, 'win_rate': metrics.win_rate, 'gains_mean': metrics.gains_mean, 'losses_mean': -metrics.losses_mean, 'class': AbuFactorBuyBreak}] sell_factor1 = {'xd': 120, 'class': AbuFactorSellBreak} sell_factor2 = {'stop_loss_n': 0.5, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop} sell_factor3 = {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.0} sell_factor4 = {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5} sell_factors = [sell_factor1, sell_factor2, sell_factor3, sell_factor4] benchmark = AbuBenchmark() choice_symbols = ['usTSLA', 'usNOAH', 'usSFUN', 'usBIDU', 'usAAPL', 'usGOOG', 'usWUBA', 'usVIPS'] capital = AbuCapital(1000000, benchmark) orders_pd, action_pd, all_fit_symbols_cnt = ABuPickTimeExecute.do_symbols_with_same_factors(choice_symbols, benchmark, buy_factors2, sell_factors, capital, show=False) print(orders_pd[:10].filter(['symbol', 'buy_cnt', 'buy_factor', 'buy_pos']))
def sample_816(): """ 8.1.6 多支股票使用不同的因子进行择时 :return: """ # 选定noah和sfun target_symbols = ['usSFUN', 'usNOAH'] # 针对sfun只使用42d向上突破作为买入因子 buy_factors_sfun = [{'xd': 42, 'class': AbuFactorBuyBreak}] # 针对sfun只使用60d向下突破作为卖出因子 sell_factors_sfun = [{'xd': 60, 'class': AbuFactorSellBreak}] # 针对noah只使用21d向上突破作为买入因子 buy_factors_noah = [{'xd': 21, 'class': AbuFactorBuyBreak}] # 针对noah只使用42d向下突破作为卖出因子 sell_factors_noah = [{'xd': 42, 'class': AbuFactorSellBreak}] factor_dict = dict() # 构建SFUN独立的buy_factors,sell_factors的dict factor_dict['usSFUN'] = {'buy_factors': buy_factors_sfun, 'sell_factors': sell_factors_sfun} # 构建NOAH独立的buy_factors,sell_factors的dict factor_dict['usNOAH'] = {'buy_factors': buy_factors_noah, 'sell_factors': sell_factors_noah} # 初始化资金 benchmark = AbuBenchmark() capital = AbuCapital(1000000, benchmark) # 使用do_symbols_with_diff_factors执行 orders_pd, action_pd, all_fit_symbols = ABuPickTimeExecute.do_symbols_with_diff_factors( target_symbols, benchmark, factor_dict, capital) print('pd.crosstab(orders_pd.buy_factor, orders_pd.symbol):\n', pd.crosstab(orders_pd.buy_factor, orders_pd.symbol))
def sample_814(show=True): """ 8.1.4 对多支股票进行择时 :return: """ sell_factor1 = {'xd': 120, 'class': AbuFactorSellBreak} sell_factor2 = {'stop_loss_n': 0.5, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop} sell_factor3 = {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.0} sell_factor4 = {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5} sell_factors = [sell_factor1, sell_factor2, sell_factor3, sell_factor4] benchmark = AbuBenchmark() buy_factors = [{'xd': 60, 'class': AbuFactorBuyBreak}, {'xd': 42, 'class': AbuFactorBuyBreak}] choice_symbols = ['usTSLA', 'usNOAH', 'usSFUN', 'usBIDU', 'usAAPL', 'usGOOG', 'usWUBA', 'usVIPS'] capital = AbuCapital(1000000, benchmark) orders_pd, action_pd, all_fit_symbols_cnt = ABuPickTimeExecute.do_symbols_with_same_factors(choice_symbols, benchmark, buy_factors, sell_factors, capital, show=False) metrics = AbuMetricsBase(orders_pd, action_pd, capital, benchmark) metrics.fit_metrics() if show: print('orders_pd[:10]:\n', orders_pd[:10].filter( ['symbol', 'buy_price', 'buy_cnt', 'buy_factor', 'buy_pos', 'sell_date', 'sell_type_extra', 'sell_type', 'profit'])) print('action_pd[:10]:\n', action_pd[:10]) metrics.plot_returns_cmp(only_show_returns=True) return metrics
def sample_812(): """ 8.1.2 卖出因子的实现 :return: """ # 120天向下突破为卖出信号 sell_factor1 = {'xd': 120, 'class': AbuFactorSellBreak} # 趋势跟踪策略止盈要大于止损设置值,这里0.5,3.0 sell_factor2 = { 'stop_loss_n': 0.5, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop } # 暴跌止损卖出因子形成dict sell_factor3 = {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.0} # 保护止盈卖出因子组成dict sell_factor4 = {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5} # 四个卖出因子同时生效,组成sell_factors sell_factors = [sell_factor1, sell_factor2, sell_factor3, sell_factor4] # buy_factors 60日向上突破,42日向上突破两个因子 buy_factors = [{ 'xd': 60, 'class': AbuFactorBuyBreak }, { 'xd': 42, 'class': AbuFactorBuyBreak }] benchmark = AbuBenchmark() capital = AbuCapital(1000000, benchmark) orders_pd, action_pd, _ = ABuPickTimeExecute.do_symbols_with_same_factors( ['usTSLA'], benchmark, buy_factors, sell_factors, capital, show=True)
def sample_813(): """ 8.1.3 滑点买入卖出价格确定及策略实现 :return: """ from abupy import AbuSlippageBuyBase # 修改g_open_down_rate的值为0.02 g_open_down_rate = 0.02 # noinspection PyClassHasNoInit class AbuSlippageBuyMean2(AbuSlippageBuyBase): def fit_price(self): if (self.kl_pd_buy.open / self.kl_pd_buy.pre_close) < (1 - g_open_down_rate): # 开盘下跌K_OPEN_DOWN_RATE以上,单子失效 print(self.factor_name + 'open down threshold') return np.inf # 买入价格为当天均价 self.buy_price = np.mean( [self.kl_pd_buy['high'], self.kl_pd_buy['low']]) return self.buy_price # 只针对60使用AbuSlippageBuyMean2 buy_factors2 = [{ 'slippage': AbuSlippageBuyMean2, 'xd': 60, 'class': AbuFactorBuyBreak }, { 'xd': 42, 'class': AbuFactorBuyBreak }] sell_factor1 = {'xd': 120, 'class': AbuFactorSellBreak} sell_factor2 = { 'stop_loss_n': 0.5, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop } sell_factor3 = {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.0} sell_factor4 = {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5} sell_factors = [sell_factor1, sell_factor2, sell_factor3, sell_factor4] benchmark = AbuBenchmark() capital = AbuCapital(1000000, benchmark) orders_pd, action_pd, _ = ABuPickTimeExecute.do_symbols_with_same_factors( ['usTSLA'], benchmark, buy_factors2, sell_factors, capital, show=True)
def sample_812(): """ 8.1.2 卖出因子的实现 :return: """ # 120天向下突破为卖出信号 sell_factor1 = {'xd': 120, 'class': AbuFactorSellBreak} # 趋势跟踪策略止盈要大于止损设置值,这里0.5,3.0 sell_factor2 = {'stop_loss_n': 0.5, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop} # 暴跌止损卖出因子形成dict sell_factor3 = {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.0} # 保护止盈卖出因子组成dict sell_factor4 = {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5} # 四个卖出因子同时生效,组成sell_factors sell_factors = [sell_factor1, sell_factor2, sell_factor3, sell_factor4] # buy_factors 60日向上突破,42日向上突破两个因子 buy_factors = [{'xd': 60, 'class': AbuFactorBuyBreak}, {'xd': 42, 'class': AbuFactorBuyBreak}] benchmark = AbuBenchmark() capital = AbuCapital(1000000, benchmark) orders_pd, action_pd, _ = ABuPickTimeExecute.do_symbols_with_same_factors( ['usTSLA'], benchmark, buy_factors, sell_factors, capital, show=True)
def sample_813(): """ 8.1.3 滑点买入卖出价格确定及策略实现 :return: """ from abupy import AbuSlippageBuyBase # 修改g_open_down_rate的值为0.02 g_open_down_rate = 0.02 # noinspection PyClassHasNoInit class AbuSlippageBuyMean2(AbuSlippageBuyBase): def fit_price(self): if (self.kl_pd_buy.open / self.kl_pd_buy.pre_close) < ( 1 - g_open_down_rate): # 开盘下跌K_OPEN_DOWN_RATE以上,单子失效 print(self.factor_name + 'open down threshold') return np.inf # 买入价格为当天均价 self.buy_price = np.mean( [self.kl_pd_buy['high'], self.kl_pd_buy['low']]) return self.buy_price # 只针对60使用AbuSlippageBuyMean2 buy_factors2 = [{'slippage': AbuSlippageBuyMean2, 'xd': 60, 'class': AbuFactorBuyBreak}, {'xd': 42, 'class': AbuFactorBuyBreak}] sell_factor1 = {'xd': 120, 'class': AbuFactorSellBreak} sell_factor2 = {'stop_loss_n': 0.5, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop} sell_factor3 = {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.0} sell_factor4 = {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5} sell_factors = [sell_factor1, sell_factor2, sell_factor3, sell_factor4] benchmark = AbuBenchmark() capital = AbuCapital(1000000, benchmark) orders_pd, action_pd, _ = ABuPickTimeExecute.do_symbols_with_same_factors( ['usTSLA'], benchmark, buy_factors2, sell_factors, capital, show=True)
abu_worker.fit(); # visualize orders from abupy import ABuTradeProxy; orders_pd, action_pd, _ = ABuTradeProxy.trade_summary(abu_worker.orders, kl_pd, draw = True, show_info = False); # visualize capitalism from abupy import ABuTradeExecute; ABuTradeExecute.apply_action_to_capital(capital, action_pd, kl_pd_manager); capital.capital_pd.capital_blance.plot(); ''' # 2) simple way from abupy import ABuPickTimeExecute orders_pd, action_pd, _ = ABuPickTimeExecute.do_symbols_with_same_factors( [ 'usTSLA', 'usNOAH', 'usSFUN', 'usBIDU', 'usAAPL', 'usGOOG', 'usWUBA', 'usVIPS' ], benchmark, buy_factors, sell_factors, capital, show=False) print(orders_pd[:10]) # 3) metric the profit from abupy import AbuMetricsBase metrics = AbuMetricsBase(orders_pd, action_pd, capital, benchmark) metrics.fit_metrics() metrics.plot_returns_cmp(only_show_returns=True) # 4) evaluate win_rate(为了计算胜率) win_rate = metrics.win_rate gains_mean = metrics.gains_mean losses_mean = -metrics.losses_mean # 5) add position control
orders_pd, action_pd, _ = ABuTradeProxy.trade_summary(abu_worker.orders, kl_pd, draw=False) # 上面是从股价角度,下面从我们的资金来看 # ABuTradeExecute.apply_action_to_capital(capital, action_pd, kl_pd_manager) # print(capital.capital_pd.head()) # capital.capital_pd.capital_blance.plot() # plt.show() # 上面只是实现了买入突破,下面我们用卖出突破来试试 # 2、这里是卖出突破 sell_factor1 = {'xd': 120, 'class': AbuFactorSellBreak} sell_factors = [sell_factor1] capital = AbuCapital(1000000, benchmark) orders_pd, action_pd, _ = ABuPickTimeExecute.do_symbols_with_same_factors( ['usTSLA'], benchmark, buy_factors, sell_factors, capital, show=False) ''' 下面会用到ATR这个指标,解释一下这个指标。 1. 设当前交易日的最高价减最低价为x1, 2. 前一个交易日的收盘件减去当前交易日的最高价的绝对值为x2 3. 前一个交易日的收盘件减去当前交易日的最低价的绝对值为x3 4. 那么真实波动TR=max(x1,x2,x3) 5. ATR,就是求N天这个值(TR)的平均,ATR=(∑TR)/n 作用: 1. 用来衡量价格的波动强度,和价格的绝对值没有关系 ''' ''' 2) 上面给出了买入点和卖出点的定义,以及他们在历史数据上的表现 但是现在很多操作会有止盈和止损的操作,我们使用ATR来协助判断止盈和止损 具体的止盈止损策略:
from abupy import AbuFactorAtrNStop from abupy import ABuPickTimeExecute, AbuBenchmark, AbuCapital # 趋势跟踪策略止盈要大于止损设置值,这里0.5,3.0 sell_factor2 = { 'stop_loss_n': 0.5, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop } # 两个卖出因子策略并行同时生效 sell_factors = [sell_factor1, sell_factor2] benchmark = AbuBenchmark() capital = AbuCapital(1000000, benchmark) orders_pd, action_pd, _ = ABuPickTimeExecute.do_symbols_with_same_factors( ['usTSLA'], benchmark, buy_factors, sell_factors, capital, show=True) from abupy import AbuFactorPreAtrNStop # 暴跌止损卖出因子形成dict sell_factor3 = {'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.0} # 三个卖出因子同时生效,组成sell_factors sell_factors = [sell_factor1, sell_factor2, sell_factor3] capital = AbuCapital(1000000, benchmark) orders_pd, action_pd, _ = ABuPickTimeExecute.do_symbols_with_same_factors( ['usTSLA'], benchmark, buy_factors, sell_factors, capital, show=True) from abupy import AbuFactorCloseAtrNStop # 保护止盈卖出因子组成dict sell_factor4 = {'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5}
'stop_loss_n': 0.5, 'stop_win_n': 3.0, 'class': AbuFactorAtrNStop }, { 'class': AbuFactorPreAtrNStop, 'pre_atr_n': 1.0 }, { 'class': AbuFactorCloseAtrNStop, 'close_atr_n': 1.5 }] benchmark = AbuBenchmark() capital = AbuCapital(1000000, benchmark) # 我们假定choice_symbols是我们选股模块的结果, choice_symbols = [ 'usTSLA', 'usNOAH', 'usSFUN', 'usBIDU', 'usAAPL', 'usGOOG', 'usWUBA', 'usVIPS' ] orders_pd, action_pd, all_fit_symbols_cnt = ABuPickTimeExecute.do_symbols_with_same_factors( choice_symbols, benchmark, buy_factors, sell_factors, capital, show=False) metrics = AbuMetricsBase(orders_pd, action_pd, capital, benchmark) metrics.fit_metrics() metrics.plot_returns_cmp(only_show_returns=True) print(all_fit_symbols_cnt)