コード例 #1
0
def line_datazoom_CO2(dataframe) -> Line:
    Line_CO2 = (
        Line().add_xaxis(dataframe['time'].values.tolist(), )  # 添加x轴
        .add_yaxis(
            series_name="CO2浓度",
            y_axis=dataframe['CO2'].values.tolist(),
            is_smooth=True,
            label_opts=opts.LabelOpts(is_show=False),
        ).set_global_opts(
            # xaxis_opts=opts.AxisOpts(type_="time"),
            title_opts=opts.TitleOpts(title='实时CO2浓度折线图'),
            datazoom_opts=opts.DataZoomOpts(
                is_show=True,
                pos_bottom=-2,
                xaxis_index=[0, 1, 2],
            ),
            tooltip_opts=opts.TooltipOpts(
                is_show=True,
                trigger="axis",
                axis_pointer_type='cross',
            ),
        ))

    return Line_CO2
コード例 #2
0
def gen_line(df1, s1, price_min, price_max):
    df1['datetime'] = df1['date']
    dt_list1 = list(df1['datetime'])
    dt_list1 = [s[5:10] for s in dt_list1]
    # 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.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",
                range_start=0,
                range_end=100,
            ),
        ],
    )
    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
コード例 #3
0
def heliu() -> Bar:

    a = [1, 10, 100, 150, 180, 200]  #模拟确诊
    b = [0, 2, 20, 50, 100, 102]  #模拟治愈
    c = [0, 1, 10, 15, 18, 18]  #模拟死亡
    v = list(map(lambda x: x[0] - x[1] - x[2], zip(a, b, c)))  #等待治愈
    x = [0, 1, 2, 3, 4, 5]  #模拟日
    c = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.VINTAGE))  #设置主题
        .add_xaxis(x)  #直接列表
        #.add_yaxis('确诊',v,stack="stack1")
        .add_yaxis('死亡', c, stack="stack3").add_yaxis(
            '治愈', b,
            stack="stack3").add_yaxis('确诊', v, stack="stack3").set_global_opts(
                title_opts=opts.TitleOpts(title="2019-nCov 海外国家疫情分析",
                                          subtitle=""),
                toolbox_opts=opts.ToolboxOpts(is_show=True),  # 
                datazoom_opts=opts.DataZoomOpts(),
            ).set_series_opts(
                # 设置系列配置
                areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
                label_opts=opts.LabelOpts(is_show=False),
                singleaxis_opts=opts.SingleAxisOpts(max_=80)))
    return c
コード例 #4
0
    def _init_base_axis(self):
        self.init_opt['page_title'] = self.title
        self.global_opt['title_opts'] = opts.TitleOpts(title=self.title)
        self.global_opt['toolbox_opts'] = opts.ToolboxOpts(is_show=True)
        self.global_opt['datazoom_opts'] = opts.DataZoomOpts(is_show=True,
                                                             type_='slider',
                                                             range_start=0,
                                                             range_end=100)
        self.global_opt['xaxis_opts'] = opts.AxisOpts(
            name=self.x_axis_name,
            type_=self._x_axis_type,
            is_scale=True,
            splitline_opts=opts.SplitLineOpts(is_show=True))
        self.global_opt['yaxis_opts'] = opts.AxisOpts(
            name=self.y_axis_name,
            is_scale=True,
            splitline_opts=opts.SplitLineOpts(is_show=True))

        if self.width > 0:
            self.init_opt['width'] = str(self.width) + 'px'
        if self.height > 0:
            self.init_opt['height'] = str(self.height) + 'px'
        self.chart = self._main_chart_type(init_opts=opts.InitOpts(
            **self.init_opt))
コード例 #5
0
def bar_datazoom_inside() -> Timeline:
    tl = Timeline()
    for i in range(2014, 2020):
        c = (Bar(init_opts=opts.InitOpts(animation_opts=opts.AnimationOpts(
            animation_delay=1000, animation_easing="elasticOut"))).add_xaxis(
                list(zip(list(data总.set_index('类别').index)))).add_yaxis(
                    "显示", list(data总["{}".format(i)])).set_global_opts(
                        title_opts=opts.TitleOpts(title="纵横小说月票榜"),
                        datazoom_opts=opts.DataZoomOpts(type_="inside"),
                        visualmap_opts=opts.VisualMapOpts(type_="color",
                                                          max_=250000,
                                                          min_=200,
                                                          pos_right='20',
                                                          pos_top='middle'),
                        toolbox_opts=opts.ToolboxOpts(),
                    ).set_series_opts(
                        label_opts=opts.LabelOpts(is_show=False),
                        markpoint_opts=opts.MarkPointOpts(data=[
                            opts.MarkPointItem(type_="max", name="最大值"),
                            opts.MarkPointItem(type_="min", name="最小值"),
                        ]),
                    ))
        tl.add(c, "{}年".format(i))
    return tl
コード例 #6
0
def day_word_count():
    ddata = []
    kait = dict()
    wordCount = []
    for i in json_data:  #
        if i[0] not in ddata:
            ddata.append(i[0])
    for i in json_data:
        if ids[i[3]] not in kait:
            kait[ids[i[3]]] = dict()
            for k in ddata:
                kait[ids[i[3]]][k] = 0
        kait[ids[i[3]]][i[0]] += len(i[4])
    ddata = sort(ddata)
    for i in ddata:
        wordCount.append(
            [i, [kait[k][i] for k in [i for i, j in kait.items()]]])
    c = (Line().add_xaxis([i[0] for i in wordCount]).add_yaxis(
        "A", [i[1][0] for i in wordCount]).add_yaxis(
            "B", [i[1][1] for i in wordCount]).add_yaxis(
                "C", [i[1][2] for i in wordCount]).set_global_opts(
                    title_opts=opts.TitleOpts(title=""),
                    datazoom_opts=opts.DataZoomOpts(
                        type_="slider")).render("line_.html"))
コード例 #7
0
ファイル: echarts_plot.py プロジェクト: newlyedward/czsc
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
コード例 #8
0
from pywebio.output import put_html
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.faker import Faker

c = (Bar().add_xaxis(Faker.days_attrs).add_yaxis(
    "商家A", Faker.days_values, color=Faker.rand_color()).set_global_opts(
        title_opts=opts.TitleOpts(title="Bar-DataZoom(slider+inside)"),
        datazoom_opts=[opts.DataZoomOpts(),
                       opts.DataZoomOpts(type_="inside")],
    ))

c.width = "100%"
put_html(c.render_notebook())
コード例 #9
0
import pandas as pd
from pyecharts import options as opts
from pyecharts.charts import Line, Kline, Scatter

kline1 = Kline()
kline2 = Kline()

kline1.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True),
                       yaxis_opts=opts.AxisOpts(is_scale=True),
                       datazoom_opts=[opts.DataZoomOpts()])
kline1.extend_axis(yaxis=opts.AxisOpts(type_='value', position='right'))
kline1.extend_axis(yaxis=opts.AxisOpts(type_='value', position='right'))

kline2.set_global_opts(xaxis_opts=opts.AxisOpts(is_scale=True),
                       yaxis_opts=opts.AxisOpts(is_scale=True),
                       datazoom_opts=[opts.DataZoomOpts()])
kline2.extend_axis(yaxis=opts.AxisOpts(type_='value', position='right'))
kline2.extend_axis(yaxis=opts.AxisOpts(type_='value', position='right'))

df = pd.read_csv('F:/Stock/kline.csv')

str1 = str(df.iloc[0, 1])
str2 = str(df.iloc[1, 1])

#-------------------------------------------------------------------------------------------------------------------

