Skip to content

Commit

Permalink
第30节-趋势跟踪与均值回复的长短线搭配
Browse files Browse the repository at this point in the history
plt.show的规范使用
  • Loading branch information
bbfamily committed Oct 11, 2017
1 parent b5ec880 commit 082f145
Show file tree
Hide file tree
Showing 22 changed files with 1,232 additions and 339 deletions.
8 changes: 5 additions & 3 deletions abupy/CoreBu/ABuEnv.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,18 +508,20 @@ def init_logging():

init_logging()


# ******************** 日志 end ****************

g_plt_figsize = (14, 7)


def init_plot_set():
"""全局plot设置"""
import seaborn as sns
sns.set_context('notebook', rc={'figure.figsize': (14, 7)})
sns.set_context('notebook', rc={'figure.figsize': g_plt_figsize})
sns.set_style("darkgrid")

import matplotlib
# conda 5.0后需要添加单独matplotlib的figure设置否则pandas的plot size不生效
matplotlib.rcParams['figure.figsize'] = (14, 7)
matplotlib.rcParams['figure.figsize'] = g_plt_figsize


init_plot_set()
94 changes: 0 additions & 94 deletions abupy/FactorBuyBu/ABuFactorBuyGolden.py

This file was deleted.

118 changes: 118 additions & 0 deletions abupy/FactorBuyBu/ABuFactorBuyTrend.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# -*- encoding:utf-8 -*-
"""
买入择时示例因子:长线趋势跟踪与短线均值回复的配合
"""

from __future__ import absolute_import
from __future__ import print_function
from __future__ import division

from ..TLineBu.ABuTLine import AbuTLine
from ..TLineBu.ABuTLGolden import calc_golden
from .ABuFactorBuyBase import AbuFactorBuyXD, BuyCallMixin

__author__ = '阿布'
__weixin__ = 'abu_quant'


# noinspection PyAttributeOutsideInit
class AbuUpDownTrend(AbuFactorBuyXD, BuyCallMixin):
"""示例长线上涨中寻找短线下跌买入择时因子,混入BuyCallMixin"""

def _init_self(self, **kwargs):
"""
kwargs中可以包含xd: 比如20,30,40天...突破,默认20
kwargs中可以包含past_factor: 代表长线的趋势判断长度,默认4,long = xd * past_factor->eg: long = 20 * 4
kwargs中可以包含up_deg_threshold: 代表判断上涨趋势拟合角度阀值,即长线拟合角度值多少决策为上涨,默认3
"""
if 'xd' not in kwargs:
# 如果外部没有设置xd值,默认给一个30
kwargs['xd'] = 20
super(AbuUpDownTrend, self)._init_self(**kwargs)
# 代表长线的趋势判断长度,默认4,long = xd * past_factor->eg: long = 30 * 4
self.past_factor = kwargs.pop('past_factor', 4)
# 代表判断上涨趋势拟合角度阀值,即长线拟合角度值多少决策为上涨,默认4
self.up_deg_threshold = kwargs.pop('up_deg_threshold', 3)

def fit_day(self, today):
"""
长线周期选择目标为上升趋势的目标,短线寻找近期走势为向下趋势的目标进行买入,期望是持续之前长相的趋势
1. 通过past_today_kl获取长周期的金融时间序列,通过AbuTLine中的is_up_trend判断
长周期是否属于上涨趋势,
2. 今天收盘价为最近xd天内最低价格,且短线xd天的价格走势为下跌趋势
3. 满足1,2发出买入信号
:param today: 当前驱动的交易日金融时间序列数据
"""
long_kl = self.past_today_kl(today, self.past_factor * self.xd)
tl_long = AbuTLine(long_kl.close, 'long')
# 判断长周期是否属于上涨趋势
if tl_long.is_up_trend(up_deg_threshold=self.up_deg_threshold, show=False):
if today.close == self.xd_kl.close.min() and AbuTLine(
self.xd_kl.close, 'short').is_down_trend(down_deg_threshold=-self.up_deg_threshold, show=False):
# 今天收盘价为最近xd天内最低价格,且短线xd天的价格走势为下跌趋势
return self.buy_tomorrow()


