analyze.py 27.2 KB
Newer Older
Z
zengbin93 已提交
1
# coding: utf-8
Z
zengbin93 已提交
2 3
import traceback
import pandas as pd
Z
zengbin93 已提交
4
from functools import lru_cache
Z
zengbin93 已提交
5

Z
zengbin93 已提交
6
from .ta import macd, ma, boll
Z
zengbin93 已提交
7
from .utils import plot_kline, plot_ka
Z
zengbin93 已提交
8

Z
zengbin93 已提交
9

10
def is_bei_chi(ka, zs1, zs2, mode="bi", adjust=0.9):
11 12
    """判断 zs1 对 zs2 是否有背驰

13 14
    注意:力度的比较,并没有要求两段走势方向一致;但是如果两段走势之间存在包含关系,这样的力度比较是没有意义的。

15 16
    :param ka: KlineAnalyze
        缠论的分析结果,即去除包含关系后,识别出分型、笔、线段的K线
17 18 19 20 21 22 23 24 25

    :param zs1: dict
        用于比较的走势,通常是最近的走势,示例如下:
        zs1 = {"start_dt": "2020-02-20 11:30:00", "end_dt": "2020-02-20 14:30:00", "direction": "up"}

    :param zs2: dict
        被比较的走势,通常是较前的走势,示例如下:
        zs2 = {"start_dt": "2020-02-21 11:30:00", "end_dt": "2020-02-21 14:30:00", "direction": "down"}

26
    :param mode: str
27
        default `bi`, optional value [`xd`, `bi`]
28 29
        xd  判断两个线段之间是否存在背驰
        bi  判断两笔之间是否存在背驰
30

Z
zengbin93 已提交
31 32 33
    :param adjust: float
        调整 zs2 的力度,建议设置范围在 0.6 ~ 1.0 之间,默认设置为 0.9;
        其作用是确保 zs1 相比于 zs2 的力度足够小。
34 35
    :return:
    """
36 37 38
    assert zs1["start_dt"] > zs2["end_dt"], "zs1 必须是最近的走势,用于比较;zs2 必须是较前的走势,被比较。"
    assert zs1["start_dt"] < zs1["end_dt"], "走势的时间区间定义错误,必须满足 start_dt < end_dt"
    assert zs2["start_dt"] < zs2["end_dt"], "走势的时间区间定义错误,必须满足 start_dt < end_dt"
Z
zengbin93 已提交
39

Z
zengbin93 已提交
40
    df = create_df(ka, ma_params=(5,), use_macd=True, use_boll=False)
41 42
    k1 = df[(df['dt'] >= zs1["start_dt"]) & (df['dt'] <= zs1["end_dt"])]
    k2 = df[(df['dt'] >= zs2["start_dt"]) & (df['dt'] <= zs2["end_dt"])]
43 44 45 46 47

    bc = False
    if mode == 'bi':
        macd_sum1 = sum([abs(x) for x in k1.macd])
        macd_sum2 = sum([abs(x) for x in k2.macd])
Z
zengbin93 已提交
48
        # print("bi: ", macd_sum1, macd_sum2)
Z
zengbin93 已提交
49
        if macd_sum1 < macd_sum2 * adjust:
50 51 52
            bc = True

    elif mode == 'xd':
53 54 55 56
        assert zs1['direction'] in ['down', 'up'], "走势的 direction 定义错误,可取值为 up 或 down"
        assert zs2['direction'] in ['down', 'up'], "走势的 direction 定义错误,可取值为 up 或 down"

        if zs1['direction'] == "down":
57
            macd_sum1 = sum([abs(x) for x in k1.macd if x < 0])
58
        else:
59
            macd_sum1 = sum([abs(x) for x in k1.macd if x > 0])
60 61 62

        if zs2['direction'] == "down":
            macd_sum2 = sum([abs(x) for x in k2.macd if x < 0])
63
        else:
64 65
            macd_sum2 = sum([abs(x) for x in k2.macd if x > 0])

Z
zengbin93 已提交
66
        # print("xd: ", macd_sum1, macd_sum2)
Z
zengbin93 已提交
67
        if macd_sum1 < macd_sum2 * adjust:
68 69 70 71 72 73 74 75
            bc = True

    else:
        raise ValueError("mode value error")

    return bc


Z
zengbin93 已提交
76
def get_ka_feature(ka):
Z
zengbin93 已提交
77 78 79 80
    """获取 KlineAnalyze 的特征

    这只是一个样例,想做多因子的,可以发挥自己的想法,大幅扩展特征数量。
    """
