analyze.py 11.1 KB
Newer Older
Z
zengbin93 已提交
1
# coding: utf-8
Z
zengbin93 已提交
2

Z
zengbin93 已提交
3
import pandas as pd
Z
zengbin93 已提交
4
from copy import deepcopy
Z
zengbin93 已提交
5 6 7 8 9 10 11


def preprocess(kline):
    """去除包含关系

    :param kline: pd.DataFrame
        K线,columns = ["symbol", "dt", "open", "close", "high", "low", "vol"]
Z
zengbin93 已提交
12
    :return: list of dict
Z
zengbin93 已提交
13

Z
zengbin93 已提交
14 15
    """
    k_new = []
Z
zengbin93 已提交
16

Z
zengbin93 已提交
17 18 19
    first_row = kline.iloc[0].to_dict()
    last = deepcopy(first_row)
    k_new.append(first_row)
Z
zengbin93 已提交
20 21

    for i, row in kline.iterrows():
Z
zengbin93 已提交
22 23 24 25 26 27 28 29 30 31 32 33
        # first row
        if i == 0:
            continue

        # update direction
        if last['high'] >= k_new[-1]['high']:
            direction = 'up'
        else:
            direction = 'down'

        # 包含关系处理
        row = row.to_dict()
Z
zengbin93 已提交
34
        cur_h, cur_l = row['high'], row['low']
Z
zengbin93 已提交
35
        last_h, last_l = last['high'], last['low']
Z
zengbin93 已提交
36 37 38

        # 左包含 or 右包含
        if (cur_h <= last_h and cur_l >= last_l) or (cur_h >= last_h and cur_l <= last_l):
Z
zengbin93 已提交
39 40
            # 有包含关系,按方向分别处理
            if direction == "up":
Z
zengbin93 已提交
41 42
                last_h = max(last_h, cur_h)
                last_l = max(last_l, cur_l)
Z
zengbin93 已提交
43 44 45 46 47

            elif direction == "down":
                last_h = min(last_h, cur_h)
                last_l = min(last_l, cur_l)

Z
zengbin93 已提交
48 49 50
            else:
                raise ValueError

Z
zengbin93 已提交
51 52 53 54 55 56 57
            last = deepcopy(row)
            last['high'] = last_h
            last['low'] = last_l
        else:
            # 无包含关系,更新 K 线
            k_new.append(last)
            last = deepcopy(row)
Z
zengbin93 已提交
58

Z
modify  
zengbin93 已提交
59 60 61
        if i == len(kline)-1:
            if row['dt'] != k_new[-1]['dt']:
                k_new.append(row)
Z
zengbin93 已提交
62

Z
zengbin93 已提交
63 64
    # print('k_new nums:', len(k_new))
    return k_new
Z
zengbin93 已提交
65 66


Z
zengbin93 已提交
67 68 69 70
def find_fx(k_new):
    """查找顶分型和底分型"""
    k1 = k_new[0]
    k2 = k_new[1]
Z
zengbin93 已提交
71

Z
zengbin93 已提交
72 73 74 75 76 77 78 79
    k_fx = []
    for k in k_new[2:]:
        if k2['high'] > k1['high'] and k2['high'] > k['high']:
            k2['fx_mark'] = 'g'
            k2['fx'] = k2['high']
        elif k2['low'] < k1['low'] and k2['low'] < k['low']:
            k2['fx_mark'] = 'd'
            k2['fx'] = k2['low']
Z
zengbin93 已提交
80

Z
zengbin93 已提交
81 82
        k_fx.append(k2)
        k1, k2, = k2, k
Z
zengbin93 已提交
83

Z
zengbin93 已提交
84 85
    # print("fx nums:", len(k_fx))
    return k_fx
Z
zengbin93 已提交
86 87


Z
zengbin93 已提交
88 89 90
def find_bi(k_fx):
    """查找分型标记"""
    k_bi = []
Z
zengbin93 已提交
91