df1 = pd.read_csv('F:/Stock/Data_Day/' + df.iloc[0, 1] + ".csv")
df1 = df1.sort_index(ascending=False).reset_index(drop=True)
date1 = df1.xs('Date Time', axis=1).tolist()
data1 = []
vol1 = []
コード例 #10
0
ファイル: charts.py プロジェクト: LRCong/GovernmentDataAdmin
    def bar_base(self) -> Bar:
        # start = datetime.datetime.now()
        #
        # dispose_unit = []
        # done = []
        # undo = []
        # count_dispose_unit = 30
        #
        # event_counts = Event.objects.all().values('dispose_unit').annotate(count=Count('dispose_unit')).values('dispose_unit', 'count').order_by('-count')
        # print(event_counts)
        # event_counts = list(event_counts)
        # sum_of_done = 0
        # sum_of_undo = 0
        # # print(len(event_counts))
        # # print(event_counts)
        # for i in range(0,count_dispose_unit):
        #     undo_event = Event.objects.filter(Q(achieve=3) & Q(dispose_unit=event_counts[i]['dispose_unit']))
        #     undo_event_num = len(undo_event)
        #     dispose_unit_name = DisposeUnit.objects.filter(id=event_counts[i]['dispose_unit']).values("name")[0]['name']
        #     dispose_unit.append(dispose_unit_name)
        #     done.append(event_counts[i]['count'])
        #     undo.append(undo_event_num)
        # for i in range(count_dispose_unit,len(event_counts)):
        #     undo_event = Event.objects.filter(Q(achieve=3) & Q(dispose_unit=event_counts[i]['dispose_unit']))
        #     undo_event_num = len(undo_event)
        #     sum_of_done = sum_of_done + event_counts[i]['count']
        #     sum_of_undo = sum_of_undo + undo_event_num
        # other_unit_num = len(event_counts) - count_dispose_unit
        # dispose_unit.append("其他"+str(other_unit_num)+"个部门总和")
        # done.append(sum_of_done)
        # undo.append(sum_of_undo)
        # c = (
        #     Bar()
        #         .add_xaxis(dispose_unit)
        #         .add_yaxis("按期完成", done, stack="stack1",category_gap="60%")
        #         .add_yaxis("逾期完成", undo, stack="stack1",category_gap="60%")
        #         .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        #         .set_global_opts(
        #         xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-15)),
        #         # title_opts=opts.TitleOpts(title="处理事件最多的部门"),
        #         datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")],
        #
        #         )
        # )
        #
        # grid = Grid()
        #
        # grid.add(c, grid_opts=opts.GridOpts(pos_bottom="20%"))
        #
        # c = grid.dump_options_with_quotes()
        #
        # end = datetime.datetime.now()
        # print("Bar: " + str(end - start))

        start = datetime.date(2016, 6, 6)
        end = datetime.date(2019, 6, 6)
        y_lists = []
        x_list = []
        b = Bar()

        event_counts = DisposeUnit.objects.all().values(
            'name', 'number').order_by('-number')
        for achieve in achieves:
            new_list = [achieve.name]
            limit = 0
            for dispose_unit_node in event_counts:
                dispose_unit = DisposeUnit.objects.get(
                    name=dispose_unit_node['name'])
                if limit < 30:
                    new_len = len(
                        Event.objects.filter(
                            Q(create_time__range=(start, end))
                            & Q(dispose_unit=dispose_unit)
                            & Q(achieve=achieve)))
                    new_list.append(new_len)
                    new_len = 0
                else:
                    new_len += len(
                        Event.objects.filter(
                            Q(create_time__range=(start, end))
                            & Q(dispose_unit=dispose_unit)
                            & Q(achieve=achieve)))
                limit += 1
            new_list.append(new_len)
            y_lists.append(new_list)
        limit = 0
        for dispose_unit_node in event_counts:
            if limit >= 30:
                break
            x_list.append(dispose_unit_node['name'])
            limit += 1
        x_list.append("其他")

        b.add_xaxis(x_list)
        for y_list in y_lists:
            b.add_yaxis(y_list[0],
                        y_list[1:],
                        stack="stack1",
                        category_gap="60%")
        b.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) \
            .set_global_opts(
            xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-15)),
            # title_opts=opts.TitleOpts(title="处理事件最多的部门"),
            datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")], )
        c = (b)

        grid = Grid()

        grid.add(c, grid_opts=opts.GridOpts(pos_bottom="20%"))

        c = grid.dump_options_with_quotes()

        return c
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'))
コード例 #12
0
                                        pos_right="0%"),  # 调整图例的位置
            title_opts=opts.TitleOpts(title="行情显示图"),
        ))

line = (Line().add_xaxis(dates.tolist()).add_yaxis(
    "Ma20", df_stockload["Ma20"].tolist()).add_yaxis(
        "Ma30", df_stockload["Ma30"].tolist()).add_yaxis(
            "Ma60", df_stockload["Ma60"].tolist()).set_series_opts(
                label_opts=opts.LabelOpts(is_show=False)))

bar = (
    Bar().add_xaxis(dates.tolist()).add_yaxis("rvolume",
                                              volume_rise,
                                              stack="stack1",
                                              category_gap="50%")  # 堆积柱形图
    .add_yaxis("dvolume", volume_drop, stack="stack1",
               category_gap="50%")  # 堆积柱形图
    .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    #xaxis_index=[0, 1] 同时显示两幅图
    .set_global_opts(
        datazoom_opts=[opts.DataZoomOpts(xaxis_index=[0, 1],
                                         is_show=True)],  # 图表数据缩放
        legend_opts=opts.LegendOpts(orient="vertical", pos_right="0%")))

overlap_1 = kline.overlap(line)