# noinspection PyAttributeOutsideInit
class AbuUpDownGolden(AbuUpDownTrend, BuyCallMixin):
"""示例长线上涨中寻找短线下跌买入择时因子使用黄金分割线关键位置作为买入信号,混入BuyCallMixin"""

def fit_day(self, today):
"""
长线周期选择目标为上升趋势的目标,短线寻找近期走势为向下趋势的目标进行买入,期望是持续之前长相的趋势
1. 通过past_today_kl获取长周期的金融时间序列,通过AbuTLine中的is_up_trend判断
长周期是否属于上涨趋势,
2. 昨天收盘价在0.382下,今天收盘价格在0.382上,且短线xd天的价格走势为下跌趋势
3. 满足1,2发出买入信号
:param today: 当前驱动的交易日金融时间序列数据
"""
long_kl = self.past_today_kl(today, self.past_factor * self.xd)
tl_long = AbuTLine(long_kl.close, 'long')
# 判断长周期是否属于上涨趋势
if tl_long.is_up_trend(up_deg_threshold=self.up_deg_threshold, show=False):
# calc_golden计算黄金分割+关键点位值
golden = calc_golden(self.xd_kl, show=False)
if today.pre_close < golden.below382 < today.close and AbuTLine(
self.xd_kl.close, 'short').is_down_trend(down_deg_threshold=-self.up_deg_threshold,
show=False):
# 昨天收盘价在0.382下,今天收盘价格在0.382上,且短线xd天的价格走势为下跌趋势
return self.buy_tomorrow()


# noinspection PyAttributeOutsideInit
class AbuDownUpTrend(AbuFactorBuyXD, BuyCallMixin):
"""示例长线下跌中寻找短线突破反转买入择时因子,混入BuyCallMixin,即向上突破触发买入event"""

def _init_self(self, **kwargs):
"""
kwargs中可以包含xd: 比如20,30,40天...突破,默认20
kwargs中可以包含past_factor: 代表长线的趋势判断长度,默认4,long = xd * past_factor->eg: long = 20 * 4
kwargs中可以包含down_deg_threshold: 代表判断下跌趋势拟合角度阀值,即长线拟合角度值多少决策为下跌,默认-3
"""
if 'xd' not in kwargs:
# 如果外部没有设置xd值,默认给一个30
kwargs['xd'] = 20

super(AbuDownUpTrend, self)._init_self(**kwargs)
# 代表长线的趋势判断长度,默认4,long = xd * past_factor->eg: long = 20 * 4
self.past_factor = kwargs.pop('past_factor', 4)
# 代表判断下跌趋势拟合角度阀值,即长线拟合角度值多少决策为下跌,默认-3
self.down_deg_threshold = kwargs.pop('down_deg_threshold', -3)

def fit_day(self, today):
"""
长线下跌中寻找短线突破反转买入择时因子
1. 通过past_today_kl获取长周期的金融时间序列,通过AbuTLine中的is_down_trend判断
长周期是否属于下跌趋势,
2. 今天收盘价为最近xd天内最高价格,且短线xd天的价格走势为上升趋势
3. 满足1,2发出买入信号
:param today: 当前驱动的交易日金融时间序列数据
"""
long_kl = self.past_today_kl(today, self.past_factor * self.xd)
tl_long = AbuTLine(long_kl.close, 'long')
# 判断长周期是否属于下跌趋势
if tl_long.is_down_trend(down_deg_threshold=self.down_deg_threshold, show=False):
if today.close == self.xd_kl.close.max() and AbuTLine(
self.xd_kl.close, 'short').is_up_trend(up_deg_threshold=-self.down_deg_threshold, show=False):
# 今天收盘价为最近xd天内最高价格,且短线xd天的价格走势为上升趋势
return self.buy_tomorrow()
6 changes: 5 additions & 1 deletion abupy/FactorBuyBu/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from .ABuFactorBuyDemo import AbuSDBreak, AbuTwoDayBuy, AbuWeekMonthBuy, AbuFactorBuyBreakUmpDemo
from .ABuFactorBuyDemo import AbuFactorBuyBreakReocrdHitDemo, AbuFactorBuyBreakHitPredictDemo
from .ABuFactorBuyDM import AbuDoubleMaBuy
from .ABuFactorBuyTrend import AbuUpDownTrend, AbuDownUpTrend, AbuUpDownGolden

