Exemple #1
0
def test_effectscatter_item_base(fake_writer):
    x_axis = Faker.choose()
    chart_item = [
        opts.EffectScatterItem(name=d[0], value=d[1])
        for d in list(zip(x_axis, Faker.values()))
    ]

    c = EffectScatter().add_xaxis(x_axis).add_yaxis("", chart_item)
    c.render()
    _, content = fake_writer.call_args[0]
    assert_equal(c.theme, "white")
    assert_equal(c.renderer, "canvas")
Exemple #2
0
def drawEffectScatter(arr, value, name):
    c1 = EffectScatter()
    c1.add_xaxis(xaxis_data=arr)
    c1.add_yaxis(
        series_name=name,
        y_axis=value,
        # symbol='image://http://weizhendong.top/images/1.png',
        symbol=SymbolType.ARROW,
        # label_opts=opts.LabelOpts(is_show=False)
    )
    c1.set_global_opts(
        title_opts=opts.TitleOpts(title=name),
        datazoom_opts=opts.DataZoomOpts(),
    )
    c1.render("{0}.html".format(name))
Exemple #3
0
def effectscatter_symbol() -> EffectScatter:
    c = (
        EffectScatter().add_xaxis(x[::1])  #设置横坐标数据,设为年份
        .add_yaxis(
            "四川特殊教育招生数(万人)",
            [1.03, 1.04, 0.96, 0.81, 0.80, 0.82, 0.84, 0.68, 0.67, 0.65],
            color="#1E90FF",
            symbol_size=16,
            symbol="arrow").add_yaxis(
                "四川特殊教育专任教师数(万人)",
                [0.30, 0.28, 0.25, 0.24, 0.22, 0.21, 0.19, 0.18, 0.17, 0.16],
                color="#AB82FF",
                symbol_size=16,
                symbol="arrow").add_yaxis("四川特殊教育在校学生数(万人)", [
                    5.69, 5.35, 4.78, 4.33, 4.23, 4.37, 4.43, 4.09, 4.18, 4.18
                ],
                                          color="#EE2222",
                                          symbol_size=16,
                                          symbol="arrow")  # 设置纵坐标数据
        .set_global_opts(
            title_opts=opts.TitleOpts(
                title='图1-6',
                subtitle="四川特殊教育基本情况",  # 设置标题与副标题样式,进行图例说明
                subtitle_textstyle_opts=opts.TextStyleOpts(color="black",
                                                           font_size=15)),
            xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
                is_show=True)),
            yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
                is_show=True)),
        ))
    return c  #返回数据
def effectscatter_symbol():
    c = (EffectScatter().add_xaxis(Faker.choose()).add_yaxis(
        "", Faker.values(), symbol=SymbolType.ARROW).set_global_opts(
            toolbox_opts=opts.ToolboxOpts(is_show=True),
            title_opts=opts.TitleOpts(title="EffectScatter-不同Symbol"),
        ))
    return c
Exemple #5
0
def effectScatter1():
    effectScatter = (
        EffectScatter()  #实例化Line
        .add_xaxis(x2)  #加入X轴数据
        .add_yaxis("歌曲时长(m.s)", y2)  #加入Y轴数据
        .set_global_opts(title_opts=opts.TitleOpts(title="Line-歌曲时长")))
    return effectScatter
Exemple #6
0
    def pyechart_EffectScatter_plot(self, filedata, para):
        from pyecharts.charts import EffectScatter
        file_name = '散点涟漪图.html'
        path_plotly = self.path_dir_plotly_html + os.sep + file_name  # 文件路径,前面是文件夹后面是文件名
        costumeTheme = self.themedict[para['theme']]
        # -----------------------------------------------------------------------

        EffectScatter = (
            EffectScatter(init_opts=opts.InitOpts(
                theme=costumeTheme, width=para['width'],
                height=para['height']))  # ThemeType.LIGHT para['theme']
        )
        chart = EffectScatter

        df = pd.read_excel(filedata, sheet_name='Sheet1')

        columns = df.columns.values.tolist()
        xlabel = columns[0]
        xdata = df[xlabel].values.tolist()

        chart.add_xaxis(xaxis_data=xdata)
        for i in range(1, len(columns)):
            ylabel = columns[i]
            ydata = df[ylabel].values.tolist()
            chart.add_yaxis(series_name=ylabel, y_axis=ydata)
        if para['x2y']:
            chart.reversal_axis()
        self.Common_code(chart, path_plotly, para)

        print('成功绘制散点涟漪图')
        return path_plotly  # 返回该HTML文件路径
