前一阶段写了使用matplotlib画K线图,但是使用matplotlib画K线图有很多缺点,比如交易日问题、图像丑陋问题,虽然后期也可以改进,但是代码过于冗余,今天使用pyecharts画K线图,使用的pyecharts是1.9.0版本
使用pyecharts需要注意,由于numpy和pandas库数据比较大,官方并不支持,因此需要使用to_list(),进行转化,而且横坐标为日期时不支持日期格式,需要转化为str格式,K线图数据顺序需要调整为open、close、low、high,另外
kline=(Kline().add_xaxis(df.date.values.tolist()).add_yaxis("{}".format(code),data.values.tolist(),xaxis_index=0,yaxis_index=0)
在add_yaxis()中第一个参数可以使用"",但是不可以省略,否则会出错
importpandasaspdimportnumpyasnpimportdatetime,sysfrompyechartsimportoptionsasoptsfrompyecharts.chartsimportKline,Line,Bar,Gridimportpymysqlpd.set_option("display.float_format",lambdax:%.4f%x)pd.set_option(display.width,,display.max_columns,,display.max_rows,)defkline_df(code=sh.,start_date=datetime.datetime.today()-datetime.timedelta(days=),end_date=datetime.datetime.today()):#k线数据提取函数,请使用其他路径提取start_date=kline_date(start_date,end_date)[0]start_date_str=kline_date(start_date,end_date)[1]end_date=kline_date(start_date,end_date)[2]end_date_str=kline_date(start_date,end_date)[3]conn=pymysql.connect(host="localhost",user="Bran",password=,port=,database="demo")sql="select`date`,`code`,`open`,`high`,`low`,`close`,`volume`,`amount`,`peTTM`,`pbMRQ`,`psTTM`,`pcfNcfTTM`frombaostock_daily"\"where`code`={}and`date`between{}and{};".format(code,start_date_str,end_date_str)sql_stock_basic="selectdistinct`code`,`code_name`frombaostock_basicwhere`code`={}".format(code)df=pd.read_sql(sql,conn)stock=pd.read_sql(sql_stock_basic,conn)iflen(df)==0:print("没有找到{}数据,请检查是输入是否错误".format(code))sys.exit(0)else:stock_name=stock.loc[0,"code_name"]returndf,stock_name,stockdefkline_date(start_date=datetime.datetime.today()-datetime.timedelta(days=),end_date=datetime.datetime.today()):#日期处理函数,若已处理好可忽略iftype(start_date)==int:start_date_str=str(start_date)start_date=datetime.datetime.strptime(str(start_date),"%Y%m%d").date()iftype(end_date)==int:end_date_str=str(end_date)end_date=datetime.datetime.strptime(str(end_date),"%Y%m%d").date()iftype(start_date)==datetime.datetime:start_date_str=start_date.strftime(%Y%m%d)start_date=start_date.date()iftype(end_date)==datetime.datetime:end_date_str=end_date.strftime(%Y%m%d)end_date=end_date.date()iftype(start_date)==datetime.date:start_date_str=start_date.strftime(%Y%m%d)iftype(end_date)==datetime.date:end_date_str=end_date.strftime(%Y%m%d)iftype(start_date)==str:start_date_str="".join(start_date)start_date=datetime.datetime.strptime(start_date,"%Y%m%d").date()iftype(end_date)==str:end_date_str="".join(end_date)end_date=datetime.datetime.strptime(end_date,"%Y%m%d").date()ifend_datestart_date:print("开始日期大于结束日期,请检查")sys.exit(0)returnstart_date,start_date_str,end_date,end_date_strdefkline_pycharts(code,start_date=datetime.datetime.today()-datetime.timedelta(days=),end_date=datetime.datetime.today()):df=kline_df(code,start_date,end_date)[0]stock_name=kline_df(code,start_date,end_date)[1]start_date=min(df.date)end_date=max(df.date)iftype(start_date)==datetime.datetime:start_date_str=start_date.strftime(%Y%m%d)else:start_date_str=start_dateiftype(end_date)==datetime.datetime:end_date_str=end_date.strftime(%Y%m%d)else:end_date_str=end_dateiflen(df)==0:print("没有找到{}数据,请检查是输入是否错误".format(code))else:iflen(stock_name)0:code_name=code+stock_nameprint(code_name)else:code_name=codeifdf.date.dtypes==datetime64[ns]:df.date=df.date.apply(lambdax:x.strftime(%Y/%m/%d))#data=df.drop(columns=[date,code,volume,amount],axis=0)data=df.loc[:,[open,close,low,high]]data=data.apply(pd.to_numeric)data=data.loc[:,[open,close,low,high]]kline=(Kline().add_xaxis(df.date.values.tolist()).add_yaxis("{}".format(code),data.values.tolist(),xaxis_index=0,yaxis_index=0,markpoint_opts=opts.MarkPointOpts(data=[opts.MarkPointItem(type_="max",name="最大值",symbol=pin,symbol_size=[30,30]),opts.MarkPointItem(type_="min",name="最小值",symbol=arrow,symbol_size=[20,20]),],label_opts=opts.LabelOpts(position="inside",color="#",font_weight=bold),##标签字体颜色)).set_global_opts(legend_opts=opts.LegendOpts(pos_top="2%"),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)),),datazoom_opts=[opts.DataZoomOpts(is_show=False,type_="inside",xaxis_index=[0,0],range_start=0,range_end=),opts.DataZoomOpts(is_show=True,xaxis_index=[0,1],pos_top="95%",range_start=0,range_end=),opts.DataZoomOpts(is_show=False,xaxis_index=[0,2],range_start=0,range_end=),],title_opts=opts.TitleOpts(title="{}K线图".format(stock_name)),tooltip_opts=opts.TooltipOpts(axis_pointer_type=cross))#全局配置项#.set_series_opts(label_opts=opts.LabelOpts(position="inside",color="#",is_show=False))#.render("E:\\Brandon\\Desktop\\kline.html"))kline_line=(Line().add_xaxis(df.date.values.tolist()).add_yaxis("20天均线",df.close.rolling(window=20,min_periods=20).mean().round(decimals=2).values.tolist(),xaxis_index=0,yaxis_index=0).add_yaxis("60天均线",df.close.rolling(window=60,min_periods=60).mean().round(decimals=2).values.tolist(),xaxis_index=0,yaxis_index=0).add_yaxis("天均线",df.close.rolling(window=,min_periods=).mean().round(decimals=2).values.tolist(),xaxis_index=0,yaxis_index=0).set_series_opts(label_opts=opts.LabelOpts(is_show=False))#.set_global_opts(title_opts=opts.TitleOpts(title="Grid-Bar"),).set_global_opts(tooltip_opts=opts.TooltipOpts(axis_pointer_type=cross)))bar1=(Bar().add_xaxis(df.date.values.tolist()).add_yaxis("交易量",df.volume.values.tolist(),xaxis_index=0,yaxis_index=1).set_series_opts(label_opts=opts.LabelOpts(is_show=False)).set_global_opts(yaxis_opts=opts.AxisOpts(name="交易量",split_number=3,name_gap=5))#.set_global_opts(title_opts=opts.TitleOpts(title="Grid-Bar")).set_global_opts(#title_opts=opts.TitleOpts(title="交易量",subtitle="元"),legend_opts=opts.LegendOpts(pos_bottom="40%",pos_left="center"),tooltip_opts=opts.TooltipOpts(axis_pointer_type=cross)))volume_line=(Line().add_xaxis(df.date.values.tolist()).add_yaxis("20日均线",df.volume.rolling(window=20,min_periods=20).mean().round(decimals=2).values.tolist(),xaxis_index=0,yaxis_index=1,label_opts=opts.LabelOpts(is_show=False)).add_yaxis("60日均线",df.volume.rolling(window=60,min_periods=60).mean().round(decimals=2).values.tolist(),xaxis_index=0,yaxis_index=1,label_opts=opts.LabelOpts(is_show=False)).set_series_opts(label_opts=opts.LabelOpts(is_show=False),).set_global_opts(#title_opts=opts.TitleOpts(title="交易量",subtitle="元"),legend_opts=opts.LegendOpts(pos_bottom="45%",pos_left="center"),tooltip_opts=opts.TooltipOpts(axis_pointer_type=cross)))bar2=(Bar().add_xaxis(df.date.values.tolist()).add_yaxis("交易额",df.amount.values.tolist(),xaxis_index=0,yaxis_index=2).set_series_opts(label_opts=opts.LabelOpts(is_show=False)).set_global_opts(yaxis_opts=opts.AxisOpts(name="交易额",split_number=3,name_gap=5),)#.set_global_opts(title_opts=opts.TitleOpts(title="Grid-Bar")).set_global_opts(#title_opts=opts.TitleOpts(title="交易额",subtitle="元"),legend_opts=opts.LegendOpts(pos_bottom="20%",pos_left="center"),tooltip_opts=opts.TooltipOpts(axis_pointer_type=cross)))amoumt_line=(Line().add_xaxis(df.date.values.tolist()).add_yaxis("20日均线",df.amount.rolling(window=20,min_periods=20).mean().round(decimals=2).values.tolist(),xaxis_index=0,yaxis_index=0,label_opts=opts.LabelOpts(is_show=False)).add_yaxis("60日均线",df.amount.rolling(window=60,min_periods=60).mean().round(decimals=2).values.tolist(),xaxis_index=0,yaxis_index=0,label_opts=opts.LabelOpts(is_show=False)).set_series_opts(label_opts=opts.LabelOpts(is_show=False)).set_global_opts(title_opts=opts.TitleOpts(title="交易额",subtitle="元"),legend_opts=opts.LegendOpts(pos_bottom="20%",pos_left="center"),tooltip_opts=opts.TooltipOpts(axis_pointer_type=cross)))overlap_kline_line=kline.overlap(kline_line)overlap_volume_line=bar1.overlap(volume_line)overlap_amoumt_line=bar2.overlap(amoumt_line)grid=(Grid().add(overlap_kline_line,grid_opts=opts.GridOpts(pos_top=8%,pos_bottom="50%",pos_left=12%,pos_right=10%)).add(overlap_volume_line,grid_opts=opts.GridOpts(pos_top=60%,pos_bottom="30%",pos_left=12%,pos_right=10%)).add(overlap_amoumt_line,grid_opts=opts.GridOpts(pos_top=80%,pos_left=12%,pos_right=10%)))grid.render("E:\\Brandon\\Desktop\\{}{}-{}K线图.html".format(code_name,start_date_str,end_date_str))print(f"已生成{code}{stock_name}{start_date_str}至{end_date_str}的K线图")if__name__==__main__:kline_pycharts("sh.")
最终效果:
明月照猫侠