Z
zengbin93 已提交
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
    feature = dict()

    feature["分型标记"] = 1 if ka.fx[-1]['fx_mark'] == 'g' else 0
    feature["笔标记"] = 1 if ka.bi[-1]['fx_mark'] == 'g' else 0
    feature["线段标记"] = 1 if ka.xd[-1]['fx_mark'] == 'g' else 0

    feature['向上笔背驰'] = 1 if ka.bi[-1]['fx_mark'] == 'g' and ka.bi_bei_chi() else 0
    feature['向下笔背驰'] = 1 if ka.bi[-1]['fx_mark'] == 'd' and ka.bi_bei_chi() else 0
    feature['向上线段背驰'] = 1 if ka.xd[-1]['fx_mark'] == 'g' and ka.xd_bei_chi() else 0
    feature['向下线段背驰'] = 1 if ka.xd[-1]['fx_mark'] == 'd' and ka.xd_bei_chi() else 0

    ma_params = (5, 20, 120, 250)
    df = create_df(ka, ma_params)
    last = df.iloc[-1].to_dict()
    for p in ma_params:
        feature['收于MA%i上方' % p] = 1 if last['close'] > last['ma%i' % p] else 0

    feature["MACD金叉"] = 1 if last['diff'] > last['dea'] else 0
    feature["MACD死叉"] = 1 if last['diff'] < last['dea'] else 0

Z
zengbin93 已提交
101
    return {ka.name + k: v for k, v in feature.items()}
Z
zengbin93 已提交
102 103


Z
zengbin93 已提交
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141
def find_zs(points):
    """输入笔或线段标记点,输出中枢识别结果"""
    if len(points) <= 4:
        return []

    # 当输入为笔的标记点时,新增 xd 值
    for i, x in enumerate(points):
        if x.get("bi", 0):
            points[i]['xd'] = x["bi"]

    k_xd = points
    k_zs = []
    zs_xd = []

    for i in range(len(k_xd)):
        if len(zs_xd) < 5:
            zs_xd.append(k_xd[i])
            continue
        xd_p = k_xd[i]
        zs_d = max([x['xd'] for x in zs_xd[:4] if x['fx_mark'] == 'd'])
        zs_g = min([x['xd'] for x in zs_xd[:4] if x['fx_mark'] == 'g'])
        if zs_g <= zs_d:
            zs_xd.append(k_xd[i])
            zs_xd.pop(0)
            continue

        # 定义四个指标,GG=max(gn),G=min(gn),D=max(dn),DD=min(dn),
        # n遍历中枢中所有Zn。特别地,再定义ZG=min(g1、g2),
        # ZD=max(d1、d2),显然,[ZD,ZG]就是缠中说禅走势中枢的区间
        if xd_p['fx_mark'] == "d" and xd_p['xd'] > zs_g:
            # 线段在中枢上方结束,形成三买
            k_zs.append({
                'ZD': zs_d,
                "ZG": zs_g,
                'G': min([x['xd'] for x in zs_xd if x['fx_mark'] == 'g']),
                'GG': max([x['xd'] for x in zs_xd if x['fx_mark'] == 'g']),
                'D': max([x['xd'] for x in zs_xd if x['fx_mark'] == 'd']),
                'DD': min([x['xd'] for x in zs_xd if x['fx_mark'] == 'd']),
Z
zengbin93 已提交
142 143
                "points": zs_xd,
                "third_buy": xd_p
Z
zengbin93 已提交
144
            })
Z
zengbin93 已提交
145
            zs_xd = k_xd[i - 1: i + 1]
Z
zengbin93 已提交
146 147 148 149 150 151 152 153 154
        elif xd_p['fx_mark'] == "g" and xd_p['xd'] < zs_d:
            # 线段在中枢下方结束,形成三卖
            k_zs.append({
                'ZD': zs_d,
                "ZG": zs_g,
                'G': min([x['xd'] for x in zs_xd if x['fx_mark'] == 'g']),
                'GG': max([x['xd'] for x in zs_xd if x['fx_mark'] == 'g']),
                'D': max([x['xd'] for x in zs_xd if x['fx_mark'] == 'd']),
                'DD': min([x['xd'] for x in zs_xd if x['fx_mark'] == 'd']),
Z
zengbin93 已提交
155 156
                "points": zs_xd,
                "third_sell": xd_p
Z
zengbin93 已提交
157
            })
Z
zengbin93 已提交
158
            zs_xd = k_xd[i - 1: i + 1]
Z
zengbin93 已提交
159
        else:
Z
zengbin93 已提交
160
            zs_xd.append(xd_p)