Exemple #7
0
def read():
    df = pd.read_csv('data_clean.csv')

    types = get_type()
    count = {}
    for type in types:
        type = type.lower()
        for idx in df.index:
            item = df.loc[idx].values[1:]

            if item[1].lower().find(type) != -1:
                if type not in count:
                    count[type] = 1
                else:
                    count[type] += 1
    count = list(count.items())
    count.sort(key=lambda x: x[-1], reverse=True)

    from pyecharts.charts import EffectScatter

    EffectScatter().add_xaxis([item[0] for item in count]).add_yaxis("", [item[1] for item in count]).render(
        "effectscatter_base.html")

    count = {}
    for idx in df.index:
        item = df.loc[idx].values[1:]
        xl = item[3]
        if xl not in count:
            count[xl] = 1
        else:
            count[xl] += 1
    Line().add_xaxis(list(count.keys())).add_yaxis('', list(count.values())).render('学历.html')
Exemple #8
0
def effectscatter_symbol() -> EffectScatter:
    c = (
        EffectScatter()
        .add_xaxis(Faker.choose())
        .add_yaxis("", Faker.values(), symbol=SymbolType.ARROW)
    ).set_global_opts(title_opts=opts.TitleOpts(title="EffectScatter-不同Symbol"))
    return c
def effectscatter_base() -> EffectScatter:
    c = (
        EffectScatter()
        .add_xaxis(Faker.choose())
        .add_yaxis("", Faker.values())
        .set_global_opts(title_opts=opts.TitleOpts(title="EffectScatter-基本示例"))
    )
    return c
Exemple #10
0
def effectscatter_base() -> EffectScatter:
    d = (EffectScatter().add_xaxis([
        '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009',
        '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017'
    ]).add_yaxis("China", China).add_yaxis("Angola", Angola).add_yaxis(
        "Ethiopia", Ethiopia).add_yaxis("Zambia", Zambia).set_global_opts(
            title_opts=opts.TitleOpts(title="四国人均GDP")))
    return render_template("showchart3.html", bar_data3=d.dump_options())
Exemple #11
0
def effectscatter_splitline() -> EffectScatter:
    c = (EffectScatter().add_xaxis(Faker.choose()).add_yaxis(
        "", Faker.values()).set_global_opts(
            title_opts=opts.TitleOpts(title="EffectScatter-显示分割线"),
            xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
                is_show=True)),
            yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
                is_show=True)),
        ))
    return c
Exemple #12
0
def effectscatter_splitline() -> EffectScatter:
    c = (EffectScatter().add_xaxis(x3).add_yaxis("泰国汇率", 泰国).set_global_opts(
        title_opts=opts.TitleOpts(title="1987-2001泰国汇率变化"),
        toolbox_opts=opts.ToolboxOpts(),
        datazoom_opts=opts.DataZoomOpts(),
        xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
            is_show=True)),
        yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
            is_show=True)),
    ))
    return c
Exemple #13
0
def world_per1():
    data_str = df4.to_html()
    d = (EffectScatter().add_xaxis([
        '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009',
        '2010', '2011', '2012', '2013', '2014', '2015', '2016', '2017'
    ]).add_yaxis("China", China).add_yaxis("Angola", Angola).add_yaxis(
        "Ethiopia", Ethiopia).add_yaxis("Zambia", Zambia).set_global_opts(
            title_opts=opts.TitleOpts(title="四国人均GDP")))
    return render_template('results4.html',
                           bar_data3=d.dump_options(),
                           the_select_region2=world_per,
                           the_res=data_str)
def get_picture2():
    df = pd.read_csv(UPLOAD_FOLDER + '地区生产总值.csv', encoding='gbk')

    地区 = list(df.地区)
    地区生产总值 = list(df.地区生产总值)
    c = (
        EffectScatter()
            .add_xaxis(地区)
            .add_yaxis("地区生产总值", 地区生产总值)
            .set_global_opts(title_opts=opts.TitleOpts(title="EffectScatter-基本示例"))
    )
    fig = c.render('./temp/example.html');
    return fig
Exemple #15
0
def effectscatter_symbol() -> EffectScatter:
    df = pd.read_csv('data4.csv', encoding='utf8', index_col="名称")
    省 = list(df.loc["省"].values)[-24:]
    平均月薪 = list(df.loc["平均月薪"].values)[-24:]
    c = (EffectScatter().add_xaxis(省).add_yaxis(
        "平均月薪", 平均月薪, symbol=SymbolType.ARROW)).set_global_opts(
            title_opts=opts.TitleOpts(title=""))
    c.render("./templates/symbol.html")
    with open("./templates/symbol.html", encoding="utf8", mode="r") as f:
        sym = "".join(f.readlines())
        return render_template(
            'python_effectscatter_symbol.html',
            the_sym=sym,
        )