Z
zengbin93 已提交
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
    potential = None
    k_count = 0

    for k in k_fx:
        # print(k)
        if not potential:
            # 查找第一个潜在笔分型点
            if "fx_mark" in k.keys():
                potential = deepcopy(k)
            else:
                continue

        # 验证各分型点是否能够作为笔分型点
        if "fx_mark" in k.keys():
            if k['fx_mark'] == potential['fx_mark']:
                if k['fx_mark'] == "g" and k['fx'] > potential['fx']:
                    potential = deepcopy(k)
                elif k['fx_mark'] == "d" and k['fx'] < potential['fx']:
                    potential = deepcopy(k)
                else:
                    continue
                k_count = 0
            else:
                if k_count >= 3:
                    potential['bi'] = potential['fx']
                    k_bi.append(potential)
                    # print("potential old: ", k_count, potential)
                    k_count = 0
                    potential = deepcopy(k)
                    # print("potential new: ", k_count, potential)
                # k_count = 0
Z
zengbin93 已提交
123
        else:
Z
zengbin93 已提交
124 125
            # print(k_count, k)
            k_count += 1
Z
zengbin93 已提交
126

Z
zengbin93 已提交
127 128 129 130
    potential['bi'] = potential['fx']
    k_bi.append(potential)
    # print("bi nums:", len(k_bi))
    return k_bi
Z
zengbin93 已提交
131 132


Z
zengbin93 已提交
133 134
def find_xd(k_bi):
    """查找线段标记"""
Z
modify  
zengbin93 已提交
135

Z
zengbin93 已提交
136 137 138 139
    k_xd = []
    i = 0
    potential = deepcopy(k_bi[i])

Z
modify  
zengbin93 已提交
140
    # 依据不创新高、新低的近似标准找出所有潜在线段标记
Z
zengbin93 已提交
141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
    while i < len(k_bi)-3:
        k1, k2, k3 = k_bi[i+1], k_bi[i+2], k_bi[i+3]

        if potential['fx_mark'] == "d":
            assert k2['fx_mark'] == 'd'
            if k3['bi'] < k1['bi']:
                potential['xd'] = potential['bi']
                k_xd.append(potential)
                i += 1
                potential = deepcopy(k_bi[i])
            else:
                i += 2

        elif potential['fx_mark'] == "g":
            assert k2['fx_mark'] == 'g'
            if k3['bi'] > k1['bi']:
                potential['xd'] = potential['bi']
                k_xd.append(potential)
                i += 1
                potential = deepcopy(k_bi[i])
            else:
                i += 2
Z
zengbin93 已提交
163

Z
zengbin93 已提交
164 165 166 167 168
        else:
            raise ValueError
    potential['xd'] = potential['bi']
    k_xd.append(potential)
    return k_xd
Z
zengbin93 已提交
169

