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 chart(): kline=( Kline() .add_xaxis(stock_date) .add_yaxis("Kline", stock_price) .set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, # 顯示分割 splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), # 圖例位置 legend_opts=opts.LegendOpts(is_show=True, pos_top=10, pos_left="center"), # DataZoom slider 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") ), # axispointer_opts.AxisPointerOpts(is_show=True,link=[{"xAxisIndex":"all"}], # label=opts.LabelOpts(background_color=''#777'),), # 區域選擇組件 # brush_opts=opts.BrushOpts(#指定所有數列對應的座標系x_axis_index="all",#指定哪些 series # 可以被聯動brush_link="all",#定義顏色透明度out_of_brush={"colorAlpha":0.1},brush_type="lineX",), ) ) line=( Line() .add_xaxis(stock_date) .add_yaxis("10日移動平均線", sma_10, is_smooth=True, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5)) .add_yaxis("120日移動平均線", sma_120, is_smooth=True, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5)) .add_yaxis("240日移動平均線", sma_240, is_smooth=True, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5)) .set_global_opts( xaxis_opts=opts.AxisOpts(type_="category"), ) ) bar = ( Bar() .add_xaxis(stock_date) .add_yaxis("交易量", stock_volume_red, gap="0%", xaxis_index=1, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color="#A73835"), ) .add_yaxis("交易量", stock_volume_green,gap="0%", xaxis_index=1, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color="#424A56"), ) .add_yaxis("交易量", stock_volume_gray,gap="0%", xaxis_index=1, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color="#404143") ) .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, ), 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), ), legend_opts=opts.LegendOpts(is_show=False), ) ) overlap_kline_line = kline.overlap(line) global grid_chart grid_chart = ( Grid() .add(overlap_kline_line, grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", height="50%"), ) .add(bar, grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top="70%", height="16%"), ) ) grid_chart.render()
def kline(self): data = self.calculate().to_dict('list') kline = ( Kline().add_xaxis(xaxis_data=data["date"]).add_yaxis( series_name="portfolio index", y_axis=data["datas"], itemstyle_opts=opts.ItemStyleOpts( color="#ef232a", color0="#14b143", border_color="#ef232a", border_color0="#14b143", ), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", is_scale=True, boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False), splitline_opts=opts.SplitLineOpts(is_show=False), split_number=20, min_="dataMin", max_="dataMax", ), yaxis_opts=opts.AxisOpts( is_scale=True, splitline_opts=opts.SplitLineOpts(is_show=True)), 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), ], 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"), ), brush_opts=opts.BrushOpts( x_axis_index="all", brush_link="all", out_of_brush={"colorAlpha": 0.1}, brush_type="lineX", ), # 三个图的 axis 连在一块 axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), )) kline_line = (Line().add_xaxis(xaxis_data=data["date"]).add_yaxis( series_name="MA5", y_axis=self.calculate_ma(day_count=5, data=data), is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA10", y_axis=self.calculate_ma(day_count=10, data=data), is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA20", y_axis=self.calculate_ma(day_count=20, data=data), is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA30", y_axis=self.calculate_ma(day_count=30, data=data), is_smooth=True, linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( grid_index=1, split_number=3, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=True), ), )) # Overlap Kline + Line overlap_kline_line = kline.overlap(kline_line) # Bar-1 bar_1 = (Bar().add_xaxis(xaxis_data=data["date"]).add_yaxis( series_name="Volumn", y_axis=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", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=False), ), legend_opts=opts.LegendOpts(is_show=False), )) # Bar-2 (Overlap Bar + Line) bar_2 = (Bar().add_xaxis(xaxis_data=data["date"]).add_yaxis( series_name="MACD", y_axis=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), ), yaxis_opts=opts.AxisOpts( grid_index=2, split_number=4, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=True), ), legend_opts=opts.LegendOpts(is_show=False), )) line_2 = (Line().add_xaxis(xaxis_data=data["date"]).add_yaxis( series_name="DIFF", y_axis=data["DIFF"], xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="DEA", y_axis=data["DEA"], xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), ).set_global_opts(legend_opts=opts.LegendOpts(is_show=False))) # 最下面的柱状图和折线图 overlap_bar_line = bar_2.overlap(line_2) # 最后的 Grid grid_chart = Grid( init_opts=opts.InitOpts(width="1500px", height="750px")) # 这个是为了把 data.datas 这个数据写入到 html 中,还没想到怎么跨 series 传值 # demo 中的代码也是用全局变量传的 grid_chart.add_js_funcs("var barData = {}".format(data["datas"])) # K线图和 MA5 的折线图 grid_chart.add( overlap_kline_line, grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", height="60%"), ) # Volumn 柱状图 grid_chart.add( bar_1, grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", pos_top="71%", height="10%"), ) # MACD DIFS DEAS grid_chart.add( overlap_bar_line, grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", pos_top="82%", height="14%"), ) makedir(self.path, 'kline') grid_chart.render( f"{self.path}\\kline\\{str(self.names)}_{time.strftime('%Y-%m-%d', time.localtime())}.html" )
def print_line(): x_data = range(0, len(Grid)) timeline2 = Timeline(init_opts=opts.InitOpts(bg_color="black")) for i in range(len(Grid)): line = (Line(init_opts=opts.InitOpts(bg_color="black")).add_xaxis( xaxis_data=time[0:i + 1]).add_yaxis( series_name="grid", y_axis=Grid[0:i + 1], is_smooth=True, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts( width=3, color="rgb(255,0,255)", ), color="rgb(255,255,0)", symbol="diamond", symbol_size=2, ).add_yaxis( series_name="pv", y_axis=PV[0:i + 1], is_smooth=True, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3, color="rgb(0,255,255)"), color="rgb(255,255,255)", symbol="circle", symbol_size=2, ).add_yaxis( series_name="battery", y_axis=Battery[0:i + 1], is_smooth=True, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3, color="rgb(255,255,255)"), color="rgb(0,255,255)", symbol="triangle", symbol_size=2, ).add_yaxis( series_name="demand", y_axis=demand[0:i + 1], is_smooth=True, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(width=3, color="rgb(255,255,0)"), color="rgb(255,0,255)", symbol="rect", symbol_size=2, ).set_global_opts( title_opts=opts.TitleOpts( title="PV, battery, demand, grid(kW) till time {}".format( time[i]), title_textstyle_opts=opts.TextStyleOpts(color="white")), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="none"), xaxis_opts=opts.AxisOpts( boundary_gap=False, min_='dataMin', max_='dataMax', axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="white"), ), axislabel_opts=opts.LabelOpts(), ), yaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(formatter="{value}"), axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="white")), splitline_opts=opts.SplitLineOpts(is_show=True), ), visualmap_opts=opts.VisualMapOpts( is_show=False, is_piecewise=False, dimension=0, textstyle_opts=opts.TextStyleOpts(color="white")), legend_opts=opts.LegendOpts( textstyle_opts=opts.TextStyleOpts(color="white"), pos_left="right", pos_top="5%"), )) timeline2.add(line, "{}年".format(i)).add_schema(play_interval=2000, is_auto_play=True, is_timeline_show=False) timeline2.render("C:/Users/suqi/Desktop/allcode/linenew.html")
from pyecharts import options as opts from pyecharts.charts import Gauge c = (Gauge().add( "业务指标", [("完成率", 55.5)], split_number=5, axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts( color=[(0.3, "#67e0e3"), (0.7, "#37a2da"), (1, "#fd666d")], width=30)), detail_label_opts=opts.LabelOpts(formatter="{value}"), ).set_global_opts( title_opts=opts.TitleOpts(title="Gauge-分割段数-Label"), legend_opts=opts.LegendOpts(is_show=False), ).render("gauge_splitnum_label.html"))
def grid_mutil_yaxis() -> Grid: x_data = ["{}月".format(i) for i in range(1, 13)] bar = ( Bar() .add_xaxis(x_data) .add_yaxis( "蒸发量", [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3], yaxis_index=0, color="#d14a61", ) .add_yaxis( "降水量", [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3], yaxis_index=1, color="#5793f3", ) .extend_axis( yaxis=opts.AxisOpts( name="蒸发量", type_="value", min_=0, max_=250, position="right", axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="#d14a61") ), axislabel_opts=opts.LabelOpts(formatter="{value} ml"), ) ) .extend_axis( yaxis=opts.AxisOpts( type_="value", name="温度", min_=0, max_=25, position="left", axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="#675bba") ), axislabel_opts=opts.LabelOpts(formatter="{value} °C"), splitline_opts=opts.SplitLineOpts( is_show=True, linestyle_opts=opts.LineStyleOpts(opacity=1) ), ) ) .set_global_opts( yaxis_opts=opts.AxisOpts( name="降水量", min_=0, max_=250, position="right", offset=80, axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="#5793f3") ), axislabel_opts=opts.LabelOpts(formatter="{value} ml"), ), title_opts=opts.TitleOpts(title="Grid-多 Y 轴示例"), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"), ) ) line = ( Line() .add_xaxis(x_data) .add_yaxis( "平均温度", [3.3, 10.2, 20.3, 23.0, 16.5], yaxis_index=2, color="#675bba", label_opts=opts.LabelOpts(is_show=False), ) ) bar.overlap(line) return Grid().add(bar, opts.GridOpts(pos_left="5%", pos_right="20%"), is_control_axis_index=True)
center=['50%', '50%'], textstyle_opts=opts.TextStyleOpts( color='red', ), splitline_opt=opts.SplitLineOpts( is_show= True, linestyle_opts=opts.LineStyleOpts( color='#98F5FF', width=1, type_='dotted' ) ), axisline_opt=opts.AxisLineOpts( linestyle_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts( color='#98F5FF', ) ) ), splitarea_opt=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts( color=['#141c42', '#141c42'] ) ) ) .add( series_name=series[i], data=vdata[i], color=c[i], label_opts=opts.LabelOpts({
[9, 4, 28], [0, 5, 22], [1, 5, 41], [2, 5, 110], [3, 5, 39], [4, 5, 40], [5, 5, 90], [6, 5, 50], [7, 5, 60], [8, 5, 146], [9, 5, 15], ] axisOpts = opts.AxisOpts( type_="category", axisline_opts=opts.AxisLineOpts(is_show=False), axislabel_opts=opts.LabelOpts( color='#A3C7E7', font_size=10, ), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=True, linestyle_opts=opts.LineStyleOpts( is_show=True, color='black', width=10, )), ) c = ( HeatMap(init_opts=opts.InitOpts(bg_color='black', )).add_xaxis(
color='#B44038', #图元样式配置项 border_color="#B44038", #颜色 border_width=10)) #图元的大小 line.add_yaxis( "湖北新增确诊病例", hubei_statis, is_smooth=True, linestyle_opts=opts.LineStyleOpts(width=2, color='#4E87ED'), label_opts=opts.LabelOpts(position='bottom'), #标签在折线的底部 itemstyle_opts=opts.ItemStyleOpts(color='#4E87ED', border_color="#4E87ED", border_width=3)) line.add_yaxis( "其他省份新增病例", other_statis, is_smooth=True, linestyle_opts=opts.LineStyleOpts(width=2, color='#F1A846'), label_opts=opts.LabelOpts(position='bottom'), #标签在折线的底部 itemstyle_opts=opts.ItemStyleOpts(color='#F1A846', border_color="#F1A846", border_width=3)) line.set_global_opts( title_opts=opts.TitleOpts(title="新增确诊病例", subtitle='数据来源:丁香园'), yaxis_opts=opts.AxisOpts( max_=16000, min_=1, type_="log", #坐标轴配置项 splitline_opts=opts.SplitLineOpts(is_show=True), #分割线配置项 axisline_opts=opts.AxisLineOpts(is_show=True))) #坐标轴刻度线配置项 #line.render(path='/home/aistudio/data/新增确诊趋势图.html') line.render(path='D:/pycharm/projects/data/新增确诊趋势图.html')
def line_color_with_js_func(place="上海野生动物园") -> Line: if place is None: weather_data = weather_spider(weather_dict.get("上海野生动物园")) else: if place in weather_dict.keys(): place_weather_url = weather_dict.get(place) weather_data = weather_spider(place_weather_url) else: return None x_data = [ x.replace("".join(re.findall("(.*", x)), "") for x in weather_data.get("days") ] y_data = [ maxt.rstrip("℃").split("/")[0] for maxt in weather_data.get("max_min_t") ] y_data2 = [ mint.rstrip("℃").split("/")[1] for mint in weather_data.get("max_min_t") ] area_color_js = ( "new echarts.graphic.LinearGradient(0, 0, 0, 1, " "[{offset: 0, color: '#6495ED'}, {offset: 1, color: '#12406d'}], false)" ) c = ( Line(init_opts=opts.InitOpts( width="100%", height="100%")).set_series_opts( label_opts=opts.LabelOpts(is_show=True, color="white")). add_xaxis(xaxis_data=x_data).add_yaxis( "日最高气温", 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", font_size=16), 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( 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), ) # 第二 .add_xaxis(xaxis_data=x_data).add_yaxis( series_name="日最低气温", y_axis=y_data2, 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", font_size=16), itemstyle_opts=opts.ItemStyleOpts(color="#0ff", 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( 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 dray_line_piture(self,my_line_data_x,my_line_data_y): if os.path.isfile('.\line_color.html'): os.remove('.\line_color.html') if(len(my_line_data_x) != len(my_line_data_y)): print("leng not match !!!") exit() x_data = my_line_data_x y_data = my_line_data_y #print(x_data) #print(y_data) 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",formatter="{c}%"), 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="Yield", pos_left="5%", pos_top="5%", 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, linestyle_opts=opts.LineStyleOpts(width=2, color="#fff") ), 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=False, length=15, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"), ), splitline_opts=opts.SplitLineOpts( is_show=False, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f") ), ), legend_opts=opts.LegendOpts(is_show=False), ) .render("line_color.html") )
def radar_angle_radius_axis_opts() -> Radar: data = [{"value": [4, -4, 2, 3, 0, 1], "name": "预算分配"}] c_schema = [ { "name": "销售", "max": 4, "min": -4 }, { "name": "管理", "max": 4, "min": -4 }, { "name": "技术", "max": 4, "min": -4 }, { "name": "客服", "max": 4, "min": -4 }, { "name": "研发", "max": 4, "min": -4 }, { "name": "市场", "max": 4, "min": -4 }, ] c = (Radar().set_colors(["#4587E7"]).add_schema( schema=c_schema, shape="circle", center=["50%", "50%"], radius="80%", angleaxis_opts=opts.AngleAxisOpts( min_=0, max_=360, is_clockwise=False, interval=5, axistick_opts=opts.AxisTickOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), ), radiusaxis_opts=opts.RadiusAxisOpts( min_=-4, max_=4, interval=2, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), polar_opts=opts.PolarOpts(), splitarea_opt=opts.SplitAreaOpts(is_show=False), splitline_opt=opts.SplitLineOpts(is_show=False), ).add( series_name="预算", data=data, areastyle_opts=opts.AreaStyleOpts(opacity=0.1), linestyle_opts=opts.LineStyleOpts(width=1), )) return c
list(val_repot.BADRATE), yaxis_index=0, color="red", ) .set_global_opts( title_opts=opts.TitleOpts(title="行为评分卡模型表现"), ) .extend_axis( yaxis=opts.AxisOpts( name="累计坏人占比", type_="value", min_=0, max_=0.5, position="right", axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="red") ), axislabel_opts=opts.LabelOpts(formatter="{value}"), ) ) .add_xaxis(list(val_repot.index)) .add_yaxis( "KS", list(val_repot['KS']), yaxis_index=1, color="blue", label_opts=opts.LabelOpts(is_show=False), ) ) line.render_notebook()
def plot_kline(ka, bs=None, file_html="kline.html", width="1400px", height="680px"): """ :param ka: KlineAnalyze :param bs: pd.DataFrame 买卖点,包含三个字段 ["操作提示", "交易时间", "交易价格"] :param file_html: str :param width: str :param height: str :return: None """ df = ka.to_df(use_macd=True, ma_params=( 5, 20, )) x = df.dt.to_list() title = "%s | %s 至 %s" % (ka.symbol, ka.start_dt, ka.end_dt) kline = ( Kline().add_xaxis(xaxis_data=x).add_yaxis( series_name="", y_axis=df[['open', 'close', 'low', 'high']].values.tolist(), itemstyle_opts=opts.ItemStyleOpts( color="#ef232a", color0="#14b143", border_color="#ef232a", border_color0="#14b143", ), ).set_series_opts(markarea_opts=opts.MarkAreaOpts( is_silent=True)).set_global_opts( title_opts=opts.TitleOpts(title=title, pos_left="0"), xaxis_opts=opts.AxisOpts( type_="category", is_scale=True, boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False), splitline_opts=opts.SplitLineOpts(is_show=False), split_number=20, min_="dataMin", max_="dataMax", ), yaxis_opts=opts.AxisOpts( is_scale=True, splitline_opts=opts.SplitLineOpts(is_show=True), axislabel_opts=opts.LabelOpts(is_show=True, position="inside")), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="line"), datazoom_opts=[ opts.DataZoomOpts(is_show=False, type_="inside", xaxis_index=[0, 0], range_end=100), opts.DataZoomOpts(is_show=True, xaxis_index=[0, 1], pos_top="96%", range_end=100), opts.DataZoomOpts(is_show=False, xaxis_index=[0, 2], range_end=100), ], # 三个图的 axis 连在一块 axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), )) kline_line = (Line().add_xaxis(xaxis_data=x).add_yaxis( series_name="笔", y_axis=df.bi.tolist(), is_smooth=False, is_connect_nones=True, symbol='diamond', symbol_size=8, linestyle_opts=opts.LineStyleOpts(opacity=1, type_='dotted', width=2), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="线段", y_axis=df.xd.tolist(), is_smooth=False, is_connect_nones=True, symbol='triangle', symbol_size=12, linestyle_opts=opts.LineStyleOpts(opacity=1, type_='solid', width=2), label_opts=opts.LabelOpts(is_show=True, position='right'), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( grid_index=1, split_number=3, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=True, position="inside"), ), )) # Overlap Kline + Line overlap_kline_line = kline.overlap(kline_line) if isinstance(bs, pd.DataFrame) and len(bs) > 0: c = (Scatter().add_xaxis(bs['交易时间'].to_list()).add_yaxis( "买卖点", bs['交易价格'].to_list(), label_opts=opts.LabelOpts( is_show=True, position="left", formatter=JsCode( "function(params){return bsName[params.dataIndex][0];}")), )) overlap_kline_line = overlap_kline_line.overlap(c) # draw volume bar_1 = (Bar().add_xaxis(xaxis_data=x).add_yaxis( series_name="Volumn", y_axis=df.vol.tolist(), xaxis_index=1, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color=JsCode(""" function(params) { var colorList; if (barData[params.dataIndex][1] > barData[params.dataIndex][0]) { colorList = '#ef232a'; } else { colorList = '#14b143'; } return colorList; } """)), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(is_show=True, position='inside')), legend_opts=opts.LegendOpts(is_show=False), )) # Bar-2 (Overlap Bar + Line) bar_2 = (Bar().add_xaxis(xaxis_data=x).add_yaxis( series_name="MACD", y_axis=df.macd.tolist(), xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color=JsCode(""" function(params) { var colorList; if (params.data >= 0) { colorList = '#ef232a'; } else { colorList = '#14b143'; } return colorList; } """)), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( grid_index=2, split_number=4, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=True, position="inside"), ), legend_opts=opts.LegendOpts(is_show=False), )) line_2 = (Line().add_xaxis(xaxis_data=x).add_yaxis( series_name="DIF", y_axis=df['diff'].tolist(), xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="DEA", y_axis=df['dea'].tolist(), xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), ).set_global_opts(legend_opts=opts.LegendOpts(is_show=False))) # draw MACD overlap_bar_line = bar_2.overlap(line_2) # 最后的 Grid grid_chart = Grid( init_opts=opts.InitOpts(width=width, height=height, page_title=title)) grid_chart.add_js_funcs("var barData = {}".format( df[['open', 'close', 'low', 'high']].values.tolist())) if isinstance(bs, pd.DataFrame) and len(bs) > 0: grid_chart.add_js_funcs("var bsName = {}".format( bs[["操作提示", "交易价格"]].values.tolist())) grid_chart.add( overlap_kline_line, grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", height="60%"), ) grid_chart.add( bar_1, grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", pos_top="71%", height="10%"), ) grid_chart.add( overlap_bar_line, grid_opts=opts.GridOpts(pos_left="3%", pos_right="1%", pos_top="82%", height="14%"), ) grid_chart.render(path=file_html)
def generate_line_html(rows, select=None): # 用散点图展示 line = Line( opts.InitOpts(height='700px', width='1424px', theme=ThemeType.LIGHT)) x = [] y1 = [] y2 = [] y3 = [] y4 = [] y5 = [] for row in rows: x.append(row['时间']) y3.append(row['低溢价率策略累积收益率']) y2.append(row['高收益率策略累积收益率']) y1.append(row['低余额+双低策略累积收益率']) y1.append(row['低溢价率+双低策略累积收益率']) # y4.append(row['可转债指数累积收益率']) # y5.append(row['沪深300累积收益率']) line.add_xaxis(x) line.add_yaxis("低溢价率策略", y3) line.add_yaxis("高收益率策略", y2) line.add_yaxis("低余额+双低策略", y1) line.add_yaxis("低溢价+双低策略", y1) # line.add_yaxis("可转债指数", y4) # line.add_yaxis("沪深300", y5) line.set_global_opts( title_opts=opts.TitleOpts(title="策略组合收益率", pos_left='center', pos_top=-5), tooltip_opts=opts.TooltipOpts( trigger='axis', formatter=JsCode( "function (params) {" "return '<table style=\"width:150px;\">'+" "'<tr ><td style=\"height:20px;background-color:white;border:0px\" colspan=2>'+ params[0].data[0] +'</td></tr>' +" "'<tr><td style=\"height:15px;background-color:white;border:0px;text-align: left;color:'+params[1].color+'\">高收益率策略</td><td style=\"height:15px;background-color:white;border:0px\">' + params[1].value[1] + '%</td></tr>' +" "'<tr><td style=\"height:15px;background-color:white;border:0px;text-align: left;color:'+params[2].color+'\">低溢价率策略</td><td style=\"height:15px;background-color:white;border:0px\">' + params[2].value[1] + '%</td></tr>' +" "'<tr ><td style=\"height:15px;background-color:white;border:0px;text-align: left;color:'+params[0].color+'\">低余额+双低策略</td><td style=\"height:15px;background-color:white;border:0px\">' + params[3].value[1] + '%</td></tr>' +" "'<tr ><td style=\"height:15px;background-color:white;border:0px;text-align: left;color:'+params[0].color+'\">低溢价率+双低策略</td><td style=\"height:15px;background-color:white;border:0px\">' + params[4].value[1] + '%</td></tr>' +" "'<tr><td style=\"height:15px;background-color:white;border:0px;text-align: left;color:'+params[3].color+'\">可转债指数</td><td style=\"height:15px;background-color:white;border:0px\">' + params[5].value[1] + '%</td></tr>' +" "'<tr><td style=\"height:15px;background-color:white;border:0px;text-align: left;color:'+params[4].color+'\">沪深300</td><td style=\"height:15px;background-color:white;border:0px\">' + params[6].value[1] + '%</td></tr>' +" "'</table>';}")), legend_opts=opts.LegendOpts(pos_top=50, # selected_mode='single' ), datazoom_opts={ 'start': 0, 'end': 100 }, toolbox_opts=opts.ToolboxOpts(feature={ 'dataZoom': {}, }), # visualmap_opts=opts.VisualMapOpts( # type_="color", max_=150, min_=20, dimension=1 # ), xaxis_opts=opts.AxisOpts( # data=None, type_='time', name='时间', name_gap=30, is_scale=True, name_location='middle', splitline_opts=opts.SplitLineOpts(is_show=False), # axislabel_opts=opts.LabelOpts(formatter="{value}"), #echarts.format.formatTime('yy-MM-dd', value*1000) axisline_opts=opts.AxisLineOpts(is_on_zero=False, symbol=['none', 'arrow'])), yaxis_opts=opts.AxisOpts( type_='value', name='收益率(%)', name_rotate=90, name_gap=55, name_location='middle', is_scale=True, axislabel_opts=opts.LabelOpts(formatter='{value}%'), splitline_opts=opts.SplitLineOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_on_zero=False, symbol=['none', 'arrow']))) line.set_series_opts( symbol='none', smooth=False, label_opts=opts.LabelOpts(is_show=False), ) line_html = line.render_embed('template.html', env) return line_html
"蒸发量", [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3], yaxis_index=0, color="#d14a61", ).add_yaxis( "降水量", [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3], yaxis_index=1, color="#5793f3", ).extend_axis(yaxis=opts.AxisOpts( name="蒸发量", type_="value", min_=0, max_=250, position="right", axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts( color="#d14a61")), axislabel_opts=opts.LabelOpts(formatter="{value} ml"), )).extend_axis(yaxis=opts.AxisOpts( type_="value", name="温度", min_=0, max_=25, position="left", axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts( color="#675bba")), axislabel_opts=opts.LabelOpts(formatter="{value} °C"), splitline_opts=opts.SplitLineOpts( is_show=True, linestyle_opts=opts.LineStyleOpts(opacity=1)), )).set_global_opts( yaxis_opts=opts.AxisOpts( name="降水量",
def kline(self): """""" if "_" in self.bar_data.symbol[0]: symbol_split = self.bar_data.symbol[0].split("_") series_name = "_".join( [symbol_split[0], symbol_split[1][-2:], symbol_split[2][-2:]]) else: series_name = self.bar_data.symbol[0] kline = Kline(init_opts=opts.InitOpts(width="1400px", height="800px")) kline.add_xaxis(xaxis_data=self.bar_data_datetime) kline.add_yaxis( series_name=series_name, yaxis_index=0, y_axis=self.bar_data[[ "open_price", "close_price", "low_price", "high_price" ]].values.tolist(), itemstyle_opts=opts.ItemStyleOpts(color="#ef232a", color0="#14b143", border_color="#8A0000", border_color0="#008F28", opacity=0.8), ) kline.set_global_opts( datazoom_opts=[ opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0, 0], range_start=0, range_end=100, ), opts.DataZoomOpts( is_show=True, type_="slider", xaxis_index=[0, 1], pos_top="95%", range_start=0, range_end=100, ), ], xaxis_opts=opts.AxisOpts( is_scale=True, type_="category", boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False), splitline_opts=opts.SplitLineOpts(is_show=False), split_number=20, min_="dataMin", max_="dataMax", ), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=0.8)), ), brush_opts=opts.BrushOpts( tool_box=[ "rect", "polygon", "keep", "lineX", "lineY", "clear" ], x_axis_index="all", brush_link="all", out_of_brush={"colorAlpha": 0.1}, brush_type="lineX", ), tooltip_opts=opts.TooltipOpts( is_show=True, 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=12, font_family="Arial", font_weight="lighter", ), ), toolbox_opts=opts.ToolboxOpts(orient="horizontal", pos_left="right", pos_top="0%"), legend_opts=opts.LegendOpts( is_show=True, type_="scroll", selected_mode="multiple", pos_left="left", pos_top="0%", legend_icon="roundRect", ), # 多图的 axis 连在一块 axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), ) self.kline_chart = kline
def generate_bar_html(rows, title): x = [] y = [] for row in rows: x.append(row[0]) y.append({'value': row[1], 'range': [row[2], row[3]]}) bar = Bar(init_opts=opts.InitOpts(height='700px', width='1424px', theme=ThemeType.SHINE, chart_id="cb_tree_map")) bar.add_xaxis(x) bar.add_yaxis( "个数", y, yaxis_index=0, bar_width=50, category_gap='1%', gap='1%', label_opts=opts.LabelOpts( position="top", formatter=JsCode("function(x){return x.data[0];}")), ) bar.set_series_opts(itemstyle_opts=opts.ItemStyleOpts(color=JsCode( "function(x){return x.data['range'][0]=='0'?'lightgray':(x.data['range'][0] < 0 ? 'lightgreen':'lightcoral')}" ))) bar.set_global_opts( title_opts=opts.TitleOpts( title="=========" + title + "=========", subtitle_textstyle_opts=opts.TextStyleOpts(font_weight='bold', font_size='15px'), pos_left='center', pos_top='-1px', ), tooltip_opts=opts.TooltipOpts(is_show=False), legend_opts=opts.LegendOpts(is_show=False), xaxis_opts=opts.AxisOpts( # data=None, # type_='category', # name_gap=0, # name_rotate=90, # axislabel_opts=opts.LabelOpts( # rotate=-60, # ), name='价格涨跌区间', name_gap=35, is_scale=True, name_location='middle', splitline_opts=opts.SplitLineOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_on_zero=True, # symbol=['none', 'arrow'] )), yaxis_opts=opts.AxisOpts( type_='value', name='个数', # name_rotate=90, name_gap=35, name_location='middle', # min_=0, # max_=max_value, is_scale=True, axislabel_opts=opts.LabelOpts(formatter='{value}'), splitline_opts=opts.SplitLineOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_on_zero=False, # symbol=['none', 'arrow'] )), ) bar_html = bar.render_embed('template.html', html_utils.env) return bar_html
def draw_chart(ts_code, start_date, end_date): ''' pyecharts V1 版本开始支持链式调用 文档地址 https://pyecharts.org/#/zh-cn/ ''' stock_data = get_process_datas(ts_code, start_date, end_date) stock_data.index = pd.to_datetime(stock_data['TIME'], format="%Y/%m/%d") x = stock_data["TIME"].values.tolist() stock_basic_data = stock_data[[ "TIME", "OPEN", "CLOSE", "LOW", "HIGH", "VOLUME" ]] # stock_data = stock_data.sort_index(ascending=True) # 倒序,看时间顺序是否正常决定是不是要用 # k线图 kline = ( Kline().add_xaxis(x).add_yaxis( "K线图", stock_basic_data.iloc[:, 1:5].values.tolist(), itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c"), ).set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True, is_show=False), # axis_opts=opts.AxisOpts(is_scale=True,min_=0), #y轴起始坐标可以设为0 yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), # y轴起始坐标可自动调整 tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="line"), legend_opts=opts.LegendOpts(is_show=True, orient='vertical', pos_right="5%", pos_top='20%'), title_opts=opts.TitleOpts(title="股票价格", subtitle=ts_code, pos_left='22%', pos_top="20%"), #把所有的x轴连接在一起 # axispointer_opts=opts.AxisPointerOpts(is_show=True, # link=[{"xAxisIndex": "all"}], # label=opts.LabelOpts(background_color="#777"), # ), datazoom_opts=[ # 设置zoom参数后即可缩放 opts.DataZoomOpts( is_show=True, type_="inside", xaxis_index=[0, 1, 2, 3, 4], # 设置第0轴和第1轴同时缩放 range_start=0, range_end=100, ), ], )) # 成交量柱形图 bar_volumn = (Bar().add_xaxis(x).add_yaxis( "成交量", stock_basic_data["VOLUME"].values.tolist(), xaxis_index=1, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color=JsCode(""" function(params) { var colorList; if (barData[params.dataIndex][1] > barData[params.dataIndex][0]) { colorList = '#ef232a'; } else { colorList = '#14b143'; } return colorList; } """)), ).set_global_opts( title_opts=opts.TitleOpts(title="成交量", pos_left='22%', pos_top="48%"), legend_opts=opts.LegendOpts(is_show=True, orient='vertical', pos_right="5%", pos_top='48%'), )) #绘制均线图 line_ma = ( Line().add_xaxis(x).add_yaxis( series_name="MA5", y_axis=stock_data["MA5"].values.tolist(), 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="MA10", y_axis=stock_data["MA10"].values.tolist(), is_hover_animation=False, label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ).add_yaxis( series_name="MA20", y_axis=stock_data["MA20"].values.tolist(), is_hover_animation=False, label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ).set_global_opts( title_opts=opts.TitleOpts(title="MA", pos_left='22%', pos_top="88%"), xaxis_opts=opts.AxisOpts( type_="category", axislabel_opts=opts.LabelOpts(is_show=False), is_scale=True), datazoom_opts=[opts.DataZoomOpts(type_="inside")], legend_opts=opts.LegendOpts(is_show=True, orient='vertical', pos_right="5%", pos_top='85%'), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), )) #绘制jdk线 line_kdj = (Line().add_xaxis(x).add_yaxis( series_name="K", y_axis=stock_data["K"].values.tolist(), linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ).add_yaxis( series_name="D", y_axis=stock_data["D"].values.tolist(), linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ).add_yaxis( series_name="J", y_axis=stock_data["J"].values.tolist(), label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ).set_global_opts( title_opts=opts.TitleOpts(title="KDJ", pos_left='22%', pos_top="62%"), datazoom_opts=[opts.DataZoomOpts(type_="inside", )], legend_opts=opts.LegendOpts(is_show=True, orient='vertical', pos_right="7%", pos_top='60%'), xaxis_opts=opts.AxisOpts( is_scale=True, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), )) #绘制macd柱状图 bar_macd = (Bar().add_xaxis(x).add_yaxis( series_name='MACD', yaxis_data=stock_data['MACD'].values.tolist(), xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color=JsCode(""" function(params) { var colorList; if (params.data >= 0) { colorList = '#ef232a'; } else { colorList = '#14b143'; } return colorList; } """)), ).set_global_opts( title_opts=opts.TitleOpts(title="MACD", pos_left='22%', pos_top="75%"), xaxis_opts=opts.AxisOpts( type_="category", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( grid_index=2, split_number=4, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=True), ), legend_opts=opts.LegendOpts(is_show=True, orient='vertical', pos_right="5%", pos_top='70%'), )) #绘制DIF和DEA line_macd = (Line().add_xaxis(x).add_yaxis( series_name="DIF", y_axis=stock_data['DIF'].values.tolist(), xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ).add_yaxis( series_name="DEA", y_axis=stock_data['DEA'].values.tolist(), xaxis_index=2, yaxis_index=2, label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ).set_global_opts(legend_opts=opts.LegendOpts(is_show=False))) #绘制布林线 line_boll = (Line().add_xaxis(x).add_yaxis( series_name="MID", y_axis=stock_data["MID"].values.tolist(), linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ).add_yaxis( series_name="UPPER", y_axis=stock_data["UPPER"].values.tolist(), linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ).add_yaxis( series_name="LOWER", y_axis=stock_data["LOWER"].values.tolist(), linestyle_opts=opts.LineStyleOpts(opacity=0.5), label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, ).set_global_opts( datazoom_opts=[opts.DataZoomOpts(type_="inside", )], xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), )) overlap_kline_linema = kline.overlap(line_boll) overlap_macd = bar_macd.overlap(line_macd) # 使用网格将多张图标组合到一起显示 grid_chart = Grid(init_opts=opts.InitOpts( width="1400px", height="700px", animation_opts=opts.AnimationOpts(animation=False), )) # 为了把 data.datas 的数据写入到html中作为全局变量,目前无法跨 series 传值 # demo 中的代码也是用全局变量传的 grid_chart.add_js_funcs("var barData = {}".format( stock_basic_data.iloc[:, 1:5].values.tolist())) grid_chart.add( overlap_kline_linema, grid_opts=opts.GridOpts(pos_left="35%", pos_right="15%", pos_top="3%", height="40%"), ) grid_chart.add( bar_volumn, grid_opts=opts.GridOpts(pos_left="35%", pos_right="15%", pos_top="45%", height="10%"), ) grid_chart.add(line_kdj, grid_opts=opts.GridOpts(pos_left="35%", pos_right="15%", pos_top="60%", height="10%")) grid_chart.add(overlap_macd, grid_opts=opts.GridOpts(pos_left="35%", pos_right="15%", pos_top="72%", height="10%")) grid_chart.add(line_ma, grid_opts=opts.GridOpts(pos_left="35%", pos_right="15%", pos_top="85%", height="10%")) grid_chart.render('stock_{}/stock_{}.html'.format( ts_code, ts_code)) # 保存成用股票代码命名的文档 return 0
def plot_lines(self, x_data, y_data, filename_, series_name='x1_dist'): filename = self.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 = (Line( 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( 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)
textstyle_opts=opts.TextStyleOpts( color='#fff' ) ), tooltip_opts=opts.TooltipOpts( trigger="axis", axis_pointer_type="shadow", textstyle_opts=opts.TextStyleOpts( color="#fff" ) ), xaxis_opts=opts.AxisOpts( type_="category", axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts( color="white" ) ), axislabel_opts=opts.LabelOpts( ) ), yaxis_opts=opts.AxisOpts( type_="value", max_=90, axistick_opts=opts.AxisTickOpts( is_show=False ), splitline_opts=opts.SplitLineOpts( is_show=True, linestyle_opts=opts.LineStyleOpts( color='rgba(255,255,255,0.3)'
pos_top='15', pos_left='40%', title_textstyle_opts=opts.TextStyleOpts(font_size=20)), legend_opts=opts.LegendOpts( legend_icon='circle', orient='vertical', align='left', item_width=15, item_height=8, item_gap=7, pos_top="55", pos_left="110", textstyle_opts=opts.TextStyleOpts(font_size=10)), xaxis_opts=opts.AxisOpts( name_textstyle_opts=opts.TextStyleOpts(font_size=9, color='#525252'), axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts( color='#525252')), axistick_opts=opts.AxisTickOpts(linestyle_opts=opts.LineStyleOpts( color='#525252')), axislabel_opts=opts.LabelOpts(font_size=8, color='#525252')), yaxis_opts=opts.AxisOpts( name_textstyle_opts=opts.TextStyleOpts(font_size=9, color='#525252'), axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts( color='#525252')), axistick_opts=opts.AxisTickOpts(linestyle_opts=opts.LineStyleOpts( color='#525252')), axislabel_opts=opts.LabelOpts(font_size=8, color='#525252')), tooltip_opts=opts.TooltipOpts( trigger='axis', textstyle_opts=opts.TextStyleOpts(font_size=9.5)), toolbox_opts=opts.ToolboxOpts(feature=opts.ToolBoxFeatureOpts( save_as_image=opts.ToolBoxFeatureSaveAsImageOpts(type_='jpeg', pixel_ratio=2.5))))
def tradeDataShowKLine(product_code, ma=None, autoType=None) -> Grid: ''' 展示该产品的K线图,默认前复权,等值等比例的展示 :param product_code: 产品代码 :param ma=[30,60,99,120,250] 均线 :param autoType: autoType=qfq-前复权 hfq-后复权 None-不复权 :param *avg_line: 均线 暂时不做 :return: ''' ma = [30, 60, 99, 120, 250] if ma is None else ma (productname, tradeDataDf) = sttradepb.getTradeDataFromDataBase(product_code, ma, autotype=autoType) tradeDataDf = tradeDataDf.where(tradeDataDf.notnull(), None) workDateList = tradeDataDf['trade_date'].tolist() workDateList = list(map(str, workDateList)) # open,close,low,high数据获取 new_data = tradeDataDf.loc[:, gc.PRICE_COLS].values tradeDataList = new_data.tolist() kline = (Kline().add_xaxis(xaxis_data=workDateList).add_yaxis( series_name="kline", y_axis=tradeDataList, itemstyle_opts=opts.ItemStyleOpts(color="#ec0000", color0="#00da3c"), ).set_global_opts( title_opts=opts.TitleOpts( title=productname + "(%s)" % product_code, subtitle="MA%s" % 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=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=workDateList).add_yaxis( series_name="MA%s" % ma[0], y_axis=tradeDataDf.loc[:, 'ma%s' % ma[0]].values.tolist(), is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA%s" % ma[1], y_axis=tradeDataDf.loc[:, 'ma%s' % ma[1]].values.tolist(), is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA%s" % ma[2], y_axis=tradeDataDf.loc[:, 'ma%s' % ma[2]].values.tolist(), is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA%s" % ma[3], y_axis=tradeDataDf.loc[:, 'ma%s' % ma[3]].values.tolist(), is_smooth=True, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=3, opacity=0.5), label_opts=opts.LabelOpts(is_show=False), ).add_yaxis( series_name="MA%s" % ma[4], y_axis=tradeDataDf.loc[:, 'ma%s' % ma[4]].values.tolist(), 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=workDateList).add_yaxis( series_name="Volume", yaxis_data=tradeDataDf.loc[:, "volume"].values.tolist(), xaxis_index=1, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", is_scale=True, grid_index=1, boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=False), split_number=20, min_="dataMin", max_="dataMax", ), yaxis_opts=opts.AxisOpts( grid_index=1, is_scale=True, split_number=2, axislabel_opts=opts.LabelOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_show=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), ), legend_opts=opts.LegendOpts(is_show=False), )) # Kline And Line 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
xaxis_data=x_data).add_yaxis( series_name="蒸发量", y_axis=evaporation_capacity, yaxis_index=0, color=colors[1]).add_yaxis( series_name="降水量", y_axis=rainfall_capacity, yaxis_index=1, color=colors[0]).extend_axis( yaxis=opts.AxisOpts(name="蒸发量", type_="value", min_=0, max_=250, position="right", axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts( color=colors[1])), axislabel_opts=opts.LabelOpts( formatter="{value} ml"))). extend_axis(yaxis=opts.AxisOpts( type_="value", name="温度", min_=0, max_=25, position="left", axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts( color=colors[2])), axislabel_opts=opts.LabelOpts(formatter="{value} °C"), splitline_opts=opts.SplitLineOpts( is_show=True, linestyle_opts=opts.LineStyleOpts(opacity=1)), )).set_global_opts(yaxis_opts=opts.AxisOpts(
), 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")
from pyecharts import charts from pyecharts import options as opts value = 200 gu = charts.Gauge(init_opts=opts.InitOpts(width="640px", height="480px")) gu.add( "指标", [("昨日单位面积能耗", value)], split_number=10, axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color=[( 0.2, "#00B050"), (0.4, "#67e0e3"), (0.7, "#FF6600"), (1, "#fd666d")], width=25)), min_=0, # 最小刻度 max_=1400, # 最大刻度 ) gu.set_global_opts( title_opts=opts.TitleOpts( title="楼宇能耗指标表盘\n昨日单位面积能耗{0}Wh/m^2".format(value)), legend_opts=opts.LegendOpts(is_show=False), ) gu.render(r"C:\Users\CQ375\Desktop\ex\Guage-eg.html")
def Pycharts(): with open('reviews/pos.txt', "r") as f: # 训练集可持续化,读取上次写文件名,这次接着来 total_reviews_ups = f.read() if total_reviews_ups == '': print('请爬取训练集') else: total_reviews_up = int(total_reviews_ups) with open('reviews/neg.txt', "r") as f: # 训练集可持续化 total_reviews_downs = f.read() if total_reviews_downs == '': print('请爬取训练集') else: total_reviews_down = int(total_reviews_downs) file = open('reviews_over.txt', 'r', encoding='UTF-8') # 路径自定义 text = file.read() file.close() cut_text = " ".join(jieba.cut(text)) words = cut_text.split() words1 = [re.sub("[\,\。\!\;\?\、\”\“]", '', word) for word in words] # 去掉标点符号 #停用词 自定义词典 jieba.load_userdict("dict.txt") stopwords_file = "stopwords.txt" stop_f = open(stopwords_file, "r", encoding='utf-8') stop_words = list() for line in stop_f.readlines(): line = line.strip() if not len(line): continue stop_words.append(line) stop_f.close DIY_stopwords = ['一个','没有','说','玩','做','里','中','-','⣿','','感','spoiler','2','点','完','·','\\','4','走','一款',"'",'会','没',',','游戏','帧','/'] for line in range(0,len(DIY_stopwords)): stop_words.append(DIY_stopwords[line]) words2 = [word for word in words1 if word not in stop_words] #停用词 wordcounts = collections.Counter(words2).most_common(200) #print(wordcounts) #词云 cloud = ( WordCloud(opts.InitOpts(width="100%", height="950px")) .add("词频统计", wordcounts, word_size_range=[20, 300], ) .set_global_opts( title_opts=opts.TitleOpts( title="词频统计", title_textstyle_opts=opts.TextStyleOpts(font_size=23) ), tooltip_opts=opts.TooltipOpts(is_show=True), ) .render("html/wordcloud_diamond.html") ) UP = ( Gauge(init_opts=opts.InitOpts(width="500px", height="500px")) .add(series_name="推荐指数", data_pair=[["", sa.pos/(sa.pos+sa.neg)*100]], title_label_opts=opts.LabelOpts(font_size=40, color="blue", font_family="Microsoft YaHei"), ) .set_global_opts( legend_opts=opts.LegendOpts(is_show=False), tooltip_opts=opts.TooltipOpts(is_show=True, formatter="{a} <br/>{b} : {c}%"), ) .set_series_opts(axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color=[[0.3, "#67e0e3"], [0.7, "#37a2da"], [1, "#fd666d"]], width=30) ) ) .render("html/gauge_up.html") ) DOWN = ( Gauge(init_opts=opts.InitOpts(width="500px", height="500px")) .add(series_name="推荐指数", data_pair=[["", sa.neg/(sa.pos+sa.neg)*100]], title_label_opts=opts.LabelOpts(font_size=40, color="blue", font_family="Microsoft YaHei"), ) .set_global_opts( legend_opts=opts.LegendOpts(is_show=False), tooltip_opts=opts.TooltipOpts(is_show=True, formatter="{a} <br/>{b} : {c}%"), ) .set_series_opts(axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color=[[0.3, "#67e0e3"], [0.7, "#37a2da"], [1, "#fd666d"]], width=30) ) ) .render("html/gauge_down.html") ) pie = ( Pie() .add( "1", [['正面训练集数量',total_reviews_up ], ['负面训练集数量', total_reviews_down]], radius=["40%", "75%"], ) .set_global_opts( title_opts=opts.TitleOpts(title="Pie-Radius"), legend_opts=opts.LegendOpts(orient="vertical", pos_top="15%", pos_left="2%"), ) .set_series_opts(label_opts=opts.LabelOpts(formatter="{b}: {c}")) .render("html/pie.html") ) bar = ( Bar() .add_xaxis(['推荐', '不推荐']) .add_yaxis("识别成功", [pospic,negpic], stack="stack1") .add_yaxis("识别失败", [totpos-pospic,totneg-negpic], stack="stack1") .set_series_opts(label_opts=opts.LabelOpts(is_show=False)) .set_global_opts(title_opts=opts.TitleOpts(title="准确度为%s" %str(RecommendCent))) .render("html/bar.html") ) webbrowser.open('file:///F:/Project/WorkSpace/2077CommentAnalyze/Python/html/index.html')
from pyecharts import options as opts from pyecharts.charts import PictorialBar from pyecharts.globals import SymbolType location = ["山西", "四川", "西藏", "北京", "上海", "内蒙古", "云南", "黑龙江", "广东", "福建"] values = [13, 42, 67, 81, 86, 94, 166, 220, 249, 262] c = (PictorialBar().add_xaxis(location).add_yaxis( "", values, label_opts=opts.LabelOpts(is_show=False), symbol_size=18, symbol_repeat="fixed", symbol_offset=[0, 0], is_symbol_clip=True, symbol=SymbolType.ROUND_RECT, ).reversal_axis().set_global_opts( title_opts=opts.TitleOpts(title="PictorialBar-各省份人口数量(虚假数据)"), xaxis_opts=opts.AxisOpts(is_show=False), yaxis_opts=opts.AxisOpts( axistick_opts=opts.AxisTickOpts(is_show=False), axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts( opacity=0)), ), ).render("Pictorialbar_base.html"))
def bar_line(request): """各种类型房屋的平均价格和数量 柱状图——折线图""" districts = [] # 区县名称 infos = {} # 各类新房的总数和均价 # {'商业': [821, 21854707.0], '住宅': [567, 6424626.0], '别墅': [79, 1200119.0], '写字楼': [77, 1120913.0]} cursor = Mongo().connect_mongo('runoob', 'test').find() for data in cursor: if data["district"] not in districts: # 获取区县 districts.append(data["district"]) if data["type"] not in infos: infos[data["type"]] = [1, float(data["price"])] else: infos[data["type"]][0] += 1 infos[data["type"]][-1] += float(data["price"]) x_data = [x for x in infos.keys()] bar = ( Bar() .add_xaxis(x_data) .add_yaxis( "平均价格", ["{:.2f}".format(x[-1]/x[0]) for x in infos.values()], yaxis_index=0, color="#675bba", category_gap="65%", ) .extend_axis( yaxis=opts.AxisOpts( name="", type_="value", # min_=0, # max_=250, position="right", axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="#675bba") ), axislabel_opts=opts.LabelOpts(formatter="{value}"), ) ) .extend_axis( yaxis=opts.AxisOpts( type_="value", name="", # min_=0, # max_=25, position="none", axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(color="#d14a61") ), axislabel_opts=opts.LabelOpts(formatter="{value}"), splitline_opts=opts.SplitLineOpts( is_show=False, linestyle_opts=opts.LineStyleOpts(opacity=1) ) ) ) .set_global_opts( title_opts=opts.TitleOpts(title="成都各种类型新房价格与数量") ) ) line = ( Line() .add_xaxis(x_data) .add_yaxis( "新房数量", ["{}".format(x[0]) for x in infos.values()], yaxis_index=2, color="#675bba", label_opts=opts.LabelOpts(is_show=True), ) ) bar.overlap(line) bar.overlap(line).render("templates/barline.html") return HttpResponse(bar.overlap(line).render_embed())
def pollsummary(self,subset='masterCandle',dat_cursor=None,renderfile=False): # 初始化交易时间x轴 heartbeat = 300 # 如果未提供复盘时间游标,则默认使用最近交易日至收盘收盘时间的数据 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') ) int_cursorDateTime = int(str(int_latestViewDate)+'150100') int_cursorDateStart = int(str(int_latestViewDate)+'000000') # 如提供复盘游标时间,则该时间为游标卡尺的最后时间,如日期为非交易日则自动调整为最近交易日的收盘时间 else: int_cursorDate = datetime.strftime(dat_cursor,'%Y%m%d') int_latestViewDate = self.da.int_findClosestTradeDate(int_cursorDate) if int_cursorDate==int_latestViewDate: # 如相等说明提供日期为有效交易日,则使用提供的小时分钟秒为游标终点时间,否则将自动替换为最近交易日的收盘时间点 int_cursorDateTime = int(datetime.strftime(dat_cursor,'%Y%m%d%H%M%S')) int_cursorDateStart = int(datetime.strftime(dat_cursor,'%Y%m%d')+'000000') else: int_cursorDateTime = int(str(int_latestViewDate) +'150100') int_cursorDateStart = int(str(int_latestViewDate) +'000000') beatRange = Radar.pop_pulseRange(int_latestViewDate,heartbeat) df_stockPoll = pd.read_sql(DataAgent.dbsession.query(Stock_poll).filter(Stock_poll.time_index>=int_cursorDateStart, Stock_poll.time_index<=int_cursorDateTime, Stock_poll.volume!=0).statement, DataAgent.dbsession.bind) df_indexPoll = pd.read_sql(DataAgent.dbsession.query(Index_poll).filter(Index_poll.time_index>=int_cursorDateStart, Index_poll.time_index<=int_cursorDateTime, Index_poll.volume!=0).statement, DataAgent.dbsession.bind) ''' data_store = libs.tryOpenH5(cfg.H5_FILE_POLL,mode='r') if 'stockPoll' in data_store: df_stockPoll = data_store['stockPoll'] df_stockPoll = df_stockPoll[df_stockPoll['volume']!=0] # 过滤掉数据中非交易中的证券 df_stockPoll = df_stockPoll[(df_stockPoll['time_index']<=int_cursorDateTime)&(df_stockPoll['time_index']>=int_cursorDateStart)] # 过滤掉和画图期间无关的数据 else: df_stockPoll = pd.DataFrame() df_indexPoll = data_store['indexPoll'] if 'indexPoll' in data_store else pd.DataFrame() data_store.close() ''' data_store = libs.tryOpenH5(cfg.H5_FILE_PRE,mode='r') # 如果按照输入日期没有找到当日任何盘中数据,则从入库历史数据中找到当日收盘数据用于填充 if len(df_indexPoll)==0: df_indexPoll = data_store['masterCandle'][data_store['masterCandle']['trade_date']==int_latestViewDate] df_indexPoll['time_index'] = int_cursorDateTime df_indexPoll['pct_change'] = round(df_indexPoll['adj_close']/df_indexPoll['pre_close']*100,2) df_indexPoll['per'] = np.nan if len(df_stockPoll)==0: df_stockPoll = data_store['masterCandle'][data_store['masterCandle']['trade_date']==int_latestViewDate] df_stockPoll['time_index'] = int_cursorDateTime df_stockPoll['pct_change'] = round((df_stockPoll['adj_close']-df_stockPoll['pre_close'])/df_stockPoll['pre_close']*100,2) df_stockPoll.rename(columns={'pe': 'per'}, inplace=True) # 如果入库历史数据中仍未找到任何数据则退出分析程序 if any([len(df_stockPoll)==0,len(df_indexPoll)==0]): data_store.close() print('stockPoll or indexPoll does not exist for the cursor date in the offline data store, process exiting...') return False ''' ------读取security code级别的聚合数据------- ''' if subset=='masterCandle': pass #data_store = libs.tryOpenH5(cfg.H5_FILE_PRE,mode='r') else: data_store.close() # 关闭之前打开的master data file data_store = libs.tryOpenH5('{}{}.dat'.format(cfg.H5_FILE_PATH,subset),mode='r') df_histRec = data_store['AggByCode'] data_store.close() self.poll_aggHistRec = df_histRec # sec code 级别的聚合数据,集合包含证券及指数,输出至对象变量 ''' ------读取security code级别的聚合结束------- ''' sr_intBeatIndex = pd.Series(beatRange.strftime('%Y%m%d%H%M%S').astype('int64')).rename(index='time_index') df_index = pd.merge(sr_intBeatIndex,df_indexPoll,how='left',left_on='time_index',right_on='time_index',suffixes=['','1']) df_stock = pd.merge(sr_intBeatIndex,df_stockPoll,how='left',left_on='time_index',right_on='time_index',suffixes=['','1']) df_stock = pd.merge(df_stock,df_histRec,how='left',left_on='ts_code',right_index=True,suffixes=['','1']) self.poll_index = df_index #将结果输出至analyitics对象用于方法外的访问 self.poll_stock = df_stock #将结果输出至analyitics对象用于方法外的访问 # libs.df_csv(cfg.PATH_BUGFILE,(df_stock,)) ''' --------所有by time index级别的聚合在这里完成 -----''' def popPctList(x): # 移除涨跌幅超过+- 10%的, 新股不受10%涨跌幅限制因此会干扰box chart显示 return [0]*3 if len(x)<3 else [i for i in x if abs(i)<11] def bigBox(x, up=True): # 中阳(阴)以上k线数量 if up: return list(x.loc[(x['box_size']>0) & (x['klineSML'].str.match(DataAgent.re_bigUpBoxPat))]['ts_code']) else: return list(x.loc[(x['box_size']<0) & (x['klineSML'].str.match(DataAgent.re_bigDnBoxPat))]['ts_code']) def breakThrough(x,up=True): if up: # 找到上穿有效末跌高点的 return list(x.loc[x['close']>=x['validPiv_dnHigh']]['ts_code']) else: # 找到跌破有效末升低点的 return list(x.loc[x['close']<=x['validPiv_upLow']]['ts_code']) df_stockBeatGrp = df_stock.groupby('time_index') df_stockBeatRollup = df_stockBeatGrp.agg({'ts_code': ['count'], 'pct_change': [popPctList], 'per': ['median']}) # function放入中括号内会生成两个层级列名,方便后面join成新列名.如无中括号将只产生一层列名 df_stockBeatRollup.columns = ['_'.join(x) for x in df_stockBeatRollup.columns.ravel()] df_stockBeatRollup['upThruList'] = df_stockBeatGrp.apply(lambda x: breakThrough(x,up=True)) if len(df_histRec) > 0 else np.nan df_stockBeatRollup['dnThruList']= df_stockBeatGrp.apply(lambda x: breakThrough(x,up=False)) if len(df_histRec) > 0 else np.nan df_stockBeatRollup['upThruCount'] = df_stockBeatRollup.apply(lambda row: len(row['upThruList']),axis=1) if len(df_histRec) > 0 else np.nan df_stockBeatRollup['dnThruCount']= df_stockBeatRollup.apply(lambda row: len(row['dnThruList']),axis=1) if len(df_histRec) > 0 else np.nan df_stockBeatRollup['upBigBoxList'] = df_stockBeatGrp.apply(lambda x: bigBox(x,up=True)) df_stockBeatRollup['dnBigBoxList'] = df_stockBeatGrp.apply(lambda x: bigBox(x,up=False)) df_stockBeatRollup['upBigBoxCount'] = df_stockBeatRollup.apply(lambda row: len(row['upBigBoxList']),axis=1) if len(df_histRec) > 0 else np.nan df_stockBeatRollup['dnBigBoxCount'] = df_stockBeatRollup.apply(lambda row: len(row['dnBigBoxList']),axis=1) if len(df_histRec) > 0 else np.nan ''' --------by time index级别的聚合结束 -------------------------------''' df_stockBeatRollup.astype(dtype= {'ts_code_count':'int32','upThruCount':'int32','dnThruCount':'int32','upBigBoxCount':'int32','dnBigBoxCount':'int32'}) self.poll_aggStkPoll = df_stockBeatRollup.loc[df_stockBeatRollup['ts_code_count']>0] # 只将有效结果输出到analytics对象属性中用于function以外的调用 ''' ------------------作图区域---------------------------''' per_median = round(self.poll_aggStkPoll.loc[self.poll_aggStkPoll.index==self.poll_aggStkPoll.index.max()].per_median.values[0],2) lst_xaxis = ['{}:{}:{}'.format(i.hour,i.minute,i.second) for i in beatRange] marketSummaryBoxPlot = Boxplot() lst_yaxis = np.around(marketSummaryBoxPlot.prepare_data(df_stockBeatRollup['pct_change_popPctList'].values), decimals=2).tolist() marketSummaryBoxPlot.add_xaxis(lst_xaxis) marketSummaryBoxPlot.add_yaxis("%", lst_yaxis) marketSummaryBoxPlot.set_global_opts(title_opts=opts.TitleOpts(title='整体涨跌幅分布 - {} (最后市盈率中位数:{})'.format(int_latestViewDate,str(per_median))), yaxis_opts=opts.AxisOpts(name="涨幅",min_=-10,max_=10), xaxis_opts=opts.AxisOpts(name="", axislabel_opts=opts.LabelOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_show=True), axistick_opts=opts.AxisTickOpts(is_show=True), splitline_opts=opts.SplitLineOpts(is_show=False),), legend_opts=opts.LegendOpts(is_show=False), ) lst_upThruBar = df_stockBeatRollup['upThruCount'].values.tolist() lst_dnThruBar = df_stockBeatRollup['dnThruCount'].values.tolist() lst_bigUpBoxBar = df_stockBeatRollup['upBigBoxCount'].values.tolist() lst_bigDnBoxBar = df_stockBeatRollup['dnBigBoxCount'].values.tolist() pivotCountChart = ( Bar() .add_xaxis(lst_xaxis) .add_yaxis( series_name="向上突破数量", yaxis_data=lst_upThruBar, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color="#FD625E"), ) .add_yaxis( series_name="向下突破数量", xaxis_index=1, yaxis_index=1, yaxis_data=lst_dnThruBar, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color="#01B8AA"), ) .add_yaxis( series_name="长阳线数量", xaxis_index=1, yaxis_index=1, yaxis_data=lst_bigUpBoxBar, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color="red"), ) .add_yaxis( series_name="长阴线数量", xaxis_index=1, yaxis_index=1, yaxis_data=lst_bigDnBoxBar, label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts(color="green"), ) .set_global_opts( xaxis_opts=opts.AxisOpts(name="小时/分钟",), yaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(is_show=True), axisline_opts=opts.AxisLineOpts(is_show=True), axistick_opts=opts.AxisTickOpts(is_show=True), splitline_opts=opts.SplitLineOpts(is_show=True), ), legend_opts=opts.LegendOpts(is_show=True,pos_bottom='0%', pos_left="center"), ) ) gridChart = Grid() gridChart.add( marketSummaryBoxPlot, grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_bottom='45%'), ) gridChart.add( pivotCountChart, grid_opts=opts.GridOpts(pos_left="10%", pos_right="8%", pos_top="55%"), ) fname = '{}marketSummary{}.html'.format(cfg.PATH_ANAFILE,int_latestViewDate) gridChart.render(fname) if renderfile else None return gridChart