Exemple #16
0
def s_4():
    with open(r'pro.csv', 'r') as f:
        reader = csv.reader(f)
        result = list(reader)
    pro_list = [i[0] for i in result]
    total_list = [float(i[1]) for i in result]
    p = (EffectScatter(init_opts=opts.InitOpts(
        width='1200px', height='800px')).add_xaxis(pro_list).add_yaxis(
            "交易额", total_list,
            label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
                title_opts=opts.TitleOpts(title="本年度交易额省份排名分析"),
                xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
                    is_show=True)),
                yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
                    is_show=True)),
            ))
    return p
def index_bar():
    ted = pd.read_csv("./static/data/ted_main.csv")
    ted['film_date'] = ted['film_date'].apply(
        lambda x: datetime.datetime.fromtimestamp(int(x)).strftime('%d-%m-%Y'))
    ted['published_date'] = ted['published_date'].apply(
        lambda x: datetime.datetime.fromtimestamp(int(x)).strftime('%d-%m-%Y'))
    r = (
        EffectScatter().add_xaxis(ted['views'].values.tolist()).add_yaxis(
            '商家A', ted['comments'].values.tolist()).set_global_opts(
                title_opts=opts.TitleOpts(title="EffectScatter-基本示例"),
                xaxis_opts=opts.AxisOpts(
                    type_="value",  # x轴数据类型是连续型的
                    min_=0  # x轴范围最小为20
                )))
    return render_template('index.html',
                           myechart=r.render_embed(),
                           select=list(res.keys()))
Exemple #18
0
    def overlap_net_pnl(self):
        # 在K线图绘制累计净盈亏曲线(注:kline的datazoom_opts为单图形模式)

        if self.grid == True:
            print("grid应为False!")
            return

        bar_data = pd.merge(self.bar_data,
                            self.trade_data.net_pnl.cumsum(),
                            how="outer",
                            left_index=True,
                            right_index=True)
        bar_data["net_pnl"].fillna(method="ffill", inplace=True)
        bar_data["net_pnl"].fillna(value=0, inplace=True)

        self.kline_chart.extend_axis(yaxis=opts.AxisOpts(position="right"))

        net_pnl_line = (Line().add_xaxis(
            xaxis_data=self.bar_data_datetime).add_yaxis(
                series_name="Net_pnl",
                y_axis=bar_data.net_pnl.apply(
                    lambda x: round(x, 2)).values.tolist(),
                yaxis_index=1,
                label_opts=opts.LabelOpts(is_show=False),
                is_symbol_show=False,
                linestyle_opts=opts.LineStyleOpts(width=3,
                                                  opacity=0.5,
                                                  type_="solid",
                                                  color="#8A0000"),
            ))

        signal_scatter = (EffectScatter().add_xaxis(xaxis_data=list(
            self.trade_data.index.strftime("%Y-%m-%d %H:%M"))).add_yaxis(
                series_name="Signal",
                y_axis=self.trade_data.signal.values.tolist(),
                yaxis_index=1,
                symbol_size=5,
                label_opts=opts.LabelOpts(is_show=True, font_size=9),
                itemstyle_opts=opts.ItemStyleOpts(color="#0000FF",
                                                  opacity=0.9),
            ).set_global_opts(legend_opts=opts.LegendOpts(is_show=False)))

        self.kline_chart.overlap(signal_scatter)
        self.kline_chart.overlap(net_pnl_line)
Exemple #19
0
#     .set_global_opts(
#         title_opts=opts.TitleOpts(title="标题"),
#         xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(is_show=True)),
#         yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(is_show=True)),
#     )
#     .render("分割线.html")
# )

# c = (
#     Scatter()
#     .add_xaxis(Faker.choose())
#     .add_yaxis("1", Faker.values())
#     .add_yaxis("2", Faker.values())
#     .set_global_opts(
#         title_opts=opts.TitleOpts(title="标题"),
#         visualmap_opts=opts.VisualMapOpts(type_="size", max_=150, min_=20),
#     )
#     .render("凸出大小散点图.html")
# )

# c = (
#     EffectScatter()
#     .add_xaxis(Faker.choose())
#     .add_yaxis("", Faker.values())
#     .set_global_opts(title_opts=opts.TitleOpts(title="散点图"))
#     .render("动态散点图.html")
# )

c = (EffectScatter().add_xaxis(Faker.choose()).add_yaxis(
    "", Faker.values(), symbol=SymbolType.ARROW).set_global_opts(
        title_opts=opts.TitleOpts(title="标题")).render("箭头动态散点图.html"))
def test_effectscatter_base():
    c = EffectScatter().add_xaxis(Faker.choose()).add_yaxis("", Faker.values())
    eq_(c.theme, "white")
    eq_(c.renderer, "canvas")
    c.render()
