def get(self): ts_code = self.get_argument('ts_code') freq = self.get_argument('freq') trade_date = self.get_argument('trade_date') if trade_date == 'null': trade_date = datetime.now().date() else: trade_date = datetime.strptime(trade_date, "%Y%m%d") kline = get_kline(symbol=ts_code, end_date=trade_date, freq=freq, count=5000) kline.loc[:, "dt"] = pd.to_datetime(kline.dt) # kline.loc[:, "is_end"] = True if czsc.__version__ < "0.5": ka = KlineAnalyze(kline, bi_mode="new", xd_mode='strict') kline = pd.DataFrame(ka.kline_new) else: ka = KlineAnalyze(kline, bi_mode="new", verbose=False) kline = ka.to_df(ma_params=(5, 20), use_macd=True, max_count=5000) kline = kline.fillna("") kline.loc[:, "dt"] = kline.dt.apply(str) columns = [ "dt", "open", "close", "low", "high", "vol", 'fx_mark', 'fx', 'bi', 'xd' ] self.finish({'kdata': kline[columns].values.tolist()})
def get(self): ts_code = self.get_argument('ts_code') freq = self.get_argument('freq') asset = self.get_argument('asset', "E") trade_date = self.get_argument('trade_date') if trade_date == 'null': trade_date = datetime.now().date().__str__().replace("-", "") kline = get_kline(ts_code=ts_code, end_date=trade_date, freq=freq, asset=asset) kline.loc[:, "dt"] = pd.to_datetime(kline.dt) if czsc.__version__ < "0.5": ka = KlineAnalyze(kline, bi_mode="new") kline = pd.DataFrame(ka.kline_new) else: ka = KlineAnalyze(kline, verbose=False) kline = ka.to_df(ma_params=(5, 20), use_macd=True, max_count=5000) kline = kline.fillna("") kline.loc[:, "dt"] = kline.dt.apply(str) columns = [ "dt", "open", "close", "low", "high", "vol", 'fx_mark', 'fx', 'bi', 'xd' ] self.finish({'kdata': kline[columns].values.tolist()})
def get(self): ts_code = self.get_argument('ts_code') freq = self.get_argument('freq') trade_date = self.get_argument('trade_date') if trade_date == 'null': trade_date = datetime.now().date().__str__().replace("-", "") kline = get_gm_kline(symbol=ts_code, end_date=trade_date, freq=freq, k_count=3000) ka = KlineAnalyze(kline, bi_mode="new", verbose=False, use_xd=True, max_count=5000) kline = ka.to_df(ma_params=(5, 20), use_macd=True, max_count=5000, mode='new') kline = kline.fillna("") kline.loc[:, "dt"] = kline.dt.apply(str) columns = [ "dt", "open", "close", "low", "high", "vol", 'fx_mark', 'fx', 'bi', 'xd' ] self.finish({'kdata': kline[columns].values.tolist()})
def use_kline_analyze(): kline = get_kline(symbol="000001.XSHG", end_date=datetime.strptime("20200830", "%Y%m%d"), freq="D", count=5000) ka = KlineAnalyze(kline, name="日线", max_raw_len=5000, verbose=False) print("分型识别结果:", ka.fx_list[-3:]) print("笔识别结果:", ka.bi_list[-3:]) print("线段识别结果:", ka.xd_list[-3:]) kline = get_kline(symbol="300803.XSHE", end_date=datetime.strptime("20200830", "%Y%m%d"), freq="30min", count=5000) ka = KlineAnalyze(kline, name="30分钟", max_raw_len=5000, verbose=False) print("分型识别结果:", ka.fx_list[-3:]) print("笔识别结果:", ka.bi_list[-3:]) print("线段识别结果:", ka.xd_list[-3:]) kline = get_kline(symbol="300803.XSHE", end_date=datetime.strptime("20200830", "%Y%m%d"), freq="5min", count=5000) ka = KlineAnalyze(kline, name="5分钟", max_raw_len=5000, verbose=False) print("分型识别结果:", ka.fx_list[-3:]) print("笔识别结果:", ka.bi_list[-3:]) print("线段识别结果:", ka.xd_list[-3:])
def analysis(symbol=None): end_date = '2021-04-19' start_date = '2020-05-20' kline_1min = get_local_kline(symbol=[symbol], end=end_date, freq='1min', start=start_date) kline_5min = get_local_kline(symbol=[symbol], end=end_date, freq='5min', start=start_date) kline_30min = get_local_kline(symbol=[symbol], end=end_date, freq='30min', start=start_date) kline_day = get_local_day_kline(symbol, end_date, start_date) if kline_5min is None or kline_1min is None or kline_30min is None or kline_day is None: return ka_1m = KlineAnalyze(kline_1min, name="1min", verbose=False) tig_5m = TechIndicatorGenerator(kline_5min, name="5min", verbose=False) tig_30m = TechIndicatorGenerator(kline_30min, name="30min", verbose=False) tig_day = TechIndicatorGenerator(kline_day, name='day', verbose=False) fds = get_fd_from_points(ka_1m.bi_list, ka_1m.macd, symbol=ka_1m.symbol) ka_1m = TrendAnalyser(fds, ka_1m.macd) ta_5m = TrendAnalyser(ka_1m.get_zoushi_list(), tig_5m.macd) ta_30m = TrendAnalyser(ta_5m.get_zoushi_list(), tig_30m.macd) ta_day = TrendAnalyser(ta_30m.get_zoushi_list(), tig_day.macd) print("result is:") print(ta_30m.getAnalysisResult())
def kline(): if request.method == "POST": data = json.loads(request.get_data(as_text=True)) elif request.method == "GET": data = request.args else: raise ValueError ts_code = data.get('ts_code') freq = data.get('freq') k = get_kline(symbol=ts_code, freq=freq, k_count=5000) if czsc.__version__ < "0.5": ka = KlineAnalyze(k, bi_mode="new", xd_mode='strict') k = pd.DataFrame(ka.kline_new) else: ka = KlineAnalyze(k, min_bi_k=5, verbose=False) k = ka.to_df(ma_params=(5, 20), use_macd=True, max_count=5000) k = k.fillna("") kline.loc[:, "dt"] = kline.dt.apply(str) columns = ["dt", "open", "close", "low", "high", "vol", 'fx_mark', 'fx', 'bi', 'xd'] res = make_response(jsonify({'kdata': k[columns].values.tolist()})) res.headers['Access-Control-Allow-Origin'] = '*' res.headers['Access-Control-Allow-Method'] = '*' res.headers['Access-Control-Allow-Headers'] = '*' return res
def __init__(self, klines): self.klines = klines self.ka_1min = KlineAnalyze(self.klines['1分钟'], name='1分钟') self.ka_5min = KlineAnalyze(self.klines['5分钟'], name="5分钟") self.ka_D = KlineAnalyze(self.klines['日线'], name='日线') self.symbol = self.ka_1min.symbol self.end_dt = self.ka_1min.end_dt self.latest_price = self.ka_1min.latest_price self.s = self.signals() self.desc = self.__doc__
def test_kline_analyze(): df = get_kline(ts_code="300008.SZ", end_dt="2020-03-23 15:00:00", freq='30min', asset='E') ka = KlineAnalyze(df) # 测试识别结果 assert ka.bi[-1]['fx_mark'] == 'g' assert ka.xd[-1]['fx_mark'] == 'g' # 测试背驰识别 assert not ka.bi_bei_chi() assert not ka.xd_bei_chi() print(ka.zs[-2])
def use_kline_analyze(): # kline = get_kline(symbol="000001.XSHG", end_date=datetime.strptime("20200830", "%Y%m%d"), freq="D", count=5000) # ka = KlineAnalyze(kline, name="日线", verbose=False) # print("分型识别结果:", ka.fx_list[-3:]) # print("笔识别结果:", ka.bi_list[-3:]) # print("线段识别结果:", ka.xd_list[-3:]) # # kline = get_kline(symbol="300803.XSHE", end_date=datetime.strptime("20200830", "%Y%m%d"), freq="30min", count=5000) # ka = KlineAnalyze(kline, name="30分钟", verbose=False) # print("分型识别结果:", ka.fx_list[-3:]) # print("笔识别结果:", ka.bi_list[-3:]) # print("线段识别结果:", ka.xd_list[-3:]) kline = get_kline(symbol="000001.XSHE", end_date=datetime.strptime("20200830", "%Y%m%d"), freq="5min", count=5000) ka = KlineAnalyze(kline, name="5分钟", verbose=False) print("分型识别结果:", ka.fx_list[-3:]) print("笔识别结果:", ka.bi_list[-3:]) print("线段识别结果:", ka.xd_list[-3:]) zx = find_zs(ka) print(jsonpath.jsonpath(zx, '$..third_buy'))
def use_kline_analyze(): print('=' * 100, '\n') print("KlineAnalyze 的使用方法:\n") kline = get_kline(symbol='SHSE.000300', end_date="2020-02-02") ka = KlineAnalyze(kline) print("线段:", ka.xd, "\n") print("中枢:", ka.zs, "\n")
def use_kline_analyze(): kline = get_kline(symbol="000001.XSHG", end_date=datetime.strptime("20200830", "%Y%m%d"), freq="D", count=5000) ka = KlineAnalyze(kline, name="日线", bi_mode="new", use_xd=True, max_count=2000, ma_params=(5, 34, 120), verbose=False) print("分型识别结果:", ka.fx_list[-3:]) print("笔识别结果:", ka.bi_list[-3:]) print("线段识别结果:", ka.xd_list[-3:]) kline = get_kline(symbol="300803.XSHE", end_date=datetime.strptime("20200830", "%Y%m%d"), freq="30min", count=5000) ka = KlineAnalyze(kline, name="30分钟", bi_mode="new", use_xd=True, max_count=2000, ma_params=(5, 34, 120), verbose=False) print("分型识别结果:", ka.fx_list[-3:]) print("笔识别结果:", ka.bi_list[-3:]) print("线段识别结果:", ka.xd_list[-3:]) kline = get_kline(symbol="300803.XSHE", end_date=datetime.strptime("20200830", "%Y%m%d"), freq="5min", count=5000) ka = KlineAnalyze(kline, name="5分钟", bi_mode="new", use_xd=True, max_count=2000, ma_params=(5, 34, 120), verbose=False) print("分型识别结果:", ka.fx_list[-3:]) print("笔识别结果:", ka.bi_list[-3:]) print("线段识别结果:", ka.xd_list[-3:])
def use_kline_analyze(): print('=' * 100, '\n') print("KlineAnalyze 的使用方法:\n") kline = get_kline(ts_code="000009.SZ", end_date="20200210", freq='30min', asset="I") ka = KlineAnalyze(kline) print("线段:", ka.xd, "\n") print("中枢:", ka.zs, "\n")
def check_trade(ts_code, file_bs, freq, end_date="20200314", asset="E", file_html="bs.html"): """在图上画出买卖点""" bs = pd.read_excel(file_bs) bs.loc[:, 'f'] = bs.apply(lambda x: 1 if x['交易级别'] == freq_map[freq] else 0, axis=1) bs = bs[bs.f == 1] bs.loc[:, '操作提示'] = bs['操作提示'].apply(lambda x: x.replace(freq_map[freq], "")) bs = bs[["操作提示", "交易时间", "交易价格"]] print(bs) df = get_kline(ts_code, freq=freq, end_date=end_date, asset=asset) ka = KlineAnalyze(df) plot_kline(ka, bs, file_html, width="1400px", height="680px")
def make_one_day(ts_code, trade_date, asset="E"): if "-" in trade_date: end_date = datetime.strptime(trade_date, '%Y-%m-%d') else: end_date = datetime.strptime(trade_date, '%Y-%m-%d') start_date = end_date - timedelta(days=1) end_dt = end_date + timedelta(days=30) start_date = start_date.strftime("%Y-%m-%d") end_date = end_date.strftime("%Y-%m-%d") if not is_trade_day(start_date): return print(f"start trade simulator on {start_date}") trade_simulator(ts_code=ts_code, start_date=start_date, end_date=end_date, asset=asset, watch_interval=1) for freq in ['1min', '5min', '30min']: file_signals = os.path.join( data_path, f"{ts_code}_{start_date}_{end_date}_signals.txt") signals = [ eval(x) for x in open(file_signals, encoding='utf-8').readlines() ] df = pd.DataFrame(signals) kline = get_kline(ts_code, end_dt=end_dt.strftime("%Y-%m-%d %H:%M:%S"), freq=freq, asset=asset) ka = KlineAnalyze(kline) print(kline.head(), "\n\n") xd = deepcopy(ka.xd) xd = sorted(xd, key=lambda row: row['dt'], reverse=False) print(xd, "\n\n") def ___xd_status(dt): for x in xd: if x['dt'] >= dt: if x['fx_mark'] == 'd': s = "向下段" elif x['fx_mark'] == 'g': s = "向上段" else: raise ValueError return s return "o" col = f'{freq}线段状态' df[col] = df['交易时间'].apply(___xd_status) file_excel = "./data/%s_%s_%s_%s.xlsx" % (ts_code, start_date, end_date, freq) df.to_excel(file_excel, index=False)
def level_1_analysis(symbol=None): end_date = '2021-02-05' start_date = '2020-10-11' kline_day = get_local_day_kline(symbol, end_date, start_date) ka_day = KlineAnalyze(kline_day, name="30min", verbose=False) tig_day = TechIndicatorGenerator(kline_day, name="day", verbose=False) fds = get_fd_from_points(ka_day.bi_list, ka_day.macd, symbol=ka_day.symbol) ta_day = TrendAnalyser(fds, tig_day.macd) print(ta_day.getAnalysisResult())
def use_kline_analyze(): print('=' * 100, '\n') print("KlineAnalyze 的使用方法:\n") kline = get_kline(ts_code="000009.SZ", end_date="20200210", freq='30min', asset="I") ka = KlineAnalyze(kline, name="本级别", min_bi_k=5, max_raw_len=10000, verbose=False) print("分型:", ka.fx_list, "\n") print("线段:", ka.xd_list, "\n")
def get(self): ts_code = self.get_argument('ts_code') freq = self.get_argument('freq') trade_date = self.get_argument('trade_date') if trade_date == 'null': trade_date = datetime.now().date().__str__().replace("-", "") kline = get_gm_kline(symbol=ts_code, end_date=trade_date, freq=freq, k_count=3000) ka = KlineAnalyze(kline) kline = pd.DataFrame(ka.kline) kline = kline.fillna("") kline.loc[:, "dt"] = kline.dt.apply(str) columns = ["dt", "open", "close", "low", "high", "vol", 'fx_mark', 'fx', 'bi', 'xd'] self.finish({'kdata': kline[columns].values.tolist()})
def use_kline_analyze(): print('=' * 100, '\n') print("KlineAnalyze 的使用方法:\n") kline = get_kline(ts_code="000009.SZ", end_date="20200210", freq='30min', asset="I") ka = KlineAnalyze(kline, name="本级别", bi_mode="new", max_xd_len=20, ma_params=(5, 34, 120), verbose=False) print("分型:", ka.fx_list, "\n") print("线段:", ka.xd_list, "\n")
def use_kline_analyze(): print('=' * 100, '\n') print("KlineAnalyze 的使用方法:\n") ts_code = "300033.SZ" asset = "E" kline = get_kline("{}-{}".format(ts_code, asset), end_date="20201212", freq='30min', count=2000) ka = KlineAnalyze(kline, name="本级别", bi_mode="new", max_count=2000, use_ta=False, use_xd=True) print("分型:", ka.fx_list, "\n") print("线段:", ka.xd_list, "\n")
def use_kline_analyze(): kline = get_kline(symbol="000001.XSHG", end_date="20200616", freq="D", count=5000) # 输入K线即完成分析 ka = KlineAnalyze(kline, name="日线", min_bi_k=5, max_raw_len=10000, verbose=False) # 查看结果 print("分型识别结果:", ka.fx_list[-3:]) print("笔识别结果:", ka.bi_list[-3:]) print("线段识别结果:", ka.xd_list[-3:]) # 用图片或者HTML可视化 ka.to_image("test.png") ka.to_html("test.html")
def kline(): if request.method == "POST": data = json.loads(request.get_data(as_text=True)) elif request.method == "GET": data = request.args else: raise ValueError print(data) ts_code = data.get('ts_code') freq = data.get('freq') k = get_kline(symbol=ts_code, freq=freq, k_count=5000) ka = KlineAnalyze(k, bi_mode="new", xd_mode='strict') k = pd.DataFrame(ka.kline) k = k.fillna("") columns = ["dt", "open", "close", "low", "high", "vol", 'fx_mark', 'fx', 'bi', 'xd'] res = make_response(jsonify({'kdata': k[columns].values.tolist()})) res.headers['Access-Control-Allow-Origin'] = '*' res.headers['Access-Control-Allow-Method'] = '*' res.headers['Access-Control-Allow-Headers'] = '*' return res
def test_bei_chi(): df = get_kline(ts_code="000001.SH", end_dt="2020-04-28 15:00:00", freq='D', asset='I') ka = KlineAnalyze(df, name="日线") plot_ka(ka, file_image="test.jpg") # 线段背驰 zs1 = { "start_dt": '2018-07-26 15:00:00', "end_dt": '2018-10-19 15:00:00', "direction": "down" } zs2 = { "start_dt": '2018-01-29 15:00:00', "end_dt": '2018-07-06 15:00:00', "direction": "down" } assert is_bei_chi(ka, zs1, zs2, mode='xd', adjust=0.9) zs1 = { "start_dt": '2013-12-10 15:00:00', "end_dt": '2014-01-20 15:00:00', "direction": "down" } zs2 = { "start_dt": '2013-09-12 15:00:00', "end_dt": '2013-11-14 15:00:00', "direction": "down" } assert not is_bei_chi(ka, zs1, zs2, mode='xd', adjust=0.9) # 笔背驰 zs1 = {"start_dt": '2019-05-17 15:00:00', "end_dt": '2019-06-10 15:00:00'} zs2 = {"start_dt": '2019-04-08 15:00:00', "end_dt": '2019-05-10 15:00:00'} assert is_bei_chi(ka, zs1, zs2, mode='bi', adjust=0.9) zs1 = {"start_dt": '2018-09-28 15:00:00', "end_dt": '2018-10-19 15:00:00'} zs2 = {"start_dt": '2018-08-28 15:00:00', "end_dt": '2018-09-12 15:00:00'} assert not is_bei_chi(ka, zs1, zs2, mode='bi', adjust=0.9)
def enhanced_analysis(symbol=None, start_date='2020-05-20', end_date='2021-02-22'): kline_1min = get_local_kline(symbol=[symbol], end=end_date, freq='1min', start=start_date) kline_5min = get_local_kline(symbol=[symbol], end=end_date, freq='5min', start=start_date) kline_30min = get_local_kline(symbol=[symbol], end=end_date, freq='30min', start=start_date) kline_day = get_local_day_kline(symbol, end_date, start_date) if kline_5min is None or kline_1min is None or kline_30min is None or kline_day is None: return ka_1m = KlineAnalyze(kline_1min, bi_mode='old', name="1min", verbose=False) tig_5m = TechIndicatorGenerator(kline_5min, name="5min", verbose=False) tig_30m = TechIndicatorGenerator(kline_30min, name="30min", verbose=False) tig_day = TechIndicatorGenerator(kline_day, name='day', verbose=False) fds = get_fd_from_points(ka_1m.bi_list, ka_1m.macd, symbol=ka_1m.symbol) ta_1m = EnhancedTrendAnalyser(fds, ka_1m.macd) ta_5m = EnhancedTrendAnalyser(ta_1m.get_zoushi_list(), tig_5m.macd) ta_30m = EnhancedTrendAnalyser(ta_5m.get_zoushi_list(), tig_30m.macd) ta_day = EnhancedTrendAnalyser(ta_30m.get_zoushi_list(), tig_day.macd) judge_No2_buy_point(ta_day, ta_30m, end=end_date)
def use_kline_analyze(): kline = get_kline(symbol="000001.XSHG", end_date="20200616", freq="D", count=5000) # 输入K线即完成分析 ka = KlineAnalyze(kline, name="日线") # 查看结果 print("分型识别结果:", ka.fx[-3:]) print("笔识别结果:", ka.bi[-3:]) print("线段识别结果:", ka.xd[-3:]) print("中枢识别结果:", ka.zs[-1]) # 用图片或者HTML可视化 ka.to_image("test.png") ka.to_html("test.html")
def test_use_local_data(): kline_1min = get_local_kline(symbol=['300494'], end='2020-12-31', freq='1min', start='2020-01-01') kline_5min = get_local_kline(symbol=['300494'], end='2020-12-31', freq='5min', start='2020-01-01') # kline = get_local_day_kline(symbol=['000001'], end='2019-04-31', start='2018-01-01') # kline = QA_fetch_stock_week('000002', end='2019-12-13', start='2019-03-29') ka_1min = KlineAnalyze(kline_1min, name="1min", verbose=False) ka_5min = KlineAnalyze(kline_5min, name="5min", verbose=False) print("分型识别结果:", ka_1min.fx_list[-3:]) print("笔识别结果:", ka_1min.bi_list[-3:]) print("线段识别结果:", ka_1min.xd_list[-3:]) fds = get_fd_from_points(ka_1min.bi_list, ka_1min.macd, symbol=ka_1min.symbol) # zoushi = construct_zoushi(fds, ka.macd) ta_1min = TrendAnalyser(fds, ka_1min.macd) ta_5min = TrendAnalyser(ta_1min.get_zoushi_list(), ka_5min.macd) result = ta_5min.getAnalysisResult() bc = common_check_beichi(ka_1min.xd_list[-5:]) zx = find_zs_enhanced_v1(ka_1min.bi_list, ka_1min.macd) print("中枢识别结果:", zx) bei_chi = jsonpath.jsonpath(zx, '$..bei_chi') if isinstance(bei_chi, bool): bei_chi = pd.DataFrame() else: bei_chi = json_normalize(bei_chi) bei_chi.set_index('dt', inplace=True) third_buy = jsonpath.jsonpath(zx, '$..third_buy') if isinstance(third_buy, bool): third_buy = pd.DataFrame() else: third_buy = json_normalize(third_buy) third_buy['type'] = "3" second_buy = jsonpath.jsonpath(zx, '$..second_buy') if isinstance(second_buy, bool): second_buy = pd.DataFrame() else: second_buy = json_normalize(second_buy) second_buy['type'] = "2" first_buy = jsonpath.jsonpath(zx, '$..first_buy') if isinstance(first_buy, bool): first_buy = pd.DataFrame() else: first_buy = json_normalize(first_buy) first_buy['type'] = 1 # third_bs = jsonpath.jsonpath(zx, '$..third_bs_section') # third_bs = json_normalize(third_bs) # third_bs.set_index('dt', inplace=True) dfs = [first_buy, second_buy, third_buy] points = reduce(lambda left, right: pd.concat([left, right], axis=0, join='outer'), dfs) if len(points) == 0: pass else: points = pd.DataFrame(points).set_index('dt').sort_index() points = pd.concat([points, bei_chi], axis=1, join='outer') # points = pd.concat([points, third_bs], axis=1, join='outer') kline_1min = pd.DataFrame(kline_1min).set_index(['dt']) result = pd.concat([kline_1min, points], axis=1, join='outer').reset_index() result = result.fillna(0).set_index(['symbol', 'dt']) print(result) # 用图片或者HTML可视化 ka_1min.to_image("test.png")
import sys import warnings from cobra.data.kline import get_kline sys.path.insert(0, '.') sys.path.insert(0, '..') import czsc from czsc import KlineAnalyze from czsc.analyze import is_bei_chi, find_zs warnings.warn(f"czsc version is {czsc.__version__}") df = get_kline(ts_code="000001.SH", end_dt="2020-04-28 15:00:00", freq='D', asset='I') ka = KlineAnalyze(df, name="日线", bi_mode='old') print(ka) def test_kline_analyze(): assert ka.bi[-1]['fx_mark'] == 'g' assert ka.xd[-1]['fx_mark'] == 'd' # 测试背驰识别 assert ka.bi_bei_chi() assert ka.xd_bei_chi() print(ka.zs[-2]) ka.to_html("kline.html") ka.to_image("kline.png")