Z
zengbin93 已提交
161 162 163 164 165 166 167 168 169 170 171

    if len(zs_xd) >= 5:
        zs_d = max([x['xd'] for x in zs_xd[:4] if x['fx_mark'] == 'd'])
        zs_g = min([x['xd'] for x in zs_xd[:4] if x['fx_mark'] == 'g'])
        k_zs.append({
            'ZD': zs_d,
            "ZG": zs_g,
            'G': min([x['xd'] for x in zs_xd if x['fx_mark'] == 'g']),
            'GG': max([x['xd'] for x in zs_xd if x['fx_mark'] == 'g']),
            'D': max([x['xd'] for x in zs_xd if x['fx_mark'] == 'd']),
            'DD': min([x['xd'] for x in zs_xd if x['fx_mark'] == 'd']),
Z
zengbin93 已提交
172
            "points": zs_xd,
Z
zengbin93 已提交
173 174 175 176 177
        })

    return k_zs


Z
zengbin93 已提交
178
@lru_cache(maxsize=64)
Z
zengbin93 已提交
179 180
def create_df(ka, ma_params=(5, 20, 120, 250), use_macd=True, use_boll=True):
    df = pd.DataFrame(ka.kline)
Z
zengbin93 已提交
181
    df = ma(df, params=ma_params)
Z
zengbin93 已提交
182 183 184 185
    if use_macd:
        df = macd(df)
    if use_boll:
        df = boll(df)
Z
zengbin93 已提交
186 187 188
    return df


Z
zengbin93 已提交
189
class KlineAnalyze(object):
Z
zengbin93 已提交
190 191
    def __init__(self, kline, name="本级别", bi_mode="new", xd_mode="strict",
                 min_bi_gap=0.001, handle_last=True, debug=False):
Z
zengbin93 已提交
192 193 194 195 196 197 198 199 200 201
        """
        :param kline: list of dict or pd.DataFrame
            example kline:
            kline = [
                {'symbol': '600797.SH', 'dt': '2020-01-08 11:30:00', 'open': 10.72, 'close': 10.67, 'high': 10.76, 'low': 10.63, 'vol': 4464800.0},
                {'symbol': '600797.SH', 'dt': '2020-01-08 13:30:00', 'open': 10.66, 'close': 10.59, 'high': 10.66, 'low': 10.55, 'vol': 5004800.0},
                {'symbol': '600797.SH', 'dt': '2020-01-08 14:00:00', 'open': 10.58, 'close': 10.41, 'high': 10.6, 'low': 10.38, 'vol': 10650500.0},
                {'symbol': '600797.SH', 'dt': '2020-01-08 14:30:00', 'open': 10.42, 'close': 10.41, 'high': 10.48, 'low': 10.35, 'vol': 6610000.0},
                {'symbol': '600797.SH', 'dt': '2020-01-08 15:00:00', 'open': 10.42, 'close': 10.39, 'high': 10.48, 'low': 10.36, 'vol': 7160500.0}
            ]
202 203
        :param name: str
           级别名称,默认为 “本级别”
204
        :param bi_mode: str
Z
0.3.1  
zengbin93 已提交
205
           笔识别控制参数,默认为 new,表示新笔;如果不想用新笔定义识别,设置为 old
206 207 208
        :param xd_mode: str
            线段识别控制参数,默认为 loose,在这种模式下,只要线段标记内有三笔就满足会识别;另外一个可选值是 strict,
            在 strict 模式下,对于三笔形成的线段,要求其后的一笔不跌破或升破线段最后一笔的起始位置。
Z
zengbin93 已提交
209 210
        :param min_bi_gap: float
           笔内部缺口的最小百分比,默认值 0.001
Z
zengbin93 已提交
211
        :param handle_last: bool
Z
zengbin93 已提交
212
            是否使用默认的 handle_last 方法,默认值为 True
Z
zengbin93 已提交
213
        """
214
        self.name = name
215 216 217 218
        assert bi_mode in ['new', 'old'], "bi_mode 参数错误"
        assert xd_mode in ['loose', 'strict'], "bi_mode 参数错误"
        self.bi_mode = bi_mode
        self.xd_mode = xd_mode
Z
zengbin93 已提交
219
        self.handle_last = handle_last
Z
zengbin93 已提交
220
        self.min_bi_gap = min_bi_gap
Z
zengbin93 已提交
221
        self.debug = debug
Z
zengbin93 已提交
222
        self.kline = self._preprocess(kline)
223
        self.symbol = self.kline[0]['symbol']
Z
zengbin93 已提交
224
        self.latest_price = self.kline[-1]['close']