Exemple #21
0
    def generate_kchart(self,MA=[5,10,21],renderfile=False) -> Grid:        
        if self.exists == False:
            return None
        # reassign cursor tick to trigger populate attributes like self.histBar and etc.
        self.cursorTick = self._cursorTick
        df_toPlot = self.allBars.loc[self.allBars['unit_intdate'] <= self.cursorTick['unit_intdate']]
        
        # 输入时间序列中带有未来日期,则取当下能取到的最新online数据模拟
        # if len(self.allBars.loc[self.allBars['unit_intdate'] == self.cursorTick['unit_intdate']]) == 0:        
        #     df_liveQuote = self.get_livebar(assign_timestamp=self.cursorTick['timeAxis'])
        #     if len(df_liveQuote) > 0:
        #         df_toPlot = df_toPlot.append(df_liveQuote, ignore_index = True, sort=False)    
        
        str_secname = self.sec_name
        str_plotname = '{} - {}'.format(self.ts_code,str_secname)

        '''-----------------画图部分---------------------'''
        lst_ohlcv=df_toPlot.loc[:,['open','close','low','high']].values.tolist()
        lst_vol=list(df_toPlot['vol'].values)
        lst_amount=list(df_toPlot['amount'].values)

        # 需从处理过的histbar中获得,由于长度比allbar短1,需将值list添加一个空值补齐
        lst_peaks=list(abs(self.histBars['peaks'].values))
        # lst_pivotdown=[*(float('nan') if i<0 else i for i in list(self.histBars['pivots'].values)),float('nan')]
        lst_pivotdown=[*(float('nan') if i<0 else i for i in list(self.histBars['valid_pivots'].values)),float('nan')]
        # lst_pivotup=[*(float('nan') if i>0 else abs(i) for i in list(self.histBars['pivots'].values)),float('nan')]
        lst_pivotup=[*(float('nan') if i>0 else abs(i) for i in list(self.histBars['valid_pivots'].values)),float('nan')]

        lst_xaxis=list(df_toPlot['unit_intdate'].astype(str)) # xaxis values has to be STRING type, int will not work

        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

        kline = (Kline()
            .add_xaxis(lst_xaxis)
            .add_yaxis(series_name=str_secname, y_axis=lst_ohlcv,
                        markpoint_opts=opts.MarkPointOpts(
                            data=[opts.MarkPointItem(type_="min",value_dim="close"),
                                opts.MarkPointItem(type_="max",value_dim="close")],
                            symbol_size = [20, 20], #表示标记宽为 20,高为 10
                        ),                           
                        itemstyle_opts=opts.ItemStyleOpts(
                            color="#ec0000",
                            color0="#00da3c",
                            border_color="#ec0000",
                            border_color0="#00da3c",
                        ),)
            .set_global_opts(
                title_opts=opts.TitleOpts(
                    title=str_plotname,
                    subtitle='MA='+str(MA),
                ),
                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,2],
                        range_start=75,
                        range_end=100,
                    ),
                    opts.DataZoomOpts(
                        is_show=True,
                        xaxis_index=[0,1,2],
                        type_="slider",
                        pos_top="90%",
                        range_start=75,
                        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",font_size=10),
                ),
                # 阴量绿阳量红
                visualmap_opts=opts.VisualMapOpts(
                    is_show=False,
                    dimension=2,
                    series_index=list(map(lambda x: x+len(MA),[4,5])), #动态算出vol和amt柱状图的series index
                    is_piecewise=True,
                    pieces=[
                        {"value": 1, "color": "#ec0000"},
                        {"value": -1, "color": "#00da3c"},
                    ],
                ),  
                axispointer_opts=opts.AxisPointerOpts(
                    is_show=True,
                    link=[{"xAxisIndex": "all"}],
                    label=opts.LabelOpts(background_color="#777"),
                ),
                brush_opts=opts.BrushOpts(
                    x_axis_index="all",
                    brush_link="all",
                    out_of_brush={"colorAlpha": 0.1},
                    brush_type="lineX",
                ),
            )
        )
        trendline = (
            Line()
            .add_xaxis(lst_xaxis)
            .add_yaxis('高低点', lst_peaks,
                        itemstyle_opts=opts.ItemStyleOpts(color="green"))
        )
        for i in MA:
            if i is not None:
                trendline.add_yaxis(
                        series_name='MA'+str(i),
                        y_axis=calculate_ma(day_count=i, d=lst_ohlcv),
                        is_smooth=True,
                        is_hover_animation=False,
                        linestyle_opts=opts.LineStyleOpts(width=1, opacity=0.5),
                        label_opts=opts.LabelOpts(is_show=False),
                )
        trendline.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        trendline.set_global_opts(legend_opts=opts.LegendOpts(is_show=False))
        
        keyPoints = (
            EffectScatter()
            .add_xaxis(lst_xaxis)
            .add_yaxis("末跌高", lst_pivotdown,symbol=SymbolType.ARROW,symbol_rotate=180,symbol_size=5,itemstyle_opts=opts.ItemStyleOpts(color="purple"))
            .add_yaxis("末升低", lst_pivotup,symbol=SymbolType.ARROW,symbol_size=5,itemstyle_opts=opts.ItemStyleOpts(color="blue"))
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
        )
        vol_bar = (
            Bar()
            .add_xaxis(lst_xaxis)
            .add_yaxis(
                series_name="交易量",
                y_axis=[
                [i, lst_vol[i], 1 if lst_ohlcv[i][0] < lst_ohlcv[i][1] else -1]
                for i in range(len(lst_vol))
                ],
                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_="最低",
                    max_="最高",
                ),
                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),
            )
            # .add_yaxis("交易量", lst_vol,itemstyle_opts=opts.ItemStyleOpts(color="#456A76"))
        )
        amnt_bar = (
            Bar()
            .add_xaxis(lst_xaxis)
            .add_yaxis(
                series_name="交易额",
                y_axis=[
                [i, lst_amount[i], 1 if lst_ohlcv[i][0] < lst_ohlcv[i][1] else -1]
                for i in range(len(lst_amount))
                ],
                xaxis_index=2,
                yaxis_index=2,
                label_opts=opts.LabelOpts(is_show=False),
            )
            .set_global_opts(
                xaxis_opts=opts.AxisOpts(
                    type_="category",
                    is_scale=True,
                    grid_index=2,
                    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_="最低",
                    max_="最高",
                ),
                yaxis_opts=opts.AxisOpts(
                    grid_index=2,
                    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),
            )
            # .add_yaxis("交易额", lst_amount,itemstyle_opts=opts.ItemStyleOpts(color="#456A76"))
        )
        priceChart = kline.overlap(trendline).overlap(keyPoints)
        gridChart = Grid()
        gridChart.add(
            priceChart,
            grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_bottom='40%'),
        )
        gridChart.add(
            vol_bar,
            grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top="60%", height='15%'),
        )
        gridChart.add(
            amnt_bar,
            grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top="75%"),
        )

        fname = '{}{}.html'.format(cfg.PATH_ANAFILE,'kline')
        gridChart.render(fname) if renderfile else None
        self.kchart = gridChart # 将结果输出到analytics对象属性中用于function以外的调用
        return self
