Example #1
0
def signal_overview(price,
                    trades=None,
                    supplements=None,
                    plot_options={},
                    f_name="1213.html"):
    figs_counts = len(supplements)
    legends_heights = (figs_counts * 5)
    left = 90 - legends_heights
    height = left / figs_counts

    sub_plots = []

    fig_size = plot_options.setdefault("fig_size", ("1000px", "600px"))

    x_data = price.index.tolist()
    y_data = price.values.tolist()

    marks = supplements.get("marks")

    with_marks = True if marks is not None else False

    if with_marks:
        _ = pd.Series(index=price.index, data=np.arange(len(price)))

        marks_data = [
            opts.MarkPointItem(coord=[(x_data[int(l)]), (y_data[int(l)])],
                               itemstyle_opts=opts.ItemStyleOpts(
                                   color=plot_options.setdefault(
                                       v[0], colors[i]),
                                   opacity=0.6),
                               symbol_size=20,
                               symbol="pin")
            for i, v in enumerate(marks.items())
            for l in _.reindex(v[1]).dropna().values.tolist()
        ]
    else:
        marks_data = []
    with_trades = True if isinstance(trades, pd.Series) else False

    if with_trades:
        e_loc = [
            price.index.get_loc(i)
            for i in trades.index.get_level_values(0).unique()
        ]
        ex_loc = [
            price.index.get_loc(i)
            for i in trades.index.get_level_values(1).unique()
        ]
        pairs_loc = list(zip(e_loc, ex_loc))
        (pairs_loc)
        _b = [{"gt": p[0], "lte": p[1], "color": "#CD6839"} for p in pairs_loc]
        _c = [{
            "gt": pairs_loc[i][-1],
            "lte": p[0],
            "color": "#4A708B"
        } for i, p in enumerate(pairs_loc[1:])]
        _a = [{
            "lte": pairs_loc[0][0],
            "color": "#4A708B"
        }, {
            "gt": pairs_loc[-1][-1],
            "color": colors[0]
        }]
        pieces = _a + _b + _c
    else:
        pieces = []

    ds = np.unique(price.index.date)

    decor_ = price.groupby(
        price.index.date).apply(lambda x: [x.index[0], x.index[-1]]).loc[[
            l[1] for l in list(filter(lambda x: x[0] % 2 == 0, enumerate(ds)))
        ]]
    data_zoom_axis = np.arange(figs_counts).astype(int).tolist()

    line = (Line(
        init_opts=opts.InitOpts(width=fig_size[0], height=fig_size[1])
    ).add_xaxis(xaxis_data=x_data).add_yaxis(
        series_name="价格",
        y_axis=y_data,
        yaxis_index=0,
        is_smooth=True,
        is_symbol_show=False,
        is_hover_animation=False,
        linestyle_opts=opts.LineStyleOpts(width=2),
        markpoint_opts=opts.MarkPointOpts(data=marks_data, ),
    ).set_global_opts(
        title_opts=opts.TitleOpts(title="价格",
                                  pos_left='center',
                                  pos_top=str(figs_counts * 5) + "%"),
        toolbox_opts=opts.ToolboxOpts(is_show=True),
        tooltip_opts=opts.TooltipOpts(
            trigger="axis",
            axis_pointer_type="cross",
            border_width=1,
        ),
        legend_opts=opts.LegendOpts(pos_left="left"),
        axispointer_opts=opts.AxisPointerOpts(is_show=True,
                                              link=[{
                                                  "xAxisIndex": "all"
                                              }]),
        datazoom_opts=[
            opts.DataZoomOpts(is_show=True,
                              is_realtime=True,
                              xaxis_index=data_zoom_axis,
                              pos_top="5%",
                              range_start=0,
                              range_end=100,
                              orient="horizontal",
                              type_="inside"),
            opts.DataZoomOpts(type_="slider",
                              xaxis_index=data_zoom_axis,
                              pos_bottom="bottom"),
        ],
        yaxis_opts=opts.AxisOpts(
            is_scale=True,
            axistick_opts=opts.AxisTickOpts(is_inside=False),
            axispointer_opts=opts.AxisPointerOpts(is_show=True),
            axisline_opts=opts.AxisLineOpts(symbol='none'),
            splitline_opts=opts.SplitLineOpts(is_show=True)),
        xaxis_opts=opts.AxisOpts(is_show=False, ),
        visualmap_opts=opts.VisualMapOpts(
            is_show=False,
            is_piecewise=with_trades,
            dimension=0,
            pieces=pieces,
        ),
    ).set_series_opts(markarea_opts=opts.MarkAreaOpts(data=[
        opts.MarkAreaItem(
            name="",
            x=(d[0], d[1]),
            itemstyle_opts=opts.ItemStyleOpts(color="#A1A9AF", opacity=0.2),
        ) for d in decor_
    ])))

    sub_plots.append(line)

    if with_marks:
        _ = supplements.pop("marks")

    if len(supplements) > 0:

        last_pic = list(supplements.keys())[-1]

        for i, s_1 in enumerate(supplements.items()):

            k, v = s_1[0], s_1[1]
            print(k)
            ls = Line(
                init_opts=opts.InitOpts(width=fig_size[0], height=fig_size[1]))
            ls = ls.add_xaxis(xaxis_data=price.index.tolist())
            for j, s_2 in enumerate(v.items()):
                n, l = s_2[0], s_2[1]
                print(n)
                num = i * len(s_1) + j
                ls.add_yaxis(
                    series_name=n,
                    y_axis=l.tolist(),
                    yaxis_index=len(sub_plots),
                    linestyle_opts=opts.LineStyleOpts(
                        width=2, color=plot_options.setdefault(n,
                                                               colors[num])),
                    label_opts=opts.LabelOpts(is_show=False),
                )
            s = legends_heights + height * len(sub_plots)
            ls = ls.set_global_opts(
                title_opts=opts.TitleOpts(title=k,
                                          pos_left='center',
                                          pos_top=str(s) + "%"),
                legend_opts=opts.LegendOpts(pos_left="left",
                                            pos_top=str(len(sub_plots) * 5) +
                                            "%"),
                yaxis_opts=opts.AxisOpts(
                    is_scale=True,
                    axistick_opts=opts.AxisTickOpts(is_inside=False),
                    axispointer_opts=opts.AxisPointerOpts(is_show=True),
                    axisline_opts=opts.AxisLineOpts(symbol='none'),
                    splitline_opts=opts.SplitLineOpts(is_show=True)),
                xaxis_opts=opts.AxisOpts(is_show=(k == last_pic), ),
            ).set_series_opts(markarea_opts=opts.MarkAreaOpts(
                data=[
                    opts.MarkAreaItem(
                        name="",
                        x=(d[0], d[1]),
                        itemstyle_opts=opts.ItemStyleOpts(color="#A1A9AF",
                                                          opacity=0.2),
                    ) for d in decor_
                ],
                is_silent=False,
            ))
            sub_plots.append(ls)

    pos = [
        i + "%" for i in (height * np.arange(len(sub_plots)) +
                          legends_heights + 4.3).astype(str)
    ]

    g = (Grid(init_opts=opts.InitOpts(width=fig_size[0], height=fig_size[1])))
    for i, v in enumerate(sub_plots):
        g.add(
            chart=v,
            grid_opts=opts.GridOpts(pos_left=50,
                                    pos_right=50,
                                    pos_top=pos[i],
                                    height=str(height - 5) + "%"),
        )
    g.render(f_name)