grid = (
    Grid().add(bar, grid_opts=opts.GridOpts(pos_top="60%"), grid_index=0).add(
        overlap_1, grid_opts=opts.GridOpts(pos_bottom="40%"),
        grid_index=1).render(r"grid_vertical.html")  # raw string 非转义 string
)
コード例 #13
0
def vtradevolume(cftable, freq="D", rendered=True):
    """
    aid function on visualization of trade summary

    :param cftable: cftable (pandas.DataFrame) with at least date and cash columns
    :param freq: one character string, frequency label, now supporting D for date,
        W for week and M for month, namely the trade volume is shown based on the time unit
    :returns: the Bar object
    """
    ### WARN: datazoom and time conflict, sliding till 1970..., need further look into pyeacharts
    startdate = cftable.iloc[0]["date"]
    if freq == "D":
        # datedata = [d.to_pydatetime() for d in cftable["date"]]
        datedata = pd.date_range(startdate, yesterdayobj(), freq="D")
        selldata = [[row["date"].to_pydatetime(), row["cash"]]
                    for _, row in cftable.iterrows() if row["cash"] > 0]
        buydata = [[row["date"].to_pydatetime(), row["cash"]]
                   for _, row in cftable.iterrows() if row["cash"] < 0]
    elif freq == "W":
        cfmerge = cftable.groupby(
            [cftable["date"].dt.year, cftable["date"].dt.week])["cash"].sum()
        # datedata = [
        #     dt.datetime.strptime(str(a) + "4", "(%Y, %W)%w")
        #     for a, _ in cfmerge.iteritems()
        # ]
        datedata = pd.date_range(startdate,
                                 yesterdayobj() + pd.Timedelta(days=7),
                                 freq="W-THU")
        selldata = [[dt.datetime.strptime(str(a) + "4", "(%G, %V)%w"), b]
                    for a, b in cfmerge.iteritems() if b > 0]
        buydata = [[dt.datetime.strptime(str(a) + "4", "(%G, %V)%w"), b]
                   for a, b in cfmerge.iteritems() if b < 0]
        # %V pandas gives iso weeknumber which is different from python original %W or %U,
        # see https://stackoverflow.com/questions/5882405/get-date-from-iso-week-number-in-python for more details
        # python3.6+ required for %G and %V
        # but now seems no equal distance between sell and buy data, no idea why
    elif freq == "M":
        cfmerge = cftable.groupby(
            [cftable["date"].dt.year, cftable["date"].dt.month])["cash"].sum()
        # datedata = [
        #     dt.datetime.strptime(str(a) + "15", "(%Y, %m)%d")
        #     for a, _ in cfmerge.iteritems()
        # ]
        datedata = pd.date_range(startdate,
                                 yesterdayobj() + pd.Timedelta(days=31),
                                 freq="MS")
        selldata = [[dt.datetime.strptime(str(a) + "1", "(%Y, %m)%d"), b]
                    for a, b in cfmerge.iteritems() if b > 0]
        buydata = [[dt.datetime.strptime(str(a) + "1", "(%Y, %m)%d"), b]
                   for a, b in cfmerge.iteritems() if b < 0]
    else:
        raise ParserFailure("no such freq tag supporting")

    buydata = [[d, round(x, 1)] for d, x in buydata]
    selldata = [[d, round(x, 1)] for d, x in selldata]
    bar = Bar()
    datedata = list(datedata)
    bar.add_xaxis(xaxis_data=datedata)
    # buydata should before selldata, since emptylist in the first line would make the output fig empty: may be bug in pyecharts
    bar.add_yaxis(series_name="买入", yaxis_data=buydata)
    bar.add_yaxis(series_name="卖出", yaxis_data=selldata)
    bar.set_global_opts(
        tooltip_opts=opts.TooltipOpts(
            is_show=True,
            trigger="axis",
            trigger_on="mousemove",
            axis_pointer_type="cross",
        ),
        datazoom_opts=[opts.DataZoomOpts(range_start=90, range_end=100)],
    )
    if rendered:
        return bar.render_notebook()
    else:
        return bar
コード例 #14
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)
コード例 #15
0
# V1 版本开始支持链式调用
place = np.array(province)
bar = (
    Bar().add_xaxis(list(place[:, 0])).add_yaxis("热度", list(
        place[:, 1])).set_global_opts(
            # 设置全局参数
            title_opts=opts.TitleOpts(title="国庆旅游热度"),  # 设置title
            xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
                is_show=True)),  # 设置x轴
            yaxis_opts=opts.AxisOpts(splitarea_opts=opts.SplitAreaOpts(
                is_show=True, areastyle_opts=opts.AreaStyleOpts(
                    opacity=1))),  # 设置y轴
            toolbox_opts=opts.ToolboxOpts(is_show=True),  # 设置工具箱
            datazoom_opts=[
                opts.DataZoomOpts(range_start=10,
                                  range_end=80,
                                  is_zoom_lock=False)
            ],  # 设置slider
        ))
bar.render(path="国庆旅游热度1.html")

# 不习惯链式调用的开发者依旧可以单独调用方法
bar = Bar()
bar.add_xaxis(list(place[:, 0]))
bar.add_yaxis("热度", list(place[:, 1]))
bar.set_global_opts(title_opts=opts.TitleOpts(title="国庆旅游热度"))
bar.set_global_opts(xaxis_opts=opts.AxisOpts(axislabel_opts={"rotate": 45}),
                    toolbox_opts=opts.ToolboxOpts(is_show=True),
                    datazoom_opts=[
                        opts.DataZoomOpts(range_start=10,
                                          range_end=80,
コード例 #16
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)
コード例 #17
0
data['yuanchuang'] = data['yuanchuanghefawen'].apply(get_yuanchuang)
data['fawen'] = data['yuanchuanghefawen'].apply(get_fawen)
data['toutiao_read'] = data['toutiao_read'].astype('int')
data['seeing'] = data['seeing'].astype('int')

# 次幂指数
index_data = data[['name', 'index']]
index_data_sort = index_data.sort_values(by='index', ascending=False)

bar = Bar()
bar.add_xaxis(index_data_sort['name'].values.tolist())
bar.add_yaxis("", index_data_sort['index'].values.tolist())
bar.set_global_opts(
    xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-30)),
    title_opts=opts.TitleOpts(title="次幂指数"),
    datazoom_opts=opts.DataZoomOpts(),
)
bar.render_notebook()

# 阅读量
read_data = data[['name', 'toutiao_read']]
read_data_sort = read_data.sort_values(by='toutiao_read', ascending=False)

bar = Bar()
bar.add_xaxis(read_data_sort['name'].values.tolist())
bar.add_yaxis("", read_data_sort['toutiao_read'].values.tolist())
bar.set_global_opts(
    xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-30)),
    title_opts=opts.TitleOpts(title="头条平均阅读量"),
    datazoom_opts=opts.DataZoomOpts(),
)
コード例 #18
0
def vtradecost(self,
               cftable,
               unitcost=False,
               start=None,
               end=yesterdayobj(),
               rendered=True):
    """
    visualization giving the average cost line together with netvalue line as well as buy and sell points

    :returns: pyecharts.line
    """
    funddata = []
    costdata = []
    cashdata = []  #kahar add in order to observe the sum of the cash
    funddata_test = []
    pprice = self.price[self.price["date"] <= end]
    pcftable = cftable
    if start is not None:
        pprice = pprice[pprice["date"] >= start]
        pcftable = pcftable[pcftable["date"] >= start]
    for _, row in pprice.iterrows():
        date = row["date"]
        funddata.append(row["netvalue"])
        funddata_test.append(3.2)
        if unitcost:
            cost = 0
            cash = 0
            if (date - self.cftable.iloc[0].date).days >= 0:
                cost = self.unitcost(date)
                cash = self.get_datecashvalue(date)
            costdata.append(cost)
            cashdata.append(cash / 1000000.0)
    coords = []
    # pcftable = pcftable[abs(pcftable["cash"]) > threhold]
    for i, r in pcftable.iterrows():
        coords.append(
            [r.date, pprice[pprice["date"] <= r.date].iloc[-1]["netvalue"]])

    upper = pcftable.cash.abs().max()
    lower = pcftable.cash.abs().min()
    if upper == lower:
        upper = 2 * lower + 1  # avoid zero in denominator

    def marker_factory(x, y):
        buy = pcftable[pcftable["date"] <= x].iloc[-1]["cash"]
        if buy < 0:
            color = "#ff7733"
        else:

            color = "#3366ff"
        size = (abs(buy) - lower) / (upper - lower) * 5 + 5
        return opts.MarkPointItem(
            coord=[x.date(), y],
            itemstyle_opts=opts.ItemStyleOpts(color=color),
            # this nested itemstyle_opts within MarkPointItem is only supported for pyechart>1.7.1
            symbol="circle",
            symbol_size=size,
        )

    line = Line()

    line.add_xaxis([d.date() for d in pprice.date])
    print("costdata", costdata)
    if unitcost:
        line.add_yaxis(
            series_name="持仓成本",
            y_axis=costdata,
            is_symbol_show=False,
        )

    line.add_yaxis(
        series_name="持仓总额k6",
        y_axis=cashdata,
        is_symbol_show=False,
    )

    line.add_yaxis(
        series_name="基金净值",
        y_axis=funddata,
        is_symbol_show=False,
        markpoint_opts=opts.MarkPointOpts(
            data=[marker_factory(*c) for c in coords], ),
    )
    line.set_global_opts(
        datazoom_opts=[
            opts.DataZoomOpts(is_show=True,
                              type_="slider",
                              range_start=50,
                              range_end=100),
            opts.DataZoomOpts(
                is_show=True,
                type_="slider",
                orient="vertical",
                range_start=50,
                range_end=100,
            ),
        ],
        tooltip_opts=opts.TooltipOpts(
            is_show=True,
            trigger="axis",
            trigger_on="mousemove",
            axis_pointer_type="cross",
        ),
    )
    if rendered:
        return line.render_notebook()
    else:
        return line