Exemple #22
0
    def K(self) -> Kline:
        data = self.data[self.prices_cols].values.tolist()
        c = (Kline().add_xaxis(self.dateindex).add_yaxis(
            "k线", data).set_global_opts(
                title_opts=opts.TitleOpts(title=self.title, pos_left="0"),
                legend_opts=opts.LegendOpts(is_show=False,
                                            pos_bottom=10,
                                            pos_left="center"),
                datazoom_opts=[
                    opts.DataZoomOpts(
                        is_show=True,
                        xaxis_index=[0, 1],
                        type_="slider",
                        pos_top="85%",
                        range_start=0,
                        range_end=100,
                    ),
                ],
                xaxis_opts=opts.AxisOpts(
                    axislabel_opts=opts.LabelOpts(is_show=False),
                    axistick_opts=opts.AxisTickOpts(is_show=False),
                ),
                yaxis_opts=opts.AxisOpts(
                    is_scale=True,
                    splitarea_opts=opts.SplitAreaOpts(
                        is_show=True,
                        areastyle_opts=opts.AreaStyleOpts(opacity=1)),
                ),
                tooltip_opts=opts.TooltipOpts(
                    trigger="axis",
                    axis_pointer_type="cross",
                    background_color="rgba(245, 245, 245, 0.8)",
                    border_width=2,
                    border_color="#ccc",
                    textstyle_opts=opts.TextStyleOpts(color="#000"),
                ),
                visualmap_opts=opts.VisualMapOpts(
                    is_show=False,
                    dimension=2,
                    series_index=5,
                    is_piecewise=True,
                    pieces=[
                        {
                            "value": 1,
                            "color": "#00da3c"
                        },
                        {
                            "value": -1,
                            "color": "#ec0000"
                        },
                    ],
                ),
                axispointer_opts=opts.AxisPointerOpts(
                    is_show=True,
                    link=[{
                        "xAxisIndex": "all"
                    }],
                    label=opts.LabelOpts(background_color="#777"),
                ),
                brush_opts=opts.BrushOpts(
                    x_axis_index="all",
                    brush_link="all",
                    out_of_brush={"colorAlpha": 0.1},
                    brush_type="lineX",
                ),
            ))
        if len(self.klines) != 0:
            kLine = Line().add_xaxis(self.dateindex)
            for i in self.klines:
                kLine.add_yaxis(
                    i,
                    round(self.data[i], self.precision).values.tolist(),
                    is_smooth=True,
                    is_symbol_show=False,
                    is_hover_animation=False,
                    label_opts=opts.LabelOpts(is_show=True),
                    linestyle_opts=opts.LineStyleOpts(type_='solid', width=2),
                )
            kLine.set_global_opts(
                xaxis_opts=opts.AxisOpts(type_="category", is_show=False))
            c.overlap(kLine)

        if 'BUY' in self.data.columns:
            v1 = self.data[self.data['BUY'] == True].index.strftime(
                "%Y-%m-%d").tolist()
            v2 = self.data[self.data['BUY'] == True]['close']
            es_buy = (EffectScatter().add_xaxis(v1).add_yaxis(
                "", v2, symbol=SymbolType.ARROW, is_selected=True))
            c.overlap(es_buy)

        if 'SELL' in self.data.columns:
            v1 = self.data[self.data['SELL'] == True].index.strftime(
                "%Y-%m-%d").tolist()
            v2 = self.data[self.data['SELL'] == True]['low']
            es_sell = (EffectScatter().add_xaxis(v1).add_yaxis("", v2))
            c.overlap(es_sell)

        return c