225 226
        self.start_dt = self.kline[0]['dt']
        self.end_dt = self.kline[-1]['dt']
Z
zengbin93 已提交
227 228 229 230
        self.kline_new = self._remove_include()
        self.fx = self._find_fx()
        self.bi = self._find_bi()
        self.xd = self._find_xd()
Z
zengbin93 已提交
231
        self.zs = find_zs(self.xd)
Z
zengbin93 已提交
232 233
        self.__update_kline()

234
    def __repr__(self):
Z
zengbin93 已提交
235
        return "<KlineAnalyze of %s@%s, from %s to %s>" % (self.symbol, self.name, self.start_dt, self.end_dt)
236

Z
zengbin93 已提交
237 238 239 240
    @staticmethod
    def _preprocess(kline):
        """新增分析所需字段"""
        if isinstance(kline, pd.DataFrame):
Z
zengbin93 已提交
241 242
            columns = kline.columns.to_list()
            kline = [{k: v for k, v in zip(columns, row)} for row in kline.values]
Z
zengbin93 已提交
243 244 245 246 247 248 249 250 251

        results = []
        for k in kline:
            k['fx_mark'], k['fx'], k['bi'], k['xd'] = "o", None, None, None
            results.append(k)
        return results

    def _remove_include(self):
        """去除包含关系,得到新的K线数据"""
Z
zengbin93 已提交
252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269
        k_new = []

        for k in self.kline:
            if len(k_new) <= 2:
                k_new.append({
                    "symbol": k['symbol'],
                    "dt": k['dt'],
                    "open": k['open'],
                    "close": k['close'],
                    "high": k['high'],
                    "low": k['low'],
                    "vol": k['vol'],
                    "fx_mark": k['fx_mark'],
                    "fx": k['fx'],
                    "bi": k['bi'],
                    "xd": k['xd'],
                })
                continue
Z
zengbin93 已提交
270 271 272 273 274 275 276

            # 从 k_new 中取最后两根 K 线计算方向
            k1, k2 = k_new[-2:]
            if k2['high'] > k1['high']:
                direction = "up"
            elif k2['low'] < k1['low']:
                direction = "down"
Z
zengbin93 已提交
277
            else:
Z
zengbin93 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294
                direction = "up"

            # 判断 k2 与 k 之间是否存在包含关系
            cur_h, cur_l = k['high'], k['low']
            last_h, last_l = k2['high'], k2['low']

            # 左包含 or 右包含
            if (cur_h <= last_h and cur_l >= last_l) or (cur_h >= last_h and cur_l <= last_l):
                # 有包含关系,按方向分别处理
                if direction == "up":
                    last_h = max(last_h, cur_h)
                    last_l = max(last_l, cur_l)
                elif direction == "down":
                    last_h = min(last_h, cur_h)
                    last_l = min(last_l, cur_l)
                else:
                    raise ValueError
Z
zengbin93 已提交
295

Z
zengbin93 已提交
296
                k_new.pop(-1)
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324
                if k['open'] >= k['close']:
                    k_new.append({
                        "symbol": k['symbol'],
                        "dt": k['dt'],
                        "open": last_h,
                        "close": last_l,
                        "high": last_h,
                        "low": last_l,
                        "vol": k['vol'],
                        "fx_mark": k['fx_mark'],
                        "fx": k['fx'],
                        "bi": k['bi'],
                        "xd": k['xd'],
                    })
                else:
                    k_new.append({
                        "symbol": k['symbol'],
                        "dt": k['dt'],
                        "open": last_l,
                        "close": last_h,
                        "high": last_h,
                        "low": last_l,
                        "vol": k['vol'],
                        "fx_mark": k['fx_mark'],
                        "fx": k['fx'],
                        "bi": k['bi'],
                        "xd": k['xd'],
                    })
Z
zengbin93 已提交
325
            else:
Z
zengbin93 已提交
326
                # 无包含关系,更新 K 线
Z
zengbin93 已提交
327 328 329 330 331 332 333 334 335 336 337 338 339
                k_new.append({
                    "symbol": k['symbol'],
                    "dt": k['dt'],
                    "open": k['open'],
                    "close": k['close'],
                    "high": k['high'],
                    "low": k['low'],
                    "vol": k['vol'],
                    "fx_mark": k['fx_mark'],
                    "fx": k['fx'],
                    "bi": k['bi'],
                    "xd": k['xd'],
                })
Z
zengbin93 已提交
340 341 342 343 344 345 346 347 348 349 350 351
        return k_new

    def _find_fx(self):
        """识别线分型标记

        o   非分型
        d   底分型
        g   顶分型

        :return:
        """
        i = 0
