def draw_bar3D(cls, title: str, data: pd.DataFrame) -> Bar3D:
        """
        根据df内容绘制3D柱状图
        :param title:           标题
        :param data:            包含三轴数据的dataframe  index为x轴 column为Y轴 value为z轴
        :return:
        """
        data_list = []
        index_list = data.index.tolist()
        column_list = data.columns.tolist()

        # 获取dataframe最大最小值
        min_data = data.min().min()
        max_data = data.max().max()
        # 遍历dataframe,准备待操作数组
        for i in range(len(index_list)):
            for j in range(len(column_list)):
                # 记录 XYZ
                temp_list = [index_list[i], column_list[j], data.iloc[i, j]]
                # print(i,j,index_list[i],column_list[j])
                data_list.append(temp_list)

        c = (
            Bar3D(init_opts=opts.InitOpts(
                width=DEFAULT_WIDTH,
                animation_opts=opts.AnimationOpts(
                    animation_delay=200,
                    animation_easing="bounceOut"),  #   增加启动动效
            )).add(
                series_name=title,
                data=data_list,
                xaxis3d_opts=opts.Axis3DOpts(type_="category",
                                             data=index_list),
                yaxis3d_opts=opts.Axis3DOpts(type_="category",
                                             data=column_list),
                zaxis3d_opts=opts.Axis3DOpts(type_="value"),
            ).set_series_opts(label_opts=opts.LabelOpts(is_show=True)).
            set_global_opts(
                title_opts=opts.TitleOpts(title=title, pos_left="0%"),
                toolbox_opts=opts.ToolboxOpts(),  # 显示工具箱
                tooltip_opts=opts.TooltipOpts(is_show=True),
                axispointer_opts=opts.AxisPointerOpts(
                    is_show=True, type_="none"),  # 指针移动时显示所有数值
                legend_opts=opts.LegendOpts(
                    is_show=True,
                    selected_mode="multiple",
                    # pos_bottom="0%",
                    # pos_right="0%",
                    # orient="vertical",
                ),  # 显示图例说明
                # datazoom_opts=[
                #     opts.DataZoomOpts(
                #         range_start=0, range_end=100, orient="vertical", pos_left="2%"
                #     ),
                #     opts.DataZoomOpts(range_start=0, range_end=100, orient="horizontal"),
                # ],  # 增加缩放配置横纵轴都支持缩放
                visualmap_opts=opts.VisualMapOpts(max_=max_data, min_=min_data)
                # visualmap_opts=opts.VisualMapOpts(type_="color", max_=1, min_=-1),
            ))
        return c
Beispiel #2
0
def gen_kline(df1):

    dt_list = list(df1['datetime'])
    kline_data = df1.apply(lambda record: [
        float(record['open']),
        float(record['close']),
        float(record['low']),
        float(record['high'])
    ],
                           axis=1).tolist()

    #kline = Kline(init_opts=opts.InitOpts(width='1000px'))
    kline = Kline()
    kline.add_xaxis(list(df1['datetime']))
    kline.add_yaxis('日K', kline_data)

    kline.set_global_opts(
        title_opts=opts.TitleOpts(title='K线'),
        datazoom_opts=[
            opts.DataZoomOpts(
                is_show=True,
                type_="slider",
                xaxis_index=[0, 1, 2],
                range_start=0,
                range_end=100,
            ),
            opts.DataZoomOpts(
                is_show=False,
                type_="inside",
                xaxis_index=[0, 1, 2],
                range_start=0,
                range_end=100,
            ),
        ],
        legend_opts=opts.LegendOpts(is_show=False),
        yaxis_opts=opts.AxisOpts(
            is_scale=True,
            splitarea_opts=opts.SplitAreaOpts(
                is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1))),
        tooltip_opts=opts.TooltipOpts(
            trigger="axis",
            axis_pointer_type="cross",
            background_color="rgba(245, 245, 245, 0.8)",
            border_width=1,
            border_color="#ccc",
            textstyle_opts=opts.TextStyleOpts(color="#000"),
        ),
        axispointer_opts=opts.AxisPointerOpts(
            is_show=True,
            link=[{
                "xAxisIndex": "all"
            }],
            label=opts.LabelOpts(background_color="#777"),
        ),
    )

    return kline
    def draw_line(cls, title: str, xaxis_data: List[str],
                  yaxis_data: pd.DataFrame) -> Line:
        """
        根据df内容绘制折线图
        :param title:           标题
        :param xaxis_data:      横轴数据
        :param yaxis_data:      纵轴绘制数据
        :return:
        """
        # 获取dataframe最大最小值
        min_data = yaxis_data.min().min()
        max_data = yaxis_data.max().max()
        c = (
            Line(init_opts=opts.InitOpts(
                width=DEFAULT_WIDTH)).add_xaxis(xaxis_data).set_series_opts(
                    label_opts=opts.LabelOpts(is_show=True)).
            set_global_opts(
                title_opts=opts.TitleOpts(title=title, pos_left="0%"),
                toolbox_opts=opts.ToolboxOpts(),  # 显示工具箱
                tooltip_opts=opts.TooltipOpts(is_show=True),
                axispointer_opts=opts.AxisPointerOpts(
                    is_show=True, type_="none"),  # 指针移动时显示所有数值
                legend_opts=opts.LegendOpts(
                    is_show=True,
                    selected_mode="multiple",
                    # pos_bottom="0%",
                    # pos_right="0%",
                    # orient="vertical",
                ),  # 显示图例说明
                datazoom_opts=[
                    opts.DataZoomOpts(
                        range_start=0,
                        range_end=100,
                        orient="vertical",
                        pos_left=DATAZOOM_VERTICAL_POS_LEFT,
                    ),
                    opts.DataZoomOpts(range_start=0,
                                      range_end=100,
                                      orient="horizontal"),
                ],  # 增加缩放配置横纵轴都支持缩放
                # visualmap_opts = opts.VisualMapOpts(max_ = max_data, min_ = min_data, pos_bottom="10%")
            ))

        # 遍历dataframe 依次添加数据到y轴
        column_list = yaxis_data.columns.tolist()
        for column in column_list:
            c.add_yaxis(
                column,
                yaxis_data[column].tolist(),
                markpoint_opts=opts.MarkPointOpts(data=[
                    opts.MarkPointItem(type_="min", symbol_size=60),
                    opts.MarkPointItem(type_="max", symbol_size=60),
                ]),
            )
        return c
def gen_line(df1, s1, price_min, price_max):
    df1['datetime'] = df1['date'] + ' ' + df1['time']
    # df1['datetime'] = df1['date']
    dt_list1 = list(df1['datetime'])
    # print( len(dt_list1) )
    # dt_list1 = [s[5:10] for s in dt_list1]
    close_list1 = df1.apply(lambda record: float(record['close']),
                            axis=1).tolist()
    close_list1 = np.array(close_list1)
    # print(close_list1)

    #line1 = Line(init_opts=opts.InitOpts(width='1500px', height='600px'))
    line1 = Line()
    line1.set_global_opts(
        yaxis_opts=opts.AxisOpts(
            min_=price_min,
            max_=price_max,
            splitarea_opts=opts.SplitAreaOpts(
                is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)),
        ),
        datazoom_opts=[
            opts.DataZoomOpts(
                is_show=True,
                type_="slider",
                xaxis_index=[0, 1],
                range_start=0,
                range_end=100,
            ),
            opts.DataZoomOpts(
                is_show=False,
                type_="inside",
                xaxis_index=[0, 1],
                range_start=0,
                range_end=100,
            ),
        ],
        #legend_opts=opts.LegendOpts(is_show=False),
        #tooltip_opts=opts.TooltipOpts( trigger="axis",axis_pointer_type="cross" ),
        tooltip_opts=opts.TooltipOpts(axis_pointer_type="cross"),
        axispointer_opts=opts.AxisPointerOpts(
            is_show=True,
            link=[{
                "xAxisIndex": "all"
            }],
        ),
    )
    line1.add_xaxis(xaxis_data=dt_list1)
    line1.add_yaxis(
        s1,
        y_axis=close_list1,
    )
    line1.set_series_opts(label_opts=opts.LabelOpts(is_show=False))

    return line1
Beispiel #5
0
def bar_single(x, y_name, y_bar_value, title, subtitle):
    bar = (
        Bar(init_opts=opts.InitOpts(width='800px', height='400px'))
            .add_xaxis(x)
            .add_yaxis(y_name, y_bar_value, color="#5793f3")
            .set_global_opts(
            title_opts=opts.TitleOpts(title=title, subtitle=subtitle),
            axispointer_opts=opts.AxisPointerOpts(is_show=True, type_="shadow"),
        )
    )
    return bar
Beispiel #6
0
    def line_bar_draw(data,html_name):
        x_data = data.index.tolist()
        bars = data.iloc[:,1].values.tolist()
        change = data.iloc[:,0].values.tolist()
        bar = (
            Bar(init_opts=opts.InitOpts(width="1200px", height="700px"))
            .add_xaxis(xaxis_data=x_data)
            .add_yaxis(
                series_name="Stock_Price",
                yaxis_data=bars,
                label_opts=opts.LabelOpts(is_show=False),
            )

            .extend_axis(
                yaxis=opts.AxisOpts(
                    name="Value_Series",
                    type_="value",
                )
            )
            .set_global_opts(
                tooltip_opts=opts.TooltipOpts(
                    is_show=True, trigger="axis", axis_pointer_type="cross"
                ),
                xaxis_opts=opts.AxisOpts(
                    type_="category",
                    axispointer_opts=opts.AxisPointerOpts(is_show=True, type_="shadow"),
                ),
                yaxis_opts=opts.AxisOpts(
                    name="Stock_Price",
                    type_="value",
                    axistick_opts=opts.AxisTickOpts(is_show=True),
                    splitline_opts=opts.SplitLineOpts(is_show=True),
                    axislabel_opts=opts.LabelOpts(formatter="¥ {value}"),
                ),
                datazoom_opts=[
                    opts.DataZoomOpts(range_start=0, range_end=100),
                    opts.DataZoomOpts(type_="inside", range_start=0, range_end=100),
                ],
            )
        )

        line = (
            Line()
            .add_xaxis(xaxis_data=x_data)
            .add_yaxis(
                series_name="Value_Series",
                yaxis_index=1,
                y_axis=change,
                label_opts=opts.LabelOpts(is_show=False),
            )
        )

        bar.overlap(line).render('./output/'+html_name+'.html')