Z
modify  
zengbin93 已提交
170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
    # # 在向下笔构成的标准特征序列中找出所有顶分型;在向上笔构成的标准特征序列中找出所有底分型;
    # def _bi_fx(bi_list, mode):
    #
    #     if mode == 'g':
    #         direction = 'up'
    #     elif mode == 'd':
    #         direction = 'down'
    #     else:
    #         raise ValueError
    #
    #     bi_pred = []
    #     last = bi_list[0]
    #     for bi in bi_list[1:]:
    #         # 包含关系处理
    #         cur_h, cur_l = bi['high'], bi['low']
    #         last_h, last_l = last['high'], last['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)
    #                 if last_h != last['high']:
    #                     last = deepcopy(bi)
    #                 last['low'] = last_l
    #             elif direction == "down":
    #                 last_h = min(last_h, cur_h)
    #                 last_l = min(last_l, cur_l)
    #                 if last_l != last['low']:
    #                     last = deepcopy(bi)
    #                 last['high'] = last_h
    #             else:
    #                 raise ValueError
    #         else:
    #             # 无包含关系,更新 K 线
    #             bi_pred.append(last)
    #             last = deepcopy(bi)
    #
    #     return [x for x in find_fx(bi_pred) if x.get('fx_mark', None) == mode]
    #
    # bi_down = [{"dt": x['dt'], "high": x['fx'], "low": k_bi[i+1]['fx']}
    #            for i, x in enumerate(k_bi[:-1]) if x['fx_mark'] == "g"]
    # bi_g = _bi_fx(bi_down, mode='g')
    # bi_up = [{"dt": x['dt'], "high": k_bi[i+1]['fx'], "low": x['fx']}
    #          for i, x in enumerate(k_bi[:-1]) if x['fx_mark'] == "d"]
    # bi_d = _bi_fx(bi_up, mode='d')
    # valid_fx = [x['low'] for x in bi_d] + [x['high'] for x in bi_g]
    # # valid_dt = [x['dt'] for x in bi_d] + [x['dt'] for x in bi_g]
    #
    # # 利用特征序列的顶底分型确认线段标记的有效性,随后,对连续两个相同标记进行处理。
    # k_xd_valid = [k_xd[0]]
    # for x in k_xd:
    #     if x['fx'] not in valid_fx:
    #         continue
    #     else:
    #         if x['fx_mark'] == k_xd_valid[-1]['fx_mark']:
    #             if x['fx_mark'] == 'g' and x['fx'] > k_xd_valid[-1]['fx']:
    #                 k_xd_valid[-1] = x
    #             elif x['fx_mark'] == 'd' and x['fx'] < k_xd_valid[-1]['fx']:
    #                 k_xd_valid[-1] = x
    #             else:
    #                 continue
    #         else:
    #             k_xd_valid.append(x)
    #
    # # 对最后一个线段标记使用近似定义
    # if k_xd[-1] not in k_xd_valid and k_xd[-1]['fx_mark'] != k_xd_valid[-1]['fx_mark']:
    #     # print("add last xd")
    #     k_xd_valid.append(k_xd[-1])
    #
    # return k_xd_valid

Z
zengbin93 已提交
243

Z
zengbin93 已提交
244 245 246 247
def find_zs(k_xd):
    """查找中枢"""
    k_zs = []
    zs_xd = []
Z
zengbin93 已提交
248

Z
zengbin93 已提交
249 250 251 252
    for i in range(len(k_xd)-1):
        if len(zs_xd) < 4:
            zs_xd.append(k_xd[i])
            continue
Z
zengbin93 已提交
253

Z
zengbin93 已提交
254 255 256 257 258 259 260
        zs_d = max([x['xd'] for x in zs_xd if x['fx_mark'] == 'd'])
        zs_g = min([x['xd'] for x in zs_xd if x['fx_mark'] == 'g'])
        # zs = (zs_d, zs_g)
        xd_p1 = zs_xd[-1]['xd']
        xd_p2 = k_xd[i]['xd']
        if zs_g > xd_p2 > zs_d:
            zs_xd.append(k_xd[i])
Z
zengbin93 已提交
261
        else:
Z
zengbin93 已提交
262 263 264 265 266 267 268 269
            if xd_p1 > zs_g and xd_p2 > zs_g:
                # 线段在中枢上方结束,形成三买
                k_zs.append({'zs': (zs_d, zs_g), "zs_xd": deepcopy(zs_xd)})
                zs_xd = [k_xd[i]]
            elif xd_p1 < zs_g and xd_p2 < zs_g:
                # 线段在中枢下方结束,形成三卖
                k_zs.append({'zs': (zs_d, zs_g), "zs_xd": deepcopy(zs_xd)})
                zs_xd = [k_xd[i]]
Z
zengbin93 已提交
270
            else:
Z
zengbin93 已提交
271
                zs_xd.append(k_xd[i])
Z
zengbin93 已提交
272

Z
zengbin93 已提交
273
    return k_zs
Z
zengbin93 已提交
274 275