Z
zengbin93 已提交
352 353
        while i < len(self.kline_new):
            if i == 0 or i == len(self.kline_new) - 1:
Z
zengbin93 已提交
354
                i += 1
Z
zengbin93 已提交
355
                continue
Z
zengbin93 已提交
356
            k1, k2, k3 = self.kline_new[i - 1: i + 2]
Z
zengbin93 已提交
357 358 359 360 361 362 363 364 365 366 367 368
            i += 1

            # 顶分型标记
            if k2['high'] > k1['high'] and k2['high'] > k3['high']:
                k2['fx_mark'] = 'g'
                k2['fx'] = k2['high']

            # 底分型标记
            if k2['low'] < k1['low'] and k2['low'] < k3['low']:
                k2['fx_mark'] = 'd'
                k2['fx'] = k2['low']

Z
zengbin93 已提交
369 370
        fx = [{"dt": x['dt'], "fx_mark": x['fx_mark'], "fx": x['fx']}
              for x in self.kline_new if x['fx_mark'] in ['d', 'g']]
Z
zengbin93 已提交
371 372
        return fx

Z
zengbin93 已提交
373 374
    def __extract_potential(self, mode='fx', fx_mark='d'):
        if mode == 'fx':
Z
zengbin93 已提交
375
            points = self.fx
Z
zengbin93 已提交
376
        elif mode == 'bi':
Z
zengbin93 已提交
377
            points = self.bi
Z
zengbin93 已提交
378 379 380 381 382 383
        else:
            raise ValueError

        seq = [x for x in points if x['fx_mark'] == fx_mark]
        seq = sorted(seq, key=lambda x: x['dt'], reverse=False)

Z
zengbin93 已提交
384 385 386
        p = [seq[0]]
        i = 1
        while i < len(seq):
Z
zengbin93 已提交
387
            if fx_mark == 'd':
Z
zengbin93 已提交
388
                # 对于底,前面的高于后面的,只保留后面的
389 390 391 392 393 394 395 396 397
                s1 = seq[i-1]
                s2 = seq[i]
                if i == len(seq) - 1:
                    p.append(s2)
                else:
                    s3 = seq[i + 1]
                    if s1[mode] > s2[mode] < s3[mode]:
                        p.append(s2)

Z
zengbin93 已提交
398
            elif fx_mark == 'g':
Z
zengbin93 已提交
399
                # 对于顶,前面的低于后面的,只保留后面的
400 401 402 403 404 405 406 407
                s1 = seq[i-1]
                s2 = seq[i]
                if i == len(seq) - 1:
                    p.append(s2)
                else:
                    s3 = seq[i + 1]
                    if s1[mode] < s2[mode] > s3[mode]:
                        p.append(s2)
Z
zengbin93 已提交
408 409
            else:
                raise ValueError
Z
zengbin93 已提交
410
            i += 1
411

Z
zengbin93 已提交
412 413 414
        return p

    def __handle_hist_bi(self):
Z
zengbin93 已提交
415 416
        """识别笔标记:从已经识别出来的分型中确定能够构建笔的分型
        """
417 418 419 420 421 422
        if self.bi_mode == "new":
            min_k_num = 4
        elif self.bi_mode == "old":
            min_k_num = 5
        else:
            raise ValueError
Z
zengbin93 已提交
423
        self.min_k_num = min_k_num
Z
0.3.1  
zengbin93 已提交
424
        kn = self.kline_new
Z
zengbin93 已提交
425
        fx_p = self.fx
Z
zengbin93 已提交
426

Z
zengbin93 已提交
427 428 429
        # 确认哪些分型可以构成笔
        bi = []
        for i in range(len(fx_p)):
430 431 432 433 434
            k = {
                "dt": fx_p[i]['dt'],
                "fx_mark": fx_p[i]['fx_mark'],
                "bi": fx_p[i]['fx'],
            }
435
            if len(bi) == 0:
Z
zengbin93 已提交
436 437 438 439 440 441 442 443 444
                bi.append(k)
            else:
                k0 = bi[-1]
                if k0['fx_mark'] == k['fx_mark']:
                    if (k0['fx_mark'] == "g" and k0['bi'] < k['bi']) or \
                            (k0['fx_mark'] == "d" and k0['bi'] > k['bi']):
                        bi.pop(-1)
                        bi.append(k)
                else:
Z
zengbin93 已提交
445 446 447 448 449 450 451 452
                    k_inside = [x for x in kn if k0['dt'] <= x['dt'] <= k['dt']]

                    # 缺口处理:缺口的出现说明某一方力量很强,当做N根K线处理
                    k_pair = [k_inside[x: x+2] for x in range(len(k_inside)-2)]
                    has_gap = False
                    for pair in k_pair:
                        kr, kl = pair
                        # 向下缺口
Z
zengbin93 已提交
453
                        if kr['low'] > kl['high'] * (1+self.min_bi_gap):
Z
zengbin93 已提交
454 455 456 457
                            has_gap = True
                            break

                        # 向上缺口
Z
zengbin93 已提交
458
                        if kr['high'] < kl['low'] * (1-self.min_bi_gap):
Z
zengbin93 已提交
459 460 461 462 463
                            has_gap = True
                            break

                    if has_gap:
                        bi.append(k)
464 465
                        continue

Z
zengbin93 已提交
466 467 468 469 470 471 472
                    max_high = max([x['high'] for x in k_inside])
                    min_low = min([x['low'] for x in k_inside])
                    if len(k_inside) >= min_k_num:
                        # 确保相邻两个顶底之间顶大于底,并且笔分型是极值
                        if (k0['fx_mark'] == 'g' and k['bi'] < k0['bi'] and k['bi'] == min_low) or \
                                (k0['fx_mark'] == 'd' and k['bi'] > k0['bi'] and k['bi'] == max_high):
                            bi.append(k)
Z
zengbin93 已提交
473
        return bi
Z
zengbin93 已提交
474

Z
zengbin93 已提交
475
    def __handle_last_bi(self, bi):
Z
zengbin93 已提交
476 477 478 479
        """处理最后一个笔标记

        特别的,对应最后一个笔标记:最后一根K线的最高价大于顶,或最后一根K线的最低价大于底,则删除这个标记。
        """
Z
zengbin93 已提交
480
        last_bi = bi[-1]
Z
zengbin93 已提交
481
        last_k = self.kline_new[-1]
Z
zengbin93 已提交
482

Z
zengbin93 已提交
483 484
        if (last_bi['fx_mark'] == 'd' and last_k['low'] < last_bi['bi']) \
                or (last_bi['fx_mark'] == 'g' and last_k['high'] > last_bi['bi']):
485 486
            bi.pop(-1)
        return bi
Z
zengbin93 已提交
487

Z
zengbin93 已提交
488
    def _find_bi(self):
489 490 491 492 493 494 495 496 497 498 499
        try:
            bi = self.__handle_hist_bi()
            if self.handle_last:
                bi = self.__handle_last_bi(bi)

            dts = [x["dt"] for x in bi]
            for k in self.kline_new:
                if k['dt'] in dts:
                    k['bi'] = k['fx']
            return bi
        except:
Z
zengbin93 已提交
500 501
            if self.debug:
                traceback.print_exc()
502
            return []
Z
zengbin93 已提交
503

Z
zengbin93 已提交
504
    def __handle_hist_xd(self):
Z
zengbin93 已提交
505
        """识别线段标记:从已经识别出来的笔中识别线段"""
506
        bi_p = []  # 存储潜在线段标记
Z
zengbin93 已提交
507 508 509 510
        bi_p.extend(self.__extract_potential(mode='bi', fx_mark='d'))
        bi_p.extend(self.__extract_potential(mode='bi', fx_mark='g'))
        bi_p = sorted(bi_p, key=lambda x: x['dt'], reverse=False)

Z
zengbin93 已提交
511 512
        xd = []
        for i in range(len(bi_p)):
513 514 515 516 517
            k = {
                "dt": bi_p[i]['dt'],
                "fx_mark": bi_p[i]['fx_mark'],
                "xd": bi_p[i]['bi'],
            }
Z
zengbin93 已提交
518 519 520 521 522
            if len(xd) == 0:
                xd.append(k)
            else:
                k0 = xd[-1]
                if k0['fx_mark'] == k['fx_mark']:
Z
zengbin93 已提交
523
                    # 处理同一性质的笔标记
Z
zengbin93 已提交
524 525 526 527 528 529 530 531 532 533
                    if (k0['fx_mark'] == "g" and k0['xd'] < k['xd']) or \
                            (k0['fx_mark'] == "d" and k0['xd'] > k['xd']):
                        xd.pop(-1)
                        xd.append(k)
                else:
                    # 确保相邻两个顶底之间顶大于底
                    if (k0['fx_mark'] == 'g' and k['xd'] >= k0['xd']) or \
                            (k0['fx_mark'] == 'd' and k['xd'] <= k0['xd']):
                        xd.pop(-1)
                        continue
534