Beispiel #7
0
def line_two(x, y_line1_name, y2_name, y1_line_value, y2_line_value, title, subtitle):
    line = (
        Line(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
            .add_xaxis(x)
            .add_yaxis(y_line1_name, y1_line_value)
            .add_yaxis(y2_name, y2_line_value)
            .set_global_opts(title_opts=opts.TitleOpts(title=title, subtitle=subtitle))
            .set_series_opts(
            label_opts=opts.LabelOpts(is_show=True), # 显示标签
            axispointer_opts=opts.AxisPointerOpts(is_show=True, type_="shadow")
            # , markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max", name="最大值")])
        )
    )
    return line
Beispiel #8
0
def descripMixBar(colname):
    date, like, comment, repost = get_tenweibo_data(colname)
    x_data = date

    bar = (Bar(
        init_opts=opts.InitOpts(width="1600px", height="800px")).add_xaxis(
            xaxis_data=x_data).add_yaxis(
                series_name="转发量",
                yaxis_data=repost,
                label_opts=opts.LabelOpts(is_show=False),
            ).add_yaxis(
                series_name="评论量",
                yaxis_data=comment,
                label_opts=opts.LabelOpts(is_show=False),
            ).extend_axis(yaxis=opts.AxisOpts(
                name="评论",
                type_="value",
                min_=0,
                max_=4000,
                interval=500,
                axislabel_opts=opts.LabelOpts(formatter="{value}"),
            )).set_global_opts(
                title_opts=opts.TitleOpts(title="近10个微博数据对比"),
                tooltip_opts=opts.TooltipOpts(is_show=True,
                                              trigger="axis",
                                              axis_pointer_type="cross"),
                xaxis_opts=opts.AxisOpts(
                    type_="category",
                    axispointer_opts=opts.AxisPointerOpts(is_show=True,
                                                          type_="shadow"),
                    axislabel_opts=opts.LabelOpts(rotate=-15)),
                yaxis_opts=opts.AxisOpts(
                    name="转发",
                    type_="value",
                    min_=0,
                    max_=8000,
                    interval=800,
                    axislabel_opts=opts.LabelOpts(formatter="{value}"),
                    axistick_opts=opts.AxisTickOpts(is_show=True),
                    splitline_opts=opts.SplitLineOpts(is_show=True),
                ),
            ))

    line = (Line().add_xaxis(xaxis_data=x_data).add_yaxis(
        series_name="点赞量",
        yaxis_index=1,
        y_axis=like,
        label_opts=opts.LabelOpts(is_show=False),
    ))
    return bar.overlap(line)
Beispiel #9
0
def music_comments_rating_line(id, num) -> Line:
    (rt,qu,num) = music_comments_rating(id, num)
    if rt == 0:
        return 0
    l1 = (
        Line()
        .add_xaxis(xaxis_data=qu)
        .add_yaxis(
            series_name="评分",
            y_axis=rt,
            markpoint_opts=opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(type_="max", name="最大值"),
                    opts.MarkPointItem(type_="min", name="最小值"),
                ]
            ),
            markline_opts=opts.MarkLineOpts(
                data=[opts.MarkLineItem(type_="average", name="平均值")]
            ),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="评论时间季度与评分的关系",subtitle="数据量:" + str(num),),
            tooltip_opts=opts.TooltipOpts(trigger="axis", is_show=True),
            axispointer_opts=opts.AxisPointerOpts(
                is_show=True, link=[{"xAxisIndex": "all"}]
            ),
            datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
            toolbox_opts=opts.ToolboxOpts(is_show=True,
                                          #                                         orient="vertical",
                                          pos_left="95%",
                                          feature={
                                              "dataZoom": {"yAxisIndex": "none"},
                                              "dataView": {},
                                              "magicType": {
                                                  "show": True,
                                                  "title": "切换",
                                                  "type": ['line', 'bar'],
                                                  # 启用的动态类型,包括'line'(切换为折线图), 'bar'(切换为柱状图), 'stack'(切换为堆叠模式), 'tiled'(切换为平铺模式)
                                              },
                                              "restore": {},
                                              "saveAsImage": {},
                                          },
                                          ),
            xaxis_opts=opts.AxisOpts(name="评论时间季度", type_="category", boundary_gap=False),
            yaxis_opts=opts.AxisOpts(name_gap=50,name_rotate=90,name_location="center",name="评分"),
        )
        .dump_options_with_quotes()
    )
    return l1
Beispiel #10
0
def program_lang(df):
    data = analyze(df, 'LanguageRecommendationSelect').head(10)
    data_x = [y for y in data['LanguageRecommendationSelect']]
    data_y = [int(y) for y in data['num']]
    data_per = data['percent'] * 100
    c = (Bar(init_opts=opts.InitOpts(width="1200px", height="500px"))
        .add_xaxis(xaxis_data=data_x)
        .add_yaxis(series_name='编程语言', yaxis_data=data_y,
                   label_opts=opts.LabelOpts(is_show=False),
                   )
        .extend_axis(
        yaxis=opts.AxisOpts(
            name="百分比", type_="value", min_=0,
            axislabel_opts=opts.LabelOpts(formatter="{value} %"),
            position='top'
        ))
        .set_global_opts(
        tooltip_opts=opts.TooltipOpts(
            is_show=True, trigger="axis", axis_pointer_type="cross"
        ),
        xaxis_opts=opts.AxisOpts(
            type_="category",
            axispointer_opts=opts.AxisPointerOpts(is_show=True, type_="shadow"),
            axislabel_opts={"rotate": 45}, name_rotate=45
        ),
        yaxis_opts=opts.AxisOpts(
            # name="水量", type_="value",
            # min_=0, max_=250, interval=50,
            axistick_opts=opts.AxisTickOpts(is_show=True),
            splitline_opts=opts.SplitLineOpts(is_show=True),
            name_rotate=45, axislabel_opts={"rotate": 45}
        ),
        title_opts=opts.TitleOpts(title="编程语言"),
    )
    )

    line = (
        Line()
            .add_xaxis(xaxis_data=data_x)
            .add_yaxis(
            z_level=10,
            series_name="占比",
            yaxis_index=1,
            y_axis=data_per,
            label_opts=opts.LabelOpts(is_show=False, formatter="{value} %"),
        )

    )
    c.overlap(line).render('program.html')
Beispiel #11
0
def books_durations_bar(id, num) -> Bar:
    (key,val,num) = books_durations(id, num)
    if key == 0:
        return 0
    c = (
        Bar()
        .add_xaxis(list(map(str, key)))
        .add_yaxis("图书数", list(map(str, val)),
                       label_opts=opts.LabelOpts(is_show=False),
                       markpoint_opts=opts.MarkPointOpts(
                           data=[
                               opts.MarkPointItem(type_="max", name="最大值"),
                               opts.MarkPointItem(type_="min", name="最小值"),
                           ]
                       ),
                       markline_opts=opts.MarkLineOpts(
                           data=[opts.MarkLineItem(type_="average", name="平均值")]
                       ),
                       )
        .set_global_opts(
            title_opts=opts.TitleOpts(title="不同图书页数的图书产量", subtitle="数据量:" + str(num),),
            tooltip_opts=opts.TooltipOpts(trigger="axis", is_show=True),
            yaxis_opts=opts.AxisOpts(name_gap=50,name_rotate=90,name_location="center",name="图书数(个)"),
            xaxis_opts=opts.AxisOpts(name="图书页数(页)"),
            axispointer_opts=opts.AxisPointerOpts(
                is_show=True, link=[{"xAxisIndex": "all"}]
            ),
            datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
            toolbox_opts=opts.ToolboxOpts(is_show=True,
                                          #                                         orient="vertical",
                                          pos_left="95%",
                                          feature={
                                              "dataZoom": {"yAxisIndex": "none"},
                                              "dataView": {},
                                              "magicType": {
                                                  "show": True,
                                                  "title": "切换",
                                                  "type": ['line', 'bar'],
                                                  # 启用的动态类型,包括'line'(切换为折线图), 'bar'(切换为柱状图), 'stack'(切换为堆叠模式), 'tiled'(切换为平铺模式)
                                              },
                                              "restore": {},
                                              "saveAsImage": {},
                                          },
                                          ),
        )
        .dump_options_with_quotes()
    )
    return c
Beispiel #12
0
def test_kline_axispointer_opts(fake_writer):
    c = (Kline().add_xaxis(
        ["2017/7/{}".format(i + 1)
         for i in range(10)]).add_yaxis("kline", data).set_global_opts(
             yaxis_opts=opts.AxisOpts(is_scale=True),
             xaxis_opts=opts.AxisOpts(is_scale=True),
             axispointer_opts=opts.AxisPointerOpts(
                 is_show=True,
                 link=[{
                     "xAxisIndex": "all"
                 }],
                 label=opts.LabelOpts(background_color="#777"),
             ),
         ))
    c.render()
    _, content = fake_writer.call_args[0]
    assert_in("axisPointer", content)
Beispiel #13
0
def analysis_struct():
    # 处理数据
    x_data = pdata['年份'].map(lambda x: "%d" % x).tolist()
    y_data1 = pdata['0-14岁人口(万人)'].map(lambda x: "%.2f" % x).tolist()
    y_data2 = pdata['15-64岁人口(万人)'].map(lambda x: "%.2f" % x).tolist()
    y_data3 = pdata['65岁及以上人口(万人)'].map(lambda x: "%.2f" % x).tolist()

    # 人口结构折线图
    line = Line()
    line.add_xaxis(x_data)
    line.add_yaxis('0-14岁人口',
                   y_data1,
                   label_opts=opts.LabelOpts(is_show=False))
    line.add_yaxis('15-64岁人口',
                   y_data2,
                   label_opts=opts.LabelOpts(is_show=False))
    line.add_yaxis('65岁及以上人口',
                   y_data3,
                   label_opts=opts.LabelOpts(is_show=False))
    line.set_global_opts(
        title_opts=opts.TitleOpts(title="人口结构",
                                  pos_bottom="bottom",
                                  pos_left="center"),
        xaxis_opts=opts.AxisOpts(
            name='年份',
            name_location='end',
            type_="category",
            # axislabel_opts=opts.LabelOpts(is_show=True, color="#000", interval=0, rotate=90),
            axistick_opts=opts.AxisTickOpts(is_show=True,
                                            is_align_with_label=True),
            axispointer_opts=opts.AxisPointerOpts(
                type_="shadow", label=opts.LabelOpts(is_show=True))),
        # y轴相关选项设置
        yaxis_opts=opts.AxisOpts(name='人口数(万人)',
                                 type_="value",
                                 position="left",
                                 axislabel_opts=opts.LabelOpts(is_show=True)),
        legend_opts=opts.LegendOpts(is_show=True))

    # 渲染图像,将多个图像显示在一个html中
    # DraggablePageLayout表示可拖拽
    page = Page(layout=Page.DraggablePageLayout)
    page.add(line)
    page.render('population_struct.html')