Z
zengbin93 已提交
276 277 278 279 280 281
def kline_analyze(kline):
    """使用缠论分析 K 线"""
    k_new = preprocess(kline)
    k_fx = find_fx(k_new)
    k_bi = find_bi(k_fx)
    k_xd = find_xd(k_bi)
Z
zengbin93 已提交
282

Z
zengbin93 已提交
283 284
    df_fx = pd.DataFrame(k_fx)[['dt', 'fx_mark', 'fx']]
    kline = kline.merge(df_fx, how='left', on='dt')
Z
zengbin93 已提交
285

Z
zengbin93 已提交
286 287
    df_bi = pd.DataFrame(k_bi)[['dt', 'bi']]
    kline = kline.merge(df_bi, how='left', on='dt')
Z
zengbin93 已提交
288

Z
zengbin93 已提交
289 290 291
    df_xd = pd.DataFrame(k_xd)[['dt', 'xd']]
    kline = kline.merge(df_xd, how='left', on='dt')
    return kline
Z
zengbin93 已提交
292 293


Z
zengbin93 已提交
294 295 296 297 298 299 300
class KlineAnalyze(object):
    def __init__(self, kline):
        self.kline = kline
        self.k_new = preprocess(self.kline)
        self.k_fx = find_fx(self.k_new)
        self.k_bi = find_bi(self.k_fx)
        self.k_xd = find_xd(self.k_bi)
Z
modify  
zengbin93 已提交
301
        self.k_zs = find_zs(self.k_xd)
Z
zengbin93 已提交
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356

    @property
    def chan_result(self):
        k = deepcopy(self.kline)
        df_fx = pd.DataFrame(self.k_fx)[['dt', 'fx_mark', 'fx']]
        k = k.merge(df_fx, how='left', on='dt')

        df_bi = pd.DataFrame(self.k_bi)[['dt', 'bi']]
        k = k.merge(df_bi, how='left', on='dt')

        df_xd = pd.DataFrame(self.k_xd)[['dt', 'xd']]
        k = k.merge(df_xd, how='left', on='dt')
        return k

    @property
    def status_bi(self):
        k1, k2, k3 = self.k_new[-1], self.k_new[-2], self.k_new[-3]
        if k1['high'] > k2['high'] > k3['high']:
            s = "向上笔延伸中"
        elif k1['low'] < k2['low'] < k3['low']:
            s = "向下笔延伸中"
        elif max([k1['high'], k2['high'], k3['high']]) == k2['high']:
            s = "顶分型构造中"
        elif min([k1['low'], k2['low'], k3['low']]) == k2['low']:
            s = "底分型构造中"
        else:
            raise ValueError
        return s

    @property
    def status_xd(self):
        last = self.k_xd[-1]
        if last['fx_mark'] == 'g':
            s = "向下线段延伸中"
        elif last['fx_mark'] == 'd':
            s = "向上线段延伸中"
        else:
            raise ValueError
        return s

    @property
    def status_zs(self):
        if len(self.k_xd) < 5:
            return "没有中枢"

        xd1 = (self.k_xd[-5], self.k_xd[-4])
        xd2 = (self.k_xd[-4], self.k_xd[-3])
        # xd3 = (self.k_xd[-3], self.k_xd[-2])
        xd4 = (self.k_xd[-2], self.k_xd[-1])
        zs = (min([xd2[0]['fx'], xd2[1]['fx']]), max([xd2[0]['fx'], xd2[1]['fx']]))

        if xd1[0]['fx_mark'] == "g" and xd4[1]['fx'] < zs[0]:
            # 找第三卖点是否形成
            s = '中枢下移'
        elif xd1[0]['fx_mark'] == "d" and xd4[1]['fx'] > zs[1]:
Z
modify  
zengbin93 已提交
357
            # 找第三买点是否形成
Z
zengbin93 已提交
358 359 360 361
            s = '中枢上移'
        else:
            s = '中枢震荡'
        return s
Z
zengbin93 已提交
362 363


Z
zengbin93 已提交
364 365 366