__all__ = [
'AbuFactorBuyBase',
Expand All @@ -22,5 +23,8 @@
'AbuSDBreak',
'AbuTwoDayBuy',
'AbuWeekMonthBuy',
'AbuDoubleMaBuy'
'AbuDoubleMaBuy',
'AbuUpDownTrend',
'AbuDownUpTrend',
'AbuUpDownGolden'
]
3 changes: 0 additions & 3 deletions abupy/MetricsBu/ABuGridSearch.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,9 +169,6 @@ def grid_mul_func(read_cash, benchmark, factors, choice_symbols, kl_pd_manager=N
stock_pickers)
result_tuple_array.append(result_tuple)

# 清理一下输出, 不能wait, windows上一些浏览器会卡死
ABuProgress.do_clear_output(wait=False)

return result_tuple_array


Expand Down
35 changes: 18 additions & 17 deletions abupy/SimilarBu/ABuSimilarDrawing.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
# noinspection PyUnresolvedReferences
from ..CoreBu.ABuFixes import xrange
from ..CoreBu import ABuEnv
from ..UtilBu.ABuDTUtil import plt_show

"""预备颜色序列集,超出序列数量应使用itertools.cycle循环绘制"""
K_PLT_MAP_STYLE = [
Expand All @@ -40,24 +41,24 @@ def draw_show_close(sorted_ret, target_count, show_cnt):
if show_cnt <= 0:
return

# 循环K_PLT_MAP_STYLE颜色集的颜色,绘制各个金融时间序列
for x, cs_color in zip(xrange(0, show_cnt), itertools.cycle(K_PLT_MAP_STYLE)):
# 通过多少个交易日参数target_count,计算出要请求几年的数据n_folds
n_folds = int(math.ceil(target_count / ABuEnv.g_market_trade_year))
# sorted_ret[x] : ('usTSLA', 1.0) -> sorted_ret[x][0]: usTSLA
# FIXME 暂时忽略一个bug如果请求可视化时使用的是start,end,方式那么这里可视化的时间段就不符合了,需要传递完整的信息
df = ABuSymbolPd.make_kl_df(sorted_ret[x][0], n_folds=n_folds)
# 支可视化close_array
close_array = df['close']
if target_count < len(close_array):
# 再次确认时间范围
close_array = close_array[:int(target_count)]
with plt_show():
# 循环K_PLT_MAP_STYLE颜色集的颜色,绘制各个金融时间序列
for x, cs_color in zip(xrange(0, show_cnt), itertools.cycle(K_PLT_MAP_STYLE)):
# 通过多少个交易日参数target_count,计算出要请求几年的数据n_folds
n_folds = int(math.ceil(target_count / ABuEnv.g_market_trade_year))
# sorted_ret[x] : ('usTSLA', 1.0) -> sorted_ret[x][0]: usTSLA
# FIXME 暂时忽略一个bug如果请求可视化时使用的是start,end,方式那么这里可视化的时间段就不符合了,需要传递完整的信息
df = ABuSymbolPd.make_kl_df(sorted_ret[x][0], n_folds=n_folds)
# 支可视化close_array
close_array = df['close']
if target_count < len(close_array):
# 再次确认时间范围
close_array = close_array[:int(target_count)]

cs_np = np.array(close_array, dtype=np.float)
# 使用ABuScalerUtil.scaler_std将序列进行标准化在一个数量值范围内可视化
plt.plot(ABuScalerUtil.scaler_std(cs_np), cs_color, label=sorted_ret[x][0])
plt.legend(loc='best', bbox_to_anchor=(1.05, 1), borderaxespad=0.)
plt.show()
cs_np = np.array(close_array, dtype=np.float)
# 使用ABuScalerUtil.scaler_std将序列进行标准化在一个数量值范围内可视化
plt.plot(ABuScalerUtil.scaler_std(cs_np), cs_color, label=sorted_ret[x][0])
plt.legend(loc='best', bbox_to_anchor=(1.05, 1), borderaxespad=0.)


def draw_show_close_array(sorted_ret, cs_array):
Expand Down
Loading

0 comments on commit 082f145

Please sign in to comment.