Beispiel #14
0
    def gen_kline(self, df1, symbol):
        df1['datetime'] = df1['date']
        dt_list = list(df1['datetime'])
        k_plot_value = df1.apply(
            lambda record:
            [record['open'], record['close'], record['low'], record['high']],
            axis=1).tolist()
        #print(k_plot_value)

        kline = Kline(init_opts=opts.InitOpts(
            width='1500px',
            height="700px",
        ))
        kline.add_xaxis(dt_list)
        kline.add_yaxis(symbol, k_plot_value)
        kline.set_global_opts(
            title_opts=opts.TitleOpts(title='日线'),
            datazoom_opts=[
                opts.DataZoomOpts(
                    is_show=True,
                    type_="slider",
                    xaxis_index=[0, 1],
                    range_start=0,
                    range_end=100,
                ),
                opts.DataZoomOpts(
                    is_show=False,
                    type_="inside",
                    xaxis_index=[0, 1],
                    range_start=0,
                    range_end=100,
                ),
            ],
            tooltip_opts=opts.TooltipOpts(axis_pointer_type="cross"),
            axispointer_opts=opts.AxisPointerOpts(
                is_show=True,
                link=[{
                    "xAxisIndex": "all"
                }],
            ),
        )

        return kline
Beispiel #15
0
 def dayloss_line_base(self, x, y, t, st):
     c = (Line(
         init_opts=opts.InitOpts(width="1000px", height="500px")
     ).add_xaxis(x).add_yaxis("线损率(%)", y, is_smooth=True).set_global_opts(
         tooltip_opts=opts.TooltipOpts(is_show=True,
                                       trigger="axis",
                                       axis_pointer_type="cross"),
         title_opts=opts.TitleOpts(title=t, subtitle=st),
         xaxis_opts=opts.AxisOpts(
             axislabel_opts=opts.LabelOpts(rotate=-90),
             max_interval=366,
             type_="category",
             axispointer_opts=opts.AxisPointerOpts(is_show=True,
                                                   type_="shadow"),
         ),
         yaxis_opts=opts.AxisOpts(
             axislabel_opts=opts.LabelOpts(formatter="{value} %"),
             axistick_opts=opts.AxisTickOpts(is_show=True),
             splitline_opts=opts.SplitLineOpts(is_show=True),
         ),
         toolbox_opts=opts.ToolboxOpts(feature=opts.ToolBoxFeatureOpts(
             save_as_image=opts.ToolBoxFeatureSaveAsImageOpts(
                 pixel_ratio=2, background_color='white'),
             restore=opts.ToolBoxFeatureRestoreOpts(is_show=False),
             data_view=opts.ToolBoxFeatureDataViewOpts(is_show=False),
             data_zoom=opts.ToolBoxFeatureDataZoomOpts(is_show=False),
             magic_type=opts.ToolBoxFeatureMagicTypeOpts(is_show=False),
             brush=opts.ToolBoxFeatureBrushOpts(type_='clear'),
         ))).set_series_opts(
             label_opts=opts.LabelOpts(is_show=False),
             markline_opts=opts.MarkLineOpts(
                 data=[
                     opts.MarkLineItem(y=6),
                 ],
                 label_opts=opts.LabelOpts(is_show=False),
             ),
         ))
     return c
Beispiel #16
0
def analyse(sheet_title):
    data = pd.read_excel('B站{0}综合排行榜前100视频.xlsx'.format(sheet_title),
                         sheet_name=sheet_title)
    x_data = data['AV号']
    y_data_pts = data['综合评分']
    y_data_playnums = list(data['总播放量'] / 10)
    y_data_coins = list(data['投币数量'])
    y_data_views = list(data['弹幕总数'])
    bar = (Bar(
        init_opts=opts.InitOpts(width="1600px", height="800px")).add_xaxis(
            xaxis_data=x_data, ).add_yaxis(
                '总播放量', yaxis_data=y_data_playnums).add_yaxis(
                    '投币数量', yaxis_data=y_data_coins, stack=1).add_yaxis(
                        '弹幕总数', yaxis_data=y_data_views, stack=1).extend_axis(
                            yaxis=opts.AxisOpts(name='综合评分', type_='value')).
           set_series_opts(label_opts=opts.LabelOpts(
               is_show=False)).set_global_opts(
                   title_opts=opts.TitleOpts(
                       title="B站{0}综合排行榜前100视频".format(sheet_title),
                       pos_left="center",
                       pos_top="bottom"),
                   tooltip_opts=opts.TooltipOpts(is_show=True,
                                                 trigger="axis",
                                                 axis_pointer_type="cross"),
                   xaxis_opts=opts.AxisOpts(
                       type_="category",
                       axispointer_opts=opts.AxisPointerOpts(is_show=True,
                                                             type_="shadow"),
                       axislabel_opts=opts.LabelOpts(rotate=-30)),
                   yaxis_opts=opts.AxisOpts(name='总播放量*0.1/投币数量/弹幕总数',
                                            type_='value'),
                   datazoom_opts=opts.DataZoomOpts()))
    line = (Line().add_xaxis(xaxis_data=data['AV号']).add_yaxis(
        series_name='综合评分',
        yaxis_index=1,
        y_axis=y_data_pts,
        label_opts=opts.LabelOpts(is_show=False)))
    bar.overlap(line).render("B站{0}综合排行榜前100视频数据.html".format(sheet_title))
Beispiel #17
0
    def draw_pic(self, x_data, y_data1, y_data2, y_data3):
        # 处理数据
        yd1 = ["%.2f" % (x * 100) for x in y_data1]
        yd2 = ["%.2f" % (x * 100) for x in y_data2]
        yd3 = ["%.2f" % (x * 100) for x in y_data3]

        # 人口结构折线图
        line = Line(init_opts=opts.InitOpts(width='1600px', height='500px'))
        line.add_xaxis(x_data)
        line.add_yaxis('乐观上涨点数', yd1, label_opts=opts.LabelOpts(is_show=False))
        line.add_yaxis('平均上涨点数', yd2, label_opts=opts.LabelOpts(is_show=False))
        line.add_yaxis('悲观上涨点数', yd3, label_opts=opts.LabelOpts(is_show=False))
        line.set_global_opts(
            title_opts=opts.TitleOpts(title="短线操作收益",
                                      pos_bottom="bottom",
                                      pos_left="center"),
            xaxis_opts=opts.AxisOpts(
                name='日期',
                name_location='end',
                type_="category",
                # axislabel_opts=opts.LabelOpts(is_show=True, color="#000", interval=0, rotate=90),
                axistick_opts=opts.AxisTickOpts(is_show=True,
                                                is_align_with_label=True),
                axispointer_opts=opts.AxisPointerOpts(
                    type_="shadow", label=opts.LabelOpts(is_show=True))),
            # y轴相关选项设置
            yaxis_opts=opts.AxisOpts(
                name='收益点数',
                type_="value",
                position="left",
                axislabel_opts=opts.LabelOpts(is_show=True)),
            legend_opts=opts.LegendOpts(is_show=True))

        # 渲染图像,将多个图像显示在一个html中
        # DraggablePageLayout表示可拖拽
        page = Page(layout=Page.DraggablePageLayout)
        page.add(line)
        page.render('up.html')
Beispiel #18
0
def analysis_urban():
    x_data = pdata['年份'].map(lambda x: "%d" % x).tolist()
    # total = pdata['年末总人口(万人)'].map(lambda x: "%.2f" % (x / 1000)).tolist()
    y_data1 = pdata['城镇人口(万人)'].map(lambda x: "%.2f" % (x / 1000)).tolist()
    y_data2 = pdata['乡村人口(万人)'].map(lambda x: "%.2f" % (x / 1000)).tolist()

    # 城镇化比例
    # y_data_rate = pdata['城镇人口(万人)'] * 100 / pdata['年末总人口(万人)']

    bar = Bar()
    bar.add_xaxis(x_data)
    bar.add_yaxis("城镇人口", y_data1, stack="stack1", category_gap="10%")
    bar.add_yaxis("乡村人口", y_data2, stack="stack1", category_gap="10%")
    bar.set_series_opts(
        label_opts=opts.LabelOpts(is_show=True, position="inside", rotate=90))
    bar.set_global_opts(
        title_opts=opts.TitleOpts(title="中国城镇化进程"),
        xaxis_opts=opts.AxisOpts(
            name='年份',
            name_location='end',
            type_="category",
            # axislabel_opts=opts.LabelOpts(is_show=True, color="#000", interval=0, rotate=90),
            axistick_opts=opts.AxisTickOpts(is_show=True,
                                            is_align_with_label=True),
            axispointer_opts=opts.AxisPointerOpts(
                type_="shadow", label=opts.LabelOpts(is_show=True))),
        # y轴相关选项设置
        yaxis_opts=opts.AxisOpts(name='人口数(千万人)',
                                 type_="value",
                                 position="left",
                                 axislabel_opts=opts.LabelOpts(is_show=True)),
        legend_opts=opts.LegendOpts(is_show=True))

    # 渲染图像,将多个图像显示在一个html中
    page = Page(layout=Page.DraggablePageLayout)
    page.add(bar)
    page.render('population_urban.html')
