def abc(): ts_code='002713.SZ' csv_file = '{0}.csv'.format(ts_code) render_html = '{0}.html'.format(ts_code) end_date = datetime.now().strftime('%Y%m%d') df = None if not os.path.exists(csv_file): MY_TOKEN = '190040a13eb5b092ca76fa003f58d693c9121e0fc621f6d2ad221468' ts.set_token(MY_TOKEN) pro = ts.pro_api() df1 = pro.daily(ts_code=ts_code, start_date='20140101', end_date=end_date) df = df1.sort_values(by=['trade_date']) df.reset_index(level=0, inplace=True) df.drop(['index'], axis=1, inplace=True) print(df) df.to_csv(csv_file) if not df is None: df = pd.read_csv(csv_file) date = df.trade_date.tolist() data = [] for idx in df.index : row=[df.iloc[idx]['open'],df.iloc[idx]['close'],df.iloc[idx]['low'],df.iloc[idx]['high']] data.append(row) WIDTH = 1100 HEIGHT = 550 chart_init = { "width": WIDTH, "height": HEIGHT, } kline = Kline() kline.add_xaxis(date).add_yaxis('日K', data) kline.set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), datazoom_opts=[opts.DataZoomOpts()], # title_opts=opts.TitleOpts(title='日K线图:{0}'.format(ts_code)), ) # kline.add_yaxis( # "日K", # date, # data, # mark_point=["max"], # is_datazoom_show=True, # ) # 生成一个名为 render.html 的文件 kline.render(render_html) kline.render_notebook() # kline.render('a.html') # 在jupyter中使用,只需要使用xxx.render_notebook() 方法即可在Jupyter中显示图
def gen_kline(df1): dt_list = list(df1['datetime']) kline_data = df1.apply(lambda record: [ float(record['open']), float(record['close']), float(record['low']), float(record['high']) ], axis=1).tolist() #kline = Kline(init_opts=opts.InitOpts(width='1000px')) kline = Kline() kline.add_xaxis(list(df1['datetime'])) kline.add_yaxis('日K', kline_data) kline.set_global_opts( title_opts=opts.TitleOpts(title='K线'), datazoom_opts=[ opts.DataZoomOpts( is_show=True, type_="slider", xaxis_index=[0, 1, 2], range_start=0, range_end=100, ), opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0, 1, 2], range_start=0, range_end=100, ), ], legend_opts=opts.LegendOpts(is_show=False), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1))), tooltip_opts=opts.TooltipOpts( trigger="axis", axis_pointer_type="cross", background_color="rgba(245, 245, 245, 0.8)", border_width=1, border_color="#ccc", textstyle_opts=opts.TextStyleOpts(color="#000"), ), axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), ) return kline
def kline(self, data, title="K线图", open="open", close="close", high="high", low="low", date=None, blist=None, slist=None, positlist=None): if type(data) != pd.DataFrame: return None if data.empty: return None if date == None: xaxis = pd.Series( data.index).apply(lambda x: x.strftime("%Y-%m-%d")).to_list() else: xaxis = pd.Series(data["date"]).apply( lambda x: x.strftime("%Y-%m-%d")).to_list() yaxis = data[[open, close, high, low]].values.tolist() chart = Kline(init_opts=opts.InitOpts()) chart.add_xaxis(xaxis) chart.add_yaxis( "kline", yaxis, itemstyle_opts=opts.ItemStyleOpts( color="#ec0000", color0="#00da3c", border_color="#8A0000", border_color0="#008F28", ), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_="max", value_dim="close")]), markpoint_opts=bsopts(blist=blist, slist=slist)) chart.set_series_opts(markarea_opts=opts.MarkAreaOpts( data=positionsArea(positlist))) # chart = maline(data).overlap(chart) # chart.set_global_opts( # xaxis_opts=opts.AxisOpts(is_scale=True), # yaxis_opts=opts.AxisOpts( # is_scale=True, # splitarea_opts=opts.SplitAreaOpts( # is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) # ), # ), # # datazoom_opts=datazoom, # title_opts=opts.TitleOpts(title=title), # ) return chart
def draw_Kline(self): """ 画股票的K线图,需要传入四个数据 分别是["open", "close", "high", "low"] :return: 画出图像 """ Df_s1 = Read_One_Stock(self.SC).select_col("open", "high", "low", "close", "vol", "amount") length = Df_s1.shape[0] Df_s1.sort_values("trade_date", inplace=True) Df_s1.index = list(range(length)) price = np.array(Df_s1[["open", "close", "high", "low"]]).tolist() date = np.array(Df_s1["trade_date"], dtype=np.string_).tolist() ma_value_5 = calculate_ma_n(list(Df_s1['close']), 5) ma_value_10 = calculate_ma_n(list(Df_s1['close']), 10) ma_value = np.array([ma_value_5, ma_value_10]).tolist() kline = Kline() kline.set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), datazoom_opts=[opts.DataZoomOpts()], title_opts=opts.TitleOpts(title="K-Line of {}".format(self.SC)), ) kline.add_xaxis(date) kline.add_yaxis('K-Line', price) line = Line() line.add_xaxis(date) line.add_yaxis(series_name="ma5", y_axis=ma_value[0], label_opts=opts.LabelOpts(is_show=False)) line.add_yaxis(series_name="ma10", y_axis=ma_value[1], label_opts=opts.LabelOpts(is_show=False)) line.set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), datazoom_opts=[opts.DataZoomOpts()], title_opts=opts.TitleOpts(title="")) kline.overlap(line) kline.render("./Plots/{} Candle Plot.html".format(self.SC))
def _stock_(): stock_code = '000001' freq = 'day' # stock_df = download_index_bars(stock_code, freq=freq) # print(stock_df) csv = os.path.join(ct.DATA_DIR, 'index_%s_%s.csv' % (stock_code, freq)) stock_df = pd.read_csv(csv) html = os.path.join(ct.HTML_DIR, 'index_%s_%s.html' % (stock_code, freq)) stock_df.to_csv(csv, index=False) from pyecharts import options as opts from pyecharts.charts import Kline WIDTH = 1100 HEIGHT = 550 chart_init = { "width": WIDTH, "height": HEIGHT, } kline = Kline() date = stock_df.datetime.tolist() data = [] for index, row in stock_df.iterrows(): item = [row.open, row.close, row.low, row.high] data.append(item) print(data) kline.add_xaxis(date).add_yaxis('日K', data) kline.set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), datazoom_opts=[opts.DataZoomOpts()], # title_opts=opts.TitleOpts(title='日K线图:{0}'.format(ts_code)), ) # kline.add_yaxis( # "日K", # date, # data, # mark_point=["max"], # is_datazoom_show=True, # ) # 生成一个名为 render.html 的文件 kline.render(html)
def gen_kline_two(df1): dt_list = list(df1['datetime']) kline_data = df1.apply(lambda record: [float(record['open']), float(record['close']), float(record['low']), float(record['high'])], axis=1).tolist() kline = Kline() kline.add_xaxis( list(df1['datetime']) ) kline.add_yaxis('y', kline_data, xaxis_index=1,yaxis_index=1,) kline.set_global_opts(yaxis_opts=opts.AxisOpts(is_scale=True,splitarea_opts=opts.SplitAreaOpts(is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)) ), legend_opts=opts.LegendOpts(is_show=True,pos_right="40%") #xaxis_opts=opts.AxisOpts(type_='time')) ) return kline
def kline(data, buy=[], sell=[], zone=[], title="K线图", height="250px"): if data.empty: return Kline(init_opts=opts.InitOpts(width="100%", height=height)) xaxis = pd.Series( data.index).apply(lambda x: x.strftime("%Y-%m-%d")).to_list() yaxis = data[["open", "close", "high", "low"]].values.tolist() chart = Kline(init_opts=opts.InitOpts(width="100%", height=height)) chart.add_xaxis(xaxis) chart.add_yaxis( "kline", yaxis, itemstyle_opts=opts.ItemStyleOpts( color="#ec0000", color0="#00da3c", border_color="#8A0000", border_color0="#008F28", ), # markline_opts=opts.MarkLineOpts( # data=[opts.MarkLineItem(type_="max", value_dim="close")] # ), markpoint_opts=opts.MarkPointOpts( data=buy.apply(buypoint, axis=1).values.tolist() + (sell.apply(sellpoint, axis=1).values.tolist())), ) chart.set_series_opts(markarea_opts=opts.MarkAreaOpts( data=zone.apply(bszone, axis=1).values.tolist())) # chart = chart.overlap(maline(data)) # chart.set_global_opts( # xaxis_opts=opts.AxisOpts(is_scale=True), # yaxis_opts=opts.AxisOpts( # is_scale=True, # splitarea_opts=opts.SplitAreaOpts( # is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) # ), # ), # datazoom_opts=[opts.DataZoomOpts( # pos_bottom="0px", # range_start= 100.00-(5000.00/len(xaxis)), # range_end= 100.00, # )], # title_opts=opts.TitleOpts(title=title), # ) return chart
def kline(data, title="K线图", height="250px"): # logging.debug(data) if data.empty: return Kline(init_opts=opts.InitOpts(width="100%", height=height)) xaxis = pd.Series( data.index).apply(lambda x: x.strftime("%Y-%m-%d")).to_list() yaxis = data[["open", "close", "high", "low"]].values.tolist() chart = Kline(init_opts=opts.InitOpts(width="100%", height=height)) chart.add_xaxis(xaxis) chart.add_yaxis( "kline", yaxis, itemstyle_opts=opts.ItemStyleOpts( color="#ec0000", color0="#00da3c", border_color="#8A0000", border_color0="#008F28", ), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_="max", value_dim="close")]), markpoint_opts=opts.MarkPointOpts( data=bspoint(data), label_opts=opts.LabelOpts( position="top", color="#000", font_size=8, ), ), ) chart.set_series_opts(markarea_opts=opts.MarkAreaOpts(data=bsArea)) chart = maline(data).overlap(chart) chart.set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), datazoom_opts=datazoom, title_opts=opts.TitleOpts(title=title), ) return chart
def gen_kline(df1): dt_list = list(df1['datetime']) kline_data = df1.apply(lambda record: [float(record['open']), float(record['close']), float(record['low']), float(record['high'])], axis=1).tolist() #kline = Kline(init_opts=opts.InitOpts(width='1000px')) kline = Kline() kline.add_xaxis( list(df1['datetime']) ) kline.add_yaxis('日K', kline_data) kline.set_global_opts(title_opts=opts.TitleOpts(title='Kline-基本示例'), datazoom_opts=[opts.DataZoomOpts(is_show=True,type_="slider",xaxis_index=[0,1,2],range_start=98,range_end=100,), opts.DataZoomOpts(is_show=False,type_="inside",xaxis_index=[0,1,2],range_start=98,range_end=100,), ], legend_opts=opts.LegendOpts(is_show=False), yaxis_opts=opts.AxisOpts(is_scale=True,splitarea_opts=opts.SplitAreaOpts(is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)) ), # tooltip_opts=opts.TooltipOpts( # trigger="axis", # axis_pointer_type="cross", # background_color="rgba(245, 245, 245, 0.8)", # border_width=1, # border_color="#ccc", # textstyle_opts=opts.TextStyleOpts(color="#000"), # ), # visualmap_opts=opts.VisualMapOpts( # is_show=False, # dimension=2, # series_index=5, # is_piecewise=True, # pieces=[ # {"value": 1, "color": "#ec0000"}, # {"value": -1, "color": "#00da3c"}, ], # ), # axispointer_opts=opts.AxisPointerOpts( # is_show=True, # link=[{"xAxisIndex": "all"}], # label=opts.LabelOpts(background_color="#777"), # ), # brush_opts=opts.BrushOpts( # x_axis_index="all", # brush_link="all", # out_of_brush={"colorAlpha": 0.1}, # brush_type="lineX", # ), ) return kline
def gen_kline(self, df1, symbol): df1['datetime'] = df1['date'] dt_list = list(df1['datetime']) k_plot_value = df1.apply( lambda record: [record['open'], record['close'], record['low'], record['high']], axis=1).tolist() #print(k_plot_value) kline = Kline(init_opts=opts.InitOpts( width='1500px', height="700px", )) kline.add_xaxis(dt_list) kline.add_yaxis(symbol, k_plot_value) kline.set_global_opts( title_opts=opts.TitleOpts(title='日线'), datazoom_opts=[ opts.DataZoomOpts( is_show=True, type_="slider", xaxis_index=[0, 1], range_start=0, range_end=100, ), opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0, 1], range_start=0, range_end=100, ), ], tooltip_opts=opts.TooltipOpts(axis_pointer_type="cross"), axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], ), ) return kline
def gen_kline_one(df1): dt_list = list(df1['datetime']) kline_data = df1.apply(lambda record: [float(record['open']), float(record['close']), float(record['low']), float(record['high'])], axis=1).tolist() kline = Kline(init_opts=opts.InitOpts(width='1500px')) kline.add_xaxis( list(df1['datetime']) ) kline.add_yaxis('m', kline_data) kline.set_global_opts(title_opts=opts.TitleOpts(title='K线'), #datazoom_opts=[opts.DataZoomOpts()], #xaxis_opts=opts.AxisOpts(type_='time')) yaxis_opts=opts.AxisOpts(is_scale=True,splitarea_opts=opts.SplitAreaOpts(is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)) ), datazoom_opts=[opts.DataZoomOpts(is_show=True,type_="slider",xaxis_index=[0,1],range_start=0,range_end=100,), opts.DataZoomOpts(is_show=False,type_="inside",xaxis_index=[0,1],range_start=0,range_end=100,), ], tooltip_opts=opts.TooltipOpts( trigger="axis",axis_pointer_type="cross" ), #axispointer_opts=opts.AxisPointerOpts(is_show=True, link=[{"xAxisIndex": "all"}], ), ) return kline
def gen_kline(df1, symbol): dt_list = list(df1['datetime']) #print(dt_list) k_plot_value = df1.apply( lambda record: [record['open'], record['close'], record['low'], record['high']], axis=1).tolist() #print(k_plot_value) kline = Kline(init_opts=opts.InitOpts( width='1500px', height="700px", )) kline.add_xaxis(list(df1['datetime'])) kline.add_yaxis(symbol, k_plot_value) kline.set_global_opts( title_opts=opts.TitleOpts(title='K线'), datazoom_opts=[opts.DataZoomOpts()], ) #xaxis_opts=opts.AxisOpts(type_='time')) return kline
def view_kline(time, data, title=None): """K线图""" k = Kline(init_opts=opts.InitOpts(width="1800px", height="900px", theme="dark")) # 添加x轴数据 k.add_xaxis(time) # 添加图例和y轴数据,颜色 红涨绿跌 k.add_yaxis("kline", data, itemstyle_opts=opts.ItemStyleOpts( color="#db6969", color0="#02691e", border_color="#8A0000", border_color0="#008F28", )) # 是否是脱离0值比例,双数值轴的散点图中比较有用 k.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True)) k.set_global_opts(yaxis_opts=opts.AxisOpts(is_scale=True)) if title: k.set_global_opts(title_opts=opts.TitleOpts(title=title)) # 添加滑动条,可左右滑动 k.set_global_opts(datazoom_opts=opts.DataZoomOpts(type_="inside")) # 十字星 k.set_global_opts(tooltip_opts=opts.TooltipOpts(axis_pointer_type="cross")) return k
from pyecharts.charts import Line, Kline, Bar import pandas as pd from datetime import datetime, timedelta fn = 'bar/min1_SR001.csv' df1 = pd.read_csv(fn) df1['datetime'] = df1['date'] + ' ' + df1['time'] print(df1.head()) dt_list = list(df1['datetime']) #print(dt_list) k_plot_value = df1.apply( lambda record: [record['open'], record['close'], record['low'], record['high']], axis=1).tolist() #print(k_plot_value) kline = Kline(init_opts=opts.InitOpts(width='1500px')) kline.add_xaxis(list(df1['datetime'])) kline.add_yaxis('日K', k_plot_value) kline.set_global_opts( title_opts=opts.TitleOpts(title='Kline-基本示例'), datazoom_opts=[opts.DataZoomOpts()], ) #xaxis_opts=opts.AxisOpts(type_='time')) kline.render() # if __name__ == '__main__': # pass
def kline_pro(kline: List[dict], fx: List[dict] = None, xd=None, bs: List[dict] = None, title: str = "缠中说禅K线分析", width: str = "1400px", height: str = '580px') -> Grid: """绘制缠中说禅K线分析结果 :param kline: K线 :param fx: 分型识别结果 :param bi: 笔识别结果 :param xd: 线段识别结果 :param zs: 中枢 :param bs: 买卖点 :param title: 图表标题 :param width: 图表宽度 :param height: 图表高度 :return: 用Grid组合好的图表 """ # 配置项设置 # ------------------------------------------------------------------------------------------------------------------ bg_color = "#1f212d" # 背景 up_color = "#F9293E" down_color = "#00aa3b" init_opts = opts.InitOpts(bg_color=bg_color, width=width, height=height, animation_opts=opts.AnimationOpts(False)) title_opts = opts.TitleOpts( title=title, pos_top="1%", title_textstyle_opts=opts.TextStyleOpts(color=up_color, font_size=20), subtitle_textstyle_opts=opts.TextStyleOpts(color=down_color, font_size=12)) label_not_show_opts = opts.LabelOpts(is_show=False) legend_not_show_opts = opts.LegendOpts(is_show=False) red_item_style = opts.ItemStyleOpts(color=up_color) green_item_style = opts.ItemStyleOpts(color=down_color) k_style_opts = opts.ItemStyleOpts(color=up_color, color0=down_color, border_color=up_color, border_color0=down_color, opacity=0.8) legend_opts = opts.LegendOpts(is_show=True, pos_top="1%", pos_left="30%", item_width=14, item_height=8, textstyle_opts=opts.TextStyleOpts( font_size=12, color="#0e99e2")) brush_opts = opts.BrushOpts(tool_box=["rect", "polygon", "keep", "clear"], x_axis_index="all", brush_link="all", out_of_brush={"colorAlpha": 0.1}, brush_type="lineX") axis_pointer_opts = opts.AxisPointerOpts(is_show=True, link=[{ "xAxisIndex": "all" }]) range_start = int(100 - 216 / len(kline) * 100) dz_inside = opts.DataZoomOpts(False, "inside", xaxis_index=[0, 1, 2], range_start=range_start, range_end=100) dz_slider = opts.DataZoomOpts(True, "slider", xaxis_index=[0, 1, 2], pos_top="96%", pos_bottom="0%", range_start=range_start, range_end=100) yaxis_opts = opts.AxisOpts(is_scale=True, axislabel_opts=opts.LabelOpts( color="#c7c7c7", font_size=8, position="inside")) grid0_xaxis_opts = opts.AxisOpts( type_="category", grid_index=0, axislabel_opts=label_not_show_opts, split_number=20, min_="dataMin", max_="dataMax", is_scale=True, boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False)) tool_tip_opts = opts.TooltipOpts( trigger="axis", axis_pointer_type="cross", background_color="rgba(245, 245, 245, 0.8)", border_width=1, border_color="#ccc", position=JsCode(""" function (pos, params, el, elRect, size) { var obj = {top: 10}; obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30; return obj; } """), textstyle_opts=opts.TextStyleOpts(color="#000"), ) # 数据预处理 # ------------------------------------------------------------------------------------------------------------------ # dts = [x.get('dt', x['date']) for x in kline] try: dts = [x['date'] for x in kline] except: dts = [x['dt'] for x in kline] # k_data = [[x['open'], x['close'], x['low'], x['high']] for x in kline] k_data = [ opts.CandleStickItem( name=i, value=[x['open'], x['close'], x['low'], x['high']]) for i, x in enumerate(kline) ] vol = [] for i, row in enumerate(kline): item_style = red_item_style if row['close'] > row[ 'open'] else green_item_style bar = opts.BarItem(name=i, value=row['volume'], itemstyle_opts=item_style, label_opts=label_not_show_opts) vol.append(bar) close = np.array([x['close'] for x in kline], dtype=np.double) diff, dea, macd = MACD(close) ma5 = SMA(close, timeperiod=5) ma34 = SMA(close, timeperiod=34) ma55 = SMA(close, timeperiod=55) ma233 = SMA(close, timeperiod=233) macd_bar = [] for i, v in enumerate(macd.tolist()): item_style = red_item_style if v > 0 else green_item_style bar = opts.BarItem(name=i, value=round(v, 4), itemstyle_opts=item_style, label_opts=label_not_show_opts) macd_bar.append(bar) diff = diff.round(4) dea = dea.round(4) # K 线主图 # ------------------------------------------------------------------------------------------------------------------ chart_k = Kline() chart_k.add_xaxis(xaxis_data=dts) chart_k.add_yaxis(series_name="Kline", y_axis=k_data, itemstyle_opts=k_style_opts) chart_k.set_global_opts(legend_opts=legend_opts, datazoom_opts=[dz_inside, dz_slider], yaxis_opts=yaxis_opts, tooltip_opts=tool_tip_opts, axispointer_opts=axis_pointer_opts, brush_opts=brush_opts, title_opts=title_opts, xaxis_opts=grid0_xaxis_opts) if xd: index = 0 zs_colors = [ "yellow", "white", '#f034c1', "#7944b7", "#468b58", "#c17f2f", "#9EA0A1" ] data = [] temp_xd = xd while temp_xd: zs_color = zs_colors[index % len(zs_colors)] data = data + [ opts.MarkAreaItem( name='XD{}'.format(index), x=(x['xd_list'][0]['date'], x['xd_list'][-1]['date']), y=(x['ZG']['value'], x['ZD']['value']), label_opts=opts.LabelOpts(color=zs_color), itemstyle_opts=opts.ItemStyleOpts( color=zs_color, opacity=0.2, )) for x in temp_xd.zs_list ] temp_xd = temp_xd.next index = index + 1 chart_k.set_series_opts( markarea_opts=opts.MarkAreaOpts(is_silent=True, data=data)) # 均线图 # ------------------------------------------------------------------------------------------------------------------ chart_ma = Line() chart_ma.add_xaxis(xaxis_data=dts) ma_keys = {"MA5": ma5, "MA34": ma34, "MA55": ma55, "MA233": ma233} ma_colors = ["#39afe6", "#da6ee8", "#A02128", "#00940b"] for i, (name, ma) in enumerate(ma_keys.items()): chart_ma.add_yaxis(series_name=name, y_axis=ma, is_smooth=True, is_selected=False, symbol_size=0, label_opts=label_not_show_opts, linestyle_opts=opts.LineStyleOpts( opacity=0.8, width=1.0, color=ma_colors[i])) chart_ma.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_ma) # 缠论结果 # ------------------------------------------------------------------------------------------------------------------ if fx: try: fx_dts = [x['date'] for x in fx] except: fx_dts = [x['dt'] for x in fx] fx_val = [x['value'] for x in fx] chart_fx = Scatter() chart_fx.add_xaxis(fx_dts) chart_fx.add_yaxis(series_name="FX", y_axis=fx_val, is_selected=False, symbol="circle", symbol_size=6, label_opts=label_not_show_opts, itemstyle_opts=opts.ItemStyleOpts( color="rgba(152, 147, 193, 1.0)", )) chart_fx.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_fx) if xd: index = 0 xd_colors = zs_colors while xd: xd_dts = [x['date'] for x in xd] xd_val = [x['value'] for x in xd] chart_xd = Line() chart_xd.add_xaxis(xd_dts) xd_color = xd_colors[index % len(xd_colors)] chart_xd.add_yaxis( series_name="XD{}".format(index), y_axis=xd_val, is_selected=True, symbol="triangle", symbol_size=10, linestyle_opts=opts.LineStyleOpts(color=xd_color, width=index + 1, type_="solid"), itemstyle_opts=opts.ItemStyleOpts(color=xd_color)) chart_xd.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_xd) xd = xd.next index = index + 1 if bs: b_dts = [x['date'] for x in bs if x['bs'] == 'buy'] if len(b_dts) > 0: b_val = [x['value'] for x in bs if x['bs'] == 'buy'] chart_b = Scatter() chart_b.add_xaxis(b_dts) chart_b.add_yaxis(series_name="BUY", y_axis=b_val, is_selected=False, symbol="arrow", symbol_size=8, itemstyle_opts=opts.ItemStyleOpts( color="#f31e1e", )) chart_b.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_b) s_dts = [x['date'] for x in bs if x['bs'] == 'sell'] if len(s_dts) > 0: s_val = [x['value'] for x in bs if x['bs'] == 'sell'] chart_s = Scatter() chart_s.add_xaxis(s_dts) chart_s.add_yaxis(series_name="SELL", y_axis=s_val, is_selected=False, symbol="pin", symbol_size=12, itemstyle_opts=opts.ItemStyleOpts( color="#45b97d", )) chart_s.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_s) # 成交量图 # ------------------------------------------------------------------------------------------------------------------ chart_vol = Bar() chart_vol.add_xaxis(dts) chart_vol.add_yaxis(series_name="Volume", y_axis=vol, bar_width='60%') chart_vol.set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=True, font_size=8, color="#9b9da9"), ), yaxis_opts=yaxis_opts, legend_opts=legend_not_show_opts, ) # MACD图 # ------------------------------------------------------------------------------------------------------------------ chart_macd = Bar() chart_macd.add_xaxis(dts) chart_macd.add_yaxis(series_name="MACD", y_axis=macd_bar, bar_width='60%') chart_macd.set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( grid_index=2, split_number=4, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=True, color="#c7c7c7"), ), legend_opts=opts.LegendOpts(is_show=False), ) line = Line() line.add_xaxis(dts) line.add_yaxis(series_name="DIFF", y_axis=diff, label_opts=label_not_show_opts, is_symbol_show=False, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color="#da6ee8")) line.add_yaxis(series_name="DEA", y_axis=dea, label_opts=label_not_show_opts, is_symbol_show=False, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color="#39afe6")) chart_macd = chart_macd.overlap(line) grid0_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="12%", height="58%") grid1_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="74%", height="8%") grid2_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="86%", height="10%") grid_chart = Grid(init_opts) grid_chart.add(chart_k, grid_opts=grid0_opts) grid_chart.add(chart_vol, grid_opts=grid1_opts) grid_chart.add(chart_macd, grid_opts=grid2_opts) return grid_chart
#------------------------------------------------------------------------------------------------------------------- df1 = pd.read_csv('F:/Stock/Data_Day/' + df.iloc[0, 1] + ".csv") df1 = df1.sort_index(ascending=False).reset_index(drop=True) date1 = df1.xs('Date Time', axis=1).tolist() data1 = [] vol1 = [] for idx1 in df1.index: row1 = [ df1.iloc[idx1]['Open'], df1.iloc[idx1]['Close'], df1.iloc[idx1]['Low'], df1.iloc[idx1]['High'] ] row2 = df1.iloc[idx1]['Volume'] data1.append(row1) vol1.append(row2) kline1.add_xaxis(date1) kline1.add_yaxis(str1, data1) #------------------------------------------------------------------------------------------------------------------- df2 = pd.read_csv('F:/Stock/Data_Day/' + df.iloc[1, 1] + ".csv") df2 = df2.sort_index(ascending=False).reset_index(drop=True) date2 = df2.xs('Date Time', axis=1).tolist() data2 = [] vol2 = [] for idx2 in df2.index: row3 = [ df2.iloc[idx2]['Open'], df2.iloc[idx2]['Close'], df2.iloc[idx2]['Low'], df2.iloc[idx2]['High'] ] row4 = df2.iloc[idx2]['Volume']
def kline_pro(kline: List[dict], ma: List[dict], macd: List[dict], fx: List[dict] = None, bi: List[dict] = None, xd: List[dict] = None, bs: List[dict] = None, title: str = "缠中说禅K线分析", width: str = "1200px", height: str = '680px') -> Grid: """绘制缠中说禅K线分析结果 :param kline: K线 :param ma: 均线 :param macd: MACD :param fx: 分型识别结果 :param bi: 笔识别结果 :param xd: 线段识别结果 :param bs: 买卖点 :param title: 图表标题 :param width: 图表宽度 :param height: 图表高度 :return: 用Grid组合好的图表 """ # 配置项设置 # ------------------------------------------------------------------------------------------------------------------ bg_color = "#1f212d" # 背景 up_color = "#F9293E" down_color = "#00aa3b" init_opts = opts.InitOpts(bg_color=bg_color, width=width, height=height, animation_opts=opts.AnimationOpts(False)) title_opts = opts.TitleOpts( title=title, pos_top="1%", title_textstyle_opts=opts.TextStyleOpts(color=up_color, font_size=20), subtitle_textstyle_opts=opts.TextStyleOpts(color=down_color, font_size=12)) label_not_show_opts = opts.LabelOpts(is_show=False) legend_not_show_opts = opts.LegendOpts(is_show=False) red_item_style = opts.ItemStyleOpts(color=up_color) green_item_style = opts.ItemStyleOpts(color=down_color) k_style_opts = opts.ItemStyleOpts(color=up_color, color0=down_color, border_color=up_color, border_color0=down_color, opacity=0.8) legend_opts = opts.LegendOpts(is_show=True, pos_top="1%", pos_left="30%", item_width=14, item_height=8, textstyle_opts=opts.TextStyleOpts( font_size=12, color="#0e99e2")) brush_opts = opts.BrushOpts(tool_box=["rect", "polygon", "keep", "clear"], x_axis_index="all", brush_link="all", out_of_brush={"colorAlpha": 0.1}, brush_type="lineX") axis_pointer_opts = opts.AxisPointerOpts(is_show=True, link=[{ "xAxisIndex": "all" }]) dz_inside = opts.DataZoomOpts(False, "inside", xaxis_index=[0, 1, 2]) dz_slider = opts.DataZoomOpts(True, "slider", xaxis_index=[0, 1, 2], pos_top="96%", pos_bottom="0%") yaxis_opts = opts.AxisOpts(is_scale=True, axislabel_opts=opts.LabelOpts( color="#c7c7c7", font_size=8, position="inside")) grid0_xaxis_opts = opts.AxisOpts( type_="category", grid_index=0, axislabel_opts=label_not_show_opts, split_number=20, min_="dataMin", max_="dataMax", is_scale=True, boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False)) tool_tip_opts = opts.TooltipOpts( trigger="axis", axis_pointer_type="cross", background_color="rgba(245, 245, 245, 0.8)", border_width=1, border_color="#ccc", position=JsCode(""" function (pos, params, el, elRect, size) { var obj = {top: 10}; obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30; return obj; } """), textstyle_opts=opts.TextStyleOpts(color="#000"), ) # 数据预处理 # ------------------------------------------------------------------------------------------------------------------ dts = [x['dt'] for x in kline] k_data = [[x['open'], x['close'], x['low'], x['high']] for x in kline] vol = [] for row in kline: item_style = red_item_style if row['close'] > row[ 'open'] else green_item_style bar = opts.BarItem(value=row['vol'], itemstyle_opts=item_style, label_opts=label_not_show_opts) vol.append(bar) macd_bar = [] for row in macd: item_style = red_item_style if row['macd'] > 0 else green_item_style bar = opts.BarItem(value=round(row['macd'], 4), itemstyle_opts=item_style, label_opts=label_not_show_opts) macd_bar.append(bar) diff = [round(x['diff'], 4) for x in macd] dea = [round(x['dea'], 4) for x in macd] # K 线主图 # ------------------------------------------------------------------------------------------------------------------ chart_k = Kline() chart_k.add_xaxis(xaxis_data=dts) chart_k.add_yaxis(series_name="Kline", y_axis=k_data, itemstyle_opts=k_style_opts) chart_k.set_global_opts(legend_opts=legend_opts, datazoom_opts=[dz_inside, dz_slider], yaxis_opts=yaxis_opts, tooltip_opts=tool_tip_opts, axispointer_opts=axis_pointer_opts, brush_opts=brush_opts, title_opts=title_opts, xaxis_opts=grid0_xaxis_opts) # 均线图 # ------------------------------------------------------------------------------------------------------------------ chart_ma = Line() chart_ma.add_xaxis(xaxis_data=dts) ma_keys = [x for x in ma[0].keys() if "ma" in x][:3] ma_colors = ["#39afe6", "#da6ee8", "#00940b"] for i, k in enumerate(ma_keys): y_data = [x[k] for x in ma] chart_ma.add_yaxis(series_name=k.upper(), y_axis=y_data, is_smooth=True, is_selected=False, symbol_size=0, label_opts=label_not_show_opts, linestyle_opts=opts.LineStyleOpts( opacity=0.8, width=1.0, color=ma_colors[i])) chart_ma.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_ma) # 缠论结果 # ------------------------------------------------------------------------------------------------------------------ if fx: fx_dts = [x['dt'] for x in fx] fx_val = [x['fx'] for x in fx] chart_fx = Scatter() chart_fx.add_xaxis(fx_dts) chart_fx.add_yaxis(series_name="FX", y_axis=fx_val, is_selected=False, symbol="circle", symbol_size=6, label_opts=label_not_show_opts, itemstyle_opts=opts.ItemStyleOpts( color="rgba(152, 147, 193, 1.0)", )) chart_fx.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_fx) if bi: bi_dts = [x['dt'] for x in bi] bi_val = [x['bi'] for x in bi] chart_bi = Scatter() chart_bi.add_xaxis(bi_dts) chart_bi.add_yaxis(series_name="BI", y_axis=bi_val, is_selected=True, symbol="diamond", symbol_size=10, label_opts=label_not_show_opts, itemstyle_opts=opts.ItemStyleOpts( color="rgba(184, 117, 225, 1.0)", )) chart_bi.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_bi) if xd: xd_dts = [x['dt'] for x in xd] xd_val = [x['xd'] for x in xd] chart_xd = Scatter() chart_xd.add_xaxis(xd_dts) chart_xd.add_yaxis(series_name="XD", y_axis=xd_val, is_selected=True, symbol="triangle", symbol_size=10, itemstyle_opts=opts.ItemStyleOpts( color="rgba(37, 141, 54, 1.0)", )) chart_xd.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_xd) if bs: b_dts = [x['dt'] for x in bs if x['mark'] == 'buy'] if len(b_dts) > 0: b_val = [x['buy'] for x in bs if x['mark'] == 'buy'] chart_b = Scatter() chart_b.add_xaxis(b_dts) chart_b.add_yaxis(series_name="BUY", y_axis=b_val, is_selected=False, symbol="arrow", symbol_size=8, itemstyle_opts=opts.ItemStyleOpts( color="#f31e1e", )) chart_b.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_b) s_dts = [x['dt'] for x in bs if x['mark'] == 'sell'] if len(s_dts) > 0: s_val = [x['sell'] for x in bs if x['mark'] == 'sell'] chart_s = Scatter() chart_s.add_xaxis(s_dts) chart_s.add_yaxis(series_name="SELL", y_axis=s_val, is_selected=False, symbol="pin", symbol_size=12, itemstyle_opts=opts.ItemStyleOpts( color="#45b97d", )) chart_s.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_s) # 成交量图 # ------------------------------------------------------------------------------------------------------------------ chart_vol = Bar() chart_vol.add_xaxis(dts) chart_vol.add_yaxis(series_name="Volume", y_axis=vol, bar_width='60%') chart_vol.set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=True, font_size=8, color="#9b9da9"), ), yaxis_opts=yaxis_opts, legend_opts=legend_not_show_opts, ) # MACD图 # ------------------------------------------------------------------------------------------------------------------ chart_macd = Bar() chart_macd.add_xaxis(dts) chart_macd.add_yaxis(series_name="MACD", y_axis=macd_bar, bar_width='60%') chart_macd.set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( grid_index=2, split_number=4, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=True, color="#c7c7c7"), ), legend_opts=opts.LegendOpts(is_show=False), ) line = Line() line.add_xaxis(dts) line.add_yaxis(series_name="DIFF", y_axis=diff, label_opts=label_not_show_opts, is_symbol_show=False, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color="#da6ee8")) line.add_yaxis(series_name="DEA", y_axis=dea, label_opts=label_not_show_opts, is_symbol_show=False, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color="#39afe6")) chart_macd = chart_macd.overlap(line) grid0_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="12%", height="58%") grid1_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="74%", height="8%") grid2_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="86%", height="10%") grid_chart = Grid(init_opts) grid_chart.add(chart_k, grid_opts=grid0_opts) grid_chart.add(chart_vol, grid_opts=grid1_opts) grid_chart.add(chart_macd, grid_opts=grid2_opts) return grid_chart
def kline(stock_data: pd.DataFrame): """ @input: column name ('date', 'open', 'close', 'min', 'max', 'Trading_Volume') """ def calculate_ma(day_count: int, price: list): result: List[Union[float, str]] = [] for i in range(len(price)): if i < day_count: result.append("-") continue sum_total = 0.0 for j in range(day_count): sum_total += float(price[i - j]) result.append(abs(float("%.3f" % (sum_total / day_count)))) return result def process_stock_data(data): data = data[["date", "open", "close", "min", "max", "Trading_Volume"]] data.columns = ["date", "open", "close", "low", "high", "volume"] if is_datetime(data["date"]): data_times = data["date"].dt.strftime("%Y-%m-%d").to_list() else: data_times = data["date"].to_list() values = data.values.tolist() volumes = [] for i, tick in enumerate(data.values.tolist()): volumes.append([i, tick[5], 1 if tick[1] > tick[2] else -1]) return { "categoryData": data_times, "values": values, "volumes": volumes, } chart_data = process_stock_data(stock_data) kline_data = [data[1:-1] for data in chart_data["values"]] kline = Kline(init_opts=opts.InitOpts(animation_opts=opts.AnimationOpts( animation=False), )) kline.add_xaxis(xaxis_data=chart_data["categoryData"]) kline.add_yaxis( series_name="kline", y_axis=kline_data, itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c"), ) kline.set_global_opts( legend_opts=opts.LegendOpts(is_show=True, pos_left="center"), datazoom_opts=[ opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0, 1], range_start=85, range_end=100, ), opts.DataZoomOpts( is_show=True, xaxis_index=[0, 1], type_="slider", pos_top="85%", range_start=85, range_end=100, ), ], yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), tooltip_opts=opts.TooltipOpts( trigger="axis", axis_pointer_type="cross", background_color="rgba(245, 245, 245, 0.8)", border_width=1, border_color="#ccc", textstyle_opts=opts.TextStyleOpts(color="#000"), ), visualmap_opts=opts.VisualMapOpts( is_show=False, dimension=2, series_index=5, is_piecewise=True, pieces=[ { "value": 1, "color": "#00da3c" }, { "value": -1, "color": "#ec0000" }, ], ), axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), brush_opts=opts.BrushOpts( x_axis_index="all", brush_link="all", out_of_brush={"colorAlpha": 0.1}, brush_type="lineX", ), ) close = np.array(chart_data["values"])[:, 2] ma_items = [5, 10, 20, 60] line = Line(init_opts=opts.InitOpts(animation_opts=opts.AnimationOpts( animation=False), )).add_xaxis(xaxis_data=chart_data["categoryData"]) for ma in ma_items: line.add_yaxis( series_name="MA" + str(ma), y_axis=calculate_ma(day_count=ma, price=close), is_smooth=True, is_symbol_show=False, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ) line.set_global_opts(xaxis_opts=opts.AxisOpts(type_="category")) bar = Bar(init_opts=opts.InitOpts(animation_opts=opts.AnimationOpts( animation=False), )) bar.add_xaxis(xaxis_data=chart_data["categoryData"]) bar.add_yaxis( series_name="Volume", y_axis=chart_data["volumes"], xaxis_index=1, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False), ) bar.set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", is_scale=True, grid_index=1, boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=False), split_number=20, min_="dataMin", max_="dataMax", ), yaxis_opts=opts.AxisOpts( grid_index=1, is_scale=True, split_number=2, axislabel_opts=opts.LabelOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_show=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), ), legend_opts=opts.LegendOpts(is_show=False), ) overlap_kline_line = kline.overlap(line) grid_chart = Grid(init_opts=opts.InitOpts( width="1000px", height="800px", animation_opts=opts.AnimationOpts(animation=False), )) grid_chart.add( overlap_kline_line, grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", height="50%"), ) grid_chart.add( bar, grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top="63%", height="16%"), ) grid_chart.render("kline.html") display(HTML(filename="kline.html")) return grid_chart
def ka_to_echarts(ka: KlineAnalyze, width="1500px", height='800px'): # 配置项设置 # ------------------------------------------------------------------------------------------------------------------ bg_color = "#1f212d" # 背景 up_color = "#F9293E" down_color = "#00aa3b" init_opts = opts.InitOpts(bg_color=bg_color, width=width, height=height, animation_opts=opts.AnimationOpts(False)) title_opts = opts.TitleOpts(title="{} - {}".format(ka.symbol, ka.name), subtitle="from {} to {}".format(ka.start_dt, ka.end_dt), pos_top="1%", title_textstyle_opts=opts.TextStyleOpts(color=up_color, font_size=20), subtitle_textstyle_opts=opts.TextStyleOpts(color=down_color, font_size=12)) label_not_show_opts = opts.LabelOpts(is_show=False) legend_not_show_opts = opts.LegendOpts(is_show=False) red_item_style = opts.ItemStyleOpts(color=up_color) green_item_style = opts.ItemStyleOpts(color=down_color) k_style_opts = opts.ItemStyleOpts(color=up_color, color0=down_color, border_color=up_color, border_color0=down_color, opacity=0.8) legend_opts = opts.LegendOpts(is_show=True, pos_top="1%", pos_left="30%", item_width=14, item_height=8, textstyle_opts=opts.TextStyleOpts(font_size=12, color="#0e99e2")) brush_opts = opts.BrushOpts(tool_box=["rect", "polygon", "keep", "clear"], x_axis_index="all", brush_link="all", out_of_brush={"colorAlpha": 0.1}, brush_type="lineX") axis_pointer_opts = opts.AxisPointerOpts(is_show=True, link=[{"xAxisIndex": "all"}]) dz_inside = opts.DataZoomOpts(False, "inside", xaxis_index=[0, 1, 2]) dz_slider = opts.DataZoomOpts(True, "slider", xaxis_index=[0, 1, 2], pos_top="96%", pos_bottom="0%") yaxis_opts = opts.AxisOpts(is_scale=True, axislabel_opts=opts.LabelOpts(color="#c7c7c7", font_size=8, position="inside")) grid0_xaxis_opts = opts.AxisOpts(type_="category", grid_index=0, axislabel_opts=label_not_show_opts, split_number=20, min_="dataMin", max_="dataMax", is_scale=True, boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False)) tool_tip_opts = opts.TooltipOpts( trigger="axis", axis_pointer_type="cross", background_color="rgba(245, 245, 245, 0.8)", border_width=1, border_color="#ccc", position=JsCode(""" function (pos, params, el, elRect, size) { var obj = {top: 10}; obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30; return obj; } """), textstyle_opts=opts.TextStyleOpts(color="#000"), ) # 数据预处理 # ------------------------------------------------------------------------------------------------------------------ dts = [x['dt'] for x in ka.kline_raw] k_data = [[x['open'], x['close'], x['low'], x['high']] for x in ka.kline_raw] ma = ka.ma vol = [] for row in ka.kline_raw: item_style = red_item_style if row['close'] > row['open'] else green_item_style bar = opts.BarItem(value=row['vol'], itemstyle_opts=item_style, label_opts=label_not_show_opts) vol.append(bar) macd = [] for row in ka.macd: item_style = red_item_style if row['macd'] > 0 else green_item_style bar = opts.BarItem(value=round(row['macd'], 4), itemstyle_opts=item_style, label_opts=label_not_show_opts) macd.append(bar) diff = [round(x['diff'], 4) for x in ka.macd] dea = [round(x['dea'], 4) for x in ka.macd] # K 线主图 # ------------------------------------------------------------------------------------------------------------------ chart_k = Kline() chart_k.add_xaxis(xaxis_data=dts) chart_k.add_yaxis(series_name="Kline", y_axis=k_data, itemstyle_opts=k_style_opts) chart_k.set_global_opts( legend_opts=legend_opts, datazoom_opts=[dz_inside, dz_slider], yaxis_opts=yaxis_opts, tooltip_opts=tool_tip_opts, axispointer_opts=axis_pointer_opts, brush_opts=brush_opts, title_opts=title_opts, xaxis_opts=grid0_xaxis_opts ) # 均线图 # ------------------------------------------------------------------------------------------------------------------ chart_ma = Line() chart_ma.add_xaxis(xaxis_data=dts) ma_keys = [x for x in ma[0].keys() if "ma" in x][:3] ma_colors = ["#39afe6", "#da6ee8", "#00940b"] for i, k in enumerate(ma_keys): y_data = [x[k] for x in ma] chart_ma.add_yaxis(series_name=k.upper(), y_axis=y_data, is_smooth=True, is_selected=False, symbol_size=0, label_opts=label_not_show_opts, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color=ma_colors[i])) chart_ma.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_ma) # 缠论结果 # ------------------------------------------------------------------------------------------------------------------ fx_dts = [x['dt'] for x in ka.fx_list] fx_val = [x['fx'] for x in ka.fx_list] chart_fx = Scatter() chart_fx.add_xaxis(fx_dts) chart_fx.add_yaxis(series_name="FX", y_axis=fx_val, is_selected=False, symbol="circle", symbol_size=6, label_opts=label_not_show_opts, itemstyle_opts=opts.ItemStyleOpts(color="rgba(152, 147, 193, 1.0)",)) chart_fx.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_fx) bi_dts = [x['dt'] for x in ka.bi_list] bi_val = [x['bi'] for x in ka.bi_list] chart_bi = Scatter() chart_bi.add_xaxis(bi_dts) chart_bi.add_yaxis(series_name="BI", y_axis=bi_val, is_selected=True, symbol="diamond", symbol_size=10, label_opts=label_not_show_opts, itemstyle_opts=opts.ItemStyleOpts(color="rgba(184, 117, 225, 1.0)",)) chart_bi.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_bi) xd_dts = [x['dt'] for x in ka.xd_list] xd_val = [x['xd'] for x in ka.xd_list] chart_xd = Scatter() chart_xd.add_xaxis(xd_dts) chart_xd.add_yaxis(series_name="XD", y_axis=xd_val, is_selected=True, symbol="triangle", symbol_size=10, itemstyle_opts=opts.ItemStyleOpts(color="rgba(37, 141, 54, 1.0)",)) chart_xd.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_xd) # 成交量图 # ------------------------------------------------------------------------------------------------------------------ chart_vol = Bar() chart_vol.add_xaxis(dts) chart_vol.add_yaxis(series_name="Volume", y_axis=vol, bar_width='60%') chart_vol.set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=True, font_size=8, color="#9b9da9"), ), yaxis_opts=yaxis_opts, legend_opts=legend_not_show_opts, ) # MACD图 # ------------------------------------------------------------------------------------------------------------------ chart_macd = Bar() chart_macd.add_xaxis(dts) chart_macd.add_yaxis(series_name="MACD", y_axis=macd, bar_width='60%') chart_macd.set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( grid_index=2, split_number=4, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=True, color="#c7c7c7"), ), legend_opts=opts.LegendOpts(is_show=False), ) line = Line() line.add_xaxis(dts) line.add_yaxis(series_name="DIFF", y_axis=diff, label_opts=label_not_show_opts, is_symbol_show=False, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color="#da6ee8")) line.add_yaxis(series_name="DEA", y_axis=dea, label_opts=label_not_show_opts, is_symbol_show=False, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color="#39afe6")) chart_macd = chart_macd.overlap(line) grid0_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="12%", height="58%") grid1_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="74%", height="8%") grid2_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="86%", height="10%") grid_chart = Grid(init_opts) grid_chart.add(chart_k, grid_opts=grid0_opts) grid_chart.add(chart_vol, grid_opts=grid1_opts) grid_chart.add(chart_macd, grid_opts=grid2_opts) return grid_chart
def kline(self): """""" if "_" in self.bar_data.symbol[0]: symbol_split = self.bar_data.symbol[0].split("_") series_name = "_".join( [symbol_split[0], symbol_split[1][-2:], symbol_split[2][-2:]]) else: series_name = self.bar_data.symbol[0] kline = Kline(init_opts=opts.InitOpts(width="1400px", height="800px")) kline.add_xaxis(xaxis_data=self.bar_data_datetime) kline.add_yaxis( series_name=series_name, yaxis_index=0, y_axis=self.bar_data[[ "open_price", "close_price", "low_price", "high_price" ]].values.tolist(), itemstyle_opts=opts.ItemStyleOpts(color="#ef232a", color0="#14b143", border_color="#8A0000", border_color0="#008F28", opacity=0.8), ) kline.set_global_opts( datazoom_opts=[ opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0, 0], range_start=0, range_end=100, ), opts.DataZoomOpts( is_show=True, type_="slider", xaxis_index=[0, 1], pos_top="95%", range_start=0, range_end=100, ), ], xaxis_opts=opts.AxisOpts( is_scale=True, type_="category", boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False), splitline_opts=opts.SplitLineOpts(is_show=False), split_number=20, min_="dataMin", max_="dataMax", ), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=0.8)), ), brush_opts=opts.BrushOpts( tool_box=[ "rect", "polygon", "keep", "lineX", "lineY", "clear" ], x_axis_index="all", brush_link="all", out_of_brush={"colorAlpha": 0.1}, brush_type="lineX", ), tooltip_opts=opts.TooltipOpts( is_show=True, trigger="axis", axis_pointer_type="cross", background_color="rgba(245, 245, 245, 0.8)", border_width=1, border_color="#ccc", textstyle_opts=opts.TextStyleOpts( color="#000", font_size=12, font_family="Arial", font_weight="lighter", ), ), toolbox_opts=opts.ToolboxOpts(orient="horizontal", pos_left="right", pos_top="0%"), legend_opts=opts.LegendOpts( is_show=True, type_="scroll", selected_mode="multiple", pos_left="left", pos_top="0%", legend_icon="roundRect", ), # 多图的 axis 连在一块 axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), ) self.kline_chart = kline
def draw_charts(kline_data ,canshu ={} ,canshu2={},vol_bar=False,markline_show1 =False ,markline_show2 =False, path = '0501'): ''' df['candle_begin_time','open','high','low','close','volume'] [['candle_begin_time','open','high','low','close','volume']] kdata = df[['open', 'high', 'low', 'close']].values.tolist() df['candle_begin_time'].values.tolist() :return: ''' df = kline_data.copy() df['candle_begin_time'] = pd.to_datetime(df['candle_begin_time']) time_list = df['candle_begin_time'].apply(lambda x: x.strftime('%Y-%m-%d %H:%M:%S')).values.tolist() vol = df['volume'].values.tolist() kline = Kline() kline.add_xaxis(xaxis_data=time_list) signal_pos_list = [] if 'signal' in df.columns: print('signal,存在!') df['pos'] = df['signal'].shift(1) for i in df[df['pos'] > 0].index: bar0 = df.iloc[i] sig_pos0 = opts.MarkPointItem(name="做多", coord=[bar0['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),bar0.low -2], value='买', symbol ='circle', symbol_size =[20,40], itemstyle_opts = {'color': 'red'}) signal_pos_list.append(sig_pos0) for i in df[df['pos'] < 0].index: bar0 = df.iloc[i] sig_pos0 = opts.MarkPointItem(name="做空", coord=[bar0['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),bar0.high +3], value='卖', symbol='circle', symbol_size=[20, 40], itemstyle_opts={'color': 'blue'}) signal_pos_list.append(sig_pos0) for i in df[df['pos'] == 0].index: bar0 = df.iloc[i] sig_pos0 = opts.MarkPointItem(name="平仓", coord=[bar0['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'),bar0.low - 2], value='平', symbol ='triangle', symbol_size =[20,40], itemstyle_opts = {'color': 'green'}) signal_pos_list.append(sig_pos0) else : df['pos'] =None markline =[] if markline_show1 and ('signal' in df.columns) : area_index_list =[i for i in df[(df['pos'] ==0)|(df['pos'] >0)|(df['pos'] <0)].index] for ix,i in enumerate(area_index_list): if ix+1 > len(area_index_list)-1: break i_now = df.iloc[area_index_list[ix]] i_next = df.iloc[area_index_list[ix+1]] if (i_now['pos'] >0) or (i_now['pos'] <0) : log_info = f"价差:={i_next['open']-i_now['open']}--({i_next['open']}-{i_now['open']})" else : log_info =f"平仓:{i_next['open']}---开仓:{i_now['open']}" sig_area = [{"xAxis": i_now['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'), "yAxis": i_now['open'] , "value": None}, {"xAxis": i_next['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'), "yAxis": i_now['open'], "value":log_info}] sig_area_v = [{"xAxis": i_next['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'), "yAxis": i_now['open'] , "value": None}, {"xAxis": i_next['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'), "yAxis": i_next['open'], "value":None}] markline.append(sig_area) markline.append(sig_area_v) elif markline_show2 and ('signal' in df.columns): area_index_list =[i for i in df[(df['pos'] ==0)|(df['pos'] >0)|(df['pos'] <0)].index] for ix,i in enumerate(area_index_list): i_now = df.iloc[area_index_list[ix]] i_1_now = df.iloc[area_index_list[ix-1]] if ix != 0 else 0 if i_now['pos'] == 0: log_info = f"交易价: {round(i_now['open'], 1)} +- 2__盈亏:{round(i_now['open'], 1) - round(i_1_now['open'], 1)}" else: log_info = f"交易价: {round(i_now['open'],1)} +- 2" sig_area = [{"xAxis": i_now['candle_begin_time'].strftime('%Y-%m-%d %H:%M:%S'), "yAxis": i_now['open'] , "value": None}, {"xAxis": (i_now['candle_begin_time']+timedelta(minutes=15)).strftime('%Y-%m-%d %H:%M:%S'), "yAxis": i_now['open'], "value":log_info}] markline.append(sig_area) colors = {'red': 'rgb((220,20,60)','red2': 'rgb((250,20,40)', 'yangzi': 'rgb(255,0,255)', 'zi': 'rgb(128,0,128)', 'sehnzi': 'rgb(148,0,211)', 'blue': 'rgb(0,0,255)', 'qing': 'rgb(0,255,255)', 'black': 'rgb(0,0,0)', 'shengreen': 'rgb(157,255,212)', 'green': 'rgb(0,255,0)', 'yellow': 'rgb(255,255,0)', 'glod': 'rgb(218,165,32)', 'orange': 'rgb(255,165,0)', 'brown': 'rgb(165,42,42)'} kline.add_xaxis(xaxis_data=time_list) kline.add_yaxis(series_name="oclh", xaxis_index=1, yaxis_index=1, y_axis =df.loc[:, ['open', 'close', 'low', 'high']].values.tolist(), markline_opts=opts.MarkLineOpts(data=markline, linestyle_opts=opts.LineStyleOpts(type_='dotted',width=3,color='red',opacity=0.5), label_opts=opts.LabelOpts(position="right", color="blue", font_size=13),), #官网给出的样本 markpoint_opts=opts.MarkPointOpts(data=signal_pos_list), itemstyle_opts=opts.ItemStyleOpts(color="#ec0090", color0="#00aa3c"), ) kline.set_global_opts( legend_opts=opts.LegendOpts(is_show=True,pos_top=30, pos_left="left",orient='vertical'), datazoom_opts=[ opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0, 1], range_start=90, range_end=100, orient='vertical'), opts.DataZoomOpts( is_show=True, xaxis_index=[0, 1], type_="slider", pos_top="20%", range_start=90, range_end=100,orient='vertical'),], yaxis_opts =opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts(is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)),), title_opts=opts.TitleOpts( title = 'K_line', pos_top='middle', title_textstyle_opts=opts.TextStyleOpts( color='black',font_weight='bold' ,font_size=20)), tooltip_opts=opts.TooltipOpts( trigger="axis", trigger_on='"mousemove"',#click|mousemove axis_pointer_type="cross", is_show_content=True, is_always_show_content=True, background_color="rgba(20, 105, 245, 0.1)", border_width=1, border_color= "#ccc", position = ['70%','30%'], textstyle_opts=opts.TextStyleOpts(font_size=10,color="#000"),), visualmap_opts=opts.VisualMapOpts( is_show=True, dimension=2, series_index=5, is_piecewise=True, pieces=[{"value": 1, "color": "#00da3c"},{"value": -1, "color": "#ec0000"},],), axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{"xAxisIndex": "all"}], label=opts.LabelOpts(background_color="#777"),), brush_opts=opts.BrushOpts( x_axis_index="all", brush_link="all", out_of_brush={"colorAlpha": 0.1}, brush_type="lineX",), ) if len(canshu.keys())>0: cos = list(colors.values()) line = Line() for k,v in canshu.items(): line.add_xaxis(xaxis_data=time_list) line.set_global_opts(xaxis_opts=opts.AxisOpts(type_="category")) co = cos.pop() line.add_yaxis( series_name=k, y_axis = [y for y in v.values.tolist() if y != np.nan], xaxis_index=1, yaxis_index=1, is_smooth=False, is_connect_nones=False,# 是否连接空数据 is_symbol_show=False,#是否显示值的位置,默认显示。 color = co, is_hover_animation = False, # 是否开启 hover 在拐点标志上的提示动画效果。 linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.9,color=co), label_opts=opts.LabelOpts(is_show =True,position='middle',distance=2,rotate=5,color = 'rgb(165,42,42)'), itemstyle_opts=opts.ItemStyleOpts(color=co),) kline = kline.overlap(line) grid_chart = Grid(init_opts=opts.InitOpts(width = "1500px",height= "700px",theme=ThemeType.DARK)) grid_chart.add(kline,grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%",pos_top='4%' ,height="70%")) if( vol_bar == True) or (len(canshu2.keys())==0): bar = Bar() bar.add_xaxis(xaxis_data=time_list) bar.add_yaxis( series_name="volume", y_axis=vol, xaxis_index=1, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), ) bar.set_global_opts(xaxis_opts=opts.AxisOpts( type_="category", is_scale=True, grid_index=1, boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=False), split_number=20, min_="dataMin", max_="dataMax", ), yaxis_opts=opts.AxisOpts( grid_index=1, is_scale=True, split_number=2, axislabel_opts=opts.LabelOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_show=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), ), legend_opts=opts.LegendOpts(is_show=True), ) grid_chart.add(bar,grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top="80%", height="15%"),) if len(canshu2.keys())>0 : line2 = Line() line2.add_xaxis(xaxis_data=time_list) for i, k in enumerate(canshu2.keys()): co = random.choice(list(colors.values())) line2.add_yaxis( series_name=k, y_axis=[y for y in canshu2[k].values.tolist()], xaxis_index=1, yaxis_index=i + 1, is_smooth=True, is_symbol_show=False, is_hover_animation=True, color=co, z_level=0, linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.5, color=co), label_opts=opts.LabelOpts(is_show=False), ) if k == list(canshu2.keys())[-1]: continue line2.extend_axis(yaxis=opts.AxisOpts(name=k, type_="value", position="right", min_=None, max_=None, axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color=co)), axislabel_opts=opts.LabelOpts(formatter="{value}"), )) line2.set_global_opts(xaxis_opts=opts.AxisOpts( type_="category", is_scale=True, grid_index=1, split_number=20, min_="dataMin", max_="dataMax", axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts(name=k, grid_index=i + 1, position='right', splitarea_opts=opts.SplitAreaOpts(is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), min_=None, max_=None, is_scale=True, offset=50, ), ) grid_chart.add(line2,grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top="75%", height="23%"),is_control_axis_index=True) tab = Tab() zijin_data = (kline_data['per_lr'].cumsum()) zijin_data.fillna(method='ffill', inplace=True) zijin_line = Line(init_opts=opts.InitOpts(width = "1500px",height= "700px",theme=ThemeType.DARK)).add_xaxis(time_list) zijin_line.add_yaxis(series_name="zijin_line:", y_axis=zijin_data.values, color="#FF0000") zijin_line.set_global_opts( datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")], title_opts=opts.TitleOpts(title="资金曲线变化"), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"), yaxis_opts = opts.AxisOpts( is_scale=True, axislabel_opts=opts.LabelOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_show=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), ), legend_opts = opts.LegendOpts(is_show=True) ) tab.add(grid_chart,'kline' ) tab.add(zijin_line,'资金曲线变化' ) tab.render(f"{path}.html") html0 = tab.render(f"{path}.html") if os.path.exists(html0): print("ok!保存在:") print(html0) else: print('保存失败!')
def run_strategy(smaPeriod): df_new = pd.DataFrame(columns=('shares_ID', 'total number of trades', 'Profit times number of trades', 'Profit Percentage', 'Final portfolio value')) for (root, dirs, files) in os.walk("E:/Stock/Data_Day"): z = 0 for x in range(len(files)): z = z + 1 #K线图 df = pd.read_csv("E:/Stock/Data_Day/" + files[x]) df = df.sort_index(ascending=False).reset_index(drop=True) print("进度:", z / len(files) * 100, "%") date = df.xs('Date Time', axis=1).tolist() data = [] vol = [] for idx in df.index: row1 = [ df.iloc[idx]['Open'], df.iloc[idx]['Close'], df.iloc[idx]['Low'], df.iloc[idx]['High'] ] row2 = df.iloc[idx]['Volume'] data.append(row1) vol.append(row2) kline1 = Kline() line1 = Line() line2 = Line() line3 = Line() scatter1 = Scatter() scatter2 = Scatter() kline1.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts(is_scale=True), datazoom_opts=[opts.DataZoomOpts()]) kline1.extend_axis( yaxis=opts.AxisOpts(type_='value', position='right')) kline1.extend_axis( yaxis=opts.AxisOpts(type_='value', position='right')) # 价格均线 line1.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts(is_scale=True), datazoom_opts=[opts.DataZoomOpts()]) # 成交量 line2.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts(is_scale=True), datazoom_opts=[opts.DataZoomOpts()]) #资金量 line3.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts(is_scale=True), datazoom_opts=[opts.DataZoomOpts()]) #买入点 scatter1.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts(is_scale=True), datazoom_opts=[opts.DataZoomOpts()]) #卖出点 scatter2.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts(is_scale=True), datazoom_opts=[opts.DataZoomOpts()]) kline1.add_xaxis(date) kline1.add_yaxis(files[x], data) line2.add_xaxis(date) line2.add_yaxis("vol", vol, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False)) feed = GenericBarFeed(Frequency.DAY, None, None) feed.addBarsFromCSV("fd", "E:/Stock/Data_Day/" + files[x]) global myStrategy myStrategy = MyStrategy(feed, "fd", smaPeriod) trade_situation = trades.Trades() myStrategy.attachAnalyzer(trade_situation) plt = plotter.StrategyPlotter(myStrategy) # Include the SMA in the instrument's subplot to get it displayed along with the closing prices. plt.getInstrumentSubplot("test").addDataSeries( "SMA", myStrategy.getSMA()) # Plot the simple returns on each bar. # plt.getOrCreateSubplot("returns").addDataSeries("Simple returns", returnsAnalyzer.getReturns()) myStrategy.run() scatter1.add_xaxis(myStrategy.Buyday) scatter1.add_yaxis("Buy", myStrategy.Buyprice) scatter2.add_xaxis(myStrategy.Sellday) scatter2.add_yaxis("Sell", myStrategy.Sellprice) line1.add_xaxis(myStrategy.Barday) line1.add_yaxis("Price_SMA", myStrategy.Sma_price, label_opts=opts.LabelOpts(is_show=False)) line3.add_xaxis(date) line3.add_yaxis("money", myStrategy.money, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False)) plt.savePlot("E:/Stock/html_png_Total_day/" + files[x] + ".png") print(files[x] + " Final portfolio value:$%.2f" % myStrategy.getBroker().getEquity()) print("total number of trades", trade_situation.getCount()) print("Profit times number of trades ", trade_situation.getProfitableCount()) if trade_situation.getCount() > 0: Percentage = trade_situation.getProfitableCount( ) / trade_situation.getCount() print("百分比", Percentage) else: Percentage = 0 print("百分比", 0) df1 = pd.DataFrame({ "shares_ID": [files[x]], 'total number of trades': [trade_situation.getCount()], 'Profit times number of trades': trade_situation.getProfitableCount(), 'Profit Percentage': Percentage, 'Final portfolio value': [myStrategy.getBroker().getEquity()] }) kline1.overlap(scatter1) kline1.overlap(scatter2) kline1.overlap(line1) kline1.overlap(line2) kline1.overlap(line3) kline1.render(path='E:\\Stock/html_png_Total_day/' + files[x] + '.html') df_new = pd.concat([df1, df_new], ignore_index=True) df_new.to_csv("E:/Stock/html_png_Total_day/Total_Min.csv", index=False)
# %% [markdown] # ### KLine -- K线图 with open("data/candlestick.json", encoding="utf8") as j: ori_data = json.load(j) data = { "data": [rec[1:] for rec in ori_data], "times": [rec[0] for rec in ori_data], "vols": [int(rec[5]) for rec in ori_data], "macds": [rec[7] for rec in ori_data], "difs": [rec[8] for rec in ori_data], "deas": [rec[9] for rec in ori_data] } kline = Kline() kline.add_xaxis(data["times"][-100:]) kline.add_yaxis("", data["data"][-100:]) kline.render_notebook() # %% [markdown] # ### WordCloud -- 词云图 with open("data/wordcloud.json", encoding="utf8") as f: words = json.load(f) wordcloud = WordCloud() wordcloud.add("", words) wordcloud.render_notebook() # %% [markdown] # ### Timeline
if len(temp) == 2: # 给第2组xy坐标字典添加'itemStyle': {'color': '#14b143'}键值对。 # df_celue.at[temp[1]['xAxis'], 'close']为读取对应索引的收盘价。 # 第二组坐标收盘价和第一组坐标收盘价比较,大于则区域颜色是红色表示盈利,小于则绿色亏损 temp[1]["itemStyle"] = { 'color': "#ef232a" if df_celue.at[temp[1]['xAxis'], 'close'] > df_celue.at[temp[0]['xAxis'], 'close'] else "#14b143" } markareadata.append(temp) # rprint(markareadata) temp = [] vol = df_stock['vol'].tolist() # print(oclh) kline.add_xaxis(datetime) kline.add_yaxis( stock_code, oclh, itemstyle_opts=opts.ItemStyleOpts( color="#ef232a", color0="#14b143", border_color="#ef232a", border_color0="#14b143", ), # markpoint_opts=opts.MarkPointOpts( # data=[ # opts.MarkPointItem(type_="max", name="最大值"), # opts.MarkPointItem(type_="min", name="最小值"), # ] # )
def to_grid(ka, kline_mode: str = "new", with_bi: bool = False, with_xd: bool = False, with_zs: bool = False, with_bs: bool = False, with_ma: bool = False, with_vol: bool = False, with_macd: bool = False, title: str = "ChanLun In Practise", width: str = "1440px", height: str = '900px') -> Grid: """绘制缠中说禅K线分析结果 :param kline: K线 new / raw,new标识标准化后的k线,raw标识原始k线 :param with_bi: 是否显示笔识别结果,默认True,不输出False :param with_xd: 是否显示线段识别结果 :param with_zs: 是否显示中枢识别结果 :param with_bs: 是否显示买卖点 :param with_ma: 是否显示均线,默认True,不输出False :param with_macd: 是否显示macd,默认True,不输出False :param with_vol: 是否显示成交量,默认True,不输出False :param title: 图表标题 :param width: 图表宽度 :param height: 图表高度 :return: 用Grid组合好的图表 """ # 配置项设置 # ------------------------------------------------------------------------------------------------------------------ bg_color = "#1f212d" # 背景 up_color = "#F9293E" down_color = "#00aa3b" init_opts = opts.InitOpts(bg_color=bg_color, width='1400px', height='800px') title_opts = opts.TitleOpts(title=title, pos_top="1%", title_textstyle_opts=opts.TextStyleOpts(color=up_color, font_size=20), subtitle_textstyle_opts=opts.TextStyleOpts(color=down_color, font_size=12)) label_not_show_opts = opts.LabelOpts(is_show=False) legend_not_show_opts = opts.LegendOpts(is_show=False) red_item_style = opts.ItemStyleOpts(color=up_color) green_item_style = opts.ItemStyleOpts(color=down_color) k_style_opts = opts.ItemStyleOpts(color=up_color, color0=down_color, border_color=up_color, border_color0=down_color, opacity=0.8) legend_opts = opts.LegendOpts(is_show=True, pos_top="1%", pos_left="30%", item_width=14, item_height=8, textstyle_opts=opts.TextStyleOpts(font_size=12, color="#0e99e2")) brush_opts = opts.BrushOpts(tool_box=["rect", "polygon", "keep", "clear"], x_axis_index="all", brush_link="all", out_of_brush={"colorAlpha": 0.1}, brush_type="lineX") axis_pointer_opts = opts.AxisPointerOpts(is_show=True, link=[{"xAxisIndex": "all"}]) dz_inside = opts.DataZoomOpts(False, "inside", xaxis_index=[0, 1, 2]) dz_slider = opts.DataZoomOpts(True, "slider", xaxis_index=[0, 1, 2], pos_top="96%", pos_bottom="0%") yaxis_opts = opts.AxisOpts(is_scale=True, axislabel_opts=opts.LabelOpts(color="#c7c7c7", font_size=8, position="inside")) grid0_xaxis_opts = opts.AxisOpts(type_="category", grid_index=0, axislabel_opts=label_not_show_opts, split_number=20, min_="dataMin", max_="dataMax", is_scale=True, boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False)) tool_tip_opts = opts.TooltipOpts( trigger="axis", axis_pointer_type="cross", background_color="rgba(245, 245, 245, 0.8)", border_width=1, border_color="#ccc", textstyle_opts=opts.TextStyleOpts(color="#000"), ) # 数据预处理 # ------------------------------------------------------------------------------------------------------------------ kline = ka.kline_new if kline_mode == 'new' else ka.kline_raw dts = [x['dt'] for x in kline] k_data = [[x['open'], x['close'], x['low'], x['high']] for x in kline] # seriesname aggregation = len(ka.ka_list)>0 # {'freq': {'kline', 'ma', 'vol', 'macd'}} agg_dict = {} agg_dict[ka.freq] = { "kline": k_data, "ma": ka.ma, "vol": kline, "macd": ka.macd } if aggregation: for high_ka in ka.ka_list: agg_dict[high_ka.freq] = {} _high_k_data = high_ka.kline_new if kline_mode == 'new' else high_ka.kline_raw high_k_data = [] high_ma_data = [] high_vol_data = [] high_macd_data = [] for i in range(len(dts)): high_k_data.append([]) high_ma_data.append({}) high_vol_data.append(None) high_macd_data.append(None) for ki in range(len(kline)): k = kline[ki] _start = 0 for h_ki in range(_start, len(_high_k_data)): h_k = _high_k_data[h_ki] if (h_k['dt'] == k['dt']): high_k_data[ki] = [h_k['open'], h_k['close'], h_k['low'], h_k['high']] high_ma_data[ki] = high_ka.ma[h_ki] high_vol_data[ki] = h_k high_macd_data[ki] = high_ka.macd[h_ki] _start = h_ki+1 break agg_dict[high_ka.freq] = { "kline": high_k_data, "ma": high_ma_data, "vol": high_vol_data, "macd": high_macd_data } # K 线主图 # ------------------------------------------------------------------------------------------------------------------ chart_k = Kline() chart_k.add_xaxis(xaxis_data=dts) for k, v in agg_dict.items(): chart_k.add_yaxis(series_name=k if aggregation else 'kline', y_axis=v['kline'], itemstyle_opts=k_style_opts) is_selected = False chart_k.set_global_opts( legend_opts=legend_opts, datazoom_opts=[dz_inside, dz_slider], yaxis_opts=yaxis_opts, tooltip_opts=tool_tip_opts, axispointer_opts=axis_pointer_opts, brush_opts=brush_opts, title_opts=title_opts, xaxis_opts=grid0_xaxis_opts, ) if with_ma: # 均线图 # ------------------------------------------------------------------------------------------------------------------ ma_keys = [x for x in agg_dict[ka.freq]['ma'][0].keys() if "ma" in x][:3] ma_colors = ["#39afe6", "#da6ee8", "#00940b"] chart_ma = Line() chart_ma.add_xaxis(xaxis_data=dts) for key, vals in agg_dict.items(): for i, k in enumerate(ma_keys): y_data = [x[k] if k in x else None for x in v['ma']] chart_ma.add_yaxis(series_name=key if aggregation else k.upper(), y_axis=y_data, is_smooth=True, is_selected=True, is_connect_nones=True, symbol_size=0, label_opts=label_not_show_opts, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color=ma_colors[i])) chart_ma.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_ma) # 缠论结果 # ------------------------------------------------------------------------------------------------------------------ def __draw_bi_line(_ka): bi_dts = [x['dt'] for x in _ka.bi_list] bi_val = [x['bi'] for x in _ka.bi_list] chart_bi = Line() chart_bi.add_xaxis(bi_dts) chart_bi.add_yaxis(series_name=_ka.freq if aggregation else "BI", y_axis=bi_val, is_selected=True, symbol="diamond", symbol_size=10, label_opts=label_not_show_opts,) chart_bi.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) return chart_bi if with_bi: chark_k = chart_k.overlap(__draw_bi_line(ka)) for _ka in ka.ka_list: chark_k = chart_k.overlap(__draw_bi_line(_ka)) def __draw_xd_line(_ka): xd_dts = [x['dt'] for x in _ka.xd_list] xd_val = [x['xd'] for x in _ka.xd_list] chart_xd = Line() chart_xd.add_xaxis(xd_dts) chart_xd.add_yaxis(series_name=_ka.freq if aggregation else "XD", y_axis=xd_val, is_selected=True, symbol="triangle", symbol_size=10,) chart_xd.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) return chart_xd if with_xd: chark_k = chart_k.overlap(__draw_xd_line(ka)) for _ka in ka.ka_list: chark_k = chart_k.overlap(__draw_xd_line(_ka)) def __draw_zs_area(_ka): lines = [] scatters = [] for _zs in _ka.zs_list: x_start = _zs['start_point']['dt'] if _zs['zs_finished']:# 中枢完成 x_end = _zs['end_point']['dt'] chart_b = EffectScatter() if 'buy3' in _zs: chart_b.add_xaxis([_zs['buy3']['dt']]) chart_b.add_yaxis(series_name=_ka.freq if aggregation else "B", y_axis=[_zs['buy3']['xd']], is_selected=False, symbol="circle", symbol_size=8, itemstyle_opts=opts.ItemStyleOpts(color="red",)) chart_b.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) scatters.append(chart_b) elif 'sell3' in _zs: chart_b.add_xaxis([_zs['sell3']['dt']]) chart_b.add_yaxis(series_name=_ka.freq if aggregation else "S", y_axis=[_zs['sell3']['xd']], is_selected=False, symbol="circle", symbol_size=8, itemstyle_opts=opts.ItemStyleOpts(color="green",)) chart_b.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) scatters.append(chart_b) elif len(_zs['points'])>=5:# 中枢成立但未完成,有3笔或段以上 x_end = _zs['points'][-1]['dt'] else: # 中枢未完成,且未确定 continue ZD = _zs['ZD'] ZG = _zs['ZG'] area_data=[[ {'xAxis': x_start, 'yAxis': ZD, 'value': ZD }, {'xAxis': x_end, 'yAxis': ZG, 'value': ZG }]] line = (Line() .add_xaxis([x_start, x_end]) .add_yaxis(series_name=_ka.freq if aggregation else "ZS", y_axis=[ZD, ZG], symbol='none' """ , markpoint_opts = opts.MarkPointOpts( data=[ opts.MarkPointItem(type_="max", name="ZG"), opts.MarkPointItem(type_="min", name="ZD"), ] ) """ , markline_opts=opts.MarkLineOpts( label_opts=opts.LabelOpts( position="middle", color="blue", font_size=15, ), linestyle_opts=opts.LineStyleOpts(type_="dashed"), data=area_data, symbol=["none", "none"], ) ) .set_series_opts( markarea_opts=opts.MarkAreaOpts(data=area_data, itemstyle_opts=opts.ItemStyleOpts(color="#dcdcdc",opacity=0.1)) )) lines.append(line) return lines, scatters if with_zs: _areas, _scatters = __draw_zs_area(ka) for _ka in ka.ka_list: _a, _s = __draw_zs_area(_ka) _areas.extend(_a) _scatters.extend(_s) for _area in _areas: chark_k = chart_k.overlap(_area) for _scatter in _scatters: chark_k = chart_k.overlap(_scatter) # if with_vol: # 成交量图 # ------------------------------------------------------------------------------------------------------------------ chart_vol = Bar() chart_vol.add_xaxis(dts) for k, v in agg_dict.items(): vol = [] for row in v['vol']: if not row: row = {'close': 0, 'open': 0, 'vol': 0} item_style = red_item_style if row['close'] > row['open'] else green_item_style bar = opts.BarItem(name=None, value=row['vol'], itemstyle_opts=item_style, label_opts=label_not_show_opts) vol.append(bar) chart_vol.add_yaxis(series_name=k if aggregation else "Volume", y_axis=vol, bar_width='60%') chart_vol.set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=True, font_size=8, color="#9b9da9"), ), yaxis_opts=yaxis_opts, legend_opts=legend_not_show_opts, ) #if with_macd: # MACD图 # ------------------------------------------------------------------------------------------------------------------ chart_macd = Bar() chart_macd.add_xaxis(dts) for k, v in agg_dict.items(): macd_bar = [] for row in v['macd']: if not row: row = {'macd': 0} item_style = red_item_style if row['macd'] > 0 else green_item_style bar = opts.BarItem(name=None, value=round(row['macd'], 4), itemstyle_opts=item_style, label_opts=label_not_show_opts) macd_bar.append(bar) chart_macd.add_yaxis(series_name=k if aggregation else "MACD", y_axis=macd_bar, bar_width='60%') chart_macd.set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( grid_index=2, split_number=4, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=True, color="#c7c7c7"), ), legend_opts=opts.LegendOpts(is_show=False), ) line = Line() line.add_xaxis(dts) for k, v in agg_dict.items(): macd = v['macd'] diff = [round(x['diff'], 4) if x else None for x in macd] dea = [round(x['dea'], 4) if x else None for x in macd] line.add_yaxis(series_name=k if aggregation else "DIFF", y_axis=diff, label_opts=label_not_show_opts, is_symbol_show=False , is_connect_nones=True, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color="#EDCB89")) line.add_yaxis(series_name=k if aggregation else "DEA", y_axis=dea, label_opts=label_not_show_opts, is_symbol_show=False , is_connect_nones=True, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color="#FFFFFF")) chart_macd = chart_macd.overlap(line) grid0_opts = opts.GridOpts(pos_left="3%", pos_right="1%", pos_top="12%", height="58%") grid1_opts = opts.GridOpts(pos_left="3%", pos_right="1%", pos_top="74%", height="8%") grid2_opts = opts.GridOpts(pos_left="3%", pos_right="1%", pos_top="86%", height="10%") grid_chart = Grid(init_opts) grid_chart.add(chart_k, grid_opts=grid0_opts) grid_chart.add(chart_vol, grid_opts=grid1_opts) grid_chart.add(chart_macd, grid_opts=grid2_opts) return grid_chart
def gen_kline_plot( stock_data: pd.DataFrame, chart_data: typing.Dict[str, typing.List[typing.List[typing.Union[float, int]]]], ) -> Kline: xaxis_index, series_index = get_subgraph_indices(chart_data) kline_data = [ list(kline_dict.values()) for kline_dict in stock_data[ ["open", "close", "min", "max"]].to_dict("records") ] kline = Kline(init_opts=opts.InitOpts(animation_opts=opts.AnimationOpts( animation=False), )) kline.add_xaxis(xaxis_data=chart_data["categoryData"]) kline.add_yaxis( series_name="kline", y_axis=kline_data, itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c"), ) kline.set_global_opts( legend_opts=opts.LegendOpts(is_show=True, pos_left="center"), datazoom_opts=[ opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=xaxis_index, range_start=85, range_end=100, ), opts.DataZoomOpts( is_show=True, xaxis_index=xaxis_index, type_="slider", pos_top="85%", range_start=85, range_end=100, ), ], yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), tooltip_opts=opts.TooltipOpts( trigger="axis", axis_pointer_type="cross", background_color="rgba(245, 245, 245, 0.8)", border_width=1, border_color="#ccc", textstyle_opts=opts.TextStyleOpts(color="#000"), ), visualmap_opts=opts.VisualMapOpts( is_show=False, dimension=2, series_index=series_index, is_piecewise=True, pieces=[ { "value": 1, "color": "#ec0000" }, { "value": -1, "color": "#00da3c" }, ], ), axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), brush_opts=opts.BrushOpts( x_axis_index="all", brush_link="all", out_of_brush={"colorAlpha": 0.1}, brush_type="lineX", ), ) return kline