Exemple #23
0
from pywebio.output import put_html
from pyecharts import options as opts
from pyecharts.charts import EffectScatter
from pyecharts.faker import Faker

c = (
    EffectScatter()
    .add_xaxis(Faker.choose())
    .add_yaxis("", Faker.values())
    .set_global_opts(title_opts=opts.TitleOpts(title="EffectScatter-基本示例"))
    
)

c.width = "100%"
put_html(c.render_notebook())
def test_effectscatter_base(fake_writer):
    c = EffectScatter().add_xaxis(Faker.choose()).add_yaxis("", Faker.values())
    c.render()
    _, content = fake_writer.call_args[0]
    eq_(c.theme, "white")
    eq_(c.renderer, "canvas")
Exemple #25
0
line.render_notebook()


line = (
    Line()
    .add_xaxis(x)
    .add_yaxis('china', data_china, is_step=True)
    .set_global_opts(title_opts=opts.TitleOpts(title="Line - 阶梯折线图"))
)
line.render_notebook()


# 散点图
scatter = (
    EffectScatter()
    .add_xaxis(x)
    .add_yaxis("", data_china)
    .set_global_opts(title_opts=opts.TitleOpts(title="EffectScatter - 基本示例"))
)
scatter.render_notebook()


scatter = (
    EffectScatter()
    .add_xaxis(x)
    .add_yaxis("china", data_china, symbol=SymbolType.ARROW)
    .set_global_opts(
        title_opts=opts.TitleOpts(title="EffectScatter - 显示分割线"),
        xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(is_show=True)),
        yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(is_show=True)),
    )
)
Exemple #26
0
v2 = [10, 25, 8, 60, 20, 80]

scatter = (Scatter().add_xaxis(Faker.choose()).add_yaxis(
    "商家A", Faker.values()).add_yaxis("aa", v1).set_global_opts(
        title_opts=opts.TitleOpts(title="散点图", pos_top="50%"),
        legend_opts=opts.LegendOpts(pos_top="50%", pos_left="20%")))
scatter.render("scatter.html")

v3 = [11, 11, 15, 13, 12, 13, 10]
v4 = [1, -2, 2, 5, 3, 2, 0]

es = (EffectScatter().add_xaxis(
    Faker.choose()).add_yaxis("不同Symbol",
                              Faker.values(),
                              symbol=SymbolType.ARROW).set_global_opts(
                                  title_opts=opts.TitleOpts(title="动态散点图",
                                                            pos_top="50%",
                                                            pos_left="50%"),
                                  legend_opts=opts.LegendOpts(pos_top="50%",
                                                              pos_left="70%")))
es.render("es.html")

grid = (Grid(init_opts=opts.InitOpts(width="1200px", height="720px")).add(
    bar, grid_opts=opts.GridOpts(pos_right="60%", pos_bottom="60%")).add(
        line, grid_opts=opts.GridOpts(pos_left="60%", pos_bottom="60%")).add(
            scatter,
            grid_opts=opts.GridOpts(pos_right="60%", pos_top="60%")).add(
                es, grid_opts=opts.GridOpts(pos_left="60%", pos_top="60%")))

grid.render("duotu.html")
def effectscatter_base():
    c = (EffectScatter().add_xaxis(Faker.choose()).add_yaxis(
        "", Faker.values()).set_global_opts(
            toolbox_opts=opts.ToolboxOpts(is_show=True),
            title_opts=opts.TitleOpts(title="EffectScatter-基本示例")))
    return c