def updateBar(win, draw, lose, team):
    c = (Bar().add_xaxis(team).add_yaxis(
        "胜场", win, stack="stack1", color="#000079").add_yaxis(
            "平局", draw, stack="stack1", color="#7B7B7B").add_yaxis(
                "败场", lose, stack="stack1", color="#FF0000").set_series_opts(
                    label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
                        tooltip_opts=opts.TooltipOpts(
                            is_show=True,
                            trigger="axis",
                            axis_pointer_type="cross"),
                        xaxis_opts=opts.AxisOpts(
                            type_="category",
                            axispointer_opts=opts.AxisPointerOpts(
                                is_show=True, type_="shadow"),
                        ),
                        yaxis_opts=opts.AxisOpts(
                            name="场数",
                            type_="value",
                            interval=5,
                            axistick_opts=opts.AxisTickOpts(is_show=True),
                            splitline_opts=opts.SplitLineOpts(is_show=True),
                        ),
                    ))
    return c
Beispiel #20
0
def kline_pro(kline: List[dict],
              fx: List[dict] = None,
              xd=None,
              bs: List[dict] = None,
              title: str = "缠中说禅K线分析",
              width: str = "1400px",
              height: str = '580px') -> Grid:
    """绘制缠中说禅K线分析结果

    :param kline: K线
    :param fx: 分型识别结果
    :param bi: 笔识别结果
    :param xd: 线段识别结果
    :param zs: 中枢
    :param bs: 买卖点
    :param title: 图表标题
    :param width: 图表宽度
    :param height: 图表高度
    :return: 用Grid组合好的图表
    """
    # 配置项设置
    # ------------------------------------------------------------------------------------------------------------------
    bg_color = "#1f212d"  # 背景
    up_color = "#F9293E"
    down_color = "#00aa3b"

    init_opts = opts.InitOpts(bg_color=bg_color,
                              width=width,
                              height=height,
                              animation_opts=opts.AnimationOpts(False))
    title_opts = opts.TitleOpts(
        title=title,
        pos_top="1%",
        title_textstyle_opts=opts.TextStyleOpts(color=up_color, font_size=20),
        subtitle_textstyle_opts=opts.TextStyleOpts(color=down_color,
                                                   font_size=12))

    label_not_show_opts = opts.LabelOpts(is_show=False)
    legend_not_show_opts = opts.LegendOpts(is_show=False)
    red_item_style = opts.ItemStyleOpts(color=up_color)
    green_item_style = opts.ItemStyleOpts(color=down_color)
    k_style_opts = opts.ItemStyleOpts(color=up_color,
                                      color0=down_color,
                                      border_color=up_color,
                                      border_color0=down_color,
                                      opacity=0.8)

    legend_opts = opts.LegendOpts(is_show=True,
                                  pos_top="1%",
                                  pos_left="30%",
                                  item_width=14,
                                  item_height=8,
                                  textstyle_opts=opts.TextStyleOpts(
                                      font_size=12, color="#0e99e2"))
    brush_opts = opts.BrushOpts(tool_box=["rect", "polygon", "keep", "clear"],
                                x_axis_index="all",
                                brush_link="all",
                                out_of_brush={"colorAlpha": 0.1},
                                brush_type="lineX")

    axis_pointer_opts = opts.AxisPointerOpts(is_show=True,
                                             link=[{
                                                 "xAxisIndex": "all"
                                             }])

    range_start = int(100 - 216 / len(kline) * 100)
    dz_inside = opts.DataZoomOpts(False,
                                  "inside",
                                  xaxis_index=[0, 1, 2],
                                  range_start=range_start,
                                  range_end=100)
    dz_slider = opts.DataZoomOpts(True,
                                  "slider",
                                  xaxis_index=[0, 1, 2],
                                  pos_top="96%",
                                  pos_bottom="0%",
                                  range_start=range_start,
                                  range_end=100)

    yaxis_opts = opts.AxisOpts(is_scale=True,
                               axislabel_opts=opts.LabelOpts(
                                   color="#c7c7c7",
                                   font_size=8,
                                   position="inside"))

    grid0_xaxis_opts = opts.AxisOpts(
        type_="category",
        grid_index=0,
        axislabel_opts=label_not_show_opts,
        split_number=20,
        min_="dataMin",
        max_="dataMax",
        is_scale=True,
        boundary_gap=False,
        axisline_opts=opts.AxisLineOpts(is_on_zero=False))

    tool_tip_opts = opts.TooltipOpts(
        trigger="axis",
        axis_pointer_type="cross",
        background_color="rgba(245, 245, 245, 0.8)",
        border_width=1,
        border_color="#ccc",
        position=JsCode("""
                    function (pos, params, el, elRect, size) {
    					var obj = {top: 10};
    					obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
    					return obj;
    				}
                    """),
        textstyle_opts=opts.TextStyleOpts(color="#000"),
    )

    # 数据预处理
    # ------------------------------------------------------------------------------------------------------------------
    # dts = [x.get('dt', x['date']) for x in kline]
    try:
        dts = [x['date'] for x in kline]
    except:
        dts = [x['dt'] for x in kline]
    # k_data = [[x['open'], x['close'], x['low'], x['high']] for x in kline]
    k_data = [
        opts.CandleStickItem(
            name=i, value=[x['open'], x['close'], x['low'], x['high']])
        for i, x in enumerate(kline)
    ]

    vol = []
    for i, row in enumerate(kline):
        item_style = red_item_style if row['close'] > row[
            'open'] else green_item_style
        bar = opts.BarItem(name=i,
                           value=row['volume'],
                           itemstyle_opts=item_style,
                           label_opts=label_not_show_opts)
        vol.append(bar)

    close = np.array([x['close'] for x in kline], dtype=np.double)
    diff, dea, macd = MACD(close)

    ma5 = SMA(close, timeperiod=5)
    ma34 = SMA(close, timeperiod=34)
    ma55 = SMA(close, timeperiod=55)
    ma233 = SMA(close, timeperiod=233)

    macd_bar = []
    for i, v in enumerate(macd.tolist()):
        item_style = red_item_style if v > 0 else green_item_style
        bar = opts.BarItem(name=i,
                           value=round(v, 4),
                           itemstyle_opts=item_style,
                           label_opts=label_not_show_opts)
        macd_bar.append(bar)

    diff = diff.round(4)
    dea = dea.round(4)

    # K 线主图
    # ------------------------------------------------------------------------------------------------------------------
    chart_k = Kline()
    chart_k.add_xaxis(xaxis_data=dts)
    chart_k.add_yaxis(series_name="Kline",
                      y_axis=k_data,
                      itemstyle_opts=k_style_opts)

    chart_k.set_global_opts(legend_opts=legend_opts,
                            datazoom_opts=[dz_inside, dz_slider],
                            yaxis_opts=yaxis_opts,
                            tooltip_opts=tool_tip_opts,
                            axispointer_opts=axis_pointer_opts,
                            brush_opts=brush_opts,
                            title_opts=title_opts,
                            xaxis_opts=grid0_xaxis_opts)

    if xd:
        index = 0
        zs_colors = [
            "yellow", "white", '#f034c1', "#7944b7", "#468b58", "#c17f2f",
            "#9EA0A1"
        ]
        data = []
        temp_xd = xd
        while temp_xd:
            zs_color = zs_colors[index % len(zs_colors)]
            data = data + [
                opts.MarkAreaItem(
                    name='XD{}'.format(index),
                    x=(x['xd_list'][0]['date'], x['xd_list'][-1]['date']),
                    y=(x['ZG']['value'], x['ZD']['value']),
                    label_opts=opts.LabelOpts(color=zs_color),
                    itemstyle_opts=opts.ItemStyleOpts(
                        color=zs_color,
                        opacity=0.2,
                    )) for x in temp_xd.zs_list
            ]
            temp_xd = temp_xd.next
            index = index + 1

        chart_k.set_series_opts(
            markarea_opts=opts.MarkAreaOpts(is_silent=True, data=data))

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

    ma_keys = {"MA5": ma5, "MA34": ma34, "MA55": ma55, "MA233": ma233}
    ma_colors = ["#39afe6", "#da6ee8", "#A02128", "#00940b"]
    for i, (name, ma) in enumerate(ma_keys.items()):
        chart_ma.add_yaxis(series_name=name,
                           y_axis=ma,
                           is_smooth=True,
                           is_selected=False,
                           symbol_size=0,
                           label_opts=label_not_show_opts,
                           linestyle_opts=opts.LineStyleOpts(
                               opacity=0.8, width=1.0, color=ma_colors[i]))

    chart_ma.set_global_opts(xaxis_opts=grid0_xaxis_opts,
                             legend_opts=legend_not_show_opts)
    chart_k = chart_k.overlap(chart_ma)

    # 缠论结果
    # ------------------------------------------------------------------------------------------------------------------
    if fx:
        try:
            fx_dts = [x['date'] for x in fx]
        except:
            fx_dts = [x['dt'] for x in fx]

        fx_val = [x['value'] for x in fx]
        chart_fx = Scatter()
        chart_fx.add_xaxis(fx_dts)
        chart_fx.add_yaxis(series_name="FX",
                           y_axis=fx_val,
                           is_selected=False,
                           symbol="circle",
                           symbol_size=6,
                           label_opts=label_not_show_opts,
                           itemstyle_opts=opts.ItemStyleOpts(
                               color="rgba(152, 147, 193, 1.0)", ))

        chart_fx.set_global_opts(xaxis_opts=grid0_xaxis_opts,
                                 legend_opts=legend_not_show_opts)
        chart_k = chart_k.overlap(chart_fx)

    if xd:
        index = 0
        xd_colors = zs_colors
        while xd:
            xd_dts = [x['date'] for x in xd]
            xd_val = [x['value'] for x in xd]

            chart_xd = Line()
            chart_xd.add_xaxis(xd_dts)

            xd_color = xd_colors[index % len(xd_colors)]
            chart_xd.add_yaxis(
                series_name="XD{}".format(index),
                y_axis=xd_val,
                is_selected=True,
                symbol="triangle",
                symbol_size=10,
                linestyle_opts=opts.LineStyleOpts(color=xd_color,
                                                  width=index + 1,
                                                  type_="solid"),
                itemstyle_opts=opts.ItemStyleOpts(color=xd_color))

            chart_xd.set_global_opts(xaxis_opts=grid0_xaxis_opts,
                                     legend_opts=legend_not_show_opts)
            chart_k = chart_k.overlap(chart_xd)
            xd = xd.next
            index = index + 1

    if bs:
        b_dts = [x['date'] for x in bs if x['bs'] == 'buy']
        if len(b_dts) > 0:
            b_val = [x['value'] for x in bs if x['bs'] == 'buy']
            chart_b = Scatter()
            chart_b.add_xaxis(b_dts)
            chart_b.add_yaxis(series_name="BUY",
                              y_axis=b_val,
                              is_selected=False,
                              symbol="arrow",
                              symbol_size=8,
                              itemstyle_opts=opts.ItemStyleOpts(
                                  color="#f31e1e", ))

            chart_b.set_global_opts(xaxis_opts=grid0_xaxis_opts,
                                    legend_opts=legend_not_show_opts)
            chart_k = chart_k.overlap(chart_b)

        s_dts = [x['date'] for x in bs if x['bs'] == 'sell']
        if len(s_dts) > 0:
            s_val = [x['value'] for x in bs if x['bs'] == 'sell']
            chart_s = Scatter()
            chart_s.add_xaxis(s_dts)
            chart_s.add_yaxis(series_name="SELL",
                              y_axis=s_val,
                              is_selected=False,
                              symbol="pin",
                              symbol_size=12,
                              itemstyle_opts=opts.ItemStyleOpts(
                                  color="#45b97d", ))

            chart_s.set_global_opts(xaxis_opts=grid0_xaxis_opts,
                                    legend_opts=legend_not_show_opts)
            chart_k = chart_k.overlap(chart_s)

    # 成交量图
    # ------------------------------------------------------------------------------------------------------------------
    chart_vol = Bar()
    chart_vol.add_xaxis(dts)
    chart_vol.add_yaxis(series_name="Volume", y_axis=vol, bar_width='60%')
    chart_vol.set_global_opts(
        xaxis_opts=opts.AxisOpts(
            type_="category",
            grid_index=1,
            axislabel_opts=opts.LabelOpts(is_show=True,
                                          font_size=8,
                                          color="#9b9da9"),
        ),
        yaxis_opts=yaxis_opts,
        legend_opts=legend_not_show_opts,
    )

    # MACD图
    # ------------------------------------------------------------------------------------------------------------------
    chart_macd = Bar()
    chart_macd.add_xaxis(dts)
    chart_macd.add_yaxis(series_name="MACD", y_axis=macd_bar, bar_width='60%')
    chart_macd.set_global_opts(
        xaxis_opts=opts.AxisOpts(
            type_="category",
            grid_index=2,
            axislabel_opts=opts.LabelOpts(is_show=False),
        ),
        yaxis_opts=opts.AxisOpts(
            grid_index=2,
            split_number=4,
            axisline_opts=opts.AxisLineOpts(is_on_zero=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),
            axislabel_opts=opts.LabelOpts(is_show=True, color="#c7c7c7"),
        ),
        legend_opts=opts.LegendOpts(is_show=False),
    )

    line = Line()
    line.add_xaxis(dts)
    line.add_yaxis(series_name="DIFF",
                   y_axis=diff,
                   label_opts=label_not_show_opts,
                   is_symbol_show=False,
                   linestyle_opts=opts.LineStyleOpts(opacity=0.8,
                                                     width=1.0,
                                                     color="#da6ee8"))
    line.add_yaxis(series_name="DEA",
                   y_axis=dea,
                   label_opts=label_not_show_opts,
                   is_symbol_show=False,
                   linestyle_opts=opts.LineStyleOpts(opacity=0.8,
                                                     width=1.0,
                                                     color="#39afe6"))

    chart_macd = chart_macd.overlap(line)

    grid0_opts = opts.GridOpts(pos_left="0%",
                               pos_right="1%",
                               pos_top="12%",
                               height="58%")
    grid1_opts = opts.GridOpts(pos_left="0%",
                               pos_right="1%",
                               pos_top="74%",
                               height="8%")
    grid2_opts = opts.GridOpts(pos_left="0%",
                               pos_right="1%",
                               pos_top="86%",
                               height="10%")

    grid_chart = Grid(init_opts)
    grid_chart.add(chart_k, grid_opts=grid0_opts)
    grid_chart.add(chart_vol, grid_opts=grid1_opts)
    grid_chart.add(chart_macd, grid_opts=grid2_opts)
    return grid_chart