コード例 #19
0
ファイル: DrawBar2.py プロジェクト: chun-ai-zhi-qing/UIA-
import pandas as pd
from pyecharts import options as opts
for i in range(1, 258):
    df = pd.read_csv('D/' + str(i) + '.csv')
    sizeNum = df.iloc[:, 0].size
    #print(sizeNum)
    t = 1
    row = []
    col = []
    for j in range(0, sizeNum):
        row.append(df['end_geo_id'][j])
        #row.append(str(j))
        col.append(df['ans'][j])
        # if j%10==0 or j==sizeNum-1:
        #     bar = (
        #         Bar()
        #         #.set_global_opts(xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-20)))
        #     )
        #     bar.add_xaxis(row)
        #     bar.add_yaxis("people",col)
        #     # print(col)
        #     # print(row)
        #     bar.render("Ps/"+str(i)+"_Bar_From"+str(t)+"To"+str(j)+".html")
        #     t = j
        #     row = []
        #     col = []
    bar = (Bar().add_xaxis(row).add_yaxis("people", col).set_global_opts(
        title_opts=opts.TitleOpts(title="区域缩放柱状图"),
        datazoom_opts=opts.DataZoomOpts(type_="slider"),
    ))
    bar.render("Bar/" + str(i) + ".html")
コード例 #20
0
 def visual(self, name='model_visual', path=None, gif=False):
     """
     Arguments:
     name : str, train end save last image or gif file with html format name.
     path : str, train end save last image or gif file with html format to path;
     save_gif : bool, default False, if save_gif=True, train end save all image to gif;
     
     Return:
         a html file path.
     """
     if path is not None:
         assert tf.io.gfile.exists(path), "`path` not exist."
         file = path + '/' + '{}.html'.format(name)
     else:
         file = '{}.html'.format(name)
     page = Page(interval=1, layout=Page.SimplePageLayout)
     plot_list = []
     width_len = '750px'
     height_len = '450px'
     for metric_id, metric in enumerate(self.params.metrics):
         if not gif:
             line = Line(opts.InitOpts(width=width_len, height=height_len))
             line = line.add_xaxis(list(range(1, self.params.polt_num + 1)))
             line = line.add_yaxis(
                 'train',
                 Series(self.params.logs[metric]).round(4).tolist(),
                 is_smooth=True)
             if self.params.valid_fmt.format(metric) in self.params.logs:
                 line = line.add_yaxis(
                     self.params.valid_fmt.split('_')[0],
                     Series(self.params.logs[self.params.valid_fmt.format(
                         metric)]).round(4).tolist(),
                     is_smooth=True)
             line = line.set_series_opts(
                 label_opts=opts.LabelOpts(is_show=False),
                 markpoint_opts=opts.MarkPointOpts(data=[
                     opts.MarkPointItem(type_='max', name='max_value'),
                     opts.MarkPointItem(type_='min', name='min_value')
                 ]))
             line = line.set_global_opts(
                 title_opts=opts.TitleOpts(title=metric),
                 xaxis_opts=opts.AxisOpts(
                     name=self.params.xlabel[self.params.mode],
                     name_location='center',
                     is_scale=True),
                 datazoom_opts=[
                     opts.DataZoomOpts(range_start=0, range_end=100)
                 ],
                 toolbox_opts=opts.ToolboxOpts())
             plot_list.append(line)
         else:
             timeline = Timeline(
                 opts.InitOpts(width=width_len,
                               height=height_len)).add_schema(
                                   play_interval=100, is_auto_play=True)
             for i in range(1, self.params.polt_num + 1):
                 line = Line(
                     opts.InitOpts(width=width_len, height=height_len))
                 line = line.add_xaxis(list(range(1, i + 1)))
                 line = line.add_yaxis(
                     'train',
                     Series(self.params.logs[metric])[:i].round(4).tolist(),
                     is_smooth=True)
                 if self.params.valid_fmt.format(
                         metric) in self.params.logs:
                     line = line.add_yaxis(
                         self.params.valid_fmt.split('_')[0],
                         Series(
                             self.params.logs[self.params.valid_fmt.format(
                                 metric)])[:i].round(4).tolist(),
                         is_smooth=True)
                 line = line.set_series_opts(
                     label_opts=opts.LabelOpts(is_show=False),
                     markpoint_opts=opts.MarkPointOpts(data=[
                         opts.MarkPointItem(type_='max', name='max_value'),
                         opts.MarkPointItem(type_='min', name='min_value')
                     ]))
                 line = line.set_global_opts(
                     title_opts=opts.TitleOpts(title=metric),
                     xaxis_opts=opts.AxisOpts(
                         name=self.params.xlabel[self.params.mode],
                         name_location='center',
                         is_scale=True))
                 timeline.add(line, str(i))
             plot_list.append(timeline)
     page.add(*plot_list).render(file)
     return file