Z
zengbin93 已提交
535
                    bi_m = [x for x in self.bi if k0['dt'] <= x['dt'] <= k['dt']]
Z
0.3.1  
zengbin93 已提交
536
                    bi_r = [x for x in self.bi if x['dt'] >= k['dt']]
Z
zengbin93 已提交
537
                    # 一线段内部至少三笔
Z
zengbin93 已提交
538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565
                    if len(bi_m) < 4 or len(bi_r) < 4:
                        continue

                    # 线段的顶必然大于相邻的两个顶;线段的底必然小于相邻的两个底
                    assert k['fx_mark'] == bi_m[-3]['fx_mark'] == bi_r[2]['fx_mark']
                    if k['fx_mark'] == "d" and not (bi_m[-3]['bi'] > k['xd'] < bi_r[2]['bi']):
                        print("不满足线段的底必然小于相邻的两个底")
                        print(bi_m[-3], k, bi_r[2])
                        continue

                    if k['fx_mark'] == "g" and not (bi_m[-3]['bi'] < k['xd'] > bi_r[2]['bi']):
                        print("不满足线段的顶必然大于相邻的两个顶")
                        print(bi_m[-3], k, bi_r[2])
                        continue

                    # 判断线段标记是否有效
                    left_last = bi_m[-3]
                    right_first = bi_r[1]
                    assert left_last['fx_mark'] != right_first['fx_mark']

                    if k['fx_mark'] == 'd':
                        max_g = max([x['bi'] for x in bi_r[:8] if x['fx_mark'] == 'g'])
                        if max_g > right_first['bi'] and max_g > left_last['bi']:
                            xd.append(k)

                    if k['fx_mark'] == 'g':
                        min_d = min([x['bi'] for x in bi_r[:8] if x['fx_mark'] == 'd'])
                        if min_d < right_first['bi'] and min_d < left_last['bi']:
Z
0.3.1  
zengbin93 已提交
566
                            xd.append(k)
567
        return xd
Z
zengbin93 已提交
568

569
    def __handle_last_xd(self, xd):
Z
zengbin93 已提交
570 571 572 573 574 575 576 577
        """处理最后一个线段标记

        特别的,对最后一个线段标记:最后一根K线的最高价大于顶,或最后一根K线的最低价大于底,则删除这个标记。
        """
        last_k = self.kline_new[-1]
        if (xd[-1]['fx_mark'] == 'd' and last_k['low'] < xd[-1]['xd']) \
                or (xd[-1]['fx_mark'] == 'g' and last_k['high'] > xd[-1]['xd']):
            xd.pop(-1)
578
        return xd
Z
zengbin93 已提交
579

Z
zengbin93 已提交
580 581
    def _find_xd(self):
        try:
Z
zengbin93 已提交
582
            xd = self.__handle_hist_xd()
Z
zengbin93 已提交
583 584 585
            if self.handle_last:
                xd = self.__handle_last_xd(xd)

Z
zengbin93 已提交
586 587
            dts = [x["dt"] for x in xd]
            for k in self.kline_new:
Z
zengbin93 已提交
588 589
                if k['dt'] in dts:
                    k['xd'] = k['fx']
Z
zengbin93 已提交
590
            return xd
Z
zengbin93 已提交
591
        except:
Z
zengbin93 已提交
592 593
            if self.debug:
                traceback.print_exc()
Z
zengbin93 已提交
594 595 596 597 598 599 600
            return []

    def __update_kline(self):
        kn_map = {x['dt']: x for x in self.kline_new}
        for k in self.kline:
            k1 = kn_map.get(k['dt'], None)
            if k1:
Z
zengbin93 已提交
601
                k['fx_mark'], k['fx'], k['bi'], k['xd'] = k1['fx_mark'], k1['fx'], k1['bi'], k1['xd']
Z
zengbin93 已提交
602

Z
zengbin93 已提交
603 604 605 606 607 608 609 610 611 612
    def zs_mean(self, n=6, mode='xd'):
        """计算最近 n 个走势的平均波动幅度

        :param n: int
            线段数量
        :param mode: str
            xd -> 线段平均波动; bi -> 笔平均波动
        :return: float
        """
        if mode == 'xd':
Z
zengbin93 已提交
613
            latest_zs = self.xd[-n - 1:]
Z
zengbin93 已提交
614
        elif mode == 'bi':
Z
zengbin93 已提交
615
            latest_zs = self.bi[-n - 1:]
Z
zengbin93 已提交
616 617 618 619
        else:
            raise ValueError("mode value error, only support 'xd' or 'bi'")

        wave = []
620
        for i in range(len(latest_zs) - 1):