def draw(datelist, pricelist, title):
    min_value = min(pricelist)
    max_value = max(pricelist)

    line = (
        Line(init_opts=opts.InitOpts(
            width='1800px',
            height='800px',
            js_host="./",
        )).set_global_opts(
            title_opts=opts.TitleOpts(title=title,
                                      # subtitle='股票价格走势'
                                      ),
            legend_opts=opts.LegendOpts(is_show=True,
                                        pos_top=10,
                                        pos_left="center",
                                        item_width=30,
                                        item_height=15,
                                        textstyle_opts=opts.TextStyleOpts(
                                            font_family='Microsoft Yahei',
                                            font_size=14,
                                            font_style='oblique')),
            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"),
            ),
            xaxis_opts=opts.AxisOpts(
                # type_="time",
                name='日期',
                split_number=10,
                name_gap=35,
                axispointer_opts=opts.AxisPointerOpts(is_show=True),
                name_textstyle_opts=opts.TextStyleOpts(
                    font_size=16, font_family='Microsoft Yahei')),
            yaxis_opts=opts.AxisOpts(
                type_="value",
                # name='价格',
                min_=min_value,
                max_=max_value,
                split_number=4,
                axispointer_opts=opts.AxisPointerOpts(is_show=True),
                name_textstyle_opts=opts.TextStyleOpts(
                    font_size=16, font_family='Microsoft Yahei'),
                axistick_opts=opts.AxisTickOpts(is_show=True),
                splitline_opts=opts.SplitLineOpts(is_show=True),
                splitarea_opts=opts.SplitAreaOpts(
                    is_show=True,
                    areastyle_opts=opts.AreaStyleOpts(opacity=1))),
            axispointer_opts=opts.AxisPointerOpts(
                is_show=True,
                link=[{
                    "xAxisIndex": "all"
                }],
                label=opts.LabelOpts(background_color="#777"),
            ),
            datazoom_opts=[
                opts.DataZoomOpts(
                    is_show=False,
                    type_="inside",
                    # xaxis_index=[0, 1],
                    range_start=30,
                    range_end=70,
                ),
                opts.DataZoomOpts(
                    is_show=True,
                    # xaxis_index=[0, 1],
                    type_="slider",
                    pos_top="96%",
                    range_start=38,
                    range_end=70,
                ),
            ],
        ).add_xaxis(xaxis_data=datelist).add_yaxis(
            series_name="走势情况",
            is_selected=True,
            y_axis=pricelist,
            label_opts=opts.LabelOpts(is_show=False),
            markpoint_opts=opts.MarkPointOpts(data=[
                opts.MarkPointItem(type_="max", name="最大值"),
                opts.MarkPointItem(type_="min", name="最小值"),
                opts.MarkPointItem(type_="average", name="平均值")
            ])).render(title + '.html'))
Beispiel #22
0
         "2015-6",
         "2015-7",
         "2015-8",
         "2015-9",
         "2015-10",
         "2015-11",
         "2015-12",
     ],
     xaxis=opts.AxisOpts(
         type_="category",
         axistick_opts=opts.AxisTickOpts(is_align_with_label=True),
         axisline_opts=opts.AxisLineOpts(
             is_on_zero=False,
             linestyle_opts=opts.LineStyleOpts(color="#6e9ef1")),
         axispointer_opts=opts.AxisPointerOpts(
             is_show=True,
             label=opts.LabelOpts(formatter=JsCode(js_formatter))),
     ),
 ).add_yaxis(
     series_name="2015 降水量",
     is_smooth=True,
     symbol="emptyCircle",
     is_symbol_show=False,
     # xaxis_index=1,
     color="#d14a61",
     y_axis=[
         2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3
     ],
     label_opts=opts.LabelOpts(is_show=False),
     linestyle_opts=opts.LineStyleOpts(width=2),
 ).add_yaxis(
Beispiel #23
0
def show_xd_kline(kline_raw, show=True):
    freq = '5min'
    start_dt = kline_raw.iloc[0]["dt"]
    end_dt = kline_raw.iloc[-1]["dt"]

    x_data = kline_raw.dt.values.tolist()
    oclh = kline_raw[['open', 'close', 'low', 'high']].values.tolist()
    symbol = kline_raw.iloc[0]['symbol']

    kline = (
        Kline(init_opts=opts.InitOpts(theme=ThemeType.WHITE))
        .add_xaxis(xaxis_data=x_data)
        .add_yaxis(
            series_name=symbol,
            y_axis=oclh,
            itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c"),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title="缠论分析结果:%s-%s" % (symbol, freq),
                subtitle="时间区间:%s 至 %s" % (start_dt, end_dt)
            ),
            xaxis_opts=opts.AxisOpts(type_="category"),
            yaxis_opts=opts.AxisOpts(
                is_scale=True,
                splitarea_opts=opts.SplitAreaOpts(
                    is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)
                ),
            ),
            legend_opts=opts.LegendOpts(
                is_show=True, pos_top=10, pos_left="center"
            ),
            datazoom_opts=[
                opts.DataZoomOpts(
                    is_show=False,
                    type_="inside",
                    xaxis_index=[0, 1],
                    range_start=0,
                    range_end=100,
                ),
                opts.DataZoomOpts(
                    is_show=True,
                    xaxis_index=[0, 1],
                    type_="slider",
                    pos_top="90%",
                    range_start=0,
                    range_end=100,
                ),
            ],
            tooltip_opts=opts.TooltipOpts(
                trigger="axis",
                axis_pointer_type="cross",
                background_color="rgba(245, 245, 245, 0.8)",
                border_width=1,
                border_color="#ccc",
                textstyle_opts=opts.TextStyleOpts(color="#000"),
            ),
            visualmap_opts=opts.VisualMapOpts(
                is_show=False,
                dimension=2,
                series_index=5,
                is_piecewise=True,
                pieces=[
                    {"value": 1, "color": "#ec0000"},
                    {"value": -1, "color": "#00da3c"},
                ],
            ),
            axispointer_opts=opts.AxisPointerOpts(
                is_show=True,
                link=[{"xAxisIndex": "all"}],
                label=opts.LabelOpts(background_color="#777"),
            ),
            brush_opts=opts.BrushOpts(
                x_axis_index="all",
                brush_link="all",
                out_of_brush={"colorAlpha": 0.1},
                brush_type="lineX",
            ),
        )
    )

    chan_fx = (
        Scatter(init_opts=opts.InitOpts(theme=ThemeType.WHITE))
        .add_xaxis(xaxis_data=x_data)
        .add_yaxis("分型标记", kline_raw.fx.values.tolist(),
                   label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(
            visualmap_opts=opts.VisualMapOpts(type_="size", max_=150, min_=20),
        )
    )

    chan_bi = (
        Scatter(init_opts=opts.InitOpts(theme=ThemeType.WHITE))
        .add_xaxis(xaxis_data=x_data)
        .add_yaxis("笔标记", kline_raw.bi.values.tolist(),
                   label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(
            visualmap_opts=opts.VisualMapOpts(type_="size", max_=150, min_=20),
        )
    )

    chan_xd = (
        Scatter(init_opts=opts.InitOpts(theme=ThemeType.WHITE))
        .add_xaxis(xaxis_data=x_data)
        .add_yaxis("线段标记", kline_raw.xd.values.tolist(),
                   label_opts=opts.LabelOpts(is_show=False))
        .set_global_opts(
            visualmap_opts=opts.VisualMapOpts(type_="size", max_=150, min_=20),
        )
    )

    bar = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
        .add_xaxis(xaxis_data=x_data)
        .add_yaxis(
            series_name="Volume",
            yaxis_data=kline_raw.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),
        )
    )

    # Kline And Line
    kline = kline.overlap(chan_fx)
    kline = kline.overlap(chan_bi)
    kline = kline.overlap(chan_xd)

    # Grid Overlap + Bar
    grid_chart = Grid(opts.InitOpts(width="1400px", height="800px", theme=ThemeType.WHITE))
    grid_chart.add(
        kline,
        grid_opts=opts.GridOpts(
            pos_left="8%", pos_right="8%", height="60%"
        ),
    )
    grid_chart.add(
        bar,
        grid_opts=opts.GridOpts(
            pos_left="8%", pos_right="8%", pos_top="70%", height="16%"
        ),
    )

    graph_path = os.path.join(cache_path, "%s_kline_%s.html" % (symbol, "fx"))
    grid_chart.render(path=graph_path)

    # 调用浏览器打开可视化结果
    if show:
        webbrowser.open(graph_path)