コード例 #21
0
                            'Q1: ' + param.data[1],
                            'median: ' + param.data[2],
                            'Q3: ' + param.data[3],
                            'lower: ' + param.data[4]
                        ].join('<br/>') }"""))).set_global_opts(
                   title_opts=opts.TitleOpts(title="Multiple Categories",
                                             pos_left="center"),
                   legend_opts=opts.LegendOpts(pos_top="3%"),
                   tooltip_opts=opts.TooltipOpts(trigger="item",
                                                 axis_pointer_type="shadow"),
                   xaxis_opts=opts.AxisOpts(
                       name_gap=30,
                       boundary_gap=True,
                       splitarea_opts=opts.SplitAreaOpts(
                           areastyle_opts=opts.AreaStyleOpts(opacity=1)),
                       axislabel_opts=opts.LabelOpts(formatter="expr {value}"),
                       splitline_opts=opts.SplitLineOpts(is_show=False)),
                   yaxis_opts=opts.AxisOpts(
                       type_="value",
                       min_=-400,
                       max_=600,
                       splitarea_opts=opts.SplitAreaOpts(is_show=False)),
                   datazoom_opts=[
                       opts.DataZoomOpts(type_="inside",
                                         range_start=0,
                                         range_end=20),
                       opts.DataZoomOpts(type_="slider",
                                         xaxis_index=0,
                                         is_show=True)
                   ]).render("multiple_categories.html"))
コード例 #22
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"))
コード例 #23
0
         axisline_opts=opts.AxisLineOpts(
             linestyle_opts=opts.LineStyleOpts(
                 color="#90979c"
             )
         ),
         axislabel_opts=opts.LabelOpts(
             interval=0
         ),
         splitarea_opts=opts.SplitAreaOpts(
             is_show=False
         )
     ),
     datazoom_opts=opts.DataZoomOpts(
         is_show=True,
         xaxis_index=[0],
         pos_bottom=30,
         start_value=10,
         end_value=80
     )
 )
 .add_xaxis(xaxis_data=x_data)
 .add_yaxis(
     series_name="女",
     y_axis=y_data,
     stack="总量",
     label_opts=opts.LabelOpts(
         is_show=True,
         color="#fff",
         position="inside"
     ),
     itemstyle_opts=opts.ItemStyleOpts(
コード例 #24
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
コード例 #25
0
def plot_kline(df, rendered=True, col=""):
    """
    针对 dataframe 直接画出标准看盘软件的上k线图下成交量图的形式

    :param df:
    :param rendered:
    :param col:
    :return:
    """
    kline = (
        Kline()
        .add_xaxis(xaxis_data=list(df["date"]))
        .add_yaxis(
            series_name="",
            itemstyle_opts=opts.ItemStyleOpts(
                color="#ef232a",
                color0="#14b143",
                border_color="#ef232a",
                border_color0="#14b143",
            ),
            y_axis=list(zip(df["open"], df["close"], df["high"], df["low"])),
            markpoint_opts=opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(type_="max", name="最大值"),
                    opts.MarkPointItem(type_="min", name="最小值"),
                ],
                symbol="pin",
                symbol_size=[56, 40],
                # label_opts=opts.LabelOpts(color="#CCFFFF",position=["top", "bottom"])
            ),
        )
        .set_global_opts(
            datazoom_opts=[
                opts.DataZoomOpts(
                    is_show=True,
                    type_="slider",
                    range_start=50,
                    range_end=100,
                    xaxis_index=[0, 1],
                ),
                opts.DataZoomOpts(
                    is_show=False,
                    type_="inside",
                    range_start=50,
                    range_end=100,
                    xaxis_index=1,
                ),
            ],
            tooltip_opts=opts.TooltipOpts(
                is_show=True,
                trigger="axis",
                trigger_on="mousemove",
                axis_pointer_type="cross",
            ),
        )
    )
    if col:
        line = (
            Line()
            .add_xaxis(xaxis_data=list(df["date"]))
            .add_yaxis(
                series_name="",
                y_axis=list(df[col]),
                is_smooth=True,
                linestyle_opts=opts.LineStyleOpts(opacity=0.5),
                label_opts=opts.LabelOpts(is_show=False),
            )
        )
        kline = kline.overlap(line)

    if "volume" in df.columns:
        vl = list(df["volume"])
    elif "amount" in df.columns:
        vl = list(df["amount"])
    else:
        vl = [0 for _ in range(len(df))]
    bar = (
        Bar()
        .add_js_funcs("var barData = {}".format(list(df["close"] - df["open"])))
        .add_xaxis(xaxis_data=list(df["date"]))
        .add_yaxis(
            series_name="",
            yaxis_data=vl,
            label_opts=opts.LabelOpts(is_show=False),
            itemstyle_opts=opts.ItemStyleOpts(
                color=JsCode(
                    """
                function(params) {
                    var colorList;
                    if (barData[params.dataIndex]>0) {
                        colorList = '#ef232a';
                    } else {
                        colorList = '#14b143';
                    }
                    return colorList;
                }
                """
                )
            ),
        )
        .set_global_opts(
            tooltip_opts=opts.TooltipOpts(
                is_show=True,
                trigger="axis",
                trigger_on="mousemove",
                axis_pointer_type="cross",
            ),
        )
    )
    grid_chart = Grid()
    grid_chart.add_js_funcs("var barData = {}".format(list(df["close"] - df["open"])))
    grid_chart.add(
        kline,
        grid_opts=opts.GridOpts(
            pos_left="10%", pos_right="1%", pos_top="2%", height="65%"
        ),
    )

    grid_chart.add(
        bar,
        grid_opts=opts.GridOpts(
            pos_left="10%", pos_right="1%", pos_top="71%", height="22%"
        ),
    )
    if rendered:
        return grid_chart.render_notebook()
    else:
        return grid_chart
コード例 #26
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
コード例 #27
0
ファイル: echarts_plot.py プロジェクト: newlyedward/czsc
def heat_map(data: List[dict],
             x_label: List[str] = None,
             y_label: List[str] = None,
             title: str = "热力图",
             width: str = "900px",
             height: str = "680px") -> HeatMap:
    """绘制热力图

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

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

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

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

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

    hm = HeatMap(init_opts=init_opts)
    hm.add_xaxis(x_label)
    hm.add_yaxis("heat",
                 y_label,
                 value,
                 label_opts=opts.LabelOpts(is_show=True, position="inside"))
    hm.set_global_opts(title_opts=title_opts,
                       visualmap_opts=vis_map_opts,
                       legend_opts=legend_opts,
                       xaxis_opts=opts.AxisOpts(grid_index=0),
                       datazoom_opts=[dz_inside, dz_slider])
    return hm
コード例 #28
0
ファイル: Lesson22.py プロジェクト: yunfeiz/py_learnt
def draw_chart():
    kline = (Kline().add_xaxis(xaxis_data=data["times"]).add_yaxis(
        series_name="",
        y_axis=data["datas"],
        itemstyle_opts=opts.ItemStyleOpts(color="#ef232a",
                                          color0="#14b143",
                                          border_color="#ef232a",
                                          border_color0="#14b143"),
        markpoint_opts=opts.MarkPointOpts(data=[
            opts.MarkPointItem(type_="max", name="最大值"),
            opts.MarkPointItem(type_="min", name="最小值"),
        ]),
        markline_opts=opts.MarkLineOpts(
            label_opts=opts.LabelOpts(position="middle",
                                      color="blue",
                                      font_size=15),
            data=split_data_part(),
            symbol=["circle", "none"],
        ),
    ).set_series_opts(markarea_opts=opts.MarkAreaOpts(
        is_silent=True, data=split_data_part())).set_global_opts(
            title_opts=opts.TitleOpts(title="K线周期图表", pos_left="0"),
            xaxis_opts=opts.AxisOpts(
                type_="category",
                is_scale=True,
                boundary_gap=False,
                axisline_opts=opts.AxisLineOpts(is_on_zero=False),
                splitline_opts=opts.SplitLineOpts(is_show=False),
                split_number=20,
                min_="dataMin",
                max_="dataMax",
            ),
            yaxis_opts=opts.AxisOpts(
                is_scale=True,
                splitline_opts=opts.SplitLineOpts(is_show=True)),
            tooltip_opts=opts.TooltipOpts(trigger="axis",
                                          axis_pointer_type="line"),
            datazoom_opts=[
                opts.DataZoomOpts(is_show=True,
                                  type_="inside",
                                  xaxis_index=[0, 0],
                                  range_end=100),
                opts.DataZoomOpts(is_show=True,
                                  xaxis_index=[0, 1],
                                  pos_top="97%",
                                  range_end=100),
                opts.DataZoomOpts(is_show=False,
                                  xaxis_index=[0, 2],
                                  range_end=100),
            ],
        ))
    kline_line = (Line().add_xaxis(xaxis_data=data["times"]).add_yaxis(
        series_name="MA5",
        y_axis=calculate_ma(day_count=5),
        is_smooth=True,
        linestyle_opts=opts.LineStyleOpts(opacity=0.5),
        label_opts=opts.LabelOpts(is_show=False),
    ).set_global_opts(
        xaxis_opts=opts.AxisOpts(
            type_="category",
            axislabel_opts=opts.LabelOpts(is_show=False),
        ),
        yaxis_opts=opts.AxisOpts(
            split_number=3,
            axisline_opts=opts.AxisLineOpts(is_on_zero=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),
            axislabel_opts=opts.LabelOpts(is_show=True),
        ),
    ))

    overlap_kline_line = kline.overlap(kline_line)

    bar_1 = (Bar().add_xaxis(xaxis_data=data["times"]).add_yaxis(
        series_name="Volumn",
        y_axis=data["vols"],
        label_opts=opts.LabelOpts(is_show=False),
        itemstyle_opts=opts.ItemStyleOpts(color=JsCode("""
						function(params){
							var colorList;
							if(barData[params.dataIndex][1] > barData[params.dataIndex][0]){
								colorList = '#ef232a';
							}else{
								colorList = '#14b143';
							}
							return colorList;
						}

						""")),
    ).set_global_opts(
        xaxis_opts=opts.AxisOpts(
            type_="category",
            axislabel_opts=opts.LabelOpts(is_show=False),
        ),
        legend_opts=opts.LegendOpts(is_show=False),
    ))
    bar_2 = (Bar().add_xaxis(xaxis_data=data["times"]).add_yaxis(
        series_name="MACD",
        y_axis=data["macds"],
        label_opts=opts.LabelOpts(is_show=False),
        itemstyle_opts=opts.ItemStyleOpts(color=JsCode("""
						function(params){
							var colorList;
							if(params.data >= 0){
								colorList = '#ef232a';
							}else{
								colorList = '#14b143';
							}
							return colorList;
						}
					""")),
    ).set_global_opts(
        xaxis_opts=opts.AxisOpts(
            type_="category",
            axislabel_opts=opts.LabelOpts(is_show=False),
        ),
        yaxis_opts=opts.AxisOpts(
            split_number=4,
            axisline_opts=opts.AxisLineOpts(is_on_zero=False),
            axistick_opts=opts.AxisTickOpts(is_show=False),
            splitline_opts=opts.SplitLineOpts(is_show=False),
            axislabel_opts=opts.LabelOpts(is_show=True),
        ),
        legend_opts=opts.LegendOpts(is_show=False),
    ))
    line_2 = (Line().add_xaxis(xaxis_data=data["times"]).add_yaxis(
        series_name="DIF",
        y_axis=data["difs"],
        label_opts=opts.LabelOpts(is_show=False),
    ).set_global_opts(legend_opts=opts.LegendOpts(is_show=False)))
    overlap_bar_line = bar_2.overlap(line_2)

    grid_chart = Grid(init_opts=opts.InitOpts(
        width="1400px", height="800px", theme=ThemeType.ESSOS))
    grid_chart.add_js_funcs("var barData={}".format(data["datas"]))
    grid_chart.add(
        overlap_kline_line,
        grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", height="60%"),
    )

    grid_chart.add(
        bar_1,
        grid_opts=opts.GridOpts(pos_left="3%",
                                pos_right="1%",
                                pos_top="71%",
                                height="10%"),
    )

    grid_chart.add(overlap_bar_line,
                   grid_opts=opts.GridOpts(pos_left="3%",
                                           pos_right="1%",
                                           pos_top="82%",
                                           height="14%"))

    grid_chart.render("professional_kline_chart.html")