Z
zengbin93 已提交
621 622
            x1 = latest_zs[i][mode]
            x2 = latest_zs[i + 1][mode]
623
            w = abs(x1 - x2) / x1
Z
zengbin93 已提交
624 625 626
            wave.append(w)
        return round(sum(wave) / len(wave), 2)

627 628
    def bi_bei_chi(self):
        """判断最后一笔是否背驰"""
Z
zengbin93 已提交
629
        bi = self.bi
630

631 632 633 634 635
        # 最后一笔背驰出现的两种情况:
        # 1)向上笔新高且和前一个向上笔不存在包含关系;
        # 2)向下笔新低且和前一个向下笔不存在包含关系。
        if (bi[-1]['fx_mark'] == 'g' and bi[-1]["bi"] > bi[-3]["bi"] and bi[-2]["bi"] > bi[-4]["bi"]) or \
                (bi[-1]['fx_mark'] == 'd' and bi[-1]['bi'] < bi[-3]['bi'] and bi[-2]['bi'] < bi[-4]['bi']):
636 637
            zs1 = {"start_dt": bi[-2]['dt'], "end_dt": bi[-1]['dt']}
            zs2 = {"start_dt": bi[-4]['dt'], "end_dt": bi[-3]['dt']}
638 639 640 641 642 643
            return is_bei_chi(self, zs1, zs2, mode="bi")
        else:
            return False

    def xd_bei_chi(self):
        """判断最后一个线段是否背驰"""
Z
zengbin93 已提交
644
        xd = self.xd
645 646 647 648 649 650 651 652 653 654 655 656 657
        last_xd = xd[-1]
        if last_xd['fx_mark'] == 'g':
            direction = "up"
        elif last_xd['fx_mark'] == 'd':
            direction = "down"
        else:
            raise ValueError

        # 最后一个线段背驰出现的两种情况:
        # 1)向上线段新高且和前一个向上线段不存在包含关系;
        # 2)向下线段新低且和前一个向下线段不存在包含关系。
        if (last_xd['fx_mark'] == 'g' and xd[-1]["xd"] > xd[-3]["xd"] and xd[-2]["xd"] > xd[-4]["xd"]) or \
                (last_xd['fx_mark'] == 'd' and xd[-1]['xd'] < xd[-3]['xd'] and xd[-2]['xd'] < xd[-4]['xd']):
658 659 660
            zs1 = {"start_dt": xd[-2]['dt'], "end_dt": xd[-1]['dt'], "direction": direction}
            zs2 = {"start_dt": xd[-4]['dt'], "end_dt": xd[-3]['dt'], "direction": direction}
            return is_bei_chi(self, zs1, zs2, mode="xd")
661 662
        else:
            return False
Z
zengbin93 已提交
663

Z
zengbin93 已提交
664 665
    def to_html(self, file_html="kline.html", width="1400px", height="680px"):
        """保存成 html
Z
zengbin93 已提交
666

Z
zengbin93 已提交
667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
        :param file_html: str
            html文件名
        :param width: str
            页面宽度
        :param height: str
            页面高度
        :return:
        """
        plot_kline(self, file_html=file_html, width=width, height=height)

    def to_image(self, file_image, mav=(5, 20, 120, 250), max_k_count=1000, dpi=50):
        """保存成图片

        :param file_image: str
            图片名称,支持 jpg/png/svg 格式,注意后缀
        :param mav: tuple of int
            均线系统参数
        :param max_k_count: int
            设定最大K线数量,这个值越大,生成的图片越长
        :param dpi: int
            图片分辨率
        :return:
        """
        plot_ka(self, file_image=file_image, mav=mav, max_k_count=max_k_count, dpi=dpi)
Z
zengbin93 已提交
691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720

    def up_zs_number(self):
        """检查最新走势的连续向上中枢数量"""
        ka = self
        zs_num = 1
        if len(ka.zs) > 1:
            k_zs = ka.zs[::-1]
            zs_cur = k_zs[0]
            for zs_next in k_zs[1:]:
                if zs_cur["ZD"] >= zs_next["ZG"]:
                    zs_num += 1
                    zs_cur = zs_next
                else:
                    break
        return zs_num

    def down_zs_number(self):
        """检查最新走势的连续向下中枢数量"""
        ka = self
        zs_num = 1
        if len(ka.zs) > 1:
            k_zs = ka.zs[::-1]
            zs_cur = k_zs[0]
            for zs_next in k_zs[1:]:
                if zs_cur["ZG"] <= zs_next["ZD"]:
                    zs_num += 1
                    zs_cur = zs_next
                else:
                    break
        return zs_num