def effect_scatter_chart():
    # 涟漪散点图

    effect_scatter = EffectScatter()
    x_y_axis = get_chart_data()
    effect_scatter.add_xaxis(x_y_axis[0])
    for j in x_y_axis[1]:
        for key, value in j.items():
            effect_scatter.add_yaxis(key,
                                     value,
                                     label_opts=opts.LabelOpts(is_show=False))
    effect_scatter.set_series_opts(markpoint_opts=opts.MarkPointOpts(data=[
        opts.MarkPointItem(type_="max", name="最大值"),
        opts.MarkPointItem(type_="min", name="最小值"),
    ]), )
    effect_scatter.set_global_opts(
        title_opts=opts.TitleOpts(
            title="API耗时统计",
            subtitle="生产环境",
            pos_left="30%",
            title_textstyle_opts=opts.TextStyleOpts(color='red'),
            subtitle_textstyle_opts=opts.TextStyleOpts(color='blue')),
        xaxis_opts=opts.AxisOpts(
            name="运行时间",
            type_="category",
            boundary_gap=True,
            # axislabel_opts=opts.LabelOpts(rotate=15)
        ),
        yaxis_opts=opts.AxisOpts(name="实际的响应时间(单位:秒)",
                                 # min_=0,
                                 # max_=20
                                 ),
        legend_opts=opts.LegendOpts(type_='scroll',
                                    selected_mode='multiple',
                                    pos_left='right',
                                    pos_top='10%',
                                    orient='vertical'),
        tooltip_opts=opts.TooltipOpts(trigger="axis",
                                      axis_pointer_type="line"),
        toolbox_opts=opts.ToolboxOpts(is_show=True, pos_left='right'),
        visualmap_opts=opts.VisualMapOpts(is_show=True,
                                          type_="size",
                                          min_=0,
                                          max_=20,
                                          range_text=["最大值", "最小值"]),
        datazoom_opts=[opts.DataZoomOpts(range_start=50, range_end=100)],
    )
    effect_scatter = effect_scatter.dump_options_with_quotes()
    return effect_scatter
    def __draw_zs_area(_ka):
        lines = []
        scatters = []
        for _zs in _ka.zs_list:
            x_start = _zs['start_point']['dt']

            if _zs['zs_finished']:# 中枢完成
                x_end = _zs['end_point']['dt']

                chart_b = EffectScatter()

                if 'buy3' in _zs:
                    chart_b.add_xaxis([_zs['buy3']['dt']])
                    chart_b.add_yaxis(series_name=_ka.freq if aggregation else "B", y_axis=[_zs['buy3']['xd']], is_selected=False, symbol="circle", symbol_size=8,
                                itemstyle_opts=opts.ItemStyleOpts(color="red",))
                    chart_b.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts)
                    scatters.append(chart_b)
                elif 'sell3' in _zs:
                    chart_b.add_xaxis([_zs['sell3']['dt']])
                    chart_b.add_yaxis(series_name=_ka.freq if aggregation else "S", y_axis=[_zs['sell3']['xd']], is_selected=False, symbol="circle", symbol_size=8,
                                itemstyle_opts=opts.ItemStyleOpts(color="green",))
                    chart_b.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts)
                    scatters.append(chart_b)
            elif len(_zs['points'])>=5:# 中枢成立但未完成,有3笔或段以上
                x_end = _zs['points'][-1]['dt']
            else:                       # 中枢未完成,且未确定
                continue
            
            ZD = _zs['ZD']
            ZG = _zs['ZG']
            area_data=[[ {'xAxis': x_start, 'yAxis': ZD, 'value': ZD }, {'xAxis': x_end, 'yAxis': ZG, 'value': ZG }]]
            line = (Line()
            .add_xaxis([x_start, x_end])
            .add_yaxis(series_name=_ka.freq if aggregation else "ZS", y_axis=[ZD, ZG], symbol='none' 
            """        
            , markpoint_opts = opts.MarkPointOpts(
                data=[
                    opts.MarkPointItem(type_="max", name="ZG"),
                    opts.MarkPointItem(type_="min", name="ZD"),
                ]
            )
            """
            , markline_opts=opts.MarkLineOpts(
                label_opts=opts.LabelOpts(
                    position="middle", color="blue", font_size=15,
                ),
                linestyle_opts=opts.LineStyleOpts(type_="dashed"),
                data=area_data,
                symbol=["none", "none"],
            )
            )
            .set_series_opts(
                markarea_opts=opts.MarkAreaOpts(data=area_data, itemstyle_opts=opts.ItemStyleOpts(color="#dcdcdc",opacity=0.1))
            ))
            lines.append(line)
        return lines, scatters