コード例 #29
0
from pywebio.output import put_html
from pyecharts import options as opts
from pyecharts.charts import Bar
from pyecharts.faker import Faker

c = (
    Bar()
    .add_xaxis(Faker.days_attrs)
    .add_yaxis("商家A", Faker.days_values, color=Faker.rand_color())
    .set_global_opts(
        title_opts=opts.TitleOpts(title="Bar-DataZoom(slider-垂直)"),
        datazoom_opts=opts.DataZoomOpts(orient="vertical"),
    )
    
)

c.width = "100%"
put_html(c.render_notebook())
コード例 #30
0
ファイル: Start.py プロジェクト: Gisfy-code/ADRFI-ToolkitV1
def main():
    global dps

    new_input = {}

    st.sidebar.markdown('## Set A DRFI Strategy:')

    for k in show_name:
        try:
            dvalue = dps[user_input][0][k] * 100 if k in input_pct else dps[
                user_input][0][k]
            nv = st.sidebar.text_input(show_name[k], dvalue, key=k)
            nv = float(nv) / 100.0 if k in input_pct else float(nv)
            new_input[k] = nv
        except:
            pass

    bg_params = st.sidebar.empty()
    bg_expander = bg_params.beta_expander('Other model settings')
    new_bg_input = {}
    for k in dps[bg_input][0]:
        new_bg_input[k] = float(
            bg_expander.text_input(k, value=dps[bg_input][0][k], key=k))

    st.sidebar.text('')
    st.sidebar.text('')
    if st.sidebar.button('Save this strategy'):
        dps[bg_input].append(new_bg_input)
        dps[user_input].append(new_input)

    if st.sidebar.button('reset the strategies'):
        reset()
        pass

    pses = []  # 计算过程的多组参数

    cb_AMTs = []
    for i in range(len(dps[user_input])):
        dps_ = copy.deepcopy(dps)
        uinp = copy.deepcopy(dps_[user_input][i])
        bginp = copy.deepcopy(dps_[bg_input][i])
        dps_.update(uinp)
        dps_.update(bginp)
        del dps_[user_input]
        bginp = copy.deepcopy(dps_[bg_input][i])
        dps_.update(bginp)
        del dps_[bg_input]

        dps_[cb_AMT] = dps_[cb_limit] - dps_[cb_att]
        cb_AMTs.append(dps_[cb_AMT])
        dps_[tier1_RL] = dps_[tier1_AMT] * dps_[tier1_BenRate]
        dps_[tier1_Int] = dps_[tier1_AMT] * dps_[tier1_IntRate]
        dps_[tier2_RL] = dps_[tier1_RL] * dps_[tier2_BenRate]
        dps_[tier2_Int] = dps_[tier2_RL] * dps_[tier2_IntRate]
        dps_[dataSR] = min(dps_[data_Invest] * dps_[dataSR_ImpRatio],
                           dps_[dataSR_Cap])
        dps_[dataCBLoad] = dps_[dataCBLoad_Base] * max(
            0, 1 - dps_[data_Invest] * dps_[dataCBLoad_ImpRatio])
        dps_[ipSR] = min(dps_[ip_Invest] * dps_[ipSR_ImpRate], dps_[ipSR_Cap])
        dps_[ipCBLoad] = dps_[ipCBLoad_Base] * max(
            0, 1 - dps_[ip_Invest] * dps_[ipCBLoad_ImpRatio])
        dps_[ipRLLoad] = dps_[ipRLLoad_Base] * max(
            0, 1 - min(dps_[ip_Invest] * dps_[ipRLLoad_ImpRatio],
                       dps_[ipRLLoad_ImpRatio_Cap]))
        dps_[inSize_Base] = dps_[GDP] * dps_[ip_Base] * dps_[cap_Converter]
        # dps_[inSize] = dps_[inSize_Base] * (1 + min(dps_[ip_Invest] * dps_[inSize_ImpRatio], dps_[inSize_ImpRatio_Cap]))
        dps_[inSize] = dps_[GDP] * dps_[ip_Revised] * dps_[cap_Converter]

        dps_[unit] = round(3 * dps_[L200Y] / dps_[no_cells], 0)
        dps_[SharpeRatio] = dps_[SharpeRatioBaseline] * (1 - dps_[dataSR]) * (
            1 - dps_[ipSR])

        pses.append(dps_)
        pass

    AnInt = np.array(range(0, int(dps[no_cells]) + 1, 1))
    Unit = round(3 * dps[L200Y] / dps[no_cells], 0)
    LossAmountMillion: np.ndarray = AnInt * Unit
    pencentile = [0.75, 0.9, 0.95, 0.975, 0.99, 0.995]
    pctile_year = [4, 10, 20, 40, 100, 200]

    # x axis
    EP_X = np.zeros(LossAmountMillion.size)

    S2 = 1 / 2 * (0.01 + 0.05) * (dps[L100Y] - dps[L20Y])
    S3 = 1 / 2 * (0.01 + 0.005) * (dps[L200Y] - dps[L100Y])
    S3 = 1 / 2 * (0.01 + 0.005) * (dps[L200Y] - dps[L100Y])
    S4 = dps[PctAELTail] * dps[AEL]
    S1 = dps[AEL] - S2 - S3 - S4
    f1 = S1 - dps[L20Y] * 0.05
    f2 = f1 / (dps[L0Y] - 0.05)
    b = 1 / f2
    r = S4 / 0.005

    t1 = LossAmountMillion < dps[L20Y]
    t2 = LossAmountMillion >= dps[L20Y]
    t3 = LossAmountMillion < dps[L100Y]
    t4 = LossAmountMillion >= dps[L100Y]
    t5 = LossAmountMillion < dps[L200Y]
    t6 = LossAmountMillion >= dps[L200Y]
    EP_X[t1] = func1(LossAmountMillion[t1], b, dps[L0Y])
    EP_X[t2 & t3] = func2(LossAmountMillion[t2 & t3], dps[L20Y], dps[L100Y])
    EP_X[t4 & t5] = func3(LossAmountMillion[t4 & t5], dps[L100Y], dps[L200Y])
    EP_X[t6] = func4(LossAmountMillion[t6], r, dps[L200Y])
    CDF = 1 - EP_X

    st.markdown('*****')
    st.markdown('### I. Exceedance Probablility Curve')
    linedata = [e for e in zip(LossAmountMillion, EP_X)]
    xdata = [e[0] for e in linedata]
    ydata = [e[1] for e in linedata]
    c2 = (Line(init_opts=opts.InitOpts()).add_xaxis(xdata).add_yaxis(
        'Exceedance Probablility',
        ydata,
        is_smooth=True,
        is_symbol_show=False,
        symbol_size=0).set_global_opts(
            tooltip_opts=opts.TooltipOpts(is_show=True,
                                          trigger='axis',
                                          axis_pointer_type='line'),
            xaxis_opts=opts.AxisOpts(type_='value', name='Loss Amount'),
            yaxis_opts=opts.AxisOpts(type_='value',
                                     name='Exceedance Probablility',
                                     is_scale=True),
            datazoom_opts=opts.DataZoomOpts(is_show=True,
                                            type_='slider',
                                            range_start=0,
                                            range_end=100),
            title_opts=opts.TitleOpts('')))
    st_pyecharts(c2, height='400%', width='100%')

    st.markdown('*****')
    st.markdown('### II. Loss by return year period ($M)')
    LossByReturnYearPeriod_empty = st.empty()

    st.markdown('*****')
    st.markdown('### III. Cost Comparison')
    CostComparison_empty = st.empty()

    st.markdown('****')
    st.markdown('### IV. Disaster Risk Layering')

    RetainedLossWithoutPolicy = LossAmountMillion / dps[natBdt]

    series_num = 1

    c = (Bar(init_opts=opts.InitOpts()).add_xaxis([
        str(y) + '-Year' for y in pctile_year
    ]).add_yaxis(
        'Without DRFI Strategy', [
            round(
                RetainedLossWithoutPolicy[np.argmin(np.abs(CDF - pctile))] *
                100, 2) for pctile in pencentile
        ],
        label_opts=opts.LabelOpts(
            is_show=True, formatter='{c}%')).set_global_opts(
                xaxis_opts=opts.AxisOpts(type_='category',
                                         name='\n\nReturn\nYear\nPeriod'),
                yaxis_opts=opts.AxisOpts(
                    type_='value',
                    name=' % of\nNational Budget',
                    is_scale=True,
                    axislabel_opts=opts.LabelOpts(
                        formatter=JsCode("function (x){return x + '%'}"))),
                legend_opts=opts.LegendOpts(),
                datazoom_opts=opts.DataZoomOpts(xaxis_index=[0, 1],
                                                type_='inside',
                                                range_start=0,
                                                range_end=100,
                                                pos_bottom='0%'),
                tooltip_opts=opts.TooltipOpts(is_show=True,
                                              trigger='axis',
                                              axis_pointer_type='shadow',
                                              is_show_content=True)))

    c1 = (Bar(init_opts=opts.InitOpts()).add_xaxis(
        [str(y) + '-Year' for y in pctile_year]).add_yaxis(
            '', [0] * len(pctile_year),
            label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
                xaxis_opts=opts.AxisOpts(
                    type_='category',
                    name='',
                    axislabel_opts=opts.LabelOpts(is_show=False)),
                yaxis_opts=opts.AxisOpts(
                    type_='value',
                    name='Financing\nUtilization',
                    is_scale=True,
                    is_inverse=True,
                    axislabel_opts=opts.LabelOpts(
                        formatter=JsCode("function (x){return x + ' m'}"))),
                legend_opts=opts.LegendOpts(pos_top='3%'),
                tooltip_opts=opts.TooltipOpts(is_show=True,
                                              is_show_content=True),
            ))
    c1_label = opts.LabelOpts(
        is_show=True,
        position='inside',
        color='white',
        formatter=JsCode(
            "function(x) {d=x.data; if(d!==0.0){return d.toFixed() + ' m'}else{return ''};}"
        ))

    for i in range(len(pses)):
        ps = pses[i]
        if i == len(pses) - 1:
            funnel_data = [
                [
                    f'\n\n\nLayer 1:\n\nContingent budget or reserve\n\n0~{int(ps[tier1_UL])} m\n\n\nHigh{" " * 150}Low\nFrequency{" " * 140}Severity',
                    30
                ],
                [
                    f'Layer 2:\n\nContingent credit\n\n{int(ps[tier1_UL])}~{int(ps[tier2_UL])} m',
                    20
                ],
                [
                    f'Low Frequency{" " * 20}High Severity\n\n\n\nLayer 3:\n\nCapacity\nbuilding\nvehicles\n\n{int(ps[tier2_UL])}~{int(ps[tier3_UL])} m\n',
                    10
                ]
            ]
            layerc = (Funnel(init_opts=opts.InitOpts(theme='dark')).add(
                'layers',
                funnel_data,
                sort_='ascending',
                label_opts=opts.LabelOpts(
                    position='inside', color='black',
                    font_weight=['bold'])).set_global_opts(
                        legend_opts=opts.LegendOpts(is_show=False),
                        tooltip_opts=opts.TooltipOpts(is_show=False)))
            st_pyecharts(layerc, width='61.8%', height='600%')

        Limit = ps[inSize]

        RevisedLossRetainedRatio = ps[ipRLLoad]
        PctLossRetained = RevisedLossRetainedRatio
        LossTransfer = 1 - PctLossRetained

        InsurancePayout = (LossAmountMillion - ps[attachment]).clip(
            0, Limit) * LossTransfer

        CatbondSize = ps[cb_limit] - ps[cb_att]
        RetainedLossAfterInsurance = LossAmountMillion - InsurancePayout
        tier1_utilization = np.minimum(RetainedLossAfterInsurance,
                                       ps[tier1_AMT])
        Layer1FinancingBenefit = tier1_utilization * ps[tier1_BenRate]
        RetainedLossAfterLayer1Financing = np.maximum(
            0, RetainedLossAfterInsurance - tier1_utilization -
            Layer1FinancingBenefit)
        tier2_utilization = np.minimum(RetainedLossAfterLayer1Financing,
                                       ps[tier2_AMT])
        Layer2FinancingBenefit = tier2_utilization * ps[tier2_BenRate]
        RetainedLossAfterLayer2Financing = np.maximum(
            0, RetainedLossAfterLayer1Financing - tier2_utilization -
            Layer2FinancingBenefit)
        CatbondRecovery = (RetainedLossAfterLayer2Financing - ps[cb_att]).clip(
            0, CatbondSize)

        rl_pct_NB = (RetainedLossAfterLayer2Financing -
                     CatbondRecovery) / ps[natBdt]

        layer1_insurance_payout = np.minimum(LossAmountMillion, ps[tier1_UL])
        layer2_insurance_payout = np.maximum(
            np.minimum(LossAmountMillion, ps[tier2_UL]) - ps[tier1_UL], 0)
        layer3_insurance_payout = np.maximum(
            np.minimum(LossAmountMillion, ps[tier3_UL]) - ps[tier2_UL], 0)

        WT_CDF = np.zeros(CDF.size)
        WT_CDF[CDF != 0] = norm.cdf(norm.ppf(CDF[CDF != 0]) - ps[SharpeRatio])

        TransformedProbability = np.diff(WT_CDF)
        TransformedProbability = np.insert(TransformedProbability, 0,
                                           WT_CDF[0])
        InsurancePremium = (TransformedProbability * InsurancePayout).sum()
        InsurancePremiumAsPctNationalBudget = InsurancePremium / ps[natBdt]

        tier1_wtCost = (TransformedProbability * layer1_insurance_payout).sum()
        tier1_wtCost /= float(ps[tier1_UL])
        tier2_wtCost = (TransformedProbability * layer2_insurance_payout).sum()
        tier2_wtCost /= (ps[tier2_UL] - ps[tier1_UL])
        tier3_wtCost = (TransformedProbability * layer3_insurance_payout).sum()
        tier3_wtCost /= (ps[tier3_UL] - ps[tier2_UL])

        cc_df1 = pd.DataFrame([
            str(round(ps[tier1_IntRate] * 100, 0)) + '%',
            str(round(ps[tier2_IntRate] * 100, 0)) + '%'
        ],
                              index=['Debt', 'Credit Line'],
                              columns=[''])

        cc_df2 = pd.DataFrame([
            str(round(tier1_wtCost * 100, 1)) + '%',
            str(round(tier2_wtCost * 100, 1)) + '%',
            str(round(tier3_wtCost * 100, 1)) + '%'
        ],
                              index=[f'Layer {i}' for i in range(1, 4)],
                              columns=[''])
        sb, ertcc = CostComparison_empty.beta_columns(2)
        sb.markdown(
            '&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;**Sovereign Borrowing**'
        )
        ertcc.markdown(
            '&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;**Estimated Risk Transfer Capacity Cost**'
        )
        sb.table(cc_df1.T)
        ertcc.table(cc_df2.T)

        PDF = np.diff(CDF)
        PDF = np.insert(PDF, 0, CDF[0])
        ExpectedLoss = (CatbondRecovery * PDF).sum()
        CatbondAnnualCost = ExpectedLoss * ps[hisMul] * (1 + ps[ipCBLoad]) * (
            1 + ps[dataCBLoad])
        CatbondCoupon = CatbondAnnualCost
        CatbondCostAsPctNationalBudget = CatbondCoupon / ps[natBdt]

        InsurancePenetrationCostAsPctNationalBudget = ps[ip_Invest]
        DataInfrastractureCostAsPctNationalBudget = ps[data_Invest]

        Layer1BorrowingCost = ps[tier1_Int]
        Layer1CostAsPctNationalBudget = Layer1BorrowingCost / ps[natBdt]
        Layer2BorrowingCost = ps[tier2_Int]
        Layer2CostAsPctNationalBudget = Layer2BorrowingCost / ps[natBdt]

        TotalDRFIStrategyCostAsPctNatlBudget = InsurancePremiumAsPctNationalBudget + CatbondCostAsPctNationalBudget \
                                               + DataInfrastractureCostAsPctNationalBudget + InsurancePenetrationCostAsPctNationalBudget \
                                               + Layer1CostAsPctNationalBudget + Layer2CostAsPctNationalBudget

        VaR_pct_NationalBudget = rl_pct_NB + TotalDRFIStrategyCostAsPctNatlBudget

        serie_name = f'DRFI Strategy {n2c[series_num]}'
        serie_data = []
        LossByReturnYearPeriod = []
        l1FUs, l2Fus, cbrs = [], [], []
        for pctile in pencentile:
            position = np.argmin(np.abs(CDF - pctile))
            var = VaR_pct_NationalBudget[position]
            var = round(var * 100, 2)
            serie_data.append(var)
            loss = LossAmountMillion[position]
            LossByReturnYearPeriod.append(loss)
            l1FU = tier1_utilization[position]
            l1FU = round(l1FU, 0)
            l1FUs.append(l1FU)
            l2FU = tier2_utilization[position]
            l2FU = round(l2FU, 0)
            l2Fus.append(l2FU)
            cbr = CatbondRecovery[position]
            cbr = round(cbr, 0)
            cbrs.append(cbr)

        c.add_yaxis(serie_name,
                    serie_data,
                    label_opts=opts.LabelOpts(is_show=True, formatter='{c}%'))
        c1.add_yaxis('Layer 1 Financing Utilization', l1FUs, stack=serie_name, label_opts=c1_label) \
            .add_yaxis('Layer 2 Financing Utilization', l2Fus, stack=serie_name, label_opts=c1_label) \
            .add_yaxis('Capacity Building Vehicles Recovery', cbrs, stack=serie_name, label_opts=c1_label)

        LossByReturnYearPeriod_df = pd.DataFrame(
            {
                'Loss ($m)': LossByReturnYearPeriod
            },
            index=[str(y) + '-year' for y in pctile_year]).T
        LossByReturnYearPeriod_empty.table(LossByReturnYearPeriod_df)

        series_num += 1

    grid = (Grid().add(c,
                       grid_opts=opts.GridOpts(pos_top='15%',
                                               pos_left='8%',
                                               height='43%',
                                               width='79%'),
                       grid_index=0).add(c1,
                                         grid_opts=opts.GridOpts(
                                             pos_bottom='8%',
                                             pos_left='8%',
                                             height='30%',
                                             width='79%'),
                                         grid_index=1))

    df = pd.DataFrame(dps[user_input])
    df[cb_AMT] = cb_AMTs
    params_df = df.copy(deep=True)

    rn = copy.deepcopy(show_name)
    for pname in change_to_amt:
        params_df[pname] = params_df[pname].map(
            lambda x: str(round(x * dps[natBdt], 1))[:3])

    for pname in pct_params:
        params_df[pname] = params_df[pname].map(
            lambda x: str(round(x * 100, 2)) + '%')
    rn.update(bg_show_name)
    params_df.rename(columns=rn, inplace=True)
    params_df = params_df.loc[:, [show_name[k] for k in show_name]]
    name_change = {}
    for pname in change_to_amt:
        if pname in show_name:
            name_change[show_name[pname]] = show_name[pname].replace(
                ' as % National Budget', '')
    params_df.rename(columns=name_change, inplace=True)
    params_df = pd.DataFrame(
        params_df.values.T,
        index=params_df.columns,
        columns=[f'DRFI Strategy {n2c[i + 1]}' for i in params_df.index])
    st.markdown('*****')
    st.markdown('### V. The DRFI Strategies')
    st.dataframe(params_df)

    st.markdown('*****')
    st.markdown(
        '### VI. Loss Impact as % of National Budget under Various Scenarios')
    st_pyecharts(grid, width='100%', height='618%', renderer='canvas')