def draw_charts(): kline_data = [data[1:-1] for data in chart_data["values"]] kline = (Kline().add_xaxis( xaxis_data=chart_data["categoryData"]).add_yaxis( series_name="Dow-Jones index", y_axis=kline_data, itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c"), ).set_global_opts( legend_opts=opts.LegendOpts(is_show=False, pos_bottom=10, pos_left="center"), datazoom_opts=[ opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0, 1], range_start=98, range_end=100, ), opts.DataZoomOpts( is_show=True, xaxis_index=[0, 1], type_="slider", pos_top="85%", range_start=98, 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", ), )) line = (Line().add_xaxis(xaxis_data=chart_data["categoryData"]).add_yaxis( series_name="MA5", y_axis=calculate_ma(day_count=5, data=chart_data), is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA10", y_axis=calculate_ma(day_count=10, data=chart_data), is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA20", y_axis=calculate_ma(day_count=20, data=chart_data), is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA30", y_axis=calculate_ma(day_count=30, data=chart_data), is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).set_global_opts(xaxis_opts=opts.AxisOpts(type_="category"))) bar = (Bar().add_xaxis(xaxis_data=chart_data["categoryData"]).add_yaxis( series_name="Volume", y_axis=chart_data["volumes"], xaxis_index=1, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False), ).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), )) # Kline And Line overlap_kline_line = kline.overlap(line) # Grid Overlap + Bar 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("professional_kline_brush.html")
def draw_chart(): kline = ( Kline() .add_xaxis(xaxis_data = data["times"]) .add_yaxis( series_name = "", y_axis = data["datas"], 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 = "最小值"), ] ), markline_opts = opts.MarkLineOpts( label_opts = opts.LabelOpts( position = "middle", color = "blue", font_size = 15 ), data = split_data_part(), symbol = ["circle","none"], ), ) .set_series_opts( markarea_opts = opts.MarkAreaOpts(is_silent = True,data = split_data_part()) ) .set_global_opts( title_opts = opts.TitleOpts(title = "K线周期图表",pos_left = "0"), xaxis_opts = opts.AxisOpts( type_ = "category", is_scale = True, 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, splitline_opts = opts.SplitLineOpts(is_show = True) ), tooltip_opts = opts.TooltipOpts(trigger = "axis",axis_pointer_type = "line"), datazoom_opts = [ opts.DataZoomOpts( is_show = True,type_ = "inside",xaxis_index = [0,0],range_end = 100 ), opts.DataZoomOpts( is_show = True,xaxis_index = [0,1],pos_top = "97%",range_end = 100 ), opts.DataZoomOpts(is_show = False,xaxis_index = [0,2],range_end = 100), ], ) ) kline_line = ( Line() .add_xaxis(xaxis_data = data["times"]) .add_yaxis( series_name = "MA5", y_axis = calculate_ma(day_count = 5), is_smooth = True, linestyle_opts = opts.LineStyleOpts(opacity = 0.5), label_opts = opts.LabelOpts(is_show = False), ) .set_global_opts( xaxis_opts = opts.AxisOpts( type_ = "category", axislabel_opts = opts.LabelOpts(is_show = False), ), yaxis_opts = opts.AxisOpts( split_number = 3, 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), ), ) ) overlap_kline_line = kline.overlap(kline_line) bar_1 = ( Bar() .add_xaxis(xaxis_data = data["times"]) .add_yaxis( series_name = "Volumn", y_axis = data["vols"], label_opts = opts.LabelOpts(is_show = False), itemstyle_opts = opts.ItemStyleOpts( color = JsCode( """ function(params){ var colorList; if(barData[params.dataIndex][1] > barData[params.dataIndex][0]){ colorList = '#ef232a'; }else{ colorList = '#14b143'; } return colorList; } """ ) ), ) .set_global_opts( xaxis_opts = opts.AxisOpts( type_ = "category", axislabel_opts = opts.LabelOpts(is_show = False), ), legend_opts = opts.LegendOpts(is_show = False), ) ) bar_2 = ( Bar() .add_xaxis(xaxis_data = data["times"]) .add_yaxis( series_name = "MACD", y_axis = data["macds"], label_opts = opts.LabelOpts(is_show = False), itemstyle_opts = opts.ItemStyleOpts( color = JsCode( """ function(params){ var colorList; if(params.data >= 0){ colorList = '#ef232a'; }else{ colorList = '#14b143'; } return colorList; } """ ) ), ) .set_global_opts( xaxis_opts = opts.AxisOpts( type_ = "category", axislabel_opts = opts.LabelOpts(is_show = False), ), yaxis_opts = opts.AxisOpts( 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), ), legend_opts = opts.LegendOpts(is_show =False), ) ) line_2 = ( Line() .add_xaxis(xaxis_data = data["times"]) .add_yaxis( series_name = "DIF", y_axis = data["difs"], label_opts = opts.LabelOpts(is_show =False), ) .set_global_opts( legend_opts = opts.LegendOpts(is_show = False) ) ) overlap_bar_line = bar_2.overlap(line_2) grid_chart = Grid(init_opts = opts.InitOpts(width = "1400px",height = "800px",theme = ThemeType.ESSOS)) grid_chart.add_js_funcs("var barData={}".format(data["datas"])) grid_chart.add( overlap_kline_line, grid_opts = opts.GridOpts( pos_left="3%", pos_right="1%", height="60%" ), ) grid_chart.add( bar_1, grid_opts = opts.GridOpts( pos_left = "3%",pos_right = "1%",pos_top = "71%",height = "10%" ), ) grid_chart.add( overlap_bar_line, grid_opts = opts.GridOpts( pos_left = "3%",pos_right = "1%",pos_top = "82%",height = "14%" ) ) grid_chart.render("professional_kline_chart.html")
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 plot_kline(ka, bs=None, file_html="kline.html", width="1400px", height="680px"): """ :param ka: KlineAnalyze :param bs: pd.DataFrame 买卖点,包含三个字段 ["操作提示", "交易时间", "交易价格"] :param file_html: str :param width: str :param height: str :return: None """ df = ka.to_df(use_macd=True, ma_params=( 5, 20, )) x = df.dt.to_list() title = "%s | %s 至 %s" % (ka.symbol, ka.start_dt, ka.end_dt) kline = ( Kline().add_xaxis(xaxis_data=x).add_yaxis( series_name="", y_axis=df[['open', 'close', 'low', 'high']].values.tolist(), itemstyle_opts=opts.ItemStyleOpts( color="#ef232a", color0="#14b143", border_color="#ef232a", border_color0="#14b143", ), ).set_series_opts(markarea_opts=opts.MarkAreaOpts( is_silent=True)).set_global_opts( title_opts=opts.TitleOpts(title=title, pos_left="0"), xaxis_opts=opts.AxisOpts( type_="category", is_scale=True, 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, splitline_opts=opts.SplitLineOpts(is_show=True), axislabel_opts=opts.LabelOpts(is_show=True, position="inside")), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="line"), datazoom_opts=[ opts.DataZoomOpts(is_show=False, type_="inside", xaxis_index=[0, 0], range_end=100), opts.DataZoomOpts(is_show=True, xaxis_index=[0, 1], pos_top="96%", range_end=100), opts.DataZoomOpts(is_show=False, xaxis_index=[0, 2], range_end=100), ], # 三个图的 axis 连在一块 axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), )) kline_line = (Line().add_xaxis(xaxis_data=x).add_yaxis( series_name="笔", y_axis=df.bi.tolist(), is_smooth=False, is_connect_nones=True, symbol='diamond', symbol_size=8, linestyle_opts=opts.LineStyleOpts(opacity=1, type_='dotted', width=2), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="线段", y_axis=df.xd.tolist(), is_smooth=False, is_connect_nones=True, symbol='triangle', symbol_size=12, linestyle_opts=opts.LineStyleOpts(opacity=1, type_='solid', width=2), label_opts=opts.LabelOpts(is_show=True, position='right'), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( grid_index=1, split_number=3, 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, position="inside"), ), )) # Overlap Kline + Line overlap_kline_line = kline.overlap(kline_line) if isinstance(bs, pd.DataFrame) and len(bs) > 0: c = (Scatter().add_xaxis(bs['交易时间'].to_list()).add_yaxis( "买卖点", bs['交易价格'].to_list(), label_opts=opts.LabelOpts( is_show=True, position="left", formatter=JsCode( "function(params){return bsName[params.dataIndex][0];}")), )) overlap_kline_line = overlap_kline_line.overlap(c) # draw volume bar_1 = (Bar().add_xaxis(xaxis_data=x).add_yaxis( series_name="Volumn", yaxis_data=df.vol.tolist(), xaxis_index=1, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color=JsCode(""" function(params) { var colorList; if (barData[params.dataIndex][1] > barData[params.dataIndex][0]) { colorList = '#ef232a'; } else { colorList = '#14b143'; } return colorList; } """)), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(is_show=True, position='inside')), legend_opts=opts.LegendOpts(is_show=False), )) # Bar-2 (Overlap Bar + Line) bar_2 = (Bar().add_xaxis(xaxis_data=x).add_yaxis( series_name="MACD", yaxis_data=df.macd.tolist(), xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color=JsCode(""" function(params) { var colorList; if (params.data >= 0) { colorList = '#ef232a'; } else { colorList = '#14b143'; } return colorList; } """)), ).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, position="inside"), ), legend_opts=opts.LegendOpts(is_show=False), )) line_2 = (Line().add_xaxis(xaxis_data=x).add_yaxis( series_name="DIF", y_axis=df['diff'].tolist(), xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="DEA", y_axis=df['dea'].tolist(), xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), ).set_global_opts(legend_opts=opts.LegendOpts(is_show=False))) # draw MACD overlap_bar_line = bar_2.overlap(line_2) # 最后的 Grid grid_chart = Grid( init_opts=opts.InitOpts(width=width, height=height, page_title=title)) grid_chart.add_js_funcs("var barData = {}".format( df[['open', 'close', 'low', 'high']].values.tolist())) if isinstance(bs, pd.DataFrame) and len(bs) > 0: grid_chart.add_js_funcs("var bsName = {}".format( bs[["操作提示", "交易价格"]].values.tolist())) grid_chart.add( overlap_kline_line, grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", height="60%"), ) grid_chart.add( bar_1, grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", pos_top="71%", height="10%"), ) grid_chart.add( overlap_bar_line, grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", pos_top="82%", height="14%"), ) grid_chart.render(path=file_html)
def draw_charts(stock_data,name): x = stock_data['TIME'].values.tolist() y = stock_data[name].values.tolist() indexes_peaks, line_peaks=get_line_peaks(stock_data[name]) indexes_valleys, line_valleys=get_line_valleys(stock_data[name]) line = ( Line() .add_xaxis(x) .add_yaxis('收盘价', y, label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ) .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(type_="inside")], title_opts=opts.TitleOpts(title="股票价格", subtitle=ts_code, pos_left='15%', pos_top="40%"), # 把所有的x轴连接在一起 axispointer_opts=opts.AxisPointerOpts(is_show=True, link=[{"xAxisIndex": "all"}], label=opts.LabelOpts(background_color="#777"), ), ) ) # 极大值的散点图 scatter_peak = ( Scatter() .add_xaxis(indexes_peaks) .add_yaxis('Peaks', line_peaks, label_opts=opts.LabelOpts(is_show=False), symbol='triangle', symbol_rotate=180, itemstyle_opts=opts.ItemStyleOpts(color='#ef232a')) .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(type_="inside")], ) ) scatter_valley = ( Scatter() .add_xaxis(indexes_valleys) .add_yaxis('Valleys', line_valleys, label_opts=opts.LabelOpts(is_show=False), symbol='triangle', itemstyle_opts=opts.ItemStyleOpts(color='#14b143')) .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(type_="inside")], ) ) #绘制布林带 line_boll = ( Line() .add_xaxis(x) .add_yaxis( series_name="MID", y_axis=stock_data["MID"].values.tolist(), linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ) .add_yaxis( series_name="UPPER", y_axis=stock_data["UPPER"].values.tolist(), linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ) .add_yaxis( series_name="LOWER", y_axis=stock_data["LOWER"].values.tolist(), linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ) .set_global_opts(datazoom_opts=[opts.DataZoomOpts(type_="inside", )], 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) ), ), ) ) stock_basic_data = stock_data[["TIME", "OPEN", "CLOSE", "LOW", "HIGH"]] # 绘制K线图 kline = ( Kline() .add_xaxis(x) .add_yaxis("K线图", stock_basic_data.iloc[:, 1:5].values.tolist(), itemstyle_opts=opts.ItemStyleOpts( color="#ec0000", color0="#00da3c" ), ) .set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True, is_show=False), # axis_opts=opts.AxisOpts(is_scale=True,min_=0), #y轴起始坐标可以设为0 yaxis_opts=opts.AxisOpts(is_scale=True, splitarea_opts=opts.SplitAreaOpts(is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), # y轴起始坐标可自动调整 tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="line"), legend_opts=opts.LegendOpts(is_show=True, orient='vertical', pos_right="5%", pos_top='20%'), datazoom_opts=[ # 设置zoom参数后即可缩放 opts.DataZoomOpts( is_show=True, type_="inside", ), ], ) ) line_close = ( Line() .add_xaxis(x) .add_yaxis('五日均线', stock_data["MA5"].values.tolist(), label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ) .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(type_="inside")], ) ) overlap_findpeak = line.overlap(scatter_peak) overlap_findpeak = overlap_findpeak.overlap(scatter_valley) overlap_findpeak = overlap_findpeak.overlap(line_boll) overlap_findpeak = overlap_findpeak.overlap(kline) overlap_findpeak = overlap_findpeak.overlap(line_close) grid_chart = Grid(init_opts=opts.InitOpts( width="1400px", height="700px", animation_opts=opts.AnimationOpts(animation=False), )) grid_chart.add( overlap_findpeak, grid_opts=opts.GridOpts(pos_left="25%", pos_right="15%", pos_top="10%"), ) grid_chart.render('stock_{}/find_peak.html'.format(ts_code))
def kline_pro(kline: List[dict], fx: List[dict] = None, bi: List[dict] = None, xd: List[dict] = None, bs: List[dict] = None, title: str = "缠中说禅K线分析", t_seq: List[int] = None, width: str = "1400px", height: str = '580px') -> Grid: """绘制缠中说禅K线分析结果 :param kline: K线 :param fx: 分型识别结果 :param bi: 笔识别结果 {'dt': Timestamp('2020-11-26 00:00:00'), 'fx_mark': 'd', 'start_dt': Timestamp('2020-11-25 00:00:00'), 'end_dt': Timestamp('2020-11-27 00:00:00'), 'fx_high': 144.87, 'fx_low': 138.0, 'bi': 138.0} :param xd: 线段识别结果 :param bs: 买卖点 :param title: 图表标题 :param t_seq: 均线系统 :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], range_start=80, range_end=100) dz_slider = opts.DataZoomOpts(True, "slider", xaxis_index=[0, 1, 2], pos_top="96%", pos_bottom="0%", range_start=80, 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['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['vol'], 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) 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 ) # 均线图 # ------------------------------------------------------------------------------------------------------------------ chart_ma = Line() chart_ma.add_xaxis(xaxis_data=dts) if not t_seq: t_seq = [10, 20, 60, 120, 250] ma_keys = dict() for t in t_seq: ma_keys[f"MA{t}"] = SMA(close, timeperiod=t) for i, (name, ma) in enumerate(ma_keys.items()): chart_ma.add_yaxis(series_name=name, y_axis=ma, is_smooth=True, is_selected=True, symbol_size=0, label_opts=label_not_show_opts, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1)) 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 = Line() 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)", ), linestyle_opts=opts.LineStyleOpts(width=1.5)) 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 = Line() 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['price'] 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['price'] 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
[2411, 2433.13, 2403.3, 2437.42], [2432.68, 2334.48, 2427.7, 2441.73], [2430.69, 2418.53, 2394.22, 2433.89], [2416.62, 2432.4, 2414.4, 2443.03], [2441.91, 2421.56, 2418.43, 2444.8], [2420.26, 2382.91, 2373.53, 2427.07], [2383.49, 2397.18, 2370.61, 2397.94], [2378.82, 2325.95, 2309.17, 2378.82], [2322.94, 2314.16, 2308.76, 2330.88], [2320.62, 2325.82, 2315.01, 2338.78], [2313.74, 2293.34, 2289.89, 2340.71], [2297.77, 2313.22, 2292.03, 2324.63], [2322.32, 2365.59, 2308.92, 2366.16], [2364.54, 2359.51, 2330.86, 2369.65], [2332.08, 2273.4, 2259.25, 2333.54], [2274.81, 2326.31, 2270.1, 2328.14], [2333.61, 2347.18, 2321.6, 2351.44], [2340.44, 2324.29, 2304.27, 2352.02], [2326.42, 2318.61, 2314.59, 2333.67], [2314.68, 2310.59, 2296.58, 2320.96], [2309.16, 2286.6, 2264.83, 2333.29], [2282.17, 2263.97, 2253.25, 2286.33], [2255.77, 2270.28, 2253.31, 2276.22], ] c = (Kline().add_xaxis(["2017/7/{}".format(i + 1) for i in range(31) ]).add_yaxis("kline", data).set_global_opts( yaxis_opts=opts.AxisOpts(is_scale=True), xaxis_opts=opts.AxisOpts(is_scale=True), title_opts=opts.TitleOpts(title="Kline-基本示例"), ).render("5.kline_base.html"))
def K(self) -> Kline: data = self.data[self.prices_cols].values.tolist() c = (Kline().add_xaxis(self.dateindex).add_yaxis( "k线", data).set_global_opts( title_opts=opts.TitleOpts(title=self.title, pos_left="0"), legend_opts=opts.LegendOpts(is_show=False, pos_bottom=10, pos_left="center"), datazoom_opts=[ opts.DataZoomOpts( is_show=True, xaxis_index=[0, 1], type_="slider", pos_top="85%", range_start=0, range_end=100, ), ], xaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(is_show=False), axistick_opts=opts.AxisTickOpts(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=2, 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", ), )) if len(self.klines) != 0: kLine = Line().add_xaxis(self.dateindex) for i in self.klines: kLine.add_yaxis( i, round(self.data[i], self.precision).values.tolist(), is_smooth=True, is_symbol_show=False, is_hover_animation=False, label_opts=opts.LabelOpts(is_show=True), linestyle_opts=opts.LineStyleOpts(type_='solid', width=2), ) kLine.set_global_opts( xaxis_opts=opts.AxisOpts(type_="category", is_show=False)) c.overlap(kLine) if 'BUY' in self.data.columns: v1 = self.data[self.data['BUY'] == True].index.strftime( "%Y-%m-%d").tolist() v2 = self.data[self.data['BUY'] == True]['close'] es_buy = (EffectScatter().add_xaxis(v1).add_yaxis( "", v2, symbol=SymbolType.ARROW, is_selected=True)) c.overlap(es_buy) if 'SELL' in self.data.columns: v1 = self.data[self.data['SELL'] == True].index.strftime( "%Y-%m-%d").tolist() v2 = self.data[self.data['SELL'] == True]['low'] es_sell = (EffectScatter().add_xaxis(v1).add_yaxis("", v2)) c.overlap(es_sell) return c
def draw_chart(): kline = ( Kline().add_xaxis(xaxis_data=data["times"]).add_yaxis( series_name="", y_axis=data["datas"], 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="最小值"), ]), markline_opts=opts.MarkLineOpts( label_opts=opts.LabelOpts(position="middle", color="blue", font_size=15), data=split_data_part(), symbol=["circle", "none"], ), ).set_series_opts(markarea_opts=opts.MarkAreaOpts( is_silent=True, data=split_data_part())). set_global_opts( title_opts=opts.TitleOpts(title="K线周期图表", pos_left="0"), xaxis_opts=opts.AxisOpts( type_="category", is_scale=True, 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, splitline_opts=opts.SplitLineOpts(is_show=True)), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="line"), datazoom_opts=[ opts.DataZoomOpts(is_show=False, type_="inside", xaxis_index=[0, 0], range_end=100), opts.DataZoomOpts(is_show=True, xaxis_index=[0, 1], pos_top="97%", range_end=100), opts.DataZoomOpts(is_show=False, xaxis_index=[0, 2], range_end=100), ], # 三个图的 axis 连在一块 # axispointer_opts=opts.AxisPointerOpts( # is_show=True, # link=[{"xAxisIndex": "all"}], # label=opts.LabelOpts(background_color="#777"), # ), )) kline_line = (Line().add_xaxis(xaxis_data=data["times"]).add_yaxis( series_name="MA5", y_axis=calculate_ma(day_count=5), is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( grid_index=1, split_number=3, 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), ), )) # Overlap Kline + Line overlap_kline_line = kline.overlap(kline_line) # Bar-1 print(data["vols"]) bar_1 = ( Bar().add_xaxis(xaxis_data=data["times"]).add_yaxis( series_name="Volumn", y_axis=data["vols"], xaxis_index=1, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False), # 根据 echarts demo 的原版是这么写的 # itemstyle_opts=opts.ItemStyleOpts( # color=JsCode(""" # function(params) { # var colorList; # if (data.datas[params.dataIndex][1]>data.datas[params.dataIndex][0]) { # colorList = '#ef232a'; # } else { # colorList = '#14b143'; # } # return colorList; # } # """) # ) # 改进后在 grid 中 add_js_funcs 后变成如下 itemstyle_opts=opts.ItemStyleOpts(color=JsCode(""" function(params) { var colorList; if (barData[params.dataIndex][1] > barData[params.dataIndex][0]) { colorList = '#ef232a'; } else { colorList = '#14b143'; } return colorList; } """)), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=False), ), legend_opts=opts.LegendOpts(is_show=False), )) # Bar-2 (Overlap Bar + Line) bar_2 = (Bar().add_xaxis(xaxis_data=data["times"]).add_yaxis( series_name="MACD", y_axis=data["macds"], xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color=JsCode(""" function(params) { var colorList; if (params.data >= 0) { colorList = '#ef232a'; } else { colorList = '#14b143'; } return colorList; } """)), ).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), ), legend_opts=opts.LegendOpts(is_show=False), )) line_2 = (Line().add_xaxis(xaxis_data=data["times"]).add_yaxis( series_name="DIF", y_axis=data["difs"], xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="DIF", y_axis=data["deas"], xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), ).set_global_opts(legend_opts=opts.LegendOpts(is_show=False))) # 最下面的柱状图和折线图 overlap_bar_line = bar_2.overlap(line_2) # 最后的 Grid grid_chart = Grid(init_opts=opts.InitOpts(width="1400px", height="800px")) # 这个是为了把 data.datas 这个数据写入到 html 中,还没想到怎么跨 series 传值 # demo 中的代码也是用全局变量传的 grid_chart.add_js_funcs("var barData = {}".format(data["datas"])) # K线图和 MA5 的折线图 grid_chart.add( overlap_kline_line, grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", height="60%"), ) # Volumn 柱状图 grid_chart.add( bar_1, grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", pos_top="71%", height="10%"), ) # MACD DIFS DEAS grid_chart.add( overlap_bar_line, grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", pos_top="82%", height="14%"), ) grid_chart.render("1.professional_kline_chart.html")
2397.94], [2378.82, 2325.95, 2309.17, 2378.82], [2322.94, 2314.16, 2308.76, 2330.88], [2320.62, 2325.82, 2315.01, 2338.78], [2313.74, 2293.34, 2289.89, 2340.71], [2297.77, 2313.22, 2292.03, 2324.63], [2322.32, 2365.59, 2308.92, 2366.16], [2364.54, 2359.51, 2330.86, 2369.65], [2332.08, 2273.4, 2259.25, 2333.54], [2274.81, 2326.31, 2270.1, 2328.14], [2333.61, 2347.18, 2321.6, 2351.44], [2340.44, 2324.29, 2304.27, 2352.02], [2326.42, 2318.61, 2314.59, 2333.67], [2314.68, 2310.59, 2296.58, 2320.96], [2309.16, 2286.6, 2264.83, 2333.29], [2282.17, 2263.97, 2253.25, 2286.33], [2255.77, 2270.28, 2253.31, 2276.22]] c = (Kline().add_xaxis([ "2018/9/{}".format(i + 1) for i in range(31) ]).add_yaxis("kline", v1, markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_='max', value_dim="close")])) ).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(type_="inside")], title_opts=opts.TitleOpts(title="K线图示例")).render(r'k.html')
def draw2(df: pd.DataFrame, ts_name: str): kline = ( Kline().add_xaxis(df["trade_date"].values.tolist()).add_yaxis( series_name=ts_name, y_axis=df[["open", "close", "low", "high"]].values.tolist(), itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c")). set_global_opts( legend_opts=opts.LegendOpts(is_show=False, pos_bottom=10, pos_left="center"), datazoom_opts=[opts.DataZoomOpts(pos_bottom="-2%")], # datazoom_opts=[ # opts.DataZoomOpts( # is_show=False, # type_="inside", # xaxis_index=[0, 1], # range_start=98, # range_end=100, # ), # opts.DataZoomOpts( # is_show=True, # xaxis_index=[0, 1], # type_="slider", # pos_top="85%", # range_start=98, # 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", ), )) sma_5 = talib.SMA(np.array(df['close']), 5) sma_10 = talib.SMA(np.array(df['close']), 10) sma_20 = talib.SMA(np.array(df['close']), 20) sma_30 = talib.SMA(np.array(df['close']), 30) line = (Line().add_xaxis(xaxis_data=df["trade_date"]).add_yaxis( series_name="MA5", y_axis=sma_5, is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA10", y_axis=sma_10, is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA20", y_axis=sma_20, is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA30", y_axis=sma_30, is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).set_global_opts(xaxis_opts=opts.AxisOpts(type_="category"))) bar = (Bar().add_xaxis( xaxis_data=df["trade_date"].values.tolist()).add_yaxis( series_name="Volume", y_axis=df["vol"].values.tolist(), xaxis_index=1, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False), ).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 Overlap + Bar 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("b.html")
name = 'jinshan' data = [] datetime = [] for i in range(1, 30): if i % 7 == 4 or i % 7 == 5: continue datetime.append(i) date = '07-' + '{:02d}'.format(i) path = os.getcwd() + '/stock/' + name + '/金山-07-' + '{:02d}'.format( i) + '.csv' df = pd.read_csv(path) value = df.iloc[:, 2].values open = value[0] close = value[-1] highest = max(value) lowest = min(value) data.append([open, close, lowest, highest]) c = (Kline().add_xaxis(["2017/07/{}".format(i) for i in datetime]).add_yaxis( "kline", data).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(type_="inside")], title_opts=opts.TitleOpts(title="云计算第一组金山股7月k线图"), ).render("金山.html"))
[2320.62, 2325.82, 2315.01, 2338.78], [2313.74, 2293.34, 2289.89, 2340.71], [2297.77, 2313.22, 2292.03, 2324.63], [2322.32, 2365.59, 2308.92, 2366.16], [2364.54, 2359.51, 2330.86, 2369.65], [2332.08, 2273.4, 2259.25, 2333.54], [2274.81, 2326.31, 2270.1, 2328.14], [2333.61, 2347.18, 2321.6, 2351.44], [2340.44, 2324.29, 2304.27, 2352.02], [2326.42, 2318.61, 2314.59, 2333.67], [2314.68, 2310.59, 2296.58, 2320.96], [2309.16, 2286.6, 2264.83, 2333.29], [2282.17, 2263.97, 2253.25, 2286.33], [2255.77, 2270.28, 2253.31, 2276.22], ] c = (Kline().add_xaxis( ["2017/7/{}".format(i + 1) for i in range(31)]).add_yaxis( "kline", data, markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_="max", value_dim="close")]), ).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)), ), title_opts=opts.TitleOpts(title="Kline-MarkLine"), ).render("4.kline_markline.html"))
from pyecharts import options as opts from pyecharts.charts import Kline import os import pandas as pd name = 'yingbang' path = os.getcwd() + '/' + name + '.csv' df = pd.read_csv(path) data = [] datetime = [] for i in reversed(range(23)): data.append([df.iloc[i, 1], df.iloc[i, 2], df.iloc[i, 4], df.iloc[i, 3]]) datetime.append(df.iloc[i, 0]) c = (Kline().add_xaxis(datetime).add_yaxis("kline", data).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(type_="inside")], title_opts=opts.TitleOpts(title="云计算第一组人民币对英镑7月k线图"), ).render("英镑.html"))
def bar_base() -> Bar: # c = ( # Bar() # .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]) # .add_yaxis("商家A", [randrange(0, 100) for _ in range(6)]) # .add_yaxis("商家B", [randrange(0, 100) for _ in range(6)]) # .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题")) # ) data = [ [2320.26, 2320.26, 2287.3, 2362.94], [2300, 2291.3, 2288.26, 2308.38], [2295.35, 2346.5, 2295.35, 2345.92], [2347.22, 2358.98, 2337.35, 2363.8], [2360.75, 2382.48, 2347.89, 2383.76], [2383.43, 2385.42, 2371.23, 2391.82], [2377.41, 2419.02, 2369.57, 2421.15], [2425.92, 2428.15, 2417.58, 2440.38], [2411, 2433.13, 2403.3, 2437.42], [2432.68, 2334.48, 2427.7, 2441.73], [2430.69, 2418.53, 2394.22, 2433.89], [2416.62, 2432.4, 2414.4, 2443.03], [2441.91, 2421.56, 2418.43, 2444.8], [2420.26, 2382.91, 2373.53, 2427.07], [2383.49, 2397.18, 2370.61, 2397.94], [2378.82, 2325.95, 2309.17, 2378.82], [2322.94, 2314.16, 2308.76, 2330.88], [2320.62, 2325.82, 2315.01, 2338.78], [2313.74, 2293.34, 2289.89, 2340.71], [2297.77, 2313.22, 2292.03, 2324.63], [2322.32, 2365.59, 2308.92, 2366.16], [2364.54, 2359.51, 2330.86, 2369.65], [2332.08, 2273.4, 2259.25, 2333.54], [2274.81, 2326.31, 2270.1, 2328.14], [2333.61, 2347.18, 2321.6, 2351.44], [2340.44, 2324.29, 2304.27, 2352.02], [2326.42, 2318.61, 2314.59, 2333.67], [2314.68, 2310.59, 2296.58, 2320.96], [2309.16, 2286.6, 2264.83, 2333.29], [2282.17, 2263.97, 2253.25, 2286.33], [2255.77, 2270.28, 2253.31, 2276.22], ] c = (Kline().add_xaxis( ["2017/7/{}".format(i + 1) for i in range(31)]).add_yaxis( "kline", data, markline_opts=opts.MarkLineOpts(data=[ opts.MarkLineItem(type_="max", value_dim="close"), opts.MarkLineItem(type_="min", value_dim="close"), ], linestyle_opts=[]), ).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)), ), title_opts=opts.TitleOpts(title="Kline-MarkLine"), )) return c
def ohlc_kline_chart(df, x_axis_count=2, signal_infos=[]): """创建一个 OHLC K线图,并返回 :time_series 时间数组 :ohlc_data K线数据 :x_axis_count 控制要缩放的 X 轴数量 """ time_series = pyecharts_time_data(df) ohlc_data = pyecharts_ohlc_data(df) kline = (Kline().add_xaxis(xaxis_data=time_series).add_yaxis( series_name="K线", y_axis=ohlc_data, yaxis_index=2, itemstyle_opts=opts.ItemStyleOpts( color="#314555", color0="#ec0000", border_color="#314555", border_color0="#ec0000", ), markpoint_opts=opts.MarkPointOpts(data=[{ 'value': info[2], "coord": [info[0], info[1]], "itemStyle": { "color": info[3] } } for info in signal_infos]), ).set_global_opts( legend_opts=opts.LegendOpts( is_show=True, pos_top=10, pos_left="center", ), title_opts=opts.TitleOpts(title=""), datazoom_opts=[ opts.DataZoomOpts( is_show=True, xaxis_index=list(range(0, x_axis_count)), type_="slider", pos_top="90%", range_start=50, range_end=100, ), ], xaxis_opts=opts.AxisOpts( is_scale=True, splitline_opts=opts.SplitLineOpts( is_show=True, linestyle_opts=opts.LineStyleOpts(type_='dotted')), ), 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": "#314555" }, { "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", ), )) return kline
[2274.81, 2326.31, 2270.1, 2328.14], [2333.61, 2347.18, 2321.6, 2351.44], [2340.44, 2324.29, 2304.27, 2352.02], [2326.42, 2318.61, 2314.59, 2333.67], [2314.68, 2310.59, 2296.58, 2320.96], [2309.16, 2286.6, 2264.83, 2333.29], [2282.17, 2263.97, 2253.25, 2286.33], [2255.77, 2270.28, 2253.31, 2276.22], ] c = ( Kline() .add_xaxis(["2017/7/{}".format(i + 1) for i in range(31)]) .add_yaxis("kline", data) .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="-2%")], title_opts=opts.TitleOpts(title="Kline-DataZoom-slider-Position"), ) ) c.width = "100%" put_html(c.render_notebook())
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 plot_kline( df, rendered=True, ucolor="#ef232a", dcolor="#14b143", ucolorborder=None, dcolorborder=None, ucolorvolume=None, dcolorvolume=None, col="", ): """ 针对 dataframe 直接画出标准看盘软件的上k线图下成交量图的形式 :param df: :param rendered: :param ucolor: str for color when going up, default red in A stock as "#ef232a" :param dcolor: str for color when going down, default green in A stock as "#14b143" :param col: :return: """ # TODO: color changing seems to make no effect, possible issue with pyecharts if ucolorborder is None: ucolorborder = ucolor if dcolorborder is None: dcolorborder = dcolor if ucolorvolume is None: if ucolor != "#ffffff": ucolorvolume = ucolor else: ucolorvolume = ucolorborder if dcolorvolume is None: if dcolor != "#ffffff": dcolorvolume = dcolor else: dcolorvolume = dcolorborder kline = ( Kline().add_xaxis(xaxis_data=list(df["date"])).add_yaxis( series_name="", itemstyle_opts=opts.ItemStyleOpts( color=ucolor, color0=dcolor, border_color=ucolorborder, # ucolor, border_color0=dcolorborder, # dcolor, ), y_axis=list(zip(df["open"], df["close"], df["low"], df["high"])), markpoint_opts=opts.MarkPointOpts( data=[ opts.MarkPointItem(type_="max", name="最大值"), opts.MarkPointItem(type_="min", name="最小值"), ], symbol="pin", symbol_size=[56, 40], # label_opts=opts.LabelOpts(color="#CCFFFF",position=["top", "bottom"]) ), ).set_global_opts( datazoom_opts=[ opts.DataZoomOpts( is_show=True, type_="slider", range_start=50, range_end=100, xaxis_index=[0, 1], ), opts.DataZoomOpts( is_show=False, type_="inside", range_start=50, range_end=100, xaxis_index=1, ), ], tooltip_opts=opts.TooltipOpts( is_show=True, trigger="axis", trigger_on="mousemove", axis_pointer_type="cross", ), )) if col is not None: for c in col: line = (Line().add_xaxis(xaxis_data=list(df["date"])).add_yaxis( series_name=c, y_axis=list(df[c]), is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), )) kline = kline.overlap(line) if "volume" in df.columns: vl = list(df["volume"]) elif "amount" in df.columns: vl = list(df["amount"]) else: vl = [0 for _ in range(len(df))] bar = ( Bar().add_js_funcs("var barData = {}".format( list(df["close"] - df["open"]))).add_xaxis( xaxis_data=list(df["date"])).add_yaxis( series_name="", yaxis_data=vl, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts( color=JsCode(""" function(params) {{ var colorList; if (barData[params.dataIndex]>0) {{ colorList = '{ucolor}'; }} else {{ colorList = '{dcolor}'; }} return colorList; }} """.format(ucolor=ucolorvolume, dcolor=dcolorvolume)) # escape {} when using format ), ).set_global_opts(tooltip_opts=opts.TooltipOpts( is_show=True, trigger="axis", trigger_on="mousemove", axis_pointer_type="cross", ), )) grid_chart = Grid() grid_chart.add_js_funcs("var barData = {}".format( list(df["close"] - df["open"]))) grid_chart.add( kline, grid_opts=opts.GridOpts(pos_left="10%", pos_right="1%", pos_top="2%", height="65%"), ) grid_chart.add( bar, grid_opts=opts.GridOpts(pos_left="10%", pos_right="1%", pos_top="71%", height="22%"), ) if rendered: return grid_chart.render_notebook() else: return grid_chart
[2420.26, 2382.91, 2373.53, 2427.07], [2383.49, 2397.18, 2370.61, 2397.94], [2378.82, 2325.95, 2309.17, 2378.82], [2322.94, 2314.16, 2308.76, 2330.88], [2320.62, 2325.82, 2315.01, 2338.78], [2313.74, 2293.34, 2289.89, 2340.71], [2297.77, 2313.22, 2292.03, 2324.63], [2322.32, 2365.59, 2308.92, 2366.16], [2364.54, 2359.51, 2330.86, 2369.65], [2332.08, 2273.4, 2259.25, 2333.54], [2274.81, 2326.31, 2270.1, 2328.14], [2333.61, 2347.18, 2321.6, 2351.44], [2340.44, 2324.29, 2304.27, 2352.02], [2326.42, 2318.61, 2314.59, 2333.67], [2314.68, 2310.59, 2296.58, 2320.96], [2309.16, 2286.6, 2264.83, 2333.29], [2282.17, 2263.97, 2253.25, 2286.33], [2255.77, 2270.28, 2253.31, 2276.22], ] c = (Kline().add_xaxis( ["2017/7/{}".format(i + 1) for i in range(31)]).add_yaxis("kline", data).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)), ), title_opts=opts.TitleOpts(title="Kline-显示分割区域"), ).render("10.kline_split_area.html"))
def kline(self): """""" kline = Kline(init_opts=opts.InitOpts(width="1400px", height="800px")) kline.add_xaxis(xaxis_data=self.bar_data_datetime) kline.add_yaxis( series_name=f"{self.bar_data.symbol[0]}", yaxis_index=0, y_axis=self.bar_data[[ "open_price", "close_price", "low_price", "high_price" ]].values.tolist(), itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c", border_color="#8A0000", border_color0="#008F28", opacity=0.8), ) if self.grid == True and self.grid_quantity == 1: 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", ), # 添加主标题和副标题 # title_opts = opts.TitleOpts(title = "主标题", subtitle = " 副标题"), # 多图的 axis 连在一块 axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), ) elif self.grid == True and self.grid_quantity == 2: 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, ), opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0, 2], 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", ), # 添加主标题和副标题 # title_opts = opts.TitleOpts(title = "主标题", subtitle = " 副标题"), # 多图的 axis 连在一块 axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), ) else: kline.set_global_opts( # 单图形 datazoom_opts=opts.DataZoomOpts( is_show=False, type_="inside", 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", ), # 添加主标题和副标题 # title_opts = opts.TitleOpts(title = "主标题", subtitle = " 副标题"), # 多图的 axis 连在一块 axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), ) self.kline_chart = kline
x_data = [] y_data = [] for i in ret: str_date = datetime.datetime.strftime(i['date'], '%Y-%m-%d') x_data.append(str_date) y_data.append( [i['start_price'], i['max_price'], i['min_price'], i['stop_price']]) c = (Kline(init_opts=opts.InitOpts(width="1440px", height="800px")).add_xaxis( xaxis_data=x_data).add_yaxis( "kline", y_data, itemstyle_opts=opts.ItemStyleOpts( color="#ec0000", color0="#00da3c", border_color="#8A0000", border_color0="#008F28", ), ).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(type_="inside")], title_opts=opts.TitleOpts(title="abc005 K线走势图"), ).render("abc005kline.html"))
[2309.16, 2286.6, 2264.83, 2333.29], [2282.17, 2263.97, 2253.25, 2286.33], [2255.77, 2270.28, 2253.31, 2276.22], ] c=( Kline() .add_xaxis(["2017/7/{}".format(i + 1) for i in range(31)]) .add_yaxis("kline", data, itemstyle_opts=opts.ItemStyleOpts( color="#ec0000", color0="#00da3c", border_color="#8A0000", border_color0="#008F28", ) ) .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(type_="inside")], title_opts=opts.TitleOpts(title="K-line"), ) ) c.render("k-line.html")
def stock_draw_welcome(labels, mode_combo, startdate, enddate, optInterval): startdate = startdate.replace("/", "-") # 将参数日期转换为tushare的日期格式 enddate = enddate.replace("/", "-") tl = Timeline(init_opts=opts.InitOpts( width="1000px", height="500px", theme=ThemeType.WONDERLAND)) for label in labels: # 对于传入的labels一张张作图 label1 = re.split("-", label) #print(label1[0]) #print(label1[1]) if mode_combo == "KLine": array = ts.get_k_data(label1[1], start=startdate, end=enddate, ktype=optInterval) time = array['date'].tolist() # array.date # 绘图方法 if label1[2] == 'Kline': re_array = array[['open', 'close', 'high', 'low']] data_li = list(row.tolist() for index, row in re_array.iterrows()) close = array['close'].tolist() #width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels) kline = (Kline(init_opts=opts.InitOpts( width="1100px", height="500px", theme=ThemeType.WONDERLAND)).add_xaxis(time).add_yaxis( label1[0], data_li).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_top="10%")], title_opts=opts.TitleOpts(title=label1[0] + "-" + optInterval))) # 计算移动平均 if len(close) > 10: ma10 = CalculateMA(close, 10) line1 = ( Line().add_xaxis(time).add_yaxis("MA10", ma10) #.set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例")) .set_series_opts(label_opts=opts.LabelOpts( is_show=False))) kline.overlap(line1) if len(close) > 20: ma20 = CalculateMA(close, 20) line2 = ( Line().add_xaxis(time).add_yaxis("MA20", ma20) # .set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例")) .set_series_opts(label_opts=opts.LabelOpts( is_show=False))) kline.overlap(line2) if len(close) > 30: ma30 = CalculateMA(close, 30) line3 = ( Line().add_xaxis(time).add_yaxis("MA30", ma30) # .set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例")) .set_series_opts(label_opts=opts.LabelOpts( is_show=False))) kline.overlap(line3) tl.add(kline, label1[0] + "-" + optInterval) else: # label1[2]==open/close/volume if label1[2] == 'Open': list_aft = array['open'].tolist() elif label1[2] == 'Close': list_aft = array['close'].tolist() elif label1[2] == 'High': list_aft = array['high'].tolist() elif label1[2] == 'Low': list_aft = array['low'].tolist() elif label1[2] == 'Volume': # volume list_aft = array['volume'].tolist() else: list_aft = array['amount'].tolist() line = (Line().add_xaxis(time).add_yaxis( label1[0] + "-" + label1[2], list_aft).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="-8%")], title_opts=opts.TitleOpts( title=label1[0] + "-" + label1[2])).set_series_opts( label_opts=opts.LabelOpts(is_show=False))) return tl