# 轴线配置 axisline_opts=opts.AxisLineOpts( is_show=True, # 显示轴线 # 设置轴线风格 linestyle_opts=opts.LineStyleOpts(color='gray')), # 设置对应的标签, {} 数据 axislabel_opts=opts.LabelOpts(formatter='{value}'))) # 设置全局配置 bar.set_global_opts( # 标题 title_opts=opts.TitleOpts( title='中国早期疫情变化趋势图', subtitle='郑州大学信息工程学院TedLau', subtitle_textstyle_opts=opts.TextStyleOpts( font_size=12, width='1.6', ), pos_left='3%', # title 的位置 pos_top='1%', ), # 图例 legend_opts=opts.LegendOpts( pos_left='25%', pos_top='7%', ), # 提示框 tooltip_opts=opts.TooltipOpts( trigger='axis', # 坐标轴。柱状图 axis_pointer_type='cross', # 十字准星指示 表示启用两个正交的轴 ), # 对纵轴的全局配置
series_name='疑似数', # 系列名称 y_axis=suspected_data, # 数据 yaxis_index=3) # 3、全局配置 bar.set_global_opts( # 标题配置 title_opts=opts.TitleOpts( title='中国疫情数据', # 主标题 subtitle='广州0624Python全体', # 子标题 pos_left='1%', # 标题的左位置 pos_top='3%', # 标题的上位置 # 设置主标题样式 title_textstyle_opts=opts.TextStyleOpts( font_style='normal', # 字体风格 font_weight='normal', # 字体的粗细 color='#FDF5E6', # 字体颜色 font_size=25, # 字体大小 ), # 设置子标题样式 subtitle_textstyle_opts=opts.TextStyleOpts( font_style='normal', # 字体风格 font_weight='normal', # 字体的粗细 color='#FDF5E6', # 字体颜色 font_size=20, # 字体大小 )), # 图例设置 legend_opts=opts.LegendOpts( type_='plain', # 图例类型 ,plain---普通类型 is_show=True, # 显示图例 pos_left='25%', pos_top='5%',
'''依赖模块 pip install jieba, pyecharts ''' from pyecharts import options as opts from pyecharts.charts import WordCloud import jieba with open('danmus.csv', encoding='utf-8') as f: text = " ".join([line.split(',')[-1] for line in f.readlines()]) words = jieba.cut(text) _dict = {} for word in words: if len(word) >= 2: _dict[word] = _dict.get(word, 0) + 1 items = list(_dict.items()) items.sort(key=lambda x: x[1], reverse=True) # for i in range(10): # word, count = items[i] # print(f'{word:<5}{count:>5}') c = (WordCloud().add( "", items, word_size_range=[20, 120], textstyle_opts=opts.TextStyleOpts(font_family="cursive"), ).render("wordCloud.html"))
def image_host_resource(doc_path, hosts_metrics, host): options = opts.InitOpts(js_host=os.path.join(os.getcwd(), "scripts/javascript/"), animation_opts=opts.AnimationOpts(animation=False)) line1 = (Line(options).add_xaxis( hosts_metrics[host['ip']]['metrics']['datetime'] ).add_yaxis( "CPU", hosts_metrics[host['ip']]['metrics']['cpu'], is_symbol_show=False, is_smooth=True, areastyle_opts=opts.AreaStyleOpts(color=utils.JsCode( "new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:'rgb(255,158,68)'},{offset:1,color:'rgb(255,70,131)'}])" ), opacity=0.5) ).add_yaxis( "Memory", hosts_metrics[host['ip']]['metrics']['memory'], is_symbol_show=False, is_smooth=True).set_series_opts(linestyle_opts=opts.LineStyleOpts( width=2)).set_global_opts( title_opts=opts.TitleOpts( title="主机资源使用率 (%s)" % (host['ip']), title_textstyle_opts=opts.TextStyleOpts(font_size=13), subtitle=" 数据来源-健康度平台"), xaxis_opts=opts.AxisOpts(type_="time"), yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts( formatter=utils.JsCode( "function(val){return val + '%';}"))))) line2 = (Line(options).add_xaxis( hosts_metrics[host['ip']]['metrics']['datetime'] ).add_yaxis( "Process", hosts_metrics[host['ip']]['metrics']['process'], is_symbol_show=False, is_smooth=True, areastyle_opts=opts.AreaStyleOpts(color=utils.JsCode( "new echarts.graphic.LinearGradient(0,0,0,1,[{offset:0,color:'#fff'},{offset:1,color:'#61a0a8'}])" ), opacity=0.5) ).set_series_opts(linestyle_opts=opts.LineStyleOpts( width=2)).set_global_opts( xaxis_opts=opts.AxisOpts( type_="time", position="top", axislabel_opts=opts.LabelOpts(is_show=False)), yaxis_opts=opts.AxisOpts(is_inverse=True), title_opts=opts.TitleOpts( title="应用运行数量(所有)", pos_bottom="0%", title_textstyle_opts=opts.TextStyleOpts(font_size=13)), legend_opts=opts.LegendOpts(pos_bottom="0%"))) grid = (Grid(options).add( line1, grid_opts=opts.GridOpts(pos_top=50, pos_left=50, pos_right=50, pos_bottom="50%")).add(line2, grid_opts=opts.GridOpts( pos_top="58%", pos_left=50, pos_right=50, pos_bottom=30))) make_snapshot( snapshot, grid.render( os.path.join(doc_path, "render_%s.html" % (host['ip'].replace(".", "_")))), os.path.join(doc_path, "host_res_%s.png" % (host['ip'].replace(".", "_"))), pixel_ratio=1, delay=1, is_remove_html=True)
def find_aggregation_render(x, y, flag, query, table_path, answer, y_name): colorList = ['#f36c6c', '#e6cf4e', '#20d180', '#0093ff'] x_sum = ["Sum"] Sum = [] Sum.append(sum(y)) mean = np.mean(y) y1 = [] y2 = [] for i in range(len(y)): if y[i] >= mean: y1.append(round(mean, 2)) y2.append( opts.BarItem(name=x[i], value=round(y[i] - mean, 2), label_opts=opts.LabelOpts(formatter="+{c}"), itemstyle_opts=opts.ItemStyleOpts(color="red"))) else: y1.append(round(y[i], 2)) y2.append( opts.BarItem(name=x[i], value=round(mean - y[i], 2), label_opts=opts.LabelOpts(formatter="-{c}"), itemstyle_opts=opts.ItemStyleOpts(color="green", opacity=0.3))) if flag == "mean": bar = Bar() bar.add_xaxis(x) bar.add_yaxis( '', y_axis=y1, stack='stack1', label_opts=opts.LabelOpts(is_show=False), color="white", markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(name="mean:", y=round(mean, 2))], label_opts=opts.LabelOpts(formatter="Mean:{c}", color="black"), linestyle_opts=opts.LineStyleOpts(color="gray")), ) bar.add_yaxis('', y_axis=y2, stack='stack1') bar.set_global_opts( datazoom_opts=[ opts.DataZoomOpts(range_start=10, range_end=90), opts.DataZoomOpts(type_="inside") ], xaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(rotate=40, font_size='100%'), name_textstyle_opts=opts.TextStyleOpts(font_size="100%")), yaxis_opts=opts.AxisOpts( min_=int(min(y) - (max(y) - min(y)) / 10), name=y_name, axislabel_opts=opts.LabelOpts(font_size="100%"), name_textstyle_opts=opts.TextStyleOpts(font_size="100%")), graphic_opts=[ opts.GraphicText( graphic_item=opts.GraphicItem( left="center", top="bottom", ), graphic_textstyle_opts=opts.GraphicTextStyleOpts( # 可以通过jsCode添加js代码,也可以直接用字符串 text=[ '\n' + "Q:" + ' ' + query + '\n' + "\n" + 'A:' + ' ' + answer ], font="14px Microsoft YaHei", graphic_basicstyle_opts=opts.GraphicBasicStyleOpts( fill="#333"))) ]) bar.render("aggregation.html") grid = Grid(init_opts=opts.InitOpts( width="100%", height="100%", renderer=globals.RenderType.SVG, )) grid.add(bar, grid_opts={'left': '15%', 'bottom': '34%'}) grid1 = Grid() grid1.add(bar, grid_opts={'left': '15%', 'bottom': '34%'}) grid1.render("mean.html") option1 = grid.dump_options_with_quotes() option1 = json.loads(option1) option = {"option": [option1], "query": query} return option elif flag == "sum": bar = Bar() bar.add_xaxis(x_sum) bar.add_yaxis('', Sum, label_opts=opts.LabelOpts(position="inside", formatter="Sum:{c}"), color=colorList[0]) for i in range(len(y)): Y = [] Y.append(y[i]) r = str(x[i]) bar.add_yaxis('', Y, stack='stack1', label_opts=opts.LabelOpts(position="inside", formatter=r + ":{c}"), tooltip_opts=opts.TooltipOpts(is_show=False)) bar.set_global_opts( datazoom_opts=[ opts.DataZoomOpts(range_start=10, range_end=90, orient="vertical"), opts.DataZoomOpts(type_="inside") ], graphic_opts=[ opts.GraphicText( graphic_item=opts.GraphicItem( left="center", top="bottom", ), graphic_textstyle_opts=opts.GraphicTextStyleOpts( # 可以通过jsCode添加js代码,也可以直接用字符串 text=[ '\n' + "Q:" + ' ' + query + '\n' + 'A:' + ' ' + answer ], font="14px Microsoft YaHei", graphic_basicstyle_opts=opts.GraphicBasicStyleOpts( fill="#333"))) ]) grid = Grid(init_opts=opts.InitOpts( width="100%", height="100%", renderer=globals.RenderType.SVG, )) grid.add(bar, grid_opts={'left': '15%', 'bottom': '34%'}) option1 = grid.dump_options_with_quotes() option1 = json.loads(option1) option = {"option": [option1], "query": query} return option
def get_year_chart(year: str, title1, title2): map_data = [[[x["name"], x["value"]] for x in d["data"]] for d in data if d["time"] == year][0] min_data, max_data = (minNum, maxNum) data_mark: List = [] i = 0 for x in time_list: if x == year: data_mark.append(total_num[i]) else: data_mark.append("") i = i + 1 map_chart = (Map().add( series_name="", data_pair=map_data, zoom=1, center=[119.5, 34.5], is_map_symbol_show=False, itemstyle_opts={ "normal": { "areaColor": "#323c48", "borderColor": "#404a59" }, "emphasis": { "label": { "show": Timeline }, "areaColor": "rgba(255,255,255, 0.5)", }, }, ).set_global_opts( title_opts=opts.TitleOpts( title="" + str(year) + title1, subtitle="", pos_left="center", pos_top="top", title_textstyle_opts=opts.TextStyleOpts( font_size=25, color="rgba(255,255,255, 0.9)"), ), tooltip_opts=opts.TooltipOpts( is_show=True, formatter=JsCode("""function(params) { if ('value' in params.data) { return params.data.value[2] + ': ' + params.data.value[0]; } }"""), ), visualmap_opts=opts.VisualMapOpts( is_calculable=True, dimension=0, pos_left="30", pos_top="center", range_text=["High", "Low"], range_color=["lightskyblue", "yellow", "orangered"], textstyle_opts=opts.TextStyleOpts(color="#ddd"), min_=min_data, max_=max_data, ), )) line_chart = (Line().add_xaxis(time_list).add_yaxis( "", total_num).add_yaxis( "", data_mark, markpoint_opts=opts.MarkPointOpts( data=[opts.MarkPointItem(type_="max")]), ).set_series_opts(label_opts=opts.LabelOpts( is_show=False)).set_global_opts(title_opts=opts.TitleOpts( title=title2, pos_left="72%", pos_top="5%"))) bar_x_data = [x[0] for x in map_data] bar_y_data = [{"name": x[0], "value": x[1][0]} for x in map_data] bar = (Bar().add_xaxis(xaxis_data=bar_x_data).add_yaxis( series_name="", yaxis_data=bar_y_data, label_opts=opts.LabelOpts(is_show=True, position="right", formatter="{b} : {c}"), ).reversal_axis().set_global_opts( xaxis_opts=opts.AxisOpts(max_=maxNum, axislabel_opts=opts.LabelOpts(is_show=False)), yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(is_show=False)), tooltip_opts=opts.TooltipOpts(is_show=False), visualmap_opts=opts.VisualMapOpts( is_calculable=True, dimension=0, pos_left="10", pos_top="top", range_text=["High", "Low"], range_color=["lightskyblue", "yellow", "orangered"], textstyle_opts=opts.TextStyleOpts(color="#ddd"), min_=min_data, max_=max_data, ), )) pie_data = [[x[0], x[1][0]] for x in map_data] pie = (Pie().add( series_name="", data_pair=pie_data, radius=["15%", "35%"], center=["80%", "82%"], itemstyle_opts=opts.ItemStyleOpts(border_width=1, border_color="rgba(0,0,0,0.3)"), ).set_global_opts( tooltip_opts=opts.TooltipOpts(is_show=True, formatter="{b} {d}%"), legend_opts=opts.LegendOpts(is_show=False), )) grid_chart = (Grid().add( bar, grid_opts=opts.GridOpts(pos_left="10", pos_right="45%", pos_top="50%", pos_bottom="5"), ).add( line_chart, grid_opts=opts.GridOpts(pos_left="65%", pos_right="80", pos_top="10%", pos_bottom="50%"), ).add(pie, grid_opts=opts.GridOpts(pos_left="45%", pos_top="60%")).add( map_chart, grid_opts=opts.GridOpts())) return grid_chart
from pyecharts import options as opts from pyecharts.charts import WordCloud import json # 生成tag频率词云图 f = open('tag_wordcloud_data.json', encoding='utf-8') res = f.read() data = json.loads(res) words = [] for k in data.keys(): words.append((k, data[k])) c = (WordCloud().add( "", words, word_size_range=[20, 100], textstyle_opts=opts.TextStyleOpts(), ).set_global_opts(title_opts=opts.TitleOpts( title="tag-WordCloud")).render("tag_wordcloud_diamond.html"))
def draw_charts(echarts_data): kline_data = echarts_data["data"] date = echarts_data["date"] kline = ( Kline().add_xaxis(xaxis_data=date).add_yaxis( series_name="Dow-Jones index", y_axis=kline_data, itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c"), ).set_global_opts( legend_opts=opts.LegendOpts(is_show=False, pos_bottom=10, pos_left="center"), # 其中inside是支持鼠标缩放 datazoom_opts=[ opts.DataZoomOpts( is_show=True, type_="inside", xaxis_index=[0, 1, 2, 3, 4], range_start=50, range_end=100, ), opts.DataZoomOpts( is_show=True, xaxis_index=[0, 1, 2, 3, 4], type_="slider", range_start=50, range_end=100, ), ], # # 不知道为什么要分开三个写,可能是想通过xaxis_index分别配置 # datazoom_opts=[ # opts.DataZoomOpts( # is_show=False, type_="inside", xaxis_index=[0, 0], range_end=100 # ), # opts.DataZoomOpts( # is_show=True, xaxis_index=[0, 1], pos_top="97%", range_end=100 # ), # opts.DataZoomOpts(is_show=False, xaxis_index=[0, 2], range_end=100), # ], yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), title_opts=opts.TitleOpts(title="my_echart"), tooltip_opts=opts.TooltipOpts( trigger="axis", axis_pointer_type="cross", background_color="rgba(245, 245, 245, 0.8)", border_width=1, border_color="#ccc", textstyle_opts=opts.TextStyleOpts(color="#000"), ), visualmap_opts=opts.VisualMapOpts( is_show=False, dimension=2, series_index=5, is_piecewise=True, pieces=[ { "value": 1, "color": "#00da3c" }, { "value": -1, "color": "#ec0000" }, ], ), # 所有图的axis 连在一块 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=date).add_yaxis( series_name="MA5", y_axis=echarts_data['ma5'], is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, # 去掉折线上的小圆点 ).add_yaxis( series_name="MA20", y_axis=echarts_data['ma20'], is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, # 去掉折线上的小圆点 ).set_global_opts(xaxis_opts=opts.AxisOpts(type_="category"))) # Kline And Line overlap_kline_line = kline.overlap(line) bar = ( Bar().add_xaxis(xaxis_data=date).add_yaxis( series_name="Volume", y_axis=echarts_data['volume'], 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", 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), )) # Bar-2 (Overlap Bar + Line) bar_2 = ( Bar().add_xaxis(xaxis_data=date).add_yaxis( series_name="MACD", y_axis=echarts_data['macd'], 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), # 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, ), yaxis_opts=opts.AxisOpts( grid_index=2, split_number=4, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=True), ), legend_opts=opts.LegendOpts(is_show=False), )) macd_line = ( Line().add_xaxis(xaxis_data=date).add_yaxis( series_name="DIFF", y_axis=echarts_data['macd_diff'], # xaxis_index=2, # yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="DEA", y_axis=echarts_data["macd_dea"], # xaxis_index=2, # yaxis_index=2, is_symbol_show=False, # 去掉折线上的小圆点 label_opts=opts.LabelOpts(is_show=False), ) # .set_global_opts(legend_opts=opts.LegendOpts(is_show=False)) # .set_global_opts(xaxis_opts=opts.AxisOpts(type_="category")) ) # MACD BAR And MACD Line bar_macd_line = bar_2.overlap(macd_line) # KDJ kdj_line = ( Line().add_xaxis(xaxis_data=date).add_yaxis( series_name="K", y_axis=echarts_data['kdj_k'], is_symbol_show=False, # 去掉折线上的小圆点 label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="D", y_axis=echarts_data["kdj_d"], is_symbol_show=False, # 去掉折线上的小圆点 label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="J", y_axis=echarts_data["kdj_j"], is_symbol_show=False, # 去掉折线上的小圆点 label_opts=opts.LabelOpts(is_show=False), # markline_opts=opts.MarkLineOpts( # data=[100] # ), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=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, ), )) ###################### ## kdj的macd # Bar-2 (Overlap Bar + Line) macd_kdj_bar = ( Bar().add_xaxis(xaxis_data=date).add_yaxis( series_name="MACD_KDJ", y_axis=echarts_data['kdj_macd'], 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), # 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, ), yaxis_opts=opts.AxisOpts( grid_index=2, split_number=4, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=True), ), legend_opts=opts.LegendOpts(is_show=False), )) macd_kdj_line = ( Line().add_xaxis(xaxis_data=date).add_yaxis( series_name="KDJ_DIFF", y_axis=echarts_data['kdj_macd_diff'], # xaxis_index=2, # yaxis_index=2, is_symbol_show=False, # 去掉折线上的小圆点 label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="KDJ_DEA", y_axis=echarts_data["kdj_macd_dea"], # xaxis_index=2, # yaxis_index=2, is_symbol_show=False, # 去掉折线上的小圆点 label_opts=opts.LabelOpts(is_show=False), ) # .set_global_opts(legend_opts=opts.LegendOpts(is_show=False)) # .set_global_opts(xaxis_opts=opts.AxisOpts(type_="category")) ) # MACD BAR And MACD Line bar_macd_kdj_line = macd_kdj_bar.overlap(macd_kdj_line) ###################### # Grid Overlap + Bar grid_chart = Grid(init_opts=opts.InitOpts( width="1000px", height="800px", animation_opts=opts.AnimationOpts(animation=False), )) # 这个是为了把 data.datas 这个数据写入到 html 中,还没想到怎么跨 series 传值 # demo 中的代码也是用全局变量传的 grid_chart.add_js_funcs("var barData = {}".format(kline_data)) grid_chart.add( overlap_kline_line, grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", height="30%"), ) grid_chart.add( bar, grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top="35%", height="10%"), ) # 加上MACD grid_chart.add( bar_macd_line, grid_opts=opts.GridOpts( pos_left="10%", pos_right="8%", pos_top="45%", height="10%", ), ) # 加上KDJ grid_chart.add( kdj_line, grid_opts=opts.GridOpts( pos_left="10%", pos_right="8%", pos_top="55%", height="10%", ), ) # 加上KDJ的MACD grid_chart.add( bar_macd_kdj_line, grid_opts=opts.GridOpts( pos_left="10%", pos_right="8%", pos_top="65%", height="10%", ), ) grid_chart.render("300368.html")
axislabel_opts=opts.LabelOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), ), radiusaxis_opts=opts.RadiusAxisOpts( min_=0, max_=7, interval=1, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), splitline_opts=opts.series_options.SplitLineOpts(is_show=True, linestyle_opts={'color':'grey','opacity':0.8}) ), polar_opts=opts.PolarOpts(), splitline_opt=opts.SplitLineOpts(is_show=False), textstyle_opts=opts.TextStyleOpts(color="black"), ) .add( series_name="美国队长", data=captain_america, areastyle_opts=opts.AreaStyleOpts(opacity=0.1), linestyle_opts=opts.LineStyleOpts(width=1), ) .add( series_name="钢铁侠", data=iron_man, areastyle_opts=opts.AreaStyleOpts(opacity=0.1), linestyle_opts=opts.LineStyleOpts(width=1), ) .add( series_name="黑寡妇",
def draw_chart(df, extend_field, save_path="", trade_list=None, kline_title="买卖点K线图"): datetime_array = df.datetime.tolist() volume_array = df.volume.tolist() # open close low high kline_data = df[["open", "close", "low", "high"]].values.tolist() point_list = [] if trade_list is None: trade_list = [] for trade in trade_list: # 开多 if type(trade[0]) == str: trade_datetime = trade[0] else: trade_datetime = trade[0].strftime("%Y-%m-%d %H:%M:%S") if trade_datetime < datetime_array[0]: continue if trade[1] == "多" and trade[4] == "开": point_list.append( opts.MarkPointItem( name="开多", coord=[trade_datetime, trade[6]], value="开多", itemstyle_opts=opts.ItemStyleOpts(color="#ef232a"))) # 开空 elif trade[1] == "空" and trade[4] == "开": point_list.append( opts.MarkPointItem( name="开空", coord=[trade_datetime, trade[6]], value="开空", itemstyle_opts=opts.ItemStyleOpts(color="#ef232a"))) # 平多 elif trade[1] == "多" and (trade[4] == "平" or trade[4] == "平今" or trade[4] == "平昨"): point_list.append( opts.MarkPointItem( name="平空", coord=[trade_datetime, trade[6]], value="平空", itemstyle_opts=opts.ItemStyleOpts(color="#14b143"))) # 平空 elif trade[1] == "空" and (trade[4] == "平" or trade[4] == "平今" or trade[4] == "平昨"): point_list.append( opts.MarkPointItem( name="平多", coord=[trade_datetime, trade[6]], value="平多", itemstyle_opts=opts.ItemStyleOpts(color="#14b143"))) kline = (Kline().add_xaxis(xaxis_data=datetime_array).add_yaxis( series_name="Kline", y_axis=kline_data, itemstyle_opts=opts.ItemStyleOpts( color="#ef232a", color0="#14b143", border_color="#ef232a", border_color0="#14b143", ), markpoint_opts=opts.MarkPointOpts(data=point_list), ).set_global_opts( title_opts=opts.TitleOpts(title=kline_title, pos_left="2%", pos_top="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="88%", range_start=0, range_end=100, ), ], yaxis_opts=opts.AxisOpts( is_scale=True, splitline_opts=opts.SplitLineOpts(is_show=True)), tooltip_opts=opts.TooltipOpts( trigger="axis", axis_pointer_type="cross", background_color="rgba(245, 245, 245, 0.8)", border_width=1, border_color="#ccc", textstyle_opts=opts.TextStyleOpts(color="#000"), ), visualmap_opts=opts.VisualMapOpts( is_show=False, dimension=2, series_index=5, is_piecewise=True, pieces=[ { "value": 1, "color": "#00da3c" }, { "value": -1, "color": "#ec0000" }, ], ), axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), )) bar = (Bar().add_xaxis(xaxis_data=datetime_array).add_yaxis( series_name="Volume", yaxis_data=volume_array, 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), )) if len(extend_field) > 0: line = (Line().add_xaxis( xaxis_data=datetime_array).set_global_opts( xaxis_opts=opts.AxisOpts(type_="category"), legend_opts=opts.LegendOpts(is_show=True), )) for field in extend_field: field_value_array = df[field].tolist() line.add_yaxis( series_name=field, y_axis=field_value_array, is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.8), label_opts=opts.LabelOpts(is_show=False), ) # Kline And Line kline = kline.overlap(line) # Grid Overlap + Bar grid_chart = Grid(init_opts=opts.InitOpts( width="100%", height="760px", animation_opts=opts.AnimationOpts(animation=False), )) grid_chart.add( kline, grid_opts=opts.GridOpts(pos_left="3.5%", pos_right="3.5%", height="60%"), ) grid_chart.add( bar, grid_opts=opts.GridOpts(pos_left="3.5%", pos_right="3.5%", pos_top="70%", height="16%"), ) grid_chart.render(os.path.join(save_path, "KLineChart.html"))
def draw_daily_results_chart(daily_df, save_path): """绘制资金曲线图""" date_list = daily_df.index.values.tolist() balance_list = daily_df.balance.values.tolist() draw_down_list = daily_df.drawdown.values.tolist() net_pnl_list = daily_df.net_pnl.values.tolist() line1 = (Line().add_xaxis(xaxis_data=date_list).add_yaxis( series_name="Balance", y_axis=balance_list, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=2), ).set_global_opts( title_opts=opts.TitleOpts(title="回测资金曲线", pos_left="center"), 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_="category", boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=True), ), legend_opts=opts.LegendOpts(pos_left="1%"), yaxis_opts=opts.AxisOpts( type_="value", is_scale=True, splitline_opts=opts.SplitLineOpts(is_show=True), ), axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), datazoom_opts=[ opts.DataZoomOpts(range_start=0, range_end=100), opts.DataZoomOpts(type_="inside", range_start=0, range_end=100, xaxis_index=[0, 1, 2]), ], )) line2 = (Line().set_global_opts( tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"), xaxis_opts=opts.AxisOpts( type_="category", boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=True), position="top", axislabel_opts=opts.LabelOpts(is_show=False), ), legend_opts=opts.LegendOpts(pos_left="9%"), yaxis_opts=opts.AxisOpts( type_="value", is_scale=True, splitline_opts=opts.SplitLineOpts(is_show=True), ), axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), ).add_xaxis(xaxis_data=date_list).add_yaxis( series_name="Draw Down", y_axis=draw_down_list, label_opts=opts.LabelOpts(is_show=False), areastyle_opts=opts.AreaStyleOpts(opacity=0.5), )) bar3 = (Bar().set_global_opts( tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"), xaxis_opts=opts.AxisOpts( type_="category", boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=True), axislabel_opts=opts.LabelOpts(is_show=False), ), legend_opts=opts.LegendOpts(pos_left="19%"), yaxis_opts=opts.AxisOpts( type_="value", is_scale=True, splitline_opts=opts.SplitLineOpts(is_show=True), ), axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), ).add_xaxis(xaxis_data=date_list).add_yaxis( series_name="Daily Pnl", yaxis_data=net_pnl_list, label_opts=opts.LabelOpts(is_show=False))) (Grid(init_opts=opts.InitOpts(width="100%", height="720px")).add( chart=line1, grid_opts=opts.GridOpts(pos_left=50, pos_right=50, height="35%")).add( chart=line2, grid_opts=opts.GridOpts(pos_left=50, pos_right=50, pos_top="48%", height="20%"), ).add( chart=bar3, grid_opts=opts.GridOpts(pos_left=50, pos_right=50, pos_top="71%", height="20%"), ).render(os.path.join(save_path, "daily_results.html")))
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) ) .render(title + '.html') )
def Candle_render_output(x_date, y_data, vol_data) -> Grid: # ydata type : open close low high # vol_data is for bar print('Candle_render_output') kline = (Kline().add_xaxis(xaxis_data=x_date).add_yaxis( series_name="Dow-Jones index", y_axis=y_data, itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c"), ).set_global_opts( title_opts=opts.TitleOpts( title="Kline)", subtitle="MA(5, 10, 30, 60)", ), 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", ), )) bar = ( Bar().add_xaxis(xaxis_data=x_date).add_yaxis( series_name="Volume", # yaxis_data=[ # [i, y_data[i][3], 1 if y_data[i][0] > y_data[i][1] else -1] # for i in range(len(y_data)) # ], yaxis_data=vol_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), )) lines = Kline_ma_line(x_date, y_data) kline = kline.overlap(lines) # Grid Overlap + Bar grid_chart = Grid() grid_chart.add(kline, 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
def show_pyecharts(): x_data = [ '0.0', '0.1', '0.2', '0.3', '0.4', '0.5', '0.6', '0.7', '0.8', '0.9', '1.0' ] y_data = [ '1533', '573', '502', '491', '520', '556', '577', '788', '1252', '20564', '6393' ] #情感分析柱状图 bar = (Bar().add_xaxis(x_data).add_yaxis( "情感分析", y_data, label_opts=opts.LabelOpts(is_show=False), color='#3498DB').set_global_opts(title_opts={ "text": "台海舆论情感分析", "subtext": "大于0.5为正面评价,小于0.5为负面评价" })) #台湾网饼图 x_data2 = [ "文化", "经贸", "媒体专栏", "网友专栏", "两岸专家", "两岸", "台商", "部委", "台海时事", "网友快言", "海峡时评", "两岸快评" ] y_data2 = [553, 553, 35, 39, 448, 465, 553, 321, 553, 406, 553, 556] pie = (Pie(init_opts=opts.InitOpts(theme=ThemeType.CHALK)).add( series_name="中国台湾网", data_pair=[list(z) for z in zip(x_data2, y_data2)], radius=["50%", "70%"], label_opts=opts.LabelOpts(is_show=False, position="center"), ).set_colors([ "#E8F8F5", "#D1F2EB", "#A3E4D7", "#76D7C4", "#48C9B0", "#1ABC9C", "#17A589", "#148F77", "#117864", "#0E6251F", "#73C6B6", "#45B39D" ]).set_global_opts(legend_opts=opts.LegendOpts( pos_left="legft", orient="vertical")).set_series_opts( tooltip_opts=opts.TooltipOpts( trigger="item", formatter="{a} <br/>{b}: {c} ({d}%)"), )) #词云图 word = (WordCloud().add( "", list1, word_size_range=[20, 100], shape=SymbolType.DIAMOND, textstyle_opts=opts.TextStyleOpts(font_family="cursive"), )) #折线图1 y2[0], y2[1], y2[2] = None, None, None y4[1] = None line = (Line().add_xaxis(xaxis_data=x1).add_yaxis( series_name="微博", symbol="emptyCircle", is_symbol_show=True, color="#F2D7D5", y_axis=y1, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3)).add_yaxis( series_name="环球网", symbol="emptyCircle", is_symbol_show=True, color="#C0392B", y_axis=y2, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3)).add_yaxis( series_name="中国台湾网", symbol="emptyCircle", is_symbol_show=True, color="#641E16", y_axis=y3, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3)).add_yaxis( series_name="知乎", symbol="emptyCircle", is_symbol_show=True, color="#9B59B6", y_axis=y4, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3)).add_yaxis( series_name="中国日报网", symbol="emptyCircle", is_symbol_show=True, color="#512E5F", y_axis=y5, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3)).add_yaxis( series_name="中新网", symbol="emptyCircle", is_symbol_show=True, color="#2980B9", y_axis=y6, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3)). add_yaxis( series_name="今日头条", symbol="emptyCircle", is_symbol_show=True, color="#154360", y_axis=y7, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3)).add_yaxis( series_name="光明网", symbol="emptyCircle", is_symbol_show=True, color="#3498DB", y_axis=y8, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3)).add_yaxis( series_name="凤凰网", symbol="emptyCircle", is_symbol_show=True, color="#1ABC9C", y_axis=y9, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3)).add_yaxis( series_name="新华网", symbol="emptyCircle", is_symbol_show=True, color="#0E6251", y_axis=y10, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts( width=3)).set_global_opts( tooltip_opts=opts.TooltipOpts( trigger="axis"), yaxis_opts=opts.AxisOpts( type_="value", axistick_opts=opts.AxisTickOpts( is_show=True), splitline_opts=opts.SplitLineOpts( is_show=True), ), xaxis_opts=opts.AxisOpts( type_="category", boundary_gap=False, axisline_opts=opts.AxisLineOpts( is_on_zero=False, linestyle_opts=opts.LineStyleOpts( color="#d14a61"))), )) #平台占比饼图 x_data3 = [ "微博", "知乎", "中国台湾网", "环球网", "日报网", "中新网", "今日头条", "光明网", "凤凰网", "新华网" ] y_data3 = [5401, 157, 5035, 3245, 4296, 5574, 1891, 3131, 1052, 1997] data_pair = [list(z) for z in zip(x_data3, y_data3)] data_pair.sort(key=lambda x: x[1]) pie2 = (Pie(init_opts=opts.InitOpts(theme=ThemeType.ROMA)).add( series_name="访问来源", data_pair=data_pair, rosetype="radius", radius="55%", center=["50%", "50%"], label_opts=opts.LabelOpts(is_show=False, position="center"), ).set_series_opts(label_opts=opts.LabelOpts(formatter="{b}:{d}%"))) #折线图2 line2 = (Line().add_xaxis(xaxis_data=x_data4).add_yaxis( series_name="热度走势", y_axis=y_data4, color="#FF69B4", markpoint_opts=opts.MarkPointOpts( data=[opts.MarkPointItem(type_="max")]), symbol="emptyCircle", is_symbol_show=True, is_smooth=True, label_opts=opts.LabelOpts(is_show=True), ).set_global_opts( tooltip_opts=opts.TooltipOpts(is_show=False), yaxis_opts=opts.AxisOpts( type_="value", axistick_opts=opts.AxisTickOpts(is_show=True), splitline_opts=opts.SplitLineOpts(is_show=True), ), xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False, axislabel_opts=opts.LabelOpts(rotate=45)), )) #条形图 line3 = (Bar().add_xaxis(x_data5).add_yaxis( "平均值", y_data5, label_opts=opts.LabelOpts(is_show=False), color='#6A5ACD').reversal_axis().extend_axis(yaxis=opts.AxisOpts( type_='value', name='转发次数', position='left', )).set_global_opts( title_opts={"text": "评论与转发关系图"}, xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts( formatter='{value}(评论数量)')), )) #圆 radius = (Polar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT)).add_schema( radiusaxis_opts=opts.RadiusAxisOpts(data=x_data6, type_="category"), angleaxis_opts=opts.AngleAxisOpts(is_clockwise=True, max_=100000), ).add("点赞数量", y_data6, type_="bar").set_global_opts( title_opts=opts.TitleOpts(title="")).set_series_opts( label_opts=opts.LabelOpts(is_show=True))) return render_template("index2.html", bar_data=bar.dump_options(), word_data=word.dump_options(), pie_data=pie.dump_options(), pie2_data=pie2.dump_options(), line_data=line.dump_options(), line2_data=line2.dump_options(), line3_data=line3.dump_options(), radius_data=radius.dump_options())
["河口县", '没有数据']] m = (Map(init_opts=opts.InitOpts()).add( series_name="红河州各县市人口密度", maptype="红河哈尼族彝族自治州", data_pair=MAP_DATA, is_map_symbol_show=True, zoom=0.8).set_global_opts( tooltip_opts=opts.TooltipOpts(trigger="item", formatter="{b}<br/>{c} (人 / km2)"), visualmap_opts=opts.VisualMapOpts( range_color=["lightskyblue", "yellow", "orangered"], ), legend_opts=opts.LegendOpts(pos_top="15%", item_height=24, item_width=30, textstyle_opts=opts.TextStyleOpts( font_size=18, color='#28b2c7')))) # 词云 词条热词 words = get_count('honghe.txt') yun = (WordCloud().add( "", words, word_size_range=[5, 40], shape='star', width=640, height=480, pos_top='50%', pos_right='5%', pos_left='66%').set_global_opts(title_opts=opts.TitleOpts(title="红河热词"))) grid = Grid(init_opts=opts.InitOpts(width="1920px",
def candlechart(self,str_tscode=None,subset='masterCandle',dat_cursor=None,MA=[5,10,21], renderfile=False) -> Grid: str_tscode = DataAgent.formatCode(str_tscode) int_chartsize = 500 if str_tscode == False or str_tscode is None: print('invalid sec code provided...') return False dat_cursor = datetime.now().astimezone(timezone(cfg.STR_TIMEZONE)) if dat_cursor is None else dat_cursor closestTradeDate = self.da.int_findClosestTradeDate(datetime.strftime(dat_cursor,'%Y%m%d') ) tpl_dateindex = tuple(str(i) for i in self.da.df_calTbl.loc[self.da.df_calTbl['cal_date'] <= closestTradeDate]['cal_date'][-int_chartsize:] ) # 连接储存对象 if subset=='masterCandle': data_store = libs.tryOpenH5(cfg.H5_FILE_PRE,mode='r') else: data_store = libs.tryOpenH5('{}{}.dat'.format(cfg.H5_FILE_PATH,subset),mode='r') # 初始化交易日表格,作为标准交易日序列join个股交易数据 df_toPlot = data_store['masterCandle'].loc[data_store['masterCandle']['ts_code']==str_tscode] df_dateindex = pd.DataFrame({'trade_caldate': tpl_dateindex}).astype(int) data_store.close() try: str_secname = self.da.df_lookupTbl.loc[self.da.df_lookupTbl['ts_code']==str_tscode]['name'].values[0] str_sectype = self.da.df_lookupTbl.loc[self.da.df_lookupTbl['ts_code']==str_tscode]['sec_type'].values[0] except Exception as e: return libs.log_csv(str_cat='WARNING',str_op='candlechart',str_desc='security code {} does not exist in basic info table...'.format(str_tscode)) str_plotname = '{} - {}'.format(str_tscode,str_secname) # 交易日时间轴标准化,补全停牌日,当日live数据等k线 '''------ 获取实时交易数据部分--------------------''' int_liveDate = self.da.int_findClosestTradeDate(datetime.strftime(datetime.now().astimezone(timezone(cfg.STR_TIMEZONE)),'%Y%m%d') ) if int_liveDate<=closestTradeDate and int_liveDate>df_toPlot['trade_date'].max(): df_liveQuote = self.da.query('quote_now',[self.da.formatCode(str_tscode,False),]) if len(df_liveQuote)>0: df_liveQuote.rename(columns={'open':'adj_open', 'high':'adj_high', 'low':'adj_low', 'price':'adj_close', 'volume':'vol', 'amount':'amount'}, inplace=True) df_liveQuote=df_liveQuote.astype(dtype= {'adj_open':'float','adj_high':'float','adj_low':'float','adj_close':'float','vol':'float','amount':'float'}) df_liveQuote['trade_date'] = int_liveDate df_liveQuote['ts_code'] = str_tscode df_liveQuote['vol'] = df_liveQuote['vol']/100 if str_sectype==1 or str_tscode[:3]=='399' else df_liveQuote['vol'] df_liveQuote['amount'] = df_liveQuote['amount']/1000 df_toPlot = df_toPlot.append(df_liveQuote[['ts_code','trade_date','adj_open','adj_high','adj_low','adj_close','vol','amount']],sort=False) '''------ 结束 获取实时交易数据部分--------------------''' df_toPlot = pd.merge(df_dateindex, df_toPlot, left_on='trade_caldate', right_on='trade_date', how='left') df_toPlot['close'].fillna(method='ffill',inplace=True) df_toPlot['ts_code'].fillna(method='ffill',inplace=True) df_toPlot['klineSML'].fillna('NNNN',inplace=True) df_toPlot['adj_close'].fillna(method='ffill',inplace=True) df_toPlot['vol'].fillna(value=0,inplace=True) df_toPlot['amount'].fillna(value=0,inplace=True) df_toPlot['open'].fillna(df_toPlot['close'],inplace=True) df_toPlot['high'].fillna(df_toPlot['close'],inplace=True) df_toPlot['low'].fillna(df_toPlot['close'],inplace=True) df_toPlot['adj_open'].fillna(df_toPlot['adj_close'],inplace=True) df_toPlot['adj_high'].fillna(df_toPlot['adj_close'],inplace=True) df_toPlot['adj_low'].fillna(df_toPlot['adj_close'],inplace=True) self.kchartdf = df_toPlot #输出至可访问对象属性中 '''-----------------画图部分---------------------''' lst_ohlcv=df_toPlot.loc[:,['adj_open','adj_close','adj_low','adj_high']].values.tolist() lst_vol=list(df_toPlot['vol'].values) lst_amount=list(df_toPlot['amount'].values) lst_peaks=list(abs(df_toPlot['peaks'].values)) # lst_pivotdown=[float('nan') if i<0 else i for i in list(df_toPlot['pivots'].values)] lst_pivotdown=[float('nan') if i<0 else i for i in list(df_toPlot['valid_pivots'].values)] # lst_pivotup=[float('nan') if i>0 else abs(i) for i in list(df_toPlot['pivots'].values)] lst_pivotup=[float('nan') if i>0 else abs(i) for i in list(df_toPlot['valid_pivots'].values)] lst_xaxis=list(df_toPlot['trade_caldate'].astype(str)) 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="交易量", yaxis_data=[ [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="交易额", yaxis_data=[ [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
def plot_positions(self, position_list): lst_xaxis = self.df_unitAxis.loc[ self.df_unitAxis['timeAxis'] >= self.trade_start]['unit_intdate'].astype(str).values.tolist( ) # xaxis values has to be STRING type, int will not work linechart = (Line().add_xaxis(lst_xaxis)) # heartbeat的dateindex个数会>=position的timeindex个数,因为并不是没一轮market event循环都会有signal,order等事件触发,由此并不是每天都会生成position for pos in position_list: if pos.fname is not None: df = pd.read_csv(pos.fname, encoding=cfg.FILE_ENCODE) df_cash = df.loc[df['ts_code'] == 'cash'].groupby( 'timeindex').agg({'market_value': 'sum'}) df = df.groupby('timeindex').agg({'market_value': 'sum'}) linename = '{}持仓'.format(pos.name) linename_cash = '{}现金持仓'.format(pos.name) assert lst_xaxis == df.index.astype(str).values.tolist() lst_values = df['market_value'].values.tolist() lst_valuesCash = df_cash['market_value'].values.tolist() linechart.add_yaxis( linename, lst_values, is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.3), label_opts=opts.LabelOpts(is_show=False), ) linechart.add_yaxis( linename_cash, lst_valuesCash, is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.3), label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color="#bbbbbb", ), ) linechart.set_global_opts( title_opts=opts.TitleOpts(title='持仓曲线', ), xaxis_opts=opts.AxisOpts(type_="category"), yaxis_opts=opts.AxisOpts( name="市场价值(元)", is_scale=True, ), legend_opts=opts.LegendOpts(is_show=True, pos_top='5%', pos_left="center"), datazoom_opts=[ opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0], range_start=75, range_end=100, ), opts.DataZoomOpts( is_show=True, xaxis_index=[0], 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), ), 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", ), ) # put everything in a grid for easy resizing and positioning gridChart = Grid() gridChart.add( linechart, grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top='25%'), ) fname = f'{cfg.PATH_POSFILE}{pos.name}.html' gridChart.render(fname) self.chart = gridChart #输出至可访问对象属性中
def corelationMacro(self,dat_cursor=None,lst_tscode=['399002.SZ'],lst_macro=['shibor.on','PIMon.cpi'],lst_findmedian=['pe',()],renderfile=False) -> Line: lst_findmedian[1] = tuple(self.da.df_stockTbl['ts_code']) if lst_findmedian[1] is None else lst_findmedian[1] if dat_cursor is None: dat_cursor = datetime.now().astimezone(timezone(cfg.STR_TIMEZONE)) int_latestViewDate = self.da.int_findClosestTradeDate(datetime.strftime(dat_cursor,'%Y%m%d') ) df_baseCal = self.da.df_calTbl.loc[self.da.df_calTbl['cal_date']<=int_latestViewDate]['cal_date'].copy() lst_xaxis = ['{}/{}/{}'.format(i[:4],i[4:6],i[6:]) for i in df_baseCal.values.astype('str')] linechart = ( Line() .add_xaxis(lst_xaxis) ) for code in lst_tscode: str_tscode = DataAgent.formatCode(code) df_target = self.da.query('load_alldaily',tpl_dateindex=tuple(df_baseCal),ts_code=str_tscode) if len(df_target)>0: df_toPlot = pd.merge(left=df_baseCal, right=df_target, how='left', left_on='cal_date', right_on='trade_date') else: continue linename = '{} - {}'.format(str_tscode,self.da.df_lookupTbl.loc[self.da.df_lookupTbl['ts_code']==str_tscode]['name'].values[0]) lst_values = list(df_toPlot['close']) lst_values = list(Analytics.normByRange(lst_values)) linechart.add_yaxis(linename, lst_values, is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.3), label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts( color="#00da3c", ), ) try: lst_pe = df_toPlot['pe'].values.tolist() lst_pb = df_toPlot['pb'].values.tolist() lst_pepb = [round(lst_pe[index]/value,2) for index, value in enumerate(lst_pb) if value!=0] linechart.add_yaxis(str_tscode+"_PE", lst_pe, yaxis_index=1, #倍数使用右y轴 is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=1), label_opts=opts.LabelOpts(is_show=False), ) linechart.add_yaxis(str_tscode+"_PE/PB", lst_pepb, yaxis_index=1, #倍数使用右y轴 is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=1), label_opts=opts.LabelOpts(is_show=False), ) except: continue df_shibor = self.da.query('load_shibor') # print('Supported shibor columns: {}'.format(df_shibor.columns)) df_pimon = self.da.query('load_piMon') # print('Supported macro eco columns: {}'.format(df_pimon.columns)) for item in lst_macro: try: topic,colname = item.split('.') except: print('WARNING! input code {} not understood...'.format(item)) if topic=='shibor': df_target = df_shibor maxarr = df_target.max(axis=0, skipna=True).values[1:] minarr = df_target.min(axis=0, skipna=True).values[1:] deltaRng = max(maxarr)-min(minarr) # overwrite the normalization function delta to put all shibor rates comparable elif topic=='pimon': df_target = df_pimon deltaRng = None else: print('WARNING! subject code {} is not understood...'.format(topic)) if len(df_target)>0: df_toPlot = pd.merge(df_baseCal, df_target, how='left', left_on='cal_date', right_on='date') df_toPlot[colname] = df_toPlot[colname].bfill() else: continue linename = item lst_values = list(df_toPlot[colname]) lst_values = list(Analytics.normByRange(lst_values,delta=deltaRng)) linechart.add_yaxis(linename, lst_values, # 所有等比例缩放的折线都放在linechart里,使用左侧y轴 is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=1,opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ) str_cat = lst_findmedian[0] df_result = pd.DataFrame() for str_tscode in lst_findmedian[1]: try: df = self.da.query('load_alldaily',tpl_dateindex=tuple(df_baseCal),ts_code=str_tscode)[['ts_code','trade_date',str_cat]] print('{} csv file loaded for {} trend analysis...'.format(str_tscode,str_cat),end='\r') except Exception as e: print('WARNING! {} csv file not found...'.format(str_tscode)) continue df_result = pd.concat([df_result,df]) df_result.dropna(subset=[str_cat],inplace=True) df_result = df_result.loc[df_result['trade_date']>19940301] # libs.df_csv(cfg.PATH_BUGFILE,(df_result.groupby('trade_date')['ts_code'].count(),)) # print(df_result.groupby('trade_date')['ts_code'].count()) df_target = df_result.groupby('trade_date')[str_cat].median() if len(df_target)>0: df_toPlot = pd.merge(left=df_baseCal, right=df_target, how='left', left_on='cal_date', right_on='trade_date') linename = '{}-median'.format(str_cat) lst_values = list(df_toPlot[str_cat]) lst_values = list(lst_values) linechart.add_yaxis(linename, lst_values, yaxis_index=1, is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=1), label_opts=opts.LabelOpts(is_show=False), ) linechart.extend_axis( # 所有保持原比例的折线都放在linechart2里,使用右侧y轴 yaxis=opts.AxisOpts( name="倍数", type_="value", position="right", axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="black") ), axislabel_opts=opts.LabelOpts(formatter="{value}倍"), ) ) linechart.set_global_opts( title_opts=opts.TitleOpts( title='宏观比较', ), xaxis_opts=opts.AxisOpts(type_="category"), yaxis_opts=opts.AxisOpts(name="等比例", is_scale=True, ), legend_opts=opts.LegendOpts(is_show=True, pos_top='5%', pos_left="center"), datazoom_opts=[ opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0], range_start=75, range_end=100, ), opts.DataZoomOpts( is_show=True, xaxis_index=[0], 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), ), 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", ), ) fname = '{}{}.html'.format(cfg.PATH_ANAFILE,'macro') linechart.render(fname) else: pass fname = '{}{}.html'.format(cfg.PATH_ANAFILE,'macro') linechart.render(fname) if renderfile else None self.macrochart = linechart #输出至可访问对象属性中 return self
def render_wordcloud_py(): with st.echo("below"): data = [ ("生活资源", "999"), ("供热管理", "888"), ("供气质量", "777"), ("生活用水管理", "688"), ("一次供水问题", "588"), ("交通运输", "516"), ("城市交通", "515"), ("环境保护", "483"), ("房地产管理", "462"), ("城乡建设", "449"), ("社会保障与福利", "429"), ("社会保障", "407"), ("文体与教育管理", "406"), ("公共安全", "406"), ("公交运输管理", "386"), ("出租车运营管理", "385"), ("供热管理", "375"), ("市容环卫", "355"), ("自然资源管理", "355"), ("粉尘污染", "335"), ("噪声污染", "324"), ("土地资源管理", "304"), ("物业服务与管理", "304"), ("医疗卫生", "284"), ("粉煤灰污染", "284"), ("占道", "284"), ("供热发展", "254"), ("农村土地规划管理", "254"), ("生活噪音", "253"), ("供热单位影响", "253"), ("城市供电", "223"), ("房屋质量与安全", "223"), ("大气污染", "223"), ("房屋安全", "223"), ("文化活动", "223"), ("拆迁管理", "223"), ("公共设施", "223"), ("供气质量", "223"), ("供电管理", "223"), ("燃气管理", "152"), ("教育管理", "152"), ("医疗纠纷", "152"), ("执法监督", "152"), ("设备安全", "152"), ("政务建设", "152"), ("县区、开发区", "152"), ("宏观经济", "152"), ("教育管理", "112"), ("社会保障", "112"), ("生活用水管理", "112"), ("物业服务与管理", "112"), ("分类列表", "112"), ("农业生产", "112"), ("二次供水问题", "112"), ("城市公共设施", "92"), ("拆迁政策咨询", "92"), ("物业服务", "92"), ("物业管理", "92"), ("社会保障保险管理", "92"), ("低保管理", "92"), ("文娱市场管理", "72"), ("城市交通秩序管理", "72"), ("执法争议", "72"), ("商业烟尘污染", "72"), ("占道堆放", "71"), ("地上设施", "71"), ("水质", "71"), ("无水", "71"), ("供热单位影响", "71"), ("人行道管理", "71"), ("主网原因", "71"), ("集中供热", "71"), ("客运管理", "71"), ("国有公交(大巴)管理", "71"), ("工业粉尘污染", "71"), ("治安案件", "71"), ("压力容器安全", "71"), ("身份证管理", "71"), ("群众健身", "41"), ("工业排放污染", "41"), ("破坏森林资源", "41"), ("市场收费", "41"), ("生产资金", "41"), ("生产噪声", "41"), ("农村低保", "41"), ("劳动争议", "41"), ("劳动合同争议", "41"), ("劳动报酬与福利", "41"), ("医疗事故", "21"), ("停供", "21"), ("基础教育", "21"), ("职业教育", "21"), ("物业资质管理", "21"), ("拆迁补偿", "21"), ("设施维护", "21"), ("市场外溢", "11"), ("占道经营", "11"), ("树木管理", "11"), ("农村基础设施", "11"), ("无水", "11"), ("供气质量", "11"), ("停气", "11"), ("市政府工作部门(含部门管理机构、直属单位)", "11"), ("燃气管理", "11"), ("市容环卫", "11"), ("新闻传媒", "11"), ("人才招聘", "11"), ("市场环境", "11"), ("行政事业收费", "11"), ("食品安全与卫生", "11"), ("城市交通", "11"), ("房地产开发", "11"), ("房屋配套问题", "11"), ("物业服务", "11"), ("物业管理", "11"), ("占道", "11"), ("园林绿化", "11"), ("户籍管理及身份证", "11"), ("公交运输管理", "11"), ("公路(水路)交通", "11"), ("房屋与图纸不符", "11"), ("有线电视", "11"), ("社会治安", "11"), ("林业资源", "11"), ("其他行政事业收费", "11"), ("经营性收费", "11"), ("食品安全与卫生", "11"), ("体育活动", "11"), ("有线电视安装及调试维护", "11"), ("低保管理", "11"), ("劳动争议", "11"), ("社会福利及事务", "11"), ("一次供水问题", "11"), ] c = ( WordCloud() .add(series_name="热点分析", data_pair=data, word_size_range=[6, 66]) .set_global_opts( title_opts=opts.TitleOpts( title="热点分析", title_textstyle_opts=opts.TextStyleOpts(font_size=23) ), tooltip_opts=opts.TooltipOpts(is_show=True), ) ) st_pyecharts(c)
""" page = Page(page_title='iDesignLab') # 省级现存确诊 chart = Map(init_opts=opts.InitOpts(width='1500px', height='800px')) chart.add('现存确诊', [list(z) for z in zip(province_name, p_current_confirmed_count)], 'china') chart.set_global_opts( toolbox_opts=opts.ToolboxOpts(is_show=True, pos_top='20px'), title_opts=opts.TitleOpts( title='2019-nCoV疫情地图:{}({})'.format('现存确诊', time.asctime()), subtitle='2019-nCoV Map:{}({})'.format('Current Diagnosis', time.asctime()), subtitle_textstyle_opts=opts.TextStyleOpts(font_size=15), pos_left='center', pos_top='20px'), legend_opts=opts.LegendOpts(is_show=False), visualmap_opts=opts.VisualMapOpts(is_piecewise=True, pieces=[{ 'min': 10000 }, { 'min': 500, 'max': 9999 }, { 'min': 100, 'max': 499 }, { 'min': 10, 'max': 99
(Radar( init_opts=opts.InitOpts(width="1280px", height="720px", bg_color="white")). set_colors(["red"]).add_schema( schema=[ opts.RadarIndicatorItem(name="HTML语音", max_=100), opts.RadarIndicatorItem(name="CSS语言", max_=100), opts.RadarIndicatorItem(name="JavaScript语言", max_=100), opts.RadarIndicatorItem(name="FLASK模块", max_=100), opts.RadarIndicatorItem(name="Django模块", max_=100), opts.RadarIndicatorItem(name="Java语言", max_=100), opts.RadarIndicatorItem(name="python-tkinter模块", max_=100), ], splitarea_opt=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), textstyle_opts=opts.TextStyleOpts(color="black", font_size=20), ).add( series_name="感觉要求程度", data=v1, linestyle_opts=opts.LineStyleOpts(color="green", width=2), ).add(series_name="实际学习程度", data=v2, linestyle_opts=opts.LineStyleOpts( color="red", width=2, ), areastyle_opts=opts.AreaStyleOpts(opacity=0.1)).set_series_opts( label_opts=opts.LabelOpts(is_show=False)).set_global_opts( title_opts=opts.TitleOpts(title="学习进度"), legend_opts=opts.LegendOpts()).render("basic_radar_chart.html"))
def buildLiquid(name, data, center): l1 = (Liquid().add( name, data, center=center, label_opts=opts.LabelOpts( position="inside", color="white", ), background_color={ "type": 'linear', "x": 1, "y": 0, "x2": 0.5, "y2": 1, "colorStops": [{ "offset": 1, "color": 'rgba(68, 145, 253, 0)' }, { "offset": 0.5, "color": 'rgba(68, 145, 253, .25)' }, { "offset": 0, "color": 'rgba(68, 145, 253, 1)' }], "globalCoord": False }, color=[{ "type": 'linear', "x": 0, "y": 0, "x2": 0, "y2": 1, "colorStops": [{ "offset": 1, "color": 'rgba(58, 71, 212, 0)' }, { "offset": 0.5, "color": 'rgba(31, 222, 225, .2)' }, { "offset": 0, "color": 'rgba(31, 222, 225, 1)' }], "globalCoord": False }], outline_border_distance=0., outline_itemstyle_opts=opts.ItemStyleOpts( border_width=20, border_color={ "type": 'linear', "x": 0, "y": 0, "x2": 0, "y2": 1, "colorStops": [{ "offset": 0, "color": 'rgba(69, 73, 240, 0)' }, { "offset": 0.5, "color": 'rgba(69, 73, 240, .25)' }, { "offset": 1, "color": 'rgba(69, 73, 240, 1)' }], "globalCoord": False }) ).set_global_opts(title_opts=opts.TitleOpts( title="拜登和川普最新支持率", title_link="https://new.qq.com/omn/20201004/20201004A0098Z00.html", pos_left="32%", pos_top="15%", title_textstyle_opts=opts.TextStyleOpts( color="white", font_size=30, )))) return l1
("物业服务", "11"), ("物业管理", "11"), ("占道", "11"), ("园林绿化", "11"), ("户籍管理及身份证", "11"), ("公交运输管理", "11"), ("公路(水路)交通", "11"), ("房屋与图纸不符", "11"), ("有线电视", "11"), ("社会治安", "11"), ("林业资源", "11"), ("其他行政事业收费", "11"), ("经营性收费", "11"), ("食品安全与卫生", "11"), ("体育活动", "11"), ("有线电视安装及调试维护", "11"), ("低保管理", "11"), ("劳动争议", "11"), ("社会福利及事务", "11"), ("一次供水问题", "11"), ] (WordCloud().add( series_name="热点分析", data_pair=data, word_size_range=[6, 66]).set_global_opts( title_opts=opts.TitleOpts( title="热点分析", title_textstyle_opts=opts.TextStyleOpts(font_size=23)), tooltip_opts=opts.TooltipOpts(is_show=True), ).render("basic_wordcloud.html"))
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
def line_color_with_js_func() -> Line: x_data = ["14", "15", "16", "17", "18", "19", "20", "21", "22", "23"] y_data = [393, 438, 485, 631, 689, 824, 987, 1000, 1100, 1200] background_color_js = ( "new echarts.graphic.LinearGradient(0, 0, 0, 1, " "[{offset: 0, color: '#c86589'}, {offset: 1, color: '#06a7ff'}], false)" ) area_color_js = ( "new echarts.graphic.LinearGradient(0, 0, 0, 1, " "[{offset: 0, color: '#eb64fb'}, {offset: 1, color: '#3fbbff0d'}], false)" ) c = (Line(init_opts=opts.InitOpts(bg_color=JsCode( background_color_js))).add_xaxis(xaxis_data=x_data).add_yaxis( series_name="注册总量", y_axis=y_data, is_smooth=True, is_symbol_show=True, symbol="circle", symbol_size=6, linestyle_opts=opts.LineStyleOpts(color="#fff"), label_opts=opts.LabelOpts(is_show=True, position="top", color="white"), itemstyle_opts=opts.ItemStyleOpts(color="red", border_color="#fff", border_width=3), tooltip_opts=opts.TooltipOpts(is_show=False), areastyle_opts=opts.AreaStyleOpts(color=JsCode(area_color_js), opacity=1), ).set_global_opts( title_opts=opts.TitleOpts( title="OCTOBER 2015", pos_bottom="5%", pos_left="center", title_textstyle_opts=opts.TextStyleOpts(color="#fff", font_size=16), ), xaxis_opts=opts.AxisOpts( type_="category", boundary_gap=False, axislabel_opts=opts.LabelOpts(margin=30, color="#ffffff63"), axisline_opts=opts.AxisLineOpts(is_show=False), axistick_opts=opts.AxisTickOpts( is_show=True, length=25, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"), ), splitline_opts=opts.SplitLineOpts( is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")), ), yaxis_opts=opts.AxisOpts( type_="value", position="right", axislabel_opts=opts.LabelOpts(margin=20, color="#ffffff63"), axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(width=2, color="#fff")), axistick_opts=opts.AxisTickOpts( is_show=True, length=15, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"), ), splitline_opts=opts.SplitLineOpts( is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")), ), legend_opts=opts.LegendOpts(is_show=False), )) return c
def generate_mchart(self, lst_tscode=[], lst_macro=[ 'shibor.1w', 'pimon.nt_yoy', 'pimon.ppi_yoy', 'pimon.m1_yoy', 'pimon.m2_yoy', 'pimon.allstock_circ_mv_sum' ], lst_findmedian=['pe', ()], renderfile=False) -> Grid: if self.exists == False: return None ''' testing findmedian with a given index ''' # df=self._dataagent.query('index_weight',index_code='000300.SH',start_date='20200630', end_date='20200630') # lst_findmedian=['pb',tuple(df['con_code'].values)] ''' ----------test end--------------------''' lst_tscode = list(set([self.ts_code, *lst_tscode])) # lst_findmedian[1] = tuple(self._dataagent.registry.loc[self._dataagent.registry['sec_type']=='stk']['ts_code']) if lst_findmedian[1] is None or len(lst_findmedian[1])==0 else lst_findmedian[1] dat_cursor = self.cursorTick['timeAxis'] int_latestViewDate = self._dataagent.int_findClosestTradeDate( datetime.strftime(dat_cursor, '%Y%m%d')) df_baseCal = self._dataagent.df_calTbl.loc[ self._dataagent.df_calTbl['cal_date'] <= int_latestViewDate]['cal_date'].copy() lst_xaxis = [ '{}/{}/{}'.format(i[:4], i[4:6], i[6:]) for i in df_baseCal.values.astype('str') ] # xaxis values has to be STRING type, int will not work linechart = (Line().add_xaxis(lst_xaxis)) # 生成主线,即目标证券/指数,及比较用的指数 for str_tscode in lst_tscode: # str_tscode = DataAgent.formatCode(code) df_target = self._dataagent.query('load_alldaily', tpl_dateindex=tuple(df_baseCal), ts_code=str_tscode) if len(df_target) > 0: df_toPlot = pd.merge(left=df_baseCal, right=df_target, how='left', left_on='cal_date', right_on='trade_date') else: continue '''=====主图画图部分包括主标的和副标的价格曲线,在主图中续把主图及后面叠加图的option,y轴等设置好===''' linename = '{} - {}'.format(str_tscode, self.sec_name) lst_values = list(df_toPlot['close']) lst_values = list(libs.normByRange(lst_values)) linechart.add_yaxis( linename, lst_values, is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.3), label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color="#00da3c", ), ) linechart.extend_axis( # 所有保持原比例的折线都放在linechart2里,使用右侧y轴 yaxis=opts.AxisOpts( name="倍数", type_="value", position="right", axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="black")), axislabel_opts=opts.LabelOpts(formatter="{value}倍"), )) linechart.set_global_opts( title_opts=opts.TitleOpts(title='宏观比较', ), xaxis_opts=opts.AxisOpts(type_="category"), yaxis_opts=opts.AxisOpts( name="等比例", is_scale=True, ), legend_opts=opts.LegendOpts(is_show=True, pos_top='5%', pos_left="center"), datazoom_opts=[ opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0], range_start=75, range_end=100, ), opts.DataZoomOpts( is_show=True, xaxis_index=[0], 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), ), 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", ), ) '''=============================主图画图部分结束=================''' '''=========叠加图1 尝试读取pe等股票才有的属性,如失败则说明不是股票,循环继续=============''' try: lst_pe = df_toPlot['pe'].values.tolist() lst_pb = df_toPlot['pb'].values.tolist() lst_pepb = [ round(lst_pe[index] / value, 2) for index, value in enumerate(lst_pb) if value != 0 ] linechart.add_yaxis( str_tscode + "_PE", lst_pe, yaxis_index=1, #倍数使用右y轴 is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=1), label_opts=opts.LabelOpts(is_show=False), ) linechart.add_yaxis( str_tscode + "_PE/PB", lst_pepb, yaxis_index=1, #倍数使用右y轴 is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=1), label_opts=opts.LabelOpts(is_show=False), ) except: continue '''==========================叠加图1结束================================''' df_shibor = self._dataagent.query('load_shibor') # print('Supported shibor columns: {}'.format(df_shibor.columns)) df_aggDay = self._dataagent.query('load_aggDayKPI') # print('Supported macro eco columns: {}'.format(df_aggDay.columns)) df_pimon = self._dataagent.query('load_piMon') df_pimon = pd.merge( df_pimon, df_aggDay, how='left', left_on='date', right_on='trade_date') #与aggday按每月末日期合并以获得如“流通市值”等kpi # print('Supported macro eco columns: {}'.format(df_pimon.columns)) '''=================叠加图2 所有股票的倍数类KPI,使用倍数类y轴=============''' lst_aggDayKPIloop = [ 'allstock_pe_median', 'allstock_pe_ttm_median', 'allstock_pb_median', 'allstock_pepb_median' ] for kpi in lst_aggDayKPIloop: lst_values = df_aggDay[kpi].values.tolist() linechart.add_yaxis( kpi, lst_values, yaxis_index=1, #倍数使用右y轴 is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=1), label_opts=opts.LabelOpts(is_show=False), ) '''==========================叠加图2结束================================''' '''===========叠加图3 宏观数据如shibor,cpi,m1等,按“。”分割类别进行图表生成,使用等比类y轴 ========''' for item in lst_macro: try: topic, colname = item.split('.') except: cfg.applogger.warning(f'input code {item} not recognized...') if topic == 'shibor': df_target = df_shibor maxarr = df_target.max(axis=0, skipna=True).values[1:] minarr = df_target.min(axis=0, skipna=True).values[1:] deltaRng = max(maxarr) - min( minarr ) # overwrite the normalization function delta to put all shibor rates comparable elif topic == 'pimon': df_target = df_pimon deltaRng = None else: cfg.applogger.warning( f'subject code {topic} is not recognized...') if len(df_target) > 0: df_toPlot = pd.merge(df_baseCal, df_target, how='left', left_on='cal_date', right_on='date') df_toPlot[colname] = df_toPlot[colname].bfill() else: continue linename = item lst_values = list(df_toPlot[colname]) lst_values = list(libs.normByRange(lst_values, delta=deltaRng)) linechart.add_yaxis( linename, lst_values, # 所有等比例缩放的折线都放在linechart里,使用左侧y轴 is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=1, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ) '''==========================叠加图3结束================================''' '''========叠加图4 如参数给出需要寻找中位数的股票列表则读取相应所有本地文件后计算并生成叠加图标========''' if lst_findmedian[1] is not None and len(lst_findmedian[1]) > 0: str_cat = lst_findmedian[0] df_result = pd.DataFrame() for str_tscode in lst_findmedian[1]: try: df = self._dataagent.query( 'load_alldaily', tpl_dateindex=tuple(df_baseCal), ts_code=str_tscode)[['ts_code', 'trade_date', str_cat]] print('{} csv file loaded for {} trend analysis...'.format( str_tscode, str_cat), end='\r') except Exception as e: cfg.applogger.warning( f'{str_tscode} csv file not found...') continue df_result = pd.concat([df_result, df]) df_result.dropna(subset=[str_cat], inplace=True) df_result = df_result.loc[df_result['trade_date'] > 19940301] # libs.df_csv(cfg.PATH_BUGFILE,(df_result.groupby('trade_date')['ts_code'].count(),)) # print(df_result.groupby('trade_date')['ts_code'].count()) df_target = df_result.groupby('trade_date')[str_cat].median() if len(df_target) > 0: df_toPlot = pd.merge(left=df_baseCal, right=df_target, how='left', left_on='cal_date', right_on='trade_date') linename = '{}-median'.format(str_cat) lst_values = list(df_toPlot[str_cat]) lst_values = list(lst_values) linechart.add_yaxis( linename, lst_values, yaxis_index=1, is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=1), label_opts=opts.LabelOpts(is_show=False), ) else: pass '''==========================叠加图4结束================================''' # put everything in a grid for easy resizing and positioning gridChart = Grid() gridChart.add( linechart, grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top='25%'), ) fname = '{}{}.html'.format(cfg.PATH_ANAFILE, 'macro') gridChart.render(fname) if renderfile else None self.mchart = gridChart #输出至可访问对象属性中 return self
def get_images(x_data, y_data, filename_, series_name='x1_dist'): plot_line_path = '.' filename = plot_line_path + filename_ background_color_js = ( "new echarts.graphic.LinearGradient(0, 0, 0, 1, " "[{offset: 0, color: '#c86589'}, {offset: 1, color: '#06a7ff'}], false)" ) area_color_js = ( "new echarts.graphic.LinearGradient(0, 0, 0, 1, " "[{offset: 0, color: '#eb64fb'}, {offset: 1, color: '#3fbbff0d'}], false)" ) c = (Scatter(init_opts=opts.InitOpts(bg_color=JsCode( background_color_js))).add_xaxis(xaxis_data=x_data).add_yaxis( series_name=series_name, y_axis=y_data, is_smooth=True, is_symbol_show=True, symbol="circle", symbol_size=6, linestyle_opts=opts.LineStyleOpts(color="#fff"), label_opts=opts.LabelOpts(is_show=True, position="top", color="white"), itemstyle_opts=opts.ItemStyleOpts(color="red", border_color="#fff", border_width=3), tooltip_opts=opts.TooltipOpts(is_show=False), areastyle_opts=opts.AreaStyleOpts(color=JsCode(area_color_js), opacity=1), ).set_global_opts( title_opts=opts.TitleOpts( title="show %s in one image" % series_name, pos_top="5%", pos_left="center", title_textstyle_opts=opts.TextStyleOpts(color="#fff", font_size=16), ), xaxis_opts=opts.AxisOpts( type_="category", boundary_gap=False, axislabel_opts=opts.LabelOpts(margin=30, color="#ffffff63"), axisline_opts=opts.AxisLineOpts(is_show=False), axistick_opts=opts.AxisTickOpts( is_show=True, length=25, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"), ), splitline_opts=opts.SplitLineOpts( is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")), ), yaxis_opts=opts.AxisOpts( min_='dataMin', type_="value", position="right", axislabel_opts=opts.LabelOpts(margin=20, color="#ffffff63"), axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(width=2, color="#fff")), axistick_opts=opts.AxisTickOpts( is_show=True, length=15, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"), ), splitline_opts=opts.SplitLineOpts( is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")), ), datazoom_opts=[ opts.DataZoomOpts(range_start=0, range_end=100), opts.DataZoomOpts(type_="inside", range_start=0, range_end=100), ], legend_opts=opts.LegendOpts(is_show=False), )) c.render(filename)
opts.BarItem( name=area[i], value=nums[i], itemstyle_opts=opts.ItemStyleOpts(color=colors[i]) # 设置每根柱子的颜色 )) bar.add_xaxis(xaxis_data=area) bar.add_yaxis("上榜美女数", y) bar.set_global_opts( xaxis_opts=opts.AxisOpts(name='国家', axislabel_opts=opts.LabelOpts(rotate=45)), yaxis_opts=opts.AxisOpts( name='上榜美女数', min_=0, max_=55, # y轴刻度的最小值 最大值 ), title_opts=opts.TitleOpts(title="各地区上榜美女数", title_textstyle_opts=opts.TextStyleOpts( font_family="KaiTi", font_size=25, color="black"))) # 标记最大值 最小值 平均值 标记平均线 bar.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="最小值"), opts.MarkPointItem(type_="average", name="平均值") ]), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_="average", name="平均值")])) bar.render("女神地区分布.html")
( Radar(init_opts=opts.InitOpts(width="1600px", height="1000px", bg_color="#CCCCCC")) .add_schema( schema=[ opts.RadarIndicatorItem(name="销售(sales)", max_=6500), opts.RadarIndicatorItem(name="管理(Administration)", max_=16000), opts.RadarIndicatorItem(name="信息技术(Information Technology)", max_=30000), opts.RadarIndicatorItem(name="客服(Customer Support)", max_=38000), opts.RadarIndicatorItem(name="研发(Development)", max_=52000), opts.RadarIndicatorItem(name="市场(Marketing)", max_=25000), ], splitarea_opt=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), textstyle_opts=opts.TextStyleOpts(color="#fff"), ) .add( series_name="预算分配(Allocated Budget)", data=v1, linestyle_opts=opts.LineStyleOpts(color="#CD0000"), ) .add( series_name="实际开销(Actual Spending)", data=v2, linestyle_opts=opts.LineStyleOpts(color="#5CACEE"), ) .set_series_opts(label_opts=opts.LabelOpts(is_show=False)) .set_global_opts( title_opts=opts.TitleOpts(title="基础雷达图"), legend_opts=opts.LegendOpts() )
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="上证指数", subtitle="MA5", ), 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="MA5", y_axis=calculate_ma(day_count=5, 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