Example #2
0
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 = pd.DataFrame(ka.kline)
    df = macd(df)
    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)
Example #3
0
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线分析",
              width: str = "1400px",
              height: str = '580px') -> Grid:
    """绘制缠中说禅K线分析结果

    :param kline: K线
    :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],
                                  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)

    ma5 = SMA(close, timeperiod=5)
    ma34 = SMA(close, timeperiod=34)
    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)

    # 均线图
    # ------------------------------------------------------------------------------------------------------------------
    chart_ma = Line()
    chart_ma.add_xaxis(xaxis_data=dts)

    ma_keys = {"MA5": ma5, "MA34": ma34, "MA233": ma233}
    ma_colors = ["#39afe6", "#da6ee8", "#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:
        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['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
Example #4
0
# -*- coding: utf-8 -*-
Example #5
0
from pyecharts import options as opts
from pyecharts.charts import Geo
from pyecharts.globals import ChartType
import ElectricityData

c = (Geo().add_schema(maptype="china").add(
    "geo",
    [
        list(z) for z in zip(ElectricityData.provinces,
                             ElectricityData.GWP2017heatmapvalues)
    ],
    type_=ChartType.HEATMAP,
).set_series_opts(label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
    visualmap_opts=opts.VisualMapOpts(
        min_=0,
        max_=1.2,
    ),
    title_opts=opts.TitleOpts(title="Geo-HeatMap"),
).render("GWP2017heatmap.html"))
Example #6
0
        red_dict['{}'.format(i[0])] = i[1]
    for j in blue_counter.most_common():
        blue_dict['{}'.format(j[0])] = j[1]

    # 对红蓝球号码和次数重新进行排序
    red_list = sorted(red_counter.most_common(), key=lambda number: number[0])
    blue_list = sorted(blue_counter.most_common(),
                       key=lambda number: number[0])

    red_bar = Bar()
    red_x = ['{}'.format(str(x[0])) for x in red_list]
    red_y = ['{}'.format(str(x[1])) for x in red_list]
    red_bar.add_xaxis(red_x)
    red_bar.add_yaxis('红色球出现次数', red_y)
    red_bar.set_global_opts(
        title_opts=opts.TitleOpts(title='大乐透彩票', subtitle='近14年数据'),
        toolbox_opts=opts.ToolboxOpts(),
        yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(
            formatter="{value}/次")),
        xaxis_opts=opts.AxisOpts(name='开奖号码'))
    red_bar.set_series_opts(markpoint_opts=opts.MarkPointOpts(data=[
        opts.MarkPointItem(type_='max', name='最大值'),
        opts.MarkPointItem(type_='min', name='最小值')
    ]))

    blue_bar = Bar()
    blue_x = ['{}'.format(str(x[0])) for x in blue_list]
    blue_y = ['{}'.format(str(x[1])) for x in blue_list]
    blue_bar.add_xaxis(blue_x)
    blue_bar.add_yaxis('蓝色球出现次数',
                       blue_y,
#!/usr/bin/env python
# coding=utf-8
import pyecharts.options as opts
from pyecharts.charts import Funnel
"""
Gallery 使用 pyecharts 1.0.0
参考地址: https://echarts.baidu.com/examples/editor.html?c=funnel