Beispiel #24
0
        label_opts=opts.LabelOpts(is_show=False),
    )
    .extend_axis(
        yaxis=opts.AxisOpts(
            name="温度",
            type_="value",
            min_=0,
            max_=25,
            interval=5,
            axislabel_opts=opts.LabelOpts(formatter="{value} °C"),
        )
    )
    .set_global_opts(
        tooltip_opts=opts.TooltipOpts(is_show=True, trigger="axis", axis_pointer_type="cross"),
        xaxis_opts=opts.AxisOpts(
            type_="category", axispointer_opts=opts.AxisPointerOpts(is_show=True, type_="shadow")
        ),
        yaxis_opts=opts.AxisOpts(
            name="水量",
            type_="value",
            min_=0,
            max_=250,
            interval=50,
            axislabel_opts=opts.LabelOpts(formatter="{value} ml"),
            axistick_opts=opts.AxisTickOpts(is_show=True),
            splitline_opts=opts.SplitLineOpts(is_show=True),
        ),
    )
)

line = (
Beispiel #25
0
def kline_profession_example() -> Grid:

    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],
    ]

    def calculate_ma(day_count: int, d):
        result: List[Union[float, str]] = []
        for i in range(len(d)):
            if i < day_count:
                result.append("-")
                continue
            sum_total = 0.0
            for j in range(day_count):
                sum_total += float(d[i - j][1])
            result.append(abs(float("%.3f" % (sum_total / day_count))))
        return result

    x_data = ["2017-7-{}".format(i + 1) for i in range(31)]

    kline = (Kline().add_xaxis(xaxis_data=x_data).add_yaxis(
        series_name="Dow-Jones index",
        y_axis=data,
        itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c"),
    ).set_global_opts(
        title_opts=opts.TitleOpts(
            title="复杂版 Kline 示例 (Kline + Line + Bar)",
            subtitle="MA 就以(2, 4, 6, 8为例)",
        ),
        xaxis_opts=opts.AxisOpts(type_="category"),
        yaxis_opts=opts.AxisOpts(
            is_scale=True,
            splitarea_opts=opts.SplitAreaOpts(
                is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)),
        ),
        legend_opts=opts.LegendOpts(is_show=False,
                                    pos_bottom=10,
                                    pos_left="center"),
        datazoom_opts=[
            opts.DataZoomOpts(
                is_show=False,
                type_="inside",
                xaxis_index=[0, 1],
                range_start=0,
                range_end=100,
            ),
            opts.DataZoomOpts(
                is_show=True,
                xaxis_index=[0, 1],
                type_="slider",
                pos_top="90%",
                range_start=0,
                range_end=100,
            ),
        ],
        tooltip_opts=opts.TooltipOpts(
            trigger="axis",
            axis_pointer_type="cross",
            background_color="rgba(245, 245, 245, 0.8)",
            border_width=1,
            border_color="#ccc",
            textstyle_opts=opts.TextStyleOpts(color="#000"),
        ),
        visualmap_opts=opts.VisualMapOpts(
            is_show=False,
            dimension=2,
            series_index=5,
            is_piecewise=True,
            pieces=[
                {
                    "value": 1,
                    "color": "#ec0000"
                },
                {
                    "value": -1,
                    "color": "#00da3c"
                },
            ],
        ),
        axispointer_opts=opts.AxisPointerOpts(
            is_show=True,
            link=[{
                "xAxisIndex": "all"
            }],
            label=opts.LabelOpts(background_color="#777"),
        ),
        brush_opts=opts.BrushOpts(
            x_axis_index="all",
            brush_link="all",
            out_of_brush={"colorAlpha": 0.1},
            brush_type="lineX",
        ),
    ))

    line = (Line().add_xaxis(xaxis_data=x_data).add_yaxis(
        series_name="MA2",
        y_axis=calculate_ma(day_count=2, d=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="MA4",
        y_axis=calculate_ma(day_count=4, d=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="MA6",
        y_axis=calculate_ma(day_count=6, d=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="MA8",
        y_axis=calculate_ma(day_count=8, d=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=x_data).add_yaxis(
        series_name="Volume",
        yaxis_data=[[i, data[i][3], 1 if data[i][0] > data[i][1] else -1]
                    for i in range(len(data))],
        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()
    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="70%",
                                height="16%"),
    )
    return grid_chart
Beispiel #26
0
def kline_pro(kline: List[dict],
              ma: List[dict],
              macd: List[dict],
              fx: List[dict] = None,
              bi: List[dict] = None,
              xd: List[dict] = None,
              bs: List[dict] = None,
              title: str = "缠中说禅K线分析",
              width: str = "1200px",
              height: str = '680px') -> Grid:
    """绘制缠中说禅K线分析结果

    :param kline: K线
    :param ma: 均线
    :param macd: MACD
    :param fx: 分型识别结果
    :param bi: 笔识别结果
    :param xd: 线段识别结果
    :param bs: 买卖点
    :param title: 图表标题
    :param width: 图表宽度
    :param height: 图表高度
    :return: 用Grid组合好的图表
    """
    # 配置项设置
    # ------------------------------------------------------------------------------------------------------------------
    bg_color = "#1f212d"  # 背景
    up_color = "#F9293E"
    down_color = "#00aa3b"

    init_opts = opts.InitOpts(bg_color=bg_color,
                              width=width,
                              height=height,
                              animation_opts=opts.AnimationOpts(False))
    title_opts = opts.TitleOpts(
        title=title,
        pos_top="1%",
        title_textstyle_opts=opts.TextStyleOpts(color=up_color, font_size=20),
        subtitle_textstyle_opts=opts.TextStyleOpts(color=down_color,
                                                   font_size=12))

    label_not_show_opts = opts.LabelOpts(is_show=False)
    legend_not_show_opts = opts.LegendOpts(is_show=False)
    red_item_style = opts.ItemStyleOpts(color=up_color)
    green_item_style = opts.ItemStyleOpts(color=down_color)
    k_style_opts = opts.ItemStyleOpts(color=up_color,
                                      color0=down_color,
                                      border_color=up_color,
                                      border_color0=down_color,
                                      opacity=0.8)

    legend_opts = opts.LegendOpts(is_show=True,
                                  pos_top="1%",
                                  pos_left="30%",
                                  item_width=14,
                                  item_height=8,
                                  textstyle_opts=opts.TextStyleOpts(
                                      font_size=12, color="#0e99e2"))
    brush_opts = opts.BrushOpts(tool_box=["rect", "polygon", "keep", "clear"],
                                x_axis_index="all",
                                brush_link="all",
                                out_of_brush={"colorAlpha": 0.1},
                                brush_type="lineX")

    axis_pointer_opts = opts.AxisPointerOpts(is_show=True,
                                             link=[{
                                                 "xAxisIndex": "all"
                                             }])

    dz_inside = opts.DataZoomOpts(False, "inside", xaxis_index=[0, 1, 2])
    dz_slider = opts.DataZoomOpts(True,
                                  "slider",
                                  xaxis_index=[0, 1, 2],
                                  pos_top="96%",
                                  pos_bottom="0%")

    yaxis_opts = opts.AxisOpts(is_scale=True,
                               axislabel_opts=opts.LabelOpts(
                                   color="#c7c7c7",
                                   font_size=8,
                                   position="inside"))

    grid0_xaxis_opts = opts.AxisOpts(
        type_="category",
        grid_index=0,
        axislabel_opts=label_not_show_opts,
        split_number=20,
        min_="dataMin",
        max_="dataMax",
        is_scale=True,
        boundary_gap=False,
        axisline_opts=opts.AxisLineOpts(is_on_zero=False))

    tool_tip_opts = opts.TooltipOpts(
        trigger="axis",
        axis_pointer_type="cross",
        background_color="rgba(245, 245, 245, 0.8)",
        border_width=1,
        border_color="#ccc",
        position=JsCode("""
                    function (pos, params, el, elRect, size) {
    					var obj = {top: 10};
    					obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30;
    					return obj;
    				}
                    """),
        textstyle_opts=opts.TextStyleOpts(color="#000"),
    )

    # 数据预处理
    # ------------------------------------------------------------------------------------------------------------------
    dts = [x['dt'] for x in kline]
    k_data = [[x['open'], x['close'], x['low'], x['high']] for x in kline]

    vol = []
    for row in kline:
        item_style = red_item_style if row['close'] > row[
            'open'] else green_item_style
        bar = opts.BarItem(value=row['vol'],
                           itemstyle_opts=item_style,
                           label_opts=label_not_show_opts)
        vol.append(bar)

    macd_bar = []
    for row in macd:
        item_style = red_item_style if row['macd'] > 0 else green_item_style
        bar = opts.BarItem(value=round(row['macd'], 4),
                           itemstyle_opts=item_style,
                           label_opts=label_not_show_opts)
        macd_bar.append(bar)

    diff = [round(x['diff'], 4) for x in macd]
    dea = [round(x['dea'], 4) for x in macd]

    # K 线主图
    # ------------------------------------------------------------------------------------------------------------------
    chart_k = Kline()
    chart_k.add_xaxis(xaxis_data=dts)
    chart_k.add_yaxis(series_name="Kline",
                      y_axis=k_data,
                      itemstyle_opts=k_style_opts)

    chart_k.set_global_opts(legend_opts=legend_opts,
                            datazoom_opts=[dz_inside, dz_slider],
                            yaxis_opts=yaxis_opts,
                            tooltip_opts=tool_tip_opts,
                            axispointer_opts=axis_pointer_opts,
                            brush_opts=brush_opts,
                            title_opts=title_opts,
                            xaxis_opts=grid0_xaxis_opts)

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

    ma_keys = [x for x in ma[0].keys() if "ma" in x][:3]
    ma_colors = ["#39afe6", "#da6ee8", "#00940b"]
    for i, k in enumerate(ma_keys):
        y_data = [x[k] for x in ma]
        chart_ma.add_yaxis(series_name=k.upper(),
                           y_axis=y_data,
                           is_smooth=True,
                           is_selected=False,
                           symbol_size=0,
                           label_opts=label_not_show_opts,
                           linestyle_opts=opts.LineStyleOpts(
                               opacity=0.8, width=1.0, color=ma_colors[i]))

    chart_ma.set_global_opts(xaxis_opts=grid0_xaxis_opts,
                             legend_opts=legend_not_show_opts)
    chart_k = chart_k.overlap(chart_ma)

    # 缠论结果
    # ------------------------------------------------------------------------------------------------------------------
    if fx:
        fx_dts = [x['dt'] for x in fx]
        fx_val = [x['fx'] for x in fx]
        chart_fx = Scatter()
        chart_fx.add_xaxis(fx_dts)
        chart_fx.add_yaxis(series_name="FX",
                           y_axis=fx_val,
                           is_selected=False,
                           symbol="circle",
                           symbol_size=6,
                           label_opts=label_not_show_opts,
                           itemstyle_opts=opts.ItemStyleOpts(
                               color="rgba(152, 147, 193, 1.0)", ))

        chart_fx.set_global_opts(xaxis_opts=grid0_xaxis_opts,
                                 legend_opts=legend_not_show_opts)
        chart_k = chart_k.overlap(chart_fx)

    if bi:
        bi_dts = [x['dt'] for x in bi]
        bi_val = [x['bi'] for x in bi]
        chart_bi = Scatter()
        chart_bi.add_xaxis(bi_dts)
        chart_bi.add_yaxis(series_name="BI",
                           y_axis=bi_val,
                           is_selected=True,
                           symbol="diamond",
                           symbol_size=10,
                           label_opts=label_not_show_opts,
                           itemstyle_opts=opts.ItemStyleOpts(
                               color="rgba(184, 117, 225, 1.0)", ))

        chart_bi.set_global_opts(xaxis_opts=grid0_xaxis_opts,
                                 legend_opts=legend_not_show_opts)
        chart_k = chart_k.overlap(chart_bi)

    if xd:
        xd_dts = [x['dt'] for x in xd]
        xd_val = [x['xd'] for x in xd]
        chart_xd = Scatter()
        chart_xd.add_xaxis(xd_dts)
        chart_xd.add_yaxis(series_name="XD",
                           y_axis=xd_val,
                           is_selected=True,
                           symbol="triangle",
                           symbol_size=10,
                           itemstyle_opts=opts.ItemStyleOpts(
                               color="rgba(37, 141, 54, 1.0)", ))

        chart_xd.set_global_opts(xaxis_opts=grid0_xaxis_opts,
                                 legend_opts=legend_not_show_opts)
        chart_k = chart_k.overlap(chart_xd)

    if bs:
        b_dts = [x['dt'] for x in bs if x['mark'] == 'buy']
        if len(b_dts) > 0:
            b_val = [x['buy'] for x in bs if x['mark'] == 'buy']
            chart_b = Scatter()
            chart_b.add_xaxis(b_dts)
            chart_b.add_yaxis(series_name="BUY",
                              y_axis=b_val,
                              is_selected=False,
                              symbol="arrow",
                              symbol_size=8,
                              itemstyle_opts=opts.ItemStyleOpts(
                                  color="#f31e1e", ))

            chart_b.set_global_opts(xaxis_opts=grid0_xaxis_opts,
                                    legend_opts=legend_not_show_opts)
            chart_k = chart_k.overlap(chart_b)

        s_dts = [x['dt'] for x in bs if x['mark'] == 'sell']
        if len(s_dts) > 0:
            s_val = [x['sell'] for x in bs if x['mark'] == 'sell']
            chart_s = Scatter()
            chart_s.add_xaxis(s_dts)
            chart_s.add_yaxis(series_name="SELL",
                              y_axis=s_val,
                              is_selected=False,
                              symbol="pin",
                              symbol_size=12,
                              itemstyle_opts=opts.ItemStyleOpts(
                                  color="#45b97d", ))

            chart_s.set_global_opts(xaxis_opts=grid0_xaxis_opts,
                                    legend_opts=legend_not_show_opts)
            chart_k = chart_k.overlap(chart_s)

    # 成交量图
    # ------------------------------------------------------------------------------------------------------------------
    chart_vol = Bar()
    chart_vol.add_xaxis(dts)
    chart_vol.add_yaxis(series_name="Volume", y_axis=vol, bar_width='60%')
    chart_vol.set_global_opts(
        xaxis_opts=opts.AxisOpts(
            type_="category",
            grid_index=1,
            axislabel_opts=opts.LabelOpts(is_show=True,
                                          font_size=8,
                                          color="#9b9da9"),
        ),
        yaxis_opts=yaxis_opts,
        legend_opts=legend_not_show_opts,
    )

    # MACD图
    # ------------------------------------------------------------------------------------------------------------------
    chart_macd = Bar()
    chart_macd.add_xaxis(dts)
    chart_macd.add_yaxis(series_name="MACD", y_axis=macd_bar, bar_width='60%')
    chart_macd.set_global_opts(
        xaxis_opts=opts.AxisOpts(
            type_="category",
            grid_index=2,
            axislabel_opts=opts.LabelOpts(is_show=False),
        ),
        yaxis_opts=opts.AxisOpts(
            grid_index=2,
            split_number=4,
            axisline_opts=opts.AxisLineOpts(is_on_zero=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),
            axislabel_opts=opts.LabelOpts(is_show=True, color="#c7c7c7"),
        ),
        legend_opts=opts.LegendOpts(is_show=False),
    )

    line = Line()
    line.add_xaxis(dts)
    line.add_yaxis(series_name="DIFF",
                   y_axis=diff,
                   label_opts=label_not_show_opts,
                   is_symbol_show=False,
                   linestyle_opts=opts.LineStyleOpts(opacity=0.8,
                                                     width=1.0,
                                                     color="#da6ee8"))
    line.add_yaxis(series_name="DEA",
                   y_axis=dea,
                   label_opts=label_not_show_opts,
                   is_symbol_show=False,
                   linestyle_opts=opts.LineStyleOpts(opacity=0.8,
                                                     width=1.0,
                                                     color="#39afe6"))

    chart_macd = chart_macd.overlap(line)

    grid0_opts = opts.GridOpts(pos_left="0%",
                               pos_right="1%",
                               pos_top="12%",
                               height="58%")
    grid1_opts = opts.GridOpts(pos_left="0%",
                               pos_right="1%",
                               pos_top="74%",
                               height="8%")
    grid2_opts = opts.GridOpts(pos_left="0%",
                               pos_right="1%",
                               pos_top="86%",
                               height="10%")

    grid_chart = Grid(init_opts)
    grid_chart.add(chart_k, grid_opts=grid0_opts)
    grid_chart.add(chart_vol, grid_opts=grid1_opts)
    grid_chart.add(chart_macd, grid_opts=grid2_opts)
    return grid_chart
Beispiel #27
0
def quanguo_wuhan_compare(city_list):
    time = set()
    for item in city_list:
        time.add(item[0])
    TIME = {}
    for x in time:
        TIME.update({x: (0, 0)})
    for item in city_list:
        if item[1] in province:
            if item[1] != "湖北":
                TIME.update(
                    {item[0]: (TIME[item[0]][0] + item[3], TIME[item[0]][1])})
            else:
                TIME.update(
                    {item[0]: (TIME[item[0]][0], TIME[item[0]][1] + item[3])})

    time_others_wuhan = []
    for k, v in TIME.items():
        time_others_wuhan.append([k, v[0], v[1]])
    time_others_wuhan.sort()

    L1 = (Line().add_xaxis(
        xaxis_data=[x[0] for x in time_others_wuhan]).add_yaxis(
            series_name="全国其他地区",
            y_axis=[x[1] for x in time_others_wuhan],
            symbol_size=8,
            is_hover_animation=False,
            label_opts=opts.LabelOpts(is_show=False),
            linestyle_opts=opts.LineStyleOpts(width=1.5),
            is_smooth=True,
        ).set_global_opts(
            title_opts=opts.TitleOpts(title="湖北地区和全国其他地区确诊人数对比图",
                                      subtitle="截止至2020年5月21日",
                                      pos_left="center"),
            tooltip_opts=opts.TooltipOpts(trigger="axis"),
            axispointer_opts=opts.AxisPointerOpts(is_show=True,
                                                  link=[{
                                                      "xAxisIndex": "all"
                                                  }]),
            datazoom_opts=[
                opts.DataZoomOpts(
                    is_show=True,
                    is_realtime=True,
                    start_value=30,
                    end_value=70,
                    xaxis_index=[0, 1],
                )
            ],
            xaxis_opts=opts.AxisOpts(
                type_="category",
                boundary_gap=False,
                axisline_opts=opts.AxisLineOpts(is_on_zero=True),
            ),
            yaxis_opts=opts.AxisOpts(is_inverse=False, name="人数"),
            legend_opts=opts.LegendOpts(pos_left="left"),
            toolbox_opts=opts.ToolboxOpts(
                is_show=True,
                feature={
                    "dataZoom": {
                        "yAxisIndex": "none"
                    },
                    "restore": {},
                    "saveAsImage": {},
                },
            ),
        ))

    L2 = (Line().add_xaxis(
        xaxis_data=[x[0] for x in time_others_wuhan]).add_yaxis(
            series_name="湖北地区",
            y_axis=[x[2] for x in time_others_wuhan],
            xaxis_index=1,
            yaxis_index=1,
            symbol_size=8,
            is_hover_animation=False,
            label_opts=opts.LabelOpts(is_show=False),
            linestyle_opts=opts.LineStyleOpts(width=1.5),
            is_smooth=True,
        ).set_global_opts(
            axispointer_opts=opts.AxisPointerOpts(is_show=True,
                                                  link=[{
                                                      "xAxisIndex": "all"
                                                  }]),
            tooltip_opts=opts.TooltipOpts(trigger="axis"),
            xaxis_opts=opts.AxisOpts(
                grid_index=1,
                type_="category",
                boundary_gap=False,
                axisline_opts=opts.AxisLineOpts(is_on_zero=True),
                position="top",
            ),
            datazoom_opts=[
                opts.DataZoomOpts(
                    is_realtime=True,
                    type_="inside",
                    start_value=30,
                    end_value=70,
                    xaxis_index=[0, 1],
                )
            ],
            yaxis_opts=opts.AxisOpts(is_inverse=True, name="确诊人数"),
            legend_opts=opts.LegendOpts(pos_left="15%"),
        ))

    (Grid(init_opts=opts.InitOpts(width="1024px", height="768px")).add(
        chart=L1,
        grid_opts=opts.GridOpts(pos_left=50, pos_right=50, height="35%")).add(
            chart=L2,
            grid_opts=opts.GridOpts(pos_left=50,
                                    pos_right=50,
                                    pos_top="55%",
                                    height="35%"),
        ).render(path="compare.html"))
Beispiel #28
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 = 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)
Beispiel #29
0
def draw_kine(stock_data):
    '''
        pyecharts V1 版本开始支持链式调用
       文档地址 https://pyecharts.org/#/zh-cn/
    '''
    stock_data.index = pd.to_datetime(stock_data['TIME'], format="%Y/%m/%d")
    stock_data = stock_data[["TIME", "OPEN", "CLOSE", "LOW", "HIGH", "VOLUME"]]
    # stock_data = stock_data.sort_index(ascending=True)  # 倒序,看时间顺序是否正常
    # k线图
    kline = (
        Kline().add_xaxis(stock_data[["TIME"]].values.tolist()).add_yaxis(
            "K线图",
            stock_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轴起始坐标可自动调整
            title_opts=opts.TitleOpts(title="价格",
                                      subtitle=ts_code,
                                      pos_top="20%"),
            axispointer_opts=opts.AxisPointerOpts(
                is_show=True,
                link=[{
                    "xAxisIndex": "all"
                }],
                label=opts.LabelOpts(background_color="#777"),
            ),
            datazoom_opts=[  # 设置zoom参数后即可缩放
                opts.DataZoomOpts(
                    is_show=True,
                    type_="inside",
                    xaxis_index=[0, 1],  # 设置第0轴和第1轴同时缩放
                    range_start=0,
                    range_end=100,
                ),
                opts.DataZoomOpts(
                    is_show=True,
                    xaxis_index=[0, 1],
                    type_="slider",
                    pos_top="90%",
                    range_start=0,
                    range_end=100,
                ),
            ],
            brush_opts=opts.BrushOpts(
                x_axis_index="all",
                brush_link="all",
                out_of_brush={"colorAlpha": 0.1},
                brush_type="lineX",
            ),
        ))

    # 成交量柱形图
    x = stock_data[["TIME"]].values.tolist()
    y = stock_data[["VOLUME"]].values[:, 0].tolist()

    bar = (Bar().add_xaxis(x).add_yaxis(
        "成交量",
        y,
        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(
        title_opts=opts.TitleOpts(title="成交量", pos_top="70%"),
        legend_opts=opts.LegendOpts(is_show=False),
    ))

    # 使用网格将多张图标组合到一起显示
    grid_chart = Grid(init_opts=opts.InitOpts(
        width="1200px",
        height="600px",
        animation_opts=opts.AnimationOpts(animation=False),
    ))

    # 这个是为了把 data.datas 这个数据写入到 html 中,还没想到怎么跨 series 传值
    # demo 中的代码也是用全局变量传的
    grid_chart.add_js_funcs("var barData = {}".format(
        stock_data.iloc[:, 1:5].values.tolist()))
    grid_chart.add(
        kline,
        grid_opts=opts.GridOpts(pos_left="15%", pos_right="15%", height="55%"),
    )

    grid_chart.add(
        bar,
        grid_opts=opts.GridOpts(pos_left="15%",
                                pos_right="15%",
                                pos_top="70%",
                                height="20%"),
    )

    grid_chart.render('stock_{}.html'.format(ts_code))  #保存成用股票代码命名的文档
def daily_issue_plot(daily,cummulative):
    import pyecharts.options as opts
    from pyecharts.charts import Bar, Line

    # color = ["#36648B","tomato"]

    daily = daily.round(2)
    cummulative = cummulative.round(2)

    x_data = daily.index.astype(str).tolist()

    bar = (
        Bar(init_opts=opts.InitOpts(width=fig_width, height=fig_height))
            .add_xaxis(xaxis_data=x_data)
            .add_yaxis(
            series_name="每日发行数量",
            yaxis_index=2,
            yaxis_data=daily['发行数量'].tolist(),
            label_opts=opts.LabelOpts(is_show=False),
        ).add_yaxis(
            series_name="每日发行总额",
            yaxis_index=3,
            yaxis_data=daily['发行总额'].tolist(),
            label_opts=opts.LabelOpts(is_show=False),
        )
            .set_global_opts(
            tooltip_opts=opts.TooltipOpts(
                is_show=True, trigger="axis", axis_pointer_type="cross"
            ),
            xaxis_opts=opts.AxisOpts(
                type_="category",
                axispointer_opts=opts.AxisPointerOpts(is_show=True, type_="shadow"),
            ),
            yaxis_opts=opts.AxisOpts(
                name="数量",
                type_="value",
                # min_=0,
                # max_=250,
                # interval=50,
                axislabel_opts=opts.LabelOpts(formatter="{value}"),
                axistick_opts=opts.AxisTickOpts(is_show=True),
                splitline_opts=opts.SplitLineOpts(is_show=True),
            ),
            toolbox_opts=opts.ToolboxOpts(is_show=True,
                                          feature=opts.ToolBoxFeatureOpts(
                                              save_as_image=opts.ToolBoxFeatureSaveAsImageOpts(
                                                  background_color='white',
                                                  connected_background_color="white",
                                                  pixel_ratio=pixel_ratio,
                                                  name="pic",
                                              ),
                                          )
                                          )
        )
    )

    line = (
        Line(init_opts=opts.InitOpts(width=fig_width, height=fig_height))
            .add_xaxis(xaxis_data=x_data)
            .add_yaxis(
            series_name="累计发行数量",
            yaxis_index=0,
            y_axis=cummulative['累计发行数量'].tolist(),
            label_opts=opts.LabelOpts(is_show=False),

            is_smooth=True,
            is_symbol_show=True,
            symbol="circle",
            symbol_size=6,
            linestyle_opts=opts.LineStyleOpts(width=2),

        ).add_yaxis(
            series_name="累计发行总额",
            yaxis_index=1,
            is_smooth=True,
            is_symbol_show=True,
            symbol="circle",
            symbol_size=6,
            linestyle_opts=opts.LineStyleOpts(width=2),

            y_axis=cummulative['累计发行总额'].tolist(),
            label_opts=opts.LegendOpts(is_show=False),
        )
            .extend_axis(yaxis=opts.AxisOpts(
            name= "总额",
            type_="value",
            position='right',
            offset=60,
            axislabel_opts=opts.LabelOpts(formatter="{value}亿",position="right"),

        ),).extend_axis(
            yaxis=opts.AxisOpts(
                name="数量",
                type_="value",
                position="left",
                offset=0,
                axislabel_opts=opts.LabelOpts(formatter="{value}"),
            )
        )
            .extend_axis(
            yaxis=opts.AxisOpts(
                name="总额",
                type_="value",
                position="left",
                offset=60,
                axislabel_opts=opts.LabelOpts(formatter="{value}亿"),
            )
        )

        .set_global_opts(
            tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"),
            xaxis_opts=opts.AxisOpts(
                splitline_opts=opts.SplitLineOpts(
                    is_show=True, linestyle_opts=opts.LineStyleOpts(color="#E8E8E8")
                ),
            ),
            yaxis_opts=opts.AxisOpts(
                name = "数量",
                type_="value",
                position="right",
                offset=0,
                axisline_opts=opts.AxisLineOpts(
                    linestyle_opts=opts.LineStyleOpts(width=1)
                ),
                splitline_opts=opts.SplitLineOpts(
                    is_show=True, linestyle_opts=opts.LineStyleOpts(color='#E8E8E8')
                ),
            ),
            toolbox_opts=opts.ToolboxOpts(is_show=True,
                                          feature=opts.ToolBoxFeatureOpts(
                                              save_as_image=opts.ToolBoxFeatureSaveAsImageOpts(
                                                  background_color='white',
                                                  connected_background_color="white",
                                                  pixel_ratio=pixel_ratio,
                                                  name="pic",
                                              ),
                                          )
                                          ),

        )
    )
    line.overlap(bar)
    return line