Exemple #30
0
    def plot(self,
             area=['V', 'M'],
             width=1000,
             height=680,
             klines=[],
             vlines=[]) -> Grid:
        '''
        @params:
        - area : list   #显示区域
                       'V'   交易量
                       'M'   k线+MACD
                       FieldName: string   Dataframe中的字段名
                       [Field1,Field2,...] Dataframe中的字段名列表,将显示在一个区域
          width: int   #图表宽度 px
          height:int   #图表高度 px
          klines:str   #K线区域显示的数据,Dataframe中的字段名,如MA...
          vline: str   #Volume区域显示的数据,Dataframe中的字段名,如MA...
        - sample:
           chart=data.plot(area=[['small_pct','medium_pct','big_pct','super_pct'],'V','cci'],vlines=['vMA5','vMA10'],klines=['MA5','MA10'])  
        '''
        self.klines = klines
        self.vlines = vlines
        grid = (Grid(init_opts=opts.InitOpts(
            width=str(width) + "px",
            height=str(height) + "px",
            animation_opts=opts.AnimationOpts(animation=False),
        )))
        c = self.K()
        iTop = 10
        iButton = 10
        iWindows = len(area)
        iStep = 0
        if iWindows == 0:
            grid.add(c,
                     grid_opts=opts.GridOpts(pos_top="2%", pos_bottom="10%"))
        elif iWindows > 1:
            grid.add(c,
                     grid_opts=opts.GridOpts(pos_top="2%", pos_bottom="50%"))
            iStep = int(30 / iWindows)
            iButton = 50
        else:
            grid.add(c,
                     grid_opts=opts.GridOpts(pos_top="1%", pos_bottom="30%"))
            iStep = 15
            iButton = 70
        icount = 0
        for w in area:
            #print(iStep)
            if type(w) == list:
                window = Line().add_xaxis(self.dateindex)
                for l in w:
                    window.add_yaxis(
                        series_name=l,
                        y_axis=round(self.data[l],
                                     self.precision).values.tolist(),
                        is_smooth=True,
                        is_symbol_show=False,
                        is_hover_animation=False,
                        label_opts=opts.LabelOpts(is_show=False),
                        linestyle_opts=opts.LineStyleOpts(type_='solid',
                                                          width=2))
                window.axislabel_opts = opts.LabelOpts(is_show=False),
                window.set_global_opts(
                    datazoom_opts=[opts.DataZoomOpts()],
                    xaxis_opts=opts.AxisOpts(
                        type_="category",
                        axislabel_opts=opts.LabelOpts(is_show=False),
                    ),
                    legend_opts=opts.LegendOpts(orient='vertical',
                                                pos_left="top",
                                                pos_top=str(iButton) + "%"),
                )

            elif w == 'V':
                window = self.V()
                #grid.add(v,grid_opts=opts.GridOpts(pos_top= str(iButton)+'%',height=str(iStep)+'%'))
            elif w == 'M':
                window = self.MACD()
                #grid.add(macd,grid_opts=opts.GridOpts(pos_top= str(iButton)+'%',height=str(iStep)+'%'))
            else:
                window = Line().add_xaxis(self.dateindex)
                window.add_yaxis(
                    series_name=w,
                    y_axis=round(self.data[w], self.precision).values.tolist(),
                    is_smooth=True,
                    is_symbol_show=False,
                    is_hover_animation=False,
                    label_opts=opts.LabelOpts(is_show=False),
                    linestyle_opts=opts.LineStyleOpts(type_='solid', width=2))
                window.axislabel_opts = opts.LabelOpts(is_show=True),
                window.set_global_opts(
                    datazoom_opts=[opts.DataZoomOpts()],
                    xaxis_opts=opts.AxisOpts(
                        type_="category",
                        axislabel_opts=opts.LabelOpts(is_show=False),
                    ),
                    legend_opts=opts.LegendOpts(orient='horizontal',
                                                pos_left=str(icount + 20) +
                                                "%"),
                )
                if '_' + w + '_flag' in self.data.columns:
                    #print("find_flag")
                    v1 = self.data[self.data['_' + w + '_flag'] ==
                                   True].index.strftime("%Y-%m-%d").tolist()
                    v2 = self.data[self.data['_' + w + '_flag'] == True][w]
                    c_flag = (EffectScatter().add_xaxis(v1).add_yaxis("", v2))
                    window.overlap(c_flag)
                #grid.add(vLine,grid_opts=opts.GridOpts(pos_top= str(iButton)+'%',height=str(iStep)+'%'))
            icount += 1
            #最后一行加上x刻度
            if icount == iWindows:
                window.options['xAxis'][0]['axisLabel'].opts['show'] = True
            grid.add(window,
                     grid_opts=opts.GridOpts(pos_top=str(iButton) + '%',
                                             height=str(iStep) + '%'))
            iButton = iButton + iStep
        #grid.grid_opts=opts.GridOpts(pos_left="8%", pos_right="8%", height="50%"),
        grid.options['dataZoom'][0].opts['xAxisIndex'] = list(
            range(0, iWindows + 1))
        return grid