目前无法实现的功能:

1、暂时无法对漏斗图的长宽等范围操作进行修改
"""
x_data = ["展现", "点击", "访问", "咨询", "订单"]
y_data = [100, 80, 60, 40, 20]

data = [[x_data[i], y_data[i]] for i in range(len(x_data))]

(Funnel(init_opts=opts.InitOpts(width="1600px", height="800px")).add(
    series_name="",
    data_pair=data,
    gap=2,
    tooltip_opts=opts.TooltipOpts(trigger="item",
                                  formatter="{a} <br/>{b} : {c}%"),
    label_opts=opts.LabelOpts(is_show=True, position="inside"),
    itemstyle_opts=opts.ItemStyleOpts(border_color="#fff", border_width=1),
).set_global_opts(title_opts=opts.TitleOpts(
    title="漏斗图", subtitle="纯属虚构")).render("funnel_chart.html"))
Example #8
0
from pyecharts import options as opts
from pyecharts.charts import Geo
from pyecharts.faker import Faker

c = (
    Geo()
    .add_schema(maptype="china")
    .add("geo", [list(z) for z in zip(Faker.provinces, Faker.values())])
    .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    .set_global_opts(
        visualmap_opts=opts.VisualMapOpts(is_piecewise=True),
        title_opts=opts.TitleOpts(title="Geo-VisualMap(分段型)"),
    )
    .render("geo_visualmap_piecewise.html")
)
    def safe_message_count(self):
        print('本月基本信息统计')
        print('*************************************')
        df = pd.read_sql(f'select * from {self.table}', self.conn)
        safe_message_num = df['id'].count()
        print('本月安全息息条数:', safe_message_num)
        print('*************************************')
        print('本月发生不同性质的安全问题总数')
        group = df.groupby(by='性质').count()['id']
        print(group)
        print('*************************************')
        safe_message_score = df['分值'].sum()
        print(f'本月安全信息总分值为{safe_message_score}分')
        df['time'] = pd.to_datetime(df['检查时间'])
        print('**************其他功能****************')
        print('1、查询本月趋势图')
        print('2、本月小时趋势图')
        print('3、责任车间统计')
        print('4、责任人岗位统计')
        print('5、返回主菜单')
        p = input('请输入选择编号')
        if p == '1':
            df['time'] = df['time'].apply(lambda x: x.strftime('%Y%m%d'))
            ya = []
            for i in df['time'].unique():
                i = str(i)
                try:
                    bkk = df[df['time'] == i]['性质'].value_counts()['A类']
                    ya.append(str(bkk))
                except:
                    bkk = 0
                    ya.append(str(bkk))
            # print(ya, len(ya))
            yb = []
            for i in df['time'].unique():
                i = str(i)
                try:
                    bkk = df[df['time'] == i]['性质'].value_counts()['B类']
                    yb.append(str(bkk))
                except:
                    bkk = 0
                    yb.append(str(bkk))
            # print(yb, len(yb))
            yc = []
            for i in df['time'].unique():
                i = str(i)
                try:
                    bkk = df[df['time'] == i]['性质'].value_counts()['C类']
                    yc.append(str(bkk))
                except:
                    bkk = 0
                    yc.append(str(bkk))
            # print(yc, len(yc))
            yd = []
            for i in df['time'].unique():
                i = str(i)
                try:
                    bkk = df[df['time'] == i]['性质'].value_counts()['D类']
                    yd.append(str(bkk))
                except:
                    bkk = 0
                    yd.append(str(bkk))
            # print(yd, len(yd))
            x = df['time'].unique()
            a = []
            for i in x:
                a.append(str(i))
            (Line(init_opts=opts.InitOpts(
                width="1600px", height="800px")).add_xaxis(a).add_yaxis(
                    "A类", ya).add_yaxis("B类",
                                        yb).add_yaxis("C类",
                                                      yc).add_yaxis("D类", yd).
             set_global_opts(
                 title_opts=opts.TitleOpts(
                     title="现场安全信息性质分布(月)",
                     subtitle=f"统计时间:{self.table_name}"),
                 tooltip_opts=opts.TooltipOpts(trigger="axis"),
                 xaxis_opts=opts.AxisOpts(
                     axislabel_opts=opts.LabelOpts(rotate=45), name="日期"),
                 # toolbox_opts=opts.ToolBoxFeatureSaveAsImageOpts(background_color= "auto",type_='jpg'),
                 toolbox_opts=opts.ToolboxOpts(
                     is_show=True,
                     feature={
                         "saveAsImage": {
                             'backgroundColor': 'white'
                         },
                         "dataZoom": {},
                         "restore": {},
                         "magicType": {
                             "show": True,
                             "type": ["line", "bar"]
                         },
                         "dataView": {}
                     })).render(f"safe_message_month_{self.table_name}.html"))
            print('已画图成功')

        elif p == '2':
            df['time_H'] = df['time'].apply(lambda x: x.hour)
            x = df['time_H'].sort_values(ascending=True).unique()
            # print(df['time'],x)
            ya = []
            for i in x:
                try:
                    bkk = df[df['time_H'] == i]['性质'].value_counts()['A类']
                    ya.append(str(bkk))
                except:
                    bkk = 0
                    ya.append(str(bkk))
            # print(ya, len(ya))
            yb = []
            for i in x:
                try:
                    bkk = df[df['time_H'] == i]['性质'].value_counts()['B类']
                    yb.append(str(bkk))
                except:
                    bkk = 0
                    yb.append(str(bkk))
            # print(yb, len(yb))
            yc = []
            for i in x:
                try:
                    bkk = df[df['time_H'] == i]['性质'].value_counts()['C类']
                    yc.append(str(bkk))
                except:
                    bkk = 0
                    yc.append(str(bkk))
            # print(yc, len(yc))
            yd = []
            for i in x:
                try:
                    bkk = df[df['time_H'] == i]['性质'].value_counts()['D类']
                    yd.append(str(bkk))
                except:
                    bkk = 0
                    yd.append(str(bkk))
            # print(yd, len(yd))
            a = []
            for i in x:
                m = str(i) + ':00'
                a.append(m)
            (Line(init_opts=opts.InitOpts(width="1600px", height="800px")).
             add_xaxis(a).add_yaxis("A类", ya).add_yaxis("B类", yb).add_yaxis(
                 "C类", yc).add_yaxis("D类", yd).set_global_opts(
                     title_opts=opts.TitleOpts(
                         title="现场安全信息性质分布(小时)",
                         subtitle=f"统计时间:{self.table_name}"),
                     tooltip_opts=opts.TooltipOpts(trigger="axis"),
                     xaxis_opts=opts.AxisOpts(name="时间"),
                     toolbox_opts=opts.ToolboxOpts(
                         is_show=True,
                         feature={
                             "saveAsImage": {
                                 'backgroundColor': 'white'
                             },
                             "dataZoom": {},
                             "restore": {},
                             "magicType": {
                                 "show": True,
                                 "type": ["line", "bar"]
                             },
                             "dataView": {}
                         })).render(
                             f"safe_message_hour_{self.table_name}.html"))
            print('已画图成功')
        elif p == '3':
            group = df.groupby(by=df['录入科室']).count()['性质']
            x = group.index.tolist()
            y = group.values.tolist()
            # print(x)
            # print(y)
            (Line(
                init_opts=opts.InitOpts(width="1600px", height="800px")
            ).add_xaxis(x).add_yaxis("数量", y).set_global_opts(
                title_opts=opts.TitleOpts(title="现场安全信息车间统计分布",
                                          subtitle=f"统计时间:{self.table_name}"),
                tooltip_opts=opts.TooltipOpts(trigger="axis"),
                toolbox_opts=opts.ToolboxOpts(is_show=True,
                                              feature={
                                                  "saveAsImage": {
                                                      'backgroundColor':
                                                      'white'
                                                  },
                                                  "dataZoom": {},
                                                  "restore": {},
                                                  "magicType": {
                                                      "show": True,
                                                      "type": ["line", "bar"]
                                                  },
                                                  "dataView": {}
                                              }),
                # xaxis_opts=opts.AxisOpts(name_rotate=60, name="车间名称",axislabel_opts={"rotate": 45}))
                xaxis_opts=opts.AxisOpts(
                    axislabel_opts=opts.LabelOpts(rotate=30),
                    name="车间名称")).render(
                        f"safe_message_chejian_{self.table_name}.html"))
            print('已画图成功')
        elif p == '4':
            group = df.groupby(by=df['责任人岗位']).count()['性质']
            x = group.index.tolist()
            y = group.values.tolist()
            # print(x)
            # print(y)
            (Line(
                init_opts=opts.InitOpts(width="1600px", height="800px")
            ).add_xaxis(x).add_yaxis("数量", y).set_global_opts(
                title_opts=opts.TitleOpts(title="现场安全信息责任人岗位统计分布",
                                          subtitle=f"统计时间:{self.table_name}"),
                tooltip_opts=opts.TooltipOpts(trigger="axis"),
                toolbox_opts=opts.ToolboxOpts(is_show=True,
                                              feature={
                                                  "saveAsImage": {
                                                      'backgroundColor':
                                                      'white'
                                                  },
                                                  "dataZoom": {},
                                                  "restore": {},
                                                  "magicType": {
                                                      "show": True,
                                                      "type": ["line", "bar"]
                                                  },
                                                  "dataView": {}
                                              }),
                # xaxis_opts=opts.AxisOpts(name_rotate=60, name="车间名称",axislabel_opts={"rotate": 45}))
                xaxis_opts=opts.AxisOpts(
                    axislabel_opts=opts.LabelOpts(rotate=20),
                    name="责任人岗位")).render(
                        f"safe_message_duty_{self.table_name}.html"))
            print('已画图成功')
        else:
            self.run()
Example #10
0
from pywebio.output import put_html
from pyecharts import options as opts
from pyecharts.charts import Gauge

c = (Gauge().add("", [("完成率", 66.6)]).set_global_opts(
    title_opts=opts.TitleOpts(title="Gauge-基本示例")))

c.width = "100%"
put_html(c.render_notebook())
from pywebio.output import put_html
import math

from pyecharts import options as opts
from pyecharts.charts import Polar

data = []
for i in range(361):
    t = i / 180 * math.pi
    r = math.sin(2 * t) * math.cos(2 * t)
    data.append([r, i])
c = (Polar().add_schema(
    angleaxis_opts=opts.AngleAxisOpts(start_angle=0, min_=0)).add(
        "flower", data,
        label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
            title_opts=opts.TitleOpts(title="Polar-Flower")))

c.width = "100%"
put_html(c.render_notebook())
Example #12
0
#-------------------------------------------------------------------------------------
n = time.strftime("%Y-%m-%d") + "-daily.csv"
data = pd.read_csv(n)
date_list = list(data['date'])
confirm_list = list(data['confirm'])
suspect_list = list(data['suspect'])
dead_list = list(data['dead'])
heal_list = list(data['heal'])
print(date_list)  # 日期
print(confirm_list)  # 确诊数据
print(suspect_list)  # 疑似数据
print(dead_list)  # 死亡数据
print(heal_list)  # 治愈数据

#-------------------------------------------------------------------------------------
# 第二步:绘制柱状图
#-------------------------------------------------------------------------------------
line = (
    Line().add_xaxis(date_list).add_yaxis('确诊数据', confirm_list).add_yaxis(
        '疑似数据', suspect_list, is_smooth=True)  #平滑
    .add_yaxis('死亡数据', dead_list).add_yaxis(
        '治愈数据',
        heal_list).set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    # 设置x轴标签旋转角度
    .set_global_opts(
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-30)),
        yaxis_opts=opts.AxisOpts(name='人数', min_=3),
        title_opts=opts.TitleOpts(title='2019-nCoV疫情曲线图')))

line.render('2019-nCoV疫情曲线图.html')
Example #13
0
for i in range(2):
    values = df.iloc[:, i].unique()
    for value in values:
        dic = {}
        dic['name'] = value
        nodes.append(dic)

print(nodes)

links = []

for i in df.values:
    dic = {}
    # source, target, value
    dic['source'] = i[0]
    dic['target'] = i[1]
    dic['value'] = i[2]
    links.append(dic)

print(links)

pic = (Sankey().add(
    '',
    nodes,
    links,
    linestyle_opt=opts.LineStyleOpts(opacity=0.3, curve=0.5, color="source"),
    label_opts=opts.LabelOpts(position="right"),
    node_gap=30,
).set_global_opts(title_opts=opts.TitleOpts(title='熬夜原因桑基图')))
pic.render('sankey.html')
# 案例002添加标题选项
# 输出文件为图片

from pyecharts.charts import Bar
from pyecharts import options as opts

# 导入输出图片工具
# 使用snapshot-selenium 渲染图片
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot

# 创建一个柱状图Bar实例
bar = (
    Bar()
    # 添加X轴数据
    .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
    # 添加Y轴数据,系列的名称
    .add_yaxis("商家A",
               [5, 20, 36, 10, 75, 90]).add_yaxis("商家B",
                                                  [8, 15, 60, 20, 25, 30])
    # 添加标题
    .set_global_opts(
        title_opts=opts.TitleOpts(title="主标题: 双十一销量", subtitle="副标题:服饰类")))

# render 会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件
# 也可以传入路径参数,自定义名称,如 bar.render("mycharts.html")
bar.render()

# 输出保存为图片
# make_snapshot(snapshot, bar.render(), "003_Options配置项_自定义样式_保存图片.png")
Example #15
0
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
    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("professional_kline_chart.html")
Example #16
0
        total_profit.append(result[3])
    # 月定投收益
    result_month = calculate_found_profit_by_month(start_date, end_date)
    total_amount.append(result_month[2])
    total_profit.append(result_month[3])
    return total_amount, total_profit


total_amount, total_profit = calculate_found_profit_week_month()

# 这部分代码在 jupyter 中 run
line = (Line().add_xaxis(list(found_date_price.keys())).add_yaxis(
    'price',
    list(found_date_price.values()),
    label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
        title_opts=opts.TitleOpts(title=f'{foundCode}基金走势图'),
        xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
            is_show=True)),
        yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
            is_show=True)),
    ))
#line.render_notebook()

x = ['周一', '周二', '周三', '周四', '周五', '月定投']
bar = (Bar().add_xaxis(x).add_yaxis('投资金额', total_amount).add_yaxis(
    '投资收益', total_profit).set_global_opts(
        title_opts=opts.TitleOpts(title="投资总额 & 投资收益"),
        xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
            is_show=True)),
        yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
            is_show=True)),
    [57.1, 78254, "Milk Tea"],
    [74.4, 41032, "Cheese Cocoa"],
    [50.1, 12755, "Cheese Brownie"],
    [89.7, 20145, "Matcha Cocoa"],
    [68.1, 79146, "Tea"],
    [19.6, 91852, "Orange Juice"],
    [10.6, 101852, "Lemon Juice"],
    [32.7, 20112, "Walnut Brownie"],
]).add_yaxis(
    series_name="",
    y_axis=[],
    encode={
        "x": "amount",
        "y": "product"
    },
    label_opts=opts.LabelOpts(is_show=False),
).set_global_opts(
    title_opts=opts.TitleOpts(title="Dataset normal bar example"),
    xaxis_opts=opts.AxisOpts(name="amount"),
    yaxis_opts=opts.AxisOpts(type_="category"),
    visualmap_opts=opts.VisualMapOpts(
        orient="horizontal",
        pos_left="center",
        min_=10,
        max_=100,
        range_text=["High Score", "Low Score"],
        dimension=0,
        range_color=["#D7DA8B", "#E15457"],
    ),
).render("dataset_bar_1.html"))
from pyecharts import options as opts
from pyecharts.charts import Liquid

c = (Liquid().add(
    "lq", [0.6, 0.7, 0.8],
    is_outline_show=False).set_global_opts(title_opts=opts.TitleOpts(
        title="Liquid-无边框")).render("Liquid_without_outline.html"))
Example #19
0
        if base_path != "":
            path = base_path + "." + key
        else:
            path = key
        if re.match(r"/^\$/", key):
            pass
        else:
            child = {"name": path, "children": []}
            target["children"].append(child)
            if isinstance(source[key], dict):
                convert(source[key], child, path)
            else:
                target["value"] = source["$count"]


convert(source=data, target=tree_map_data, base_path="")

(TreeMap(init_opts=opts.InitOpts(width="1200px", height="720px")).add(
    series_name="option",
    data=tree_map_data["children"],
    visual_min=300,
    leaf_depth=1,
    # 标签居中为 position = "inside"
    label_opts=opts.LabelOpts(position="inside"),
).set_global_opts(
    legend_opts=opts.LegendOpts(is_show=False),
    title_opts=opts.TitleOpts(title="Echarts 配置项查询分布",
                              subtitle="2016/04",
                              pos_left="leafDepth"),
).render("echarts_option_query.html"))
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.faker import Faker


c = (
    Bar()
    .add_xaxis(Faker.choose())
    .add_yaxis("商家A", Faker.values(), gap="0%")
    .add_yaxis("商家B", Faker.values(), gap="0%")
    .set_global_opts(title_opts=opts.TitleOpts(title="Bar-不同系列柱间距离"))
    .render("Bar_different_series_gap.html")
)
Example #21
0
import pyecharts.options as opts
from pyecharts.charts import Line
from pyecharts.faker import Faker

c = (Line().add_xaxis(Faker.choose()).add_yaxis(
    "商家A", Faker.values(), is_step=True).set_global_opts(
        title_opts=opts.TitleOpts(title="Line-阶梯图")).render("Line_step.html"))
Example #22
0
# -*- coding:utf-8 -*-

from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.faker import Faker

c = (
    Bar().add_xaxis(Faker.choose()).add_yaxis("商家A",
                                              Faker.values(),
                                              stack="stack1").add_yaxis(
                                                  "商家B",
                                                  Faker.values(),
                                                  stack="stack1").add_yaxis(
                                                      "商家C", Faker.values())
    #系列配置项      LabelOpts: 标签配置项
    .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    #全局配置项     TitleOpts:标题配置项
    .set_global_opts(title_opts=opts.TitleOpts(
        title="Bar-堆叠数据(部分)")).render("bar_stack1.html"))
Example #23
0
    },
    {
        'name': '续费后50万'
    },
    {
        'name': '续费后包年'
    },
    {
        'name': '续费后单价极低'
    },
]

pic = (
    Sankey().add(
        '',  #图例名称
        nodes,  #传入节点数据
        linkes,  #传入边和流量数据
        #设置透明度、弯曲度、颜色
        linestyle_opt=opts.LineStyleOpts(opacity=0.3,
                                         curve=0.5,
                                         color="source"),
        #标签显示位置
        label_opts=opts.LabelOpts(position="right"),
        #节点之前的距离
        node_gap=30,
        # 鼠标 hover 到节点或边上,相邻接的节点和边高亮的交互,默认关闭,可手动开启
        focus_node_adjacency="allEdges").set_global_opts(
            title_opts=opts.TitleOpts(title='企业版合同续签客户流向')))
#输出文件
pic.render(r'C:\Users\YAO\AppData\Local\Temp\test.html')
Example #24
0
    [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")
Example #25
0
).add_yaxis(
    series_name="联盟广告",
    stack="总量",
    y_axis=[220, 182, 191, 234, 290, 330, 310],
    label_opts=opts.LabelOpts(is_show=False),
).add_yaxis(
    series_name="视频广告",
    stack="总量",
    y_axis=[150, 232, 201, 154, 190, 330, 410],
    label_opts=opts.LabelOpts(is_show=False),
).add_yaxis(
    series_name="直接访问",
    stack="总量",
    y_axis=[320, 332, 301, 334, 390, 330, 320],
    label_opts=opts.LabelOpts(is_show=False),
).add_yaxis(
    series_name="搜索引擎",
    stack="总量",
    y_axis=[820, 932, 901, 934, 1290, 1330, 1320],
    label_opts=opts.LabelOpts(is_show=False),
).set_global_opts(
    title_opts=opts.TitleOpts(title="折线图堆叠"),
    tooltip_opts=opts.TooltipOpts(trigger="axis"),
    yaxis_opts=opts.AxisOpts(
        type_="value",
        axistick_opts=opts.AxisTickOpts(is_show=True),
        splitline_opts=opts.SplitLineOpts(is_show=True),
    ),
    xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False),
).render("stacked_line_chart.html"))
Example #26
0
        'min': 10,
        'color': '#f27777'
    },
    {
        'max': 9,
        'min': 1,
        'color': '#f7adad'
    },
    {
        'max': 0,
        'color': '#f7e4e4'
    },
]
labels = [data[0] for data in china_data]
counts = [data[1] for data in china_data]

m = Map()
m.add("累计确诊", [list(z) for z in zip(labels, counts)], 'china')

#系列配置项,可配置图元样式、文字样式、标签样式、点线样式等
m.set_series_opts(label_opts=opts.LabelOpts(font_size=12), is_show=False)
#全局配置项,可配置标题、动画、坐标轴、图例等
m.set_global_opts(
    title_opts=opts.TitleOpts(title='全国实时确诊数据', subtitle='数据来源:丁香园'),
    legend_opts=opts.LegendOpts(is_show=False),
    visualmap_opts=opts.VisualMapOpts(
        pieces=pieces,
        is_piecewise=True,  #是否为分段型
        is_show=True))  #是否显示视觉映射配置
#render()会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件,也可以传入路径参数,如 m.render("mycharts.html")
m.render(path='html/全国实时确诊数据.html')
Example #27
0
def heat_map(data: List[dict],
             x_label: List[str] = None,
             y_label: List[str] = None,
             title: str = "热力图",
             width: str = "900px",
             height: str = "680px") -> HeatMap:
    """绘制热力图

    :param data: 用于绘制热力图的数据,示例如下
        [{'x': '0hour', 'y': '0day', 'heat': 11},
         {'x': '0hour', 'y': '1day', 'heat': 40},
         {'x': '0hour', 'y': '2day', 'heat': 38},
         {'x': '0hour', 'y': '3day', 'heat': 36},
         {'x': '0hour', 'y': '4day', 'heat': 11}]
    :param x_label: x轴标签
    :param y_label: y轴标签
    :param title: 图表标题
    :param width: 图表宽度
    :param height: 图表高度
    :return: 图表
    """

    value = [[s['x'], s['y'], s['heat']] for s in data]
    heat = [s['heat'] for s in data]

    if not x_label:
        x_label = sorted(list(set([s['x'] for s in data])))

    if not y_label:
        y_label = sorted(list(set([s['y'] for s in data])))

    vis_map_opts = opts.VisualMapOpts(pos_left="90%",
                                      pos_top="20%",
                                      min_=min(heat),
                                      max_=max(heat))
    title_opts = opts.TitleOpts(title=title)
    init_opts = opts.InitOpts(page_title=title, width=width, height=height)
    dz_inside = opts.DataZoomOpts(False,
                                  "inside",
                                  xaxis_index=[0],
                                  range_start=80,
                                  range_end=100)
    dz_slider = opts.DataZoomOpts(True,
                                  "slider",
                                  xaxis_index=[0],
                                  pos_top="96%",
                                  pos_bottom="0%",
                                  range_start=80,
                                  range_end=100)
    legend_opts = opts.LegendOpts(is_show=False)

    hm = HeatMap(init_opts=init_opts)
    hm.add_xaxis(x_label)
    hm.add_yaxis("heat",
                 y_label,
                 value,
                 label_opts=opts.LabelOpts(is_show=True, position="inside"))
    hm.set_global_opts(title_opts=title_opts,
                       visualmap_opts=vis_map_opts,
                       legend_opts=legend_opts,
                       xaxis_opts=opts.AxisOpts(grid_index=0),
                       datazoom_opts=[dz_inside, dz_slider])
    return hm
Example #28
0
    ("物业维修", 37),
    ("婚庆服务", 24),
    ("二手回收", 24),
    ("鲜花配送", 3),
    ("维修服务", 3),
    ("殡葬服务", 1),
    ("求职创业", 874),
    ("创业", 363),
    ("目标职位", 162),
    ("目标行业", 50),
    ("兼职", 21),
    ("期望年薪", 20),
    ("实习", 16),
    ("雇主类型", 10),
    ("星座运势", 789),
    ("星座", 316),
    ("算命", 303),
    ("解梦", 196),
    ("风水", 93),
    ("面相分析", 47),
    ("手相", 32),
    ("公益", 90),
]

with open("wordcloud_image_base64.json", "r", encoding="utf-8") as f:
    j = json.load(f)

c = (WordCloud().add(
    "", words, word_size_range=[12, 55],
    mask_image=j["base64"]).set_global_opts(title_opts=opts.TitleOpts(
        title="WordCloud-自定义图片")).render("Wordcloud_custom_mask_image.html"))
Example #29
0
def sankey_vertical() -> Sankey:
    colors = [
        "#67001f",
        "#b2182b",
        "#d6604d",
        "#f4a582",
        "#fddbc7",
        "#d1e5f0",
        "#92c5de",
        "#4393c3",
        "#2166ac",
        "#053061",
    ]
    nodes = [
        {
            "name": "a"
        },
        {
            "name": "b"
        },
        {
            "name": "a1"
        },
        {
            "name": "b1"
        },
        {
            "name": "c"
        },
        {
            "name": "e"
        },
    ]
    links = [
        {
            "source": "a",
            "target": "a1",
            "value": 5
        },
        {
            "source": "e",
            "target": "b",
            "value": 3
        },
        {
            "source": "a",
            "target": "b1",
            "value": 3
        },
        {
            "source": "b1",
            "target": "a1",
            "value": 1
        },
        {
            "source": "b1",
            "target": "c",
            "value": 2
        },
        {
            "source": "b",
            "target": "c",
            "value": 1
        },
    ]
    c = (Sankey().set_colors(colors).add(
        "sankey",
        nodes=nodes,
        links=links,
        pos_bottom="10%",
        focus_node_adjacency="allEdges",
        orient="vertical",
        linestyle_opt=opts.LineStyleOpts(opacity=0.2,
                                         curve=0.5,
                                         color="source"),
        label_opts=opts.LabelOpts(position="top"),
    ).set_global_opts(
        title_opts=opts.TitleOpts(title="Sankey-Vertical"),
        tooltip_opts=opts.TooltipOpts(trigger="item", trigger_on="mousemove"),
    ))
    return c
Example #30
0
def plot_performance_overview(dict_results, plot_tymod, p):

    if plot_tymod == "pic":

        figs = {}
        for k, v in dict_results.items():
            v = v.unstack()
            series = v.index.get_level_values(0).unique() if isinstance(
                v.index, pd.MultiIndex) else [k]
            c = 3
            r = np.ceil(len(series) / c)

            fig = plt.figure(figsize=(8, 6))
            plt.subplots_adjust(hspace=0.3)

            for i, _s in enumerate(series):

                _data = v.loc[_s] if isinstance(v.index, pd.MultiIndex) else v

                X, Y = np.meshgrid(_data.index, _data.columns, indexing='ij')

                Z = _data.values
                pos = int(r * 100 + c * 10 + (i + 1))
                ax = fig.add_subplot(pos, projection='3d')

                ax.plot_surface(X, Y, Z, color='b')
                ax.set_title("%s" % _s, fontdict={"size": 8})
            figs[k] = fig
            fig.savefig("%s_%s.png" % (p, k))
        return figs
    elif plot_tymod == 'dyn-3d':
        results = {}
        for k, perf in dict_results.items():
            perf = perf.unstack()
            c = (Surface3D(init_opts=opts.InitOpts(
                width="1000px", height="500px")).set_global_opts(
                    title_opts=opts.TitleOpts(title="绩效-曲面波图(%s)" % k),
                    visualmap_opts=opts.VisualMapOpts(
                        max_=perf.values.max(),
                        min_=perf.values.min(),
                        range_color=Faker.visual_color),
                    toolbox_opts=opts.ToolboxOpts(is_show=True),
                ))
            series = perf.index.get_level_values(0).unique() if isinstance(
                perf.index, pd.MultiIndex) else [k]
            for i, _s in enumerate(series):
                _data = perf.loc[_s] if isinstance(perf.index,
                                                   pd.MultiIndex) else perf
                X, Y = np.meshgrid(_data.index, _data.columns)
                d = list(
                    zip(X.flatten().astype(str),
                        Y.flatten().astype(str),
                        _data.values.T.flatten().astype(np.float)))
                c = c.add(
                    series_name=str(_s),
                    shading="color",
                    data=d,
                    xaxis3d_opts=opts.Axis3DOpts(type_="category"),
                    yaxis3d_opts=opts.Axis3DOpts(type_="category"),
                    grid3d_opts=opts.Grid3DOpts(width=100,
                                                height=50,
                                                depth=100),
                )
            results[k] = c

        tab = Tab()
        for k, v in results.items():
            tab.add(v, k)
        tab.render("%s.html" % p)
    elif plot_tymod == "dyn-hm":
        tab = Tab()
        for k, v in dict_results.items():
            v = v.unstack()
            _tl = _timeline(v, name=k)
            tab.add(_tl, k)
        tab.render("%s.html" % p)