def test_timeline_label_color(): attr = ["{}月".format(i) for i in range(1, 7)] bar = Bar("1 月份数据", "数据纯属虚构") bar.add( "bar", attr, [randint(10, 50) for _ in range(6)], label_color=["red", "#213", "black"], ) line = Line() line.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_0 = Overlap() overlap_0.add(bar) overlap_0.add(line) bar_1 = Bar("2 月份数据", "数据纯属虚构") bar_1.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_1 = Line() line_1.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_1 = Overlap() overlap_1.add(bar_1) overlap_1.add(line_1) timeline = Timeline(timeline_bottom=0) timeline.add(overlap_0, "1 月") timeline.add(overlap_1, "2 月") content = timeline._repr_html_() assert '"color": [' in content assert "red" in content assert "#213" in content assert "black" in content
def test_grid_add_overlap(): from pyecharts import Overlap grid = Grid() attr = ["{}月".format(i) for i in range(1, 13)] v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] v3 = [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2] bar = Bar("Overlap+Grid 示例", width=1200, height=600, title_pos="40%") bar.add("蒸发量", attr, v1) bar.add( "降水量", attr, v2, yaxis_formatter=" ml", yaxis_max=250, legend_pos="85%", legend_orient="vertical", legend_top="45%", ) line = Line() line.add("平均温度", attr, v3, yaxis_formatter=" °C") overlap = Overlap() overlap.add(bar) overlap.add(line, is_add_yaxis=True, yaxis_index=1) grid.add(overlap, grid_right="20%") grid.render()
def brush(data): data = hist_sum(data) kline = Kline() kline.add( 'Kline', data.index, data.loc[:, ['open', 'close', 'low', 'high']].values, mark_line=['max', 'min'], mark_line_valuedim=['highest', 'lowest'], is_datazoom_show=True, datazoom_xaxis_index=[0, 1], ) brush = Line() brush.add( 'Brush', data.index, data.endpoint.values, ) overlap = Overlap() overlap.add(kline) overlap.add(brush) macd = Bar() macd.add( 'MACD', data.index, data.hist_sum.values, ) page = Page() page.add(overlap) page.add(macd) return page
def __init__(self): self.data = {{'label': []}, } self.titles = '' self.indexes = [] self.bar = Bar() self.line = Line() self.overlap = Overlap() self.script_list = self.overlap.get_js_dependencies()
def test_not_set_in_overlap(): attr = ["A", "B", "C", "D", "E", "F"] v1 = [10, 20, 30, 40, 50, 60] line = Line() line.add("line", attr, v1) line._option["series"][0]["symbol"] = NULL overlap = Overlap() overlap.add(line) assert isinstance(overlap._option["series"][0]["symbol"], JsValue)
class Draw(object): def __init__(self, path, ispage=True): self.page = Page() self.overlap = Overlap() self.ispage = ispage self.path = path self.range_color = [ "#313695", "#4575b4", "#74add1", "#abd9e9", "#e0f3f8", "#ffffbf", "#fee090", "#fdae61", "#f46d43", "#d73027", "#a50026", ] def add(self, name, xs, ys): line = Line(name) for k, v in ys.items(): line.add(k, xs, v, is_smooth=False, is_datazoom_show=True, yaxis_min=min(v)) self.page.add(line) def add3d(self, name, data): surface3D = Scatter3D(name, width=1200, height=600) surface3D.add( "", data, is_visualmap=True, visual_range=[-1000, 4000], visual_range_color=self.range_color, ) self.page.add(surface3D) def add2y(self, name, xs, ys, yaxis_index=0): line = Line(name) for k, v in ys.items(): line.add(k, xs, v, is_smooth=False, is_datazoom_show=True) self.overlap.add(line, yaxis_index=yaxis_index, is_add_yaxis=True) def draw(self): if self.ispage: self.page.render(self.path) else: self.overlap.render(self.path)
def loc_and_mean_age(info): grouped = group(info, ['cityChn']) tidy = grouped['age'] tidy_com = tidy.agg(['mean', 'count']) tidy_com.reset_index(inplace=True) tidy_com['mean'] = round(tidy_com['mean'], 2) attr = tidy_com['cityChn'] num = tidy_com['count'] aver = tidy_com['mean'] line = Line("小姐姐-平均年龄") line.add("年龄", attr, aver, is_stack=True, xaxis_rotate=30, mark_point=['max', 'min'], yaxis_min=26, is_splitline_show=False) bar = Bar("小姐姐-城区分布") bar.add("单位:人", attr, num, mark_point=['max'], mark_line=['average'], xaxis_rotate=30, yaxis_min=0) overlap = Overlap() overlap.add(bar) overlap.add(line, yaxis_index=1, is_add_yaxis=True) overlap.render("北京百合小姐姐平均年龄与分布.html")
def kline_plot(name, ktype=0): df = cal_hadata(name) # 画K线图数据 # date = df.index.strftime('%Y%m%d').tolist() date = df.trade_date.tolist() #date = df['trade_date'].values.dt.strftime('%Y.%m.%d').tolist # date = df.index.tolist() if ktype == 0: k_value = df[['open', 'close', 'low', 'high']].values else: k_value = df[['ha_open', 'ha_close', 'ha_low', 'ha_high']].values # 引入pyecharts画图使用的是0.5.11版本,新版命令需要重写 from pyecharts import Kline, Line, Bar, Scatter, Overlap kline = Kline(name + '行情走势') kline.add('日K线图', date, k_value, is_datazoom_show=True, is_splitline_show=False) # 加入5、20日均线 df['ma20'] = df.close.rolling(20).mean() df['ma5'] = df.close.rolling(5).mean() line = Line() v0 = df['ma5'].round(2).tolist() v = df['ma20'].round(2).tolist() line.add('5日均线', date, v0, is_symbol_show=False, line_width=2) line.add('20日均线', date, v, is_symbol_show=False, line_width=2) # 成交量 bar = Bar() bar.add('成交量', date, df['vol'], tooltip_tragger='axis', is_legend_show=False, is_yaxis_show=False, yaxis_max=5 * max(df['vol'])) overlap = Overlap() overlap.add(kline) overlap.add(line, ) overlap.add(bar, yaxis_index=1, is_add_yaxis=True) return overlap
def xuqiu_diqu_mon(conn, width, height, mon): sql_xuqiu_diqu = "select name,count,mj from kanban_xuqiu_diqu where year(date_sub(create_date,interval 1 month))='%s'" \ "and month(date_sub(create_date,interval 1 month))='%s' order by mj desc"%(str(mon)[:4],str(mon)[-2:]) data_xuqiu_diqu = pd.read_sql(sql_xuqiu_diqu, conn) xuqiu_diqu_name = list(data_xuqiu_diqu.iloc[:, 0]) xuqiu_diqu_mj = list(data_xuqiu_diqu.iloc[:, 2]) xuqiu_diqu_count = list(data_xuqiu_diqu.iloc[:, 1]) xuqiu_diqu_title = str(mon)[:4] + '年' + str(mon)[-2:] + '月土流网土地需求区域分布' xuqiu_diqu_bar = Bar(xuqiu_diqu_title) xuqiu_diqu_bar.add("面积(亩)", xuqiu_diqu_name, xuqiu_diqu_mj, xaxis_interval=0, xaxis_rotate=90) xuqiu_diqu_line = Line() xuqiu_diqu_line.add("宗数", xuqiu_diqu_name, xuqiu_diqu_count, xaxis_interval=0, xaxis_rotate=90) xuqiu_diqu_overlap = Overlap(height=height, width=width) xuqiu_diqu_overlap.add(xuqiu_diqu_bar) xuqiu_diqu_overlap.add(xuqiu_diqu_line, yaxis_index=1, is_add_yaxis=True) xuqiu_diqu_overlap.render() return xuqiu_diqu_overlap
def plot_days_to_trend(video_df, save_filename): """ 使用 pyecharts 统计视频发布后上榜的天数 :param - video_df: - save_filename: """ video_df['diff'] = (video_df['trending_date'] - video_df['publish_time']).dt.days days_df = video_df['diff'].value_counts() # 观察视频发布后2个月的情况 days_df = days_df[(days_df.index >= 0) & (days_df.index <= 60)] days_df = days_df.sort_index() bar = Bar('视频发布后2个月的情况') bar.add( '柱状图', days_df.index.tolist(), days_df.values.tolist(), is_datazoom_show=True, # 启用数据缩放功能 datazoom_range=[0, 50] # 百分比范围 ) line = Line() line.add('折线图', days_df.index.tolist(), days_df.values.tolist()) overlap = Overlap() overlap.add(bar) overlap.add(line) overlap.render(os.path.join(config.output_path, save_filename))
def moneyflow_lgt(date_start, date_end, df, save_path_moneyflow_lgt): df = df.assign(hgt=df.hgt.apply(lambda x: round(x / 100, 2))) df = df.assign(sgt=df.sgt.apply(lambda x: round(x / 100, 2))) df = df.assign( north_money=df.north_money.apply(lambda x: round(x / 100, 2))) title = ' 资金流向 - 陆股通(亿元)' subtitle = ' GZH: 摸鱼大佬' bar = Bar(title, subtitle, title_pos=0.1, subtitle_text_size=15, subtitle_color='#aa8') # bar.use_theme("macarons") bar.add("沪股通", df['trade_date'], df['hgt'], bar_category_gap='40%') bar.add("深股通", df['trade_date'], df['sgt'], bar_category_gap='40%') line = Line() line.add("北上资金", df['trade_date'], df['north_money'], mark_line=['average'], mark_point=['min', 'max']) overlap = Overlap() overlap.add(bar) overlap.add(line, is_add_xaxis=False) #是否新增一个 x 坐标轴,默认为 False render_path = save_path + 'moneyflow_lgt_' + date_end + '.png' # bar.render(path=render_path) overlap.render(path=render_path) # pic_zoom(render_path, save_path_tgbhotstock, 740) print('moneyflow_lgt done: ' + render_path) return render_path
def generate_score_tabale(): city_main = city_com.sort_values('count', ascending=False)[0:20] attr = city_main['city'] v1 = city_main['count'] v2 = city_main['mean'] line = Line("主要城市平均评分") line.add("主要城市平均评分", attr, v2, is_stack=True, xaxis_rotate=50, yaxis_min=4.0, mark_point=['min', 'max'], xaxis_interval=0, line_color='lightblue', line_width=4, mark_point_textcolor='yellow', mark_point_color='lightblue', is_splitline_show=False) bar = Bar("主要城市评论数及评分") bar.add("主要城市评论数", attr, v1, is_stack=True, xaxis_rotate=50, yaxis_min=0, xaxis_interval=0, is_splitline_show=False) overlap = Overlap() # 默认不新增 x y 轴,并且 x y 轴的索引都为 0 overlap.add(bar) overlap.add(line, yaxis_index=1, is_add_yaxis=True) overlap.render('resources/city_score.html')
def brush(data): data = feature.full_data(data) print(data.tail()) kline = Kline() kline.add( 'Kline', data.index, data.loc[:, ['open', 'close', 'low', 'high']].values, # mark_line=['max', 'min'], # mark_line_valuedim=['highest', 'lowest'], # is_datazoom_show=True, # datazoom_xaxis_index=[0, 1, 2], # datazoom_type='both', # tooltip_axispointer_type='cross', # is_more_utils=True, ) brush = Line() brush.add( 'Brush', data.index, data.endpoint ) overlap = Overlap() overlap.add(kline) overlap.add(brush) turnover = Bar() turnover.add( '', data.index, data.turnover.values / pow(10, 6), mark_line=['max', 'min'] ) macd = Bar() macd.add( '', data.index, data.macdhist.values, mark_line=['max', 'min'], ) grid = Grid('', width='100%', height=900) grid.add(overlap, grid_bottom='40%') grid.add(turnover, grid_top='65%', grid_bottom='20%') grid.add(macd, grid_top='85%') return overlap
def createKlines(self): overlap = Overlap() for quote in self.quote_data: line = Line(quote['title']) line.add('open', quote['date'], quote['open'], is_smooth=True) line.add('close', quote['date'], quote['close'], is_smooth=True) line.add('high', quote['date'], quote['high'], is_smooth=True) line.add('low', quote['date'], quote['low'], is_smooth=True) overlap.add(line) snippet = TRANSLATOR.translate(overlap.options) options = snippet.as_snippet() return options
def example1(time_list, base_list, net_list, close_list): overlap = Overlap( width=1600, height=800, ) line = Line() line.add( "BTC基准线", time_list, base_list, is_datazoom_show=True, is_datazoom_extra_show=True, is_legend_show=True, # is_label_show=True, is_more_utils=True, is_xaxislabel_align=True, is_yaxislabel_align=True, line_color="#7CFC00", line_width=3, tooltip_axispointer_type="cross", # mark_point=["max", "min"] ) line.add( "净值", time_list, net_list, is_datazoom_show=True, is_datazoom_extra_show=True, is_legend_show=True, # is_label_show=True, is_more_utils=True, is_xaxislabel_align=True, is_yaxislabel_align=True, line_color="#00ff00", line_width=5, tooltip_axispointer_type="cross", # mark_point=["max", "min"] ) line2 = Line() line2.add( "BTC价格", time_list, close_list, is_datazoom_show=True, is_datazoom_extra_show=True, is_legend_show=True, # is_label_show=True, is_more_utils=True, is_xaxislabel_align=True, is_yaxislabel_align=True, line_color="#696969", line_width=3, # mark_point=["max", "min"] ) overlap.add(line) overlap.add(line2, is_add_yaxis=True, yaxis_index=1) overlap.render()
def demo(cls): page = Page("测试报告") line = Line("测试", width=1200, height=400) data_one = [list(range(1, 6)), [2, 5, 6, 3, 7]] data_two = list(range(1, 6)), [3, 9, 1, 2, 4] line.add("第一条曲线", data_one[0], data_one[1]) line.add("第二条曲线", data_two[0], data_two[1]) bar1 = Bar() bar1.add("ROKI_bar", data_one[0], data_one[1]) bar1.add("ROKI_bar", data_two[0], data_two[1]) overlap1 = Overlap(width=1200, height=400) overlap1.add(line) overlap1.add(bar1) page.add(overlap1) page.render("test.html")
def view(code, start_, end_, days): ''' 使用pyecharts展示数据 :param code: 股票代码 :param start_: 开始时间(包含)格式为'2018-01-01' :param end_: 结束时间(包含)格式为'2018-01-01' :param days: 设置求多少天内波动率 :return: ''' th = get_data_from_db(code, start_, end_) # 中间有数据缺失的情况,因为股票在工作日才会交易,非工作日的交易数据是缺失的,我们要填充上去 l = len(th) start = th.iloc[0:1].index.tolist()[0] end = th.iloc[l - 1:l].index.tolist()[0] idx = pd.date_range(start=start, end=end) # 接着我们使用reindex函数将缺失数据补全 # 数据补全的规则是,价格数据用前一个交易日的数据来填充,但是交易量需要填充为0 data = th.reindex(idx) zvalues = data.loc[~(data.volume > 0)].loc[:, ['volume']] data.update(zvalues.fillna(0)) # pad/ffill:用前一个非缺失值去填充该缺失值 # backfill/bfill:用下一个非缺失值填充该缺失值 data.fillna(method='ffill', inplace=True) # # 根据分组索引来分组,days为分组时间长度 group_index = gen_item_group_index(len(data), days) data['group_index'] = group_index group = data.groupby('group_index').agg({ 'volume': 'sum', 'low': 'min', 'high': _high_price }) # 添加每个分组起始日期 data_col = pd.DataFrame({'group_index': group_index, 'date': idx}) group['date'] = data_col.groupby('group_index').agg('first') # 添加波动率 group['ripples_radio'] = group.high / group.low attr = [str(x.strftime('%Y-%m-%d')) for x in group.date] v1 = [round(x, 2) for x in group.ripples_radio.tolist()] v2 = [round(x / 10000, 2) for x in group.volume.tolist()] bar = Bar(width=1200, height=600) bar.add("波动率", attr, v1) line = Line() line.add("成交量", attr, v2, yaxis_formatter=" 万手") overlap = Overlap() # 默认不新增 x y 轴,并且 x y 轴的索引都为 0 overlap.add(bar) # 新增一个 y 轴,此时 y 轴的数量为 2,第二个 y 轴的索引为 1(索引从 0 开始),所以设置 yaxis_index = 1 # 由于使用的是同一个 x 轴,所以 x 轴部分不用做出改变 overlap.add(line, yaxis_index=1, is_add_yaxis=True) overlap.render('股票[{0}]{1}天波动率和成交量图.html'.format(code, days))
def test_overlap_es_scatter(): v1 = [10, 20, 30, 40, 50, 60] v2 = [30, 30, 30, 30, 30, 30] v3 = [50, 50, 50, 50, 50, 50] v4 = [10, 10, 10, 10, 10, 10] es = EffectScatter("Scatter-EffectScatter 示例") es.add("es", v1, v2) scatter = Scatter() scatter.add("scatter", v1, v3) es_1 = EffectScatter() es_1.add("es_1", v1, v4, symbol="pin", effect_scale=5) overlap = Overlap() overlap.add(es) overlap.add(scatter) overlap.add(es_1) overlap.render()
def plot2MACD(Symbol): path = './data2/'+ Symbol + 'MACD.csv' df = pd.read_csv(path) l1 = Line('MACD of ' + Symbol, background_color="#FFF", width=1500, height=680) l1.add('DIFF',df['date'],df['DIFF']) l1.add('DEA',df['date'],df['DEA']) b1 = Bar(width=1500, height=680) b1.add('MACD',df['date'],df['MACD']) ov = Overlap() ov.add(l1) ov.add(b1) return ov
def name_trend(name, data, gender=['M','F'], year=1920, dodge = 500): if isinstance(gender, str): name_data = data[(data['Name'] == name)&(data['Gender']==gender)&(data['Year']>=year)] attr = list(name_data['Year'].values) bar = Bar(name) bar.add("", attr, list(name_data['Count'].values), mark_line=["average"], mark_point=["max", "min"], legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18) line = Line() line.add("", attr, list(name_data['Count'].values + dodge)) else: name_data = data[(data['Name'] == name)&(data['Year']>=year)] attr = list(range(year, 2018)) v1 = name_data[name_data['Gender']==gender[0]].Count.values v2 = name_data[name_data['Gender']==gender[1]].Count.values bar = Bar(name) bar.add("男", attr, list(v1), legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18) bar.add("女", attr, list(v2), legend_text_size=18,xaxis_label_textsize=18,yaxis_label_textsize=18) line = Line() line.add("", attr, list(v1 + dodge)) line.add("", attr, list(v2 + dodge)) overlap = Overlap() overlap.add(bar) overlap.add(line) return overlap.render(str(name)+str(gender)+str(dodge)+'.html')
def strategy(): form = request.form getStock = form.get('stock') stock = getStock if getStock else "usTSLA" getCircle = form.get('circle') circle = getCircle if getCircle else "120" buyStrategy = BuyTrendStrategy(stock, int(circle), 1000000) closeDayList, closeValueList = buyStrategy.get_close_line() buyDayList, buyValueList = buyStrategy.get_buy_point() closeLine = Line("趋势购买策略", width="400", height="300") closeLine.add(stock, closeDayList, closeValueList) buyES = EffectScatter("购买点", width="400", height="300") buyES.add("购买点", buyDayList, buyValueList, symbol_size=8, effect_scale=3, effect_period=3, symbol="triangle") overlap = Overlap() overlap.add(closeLine) overlap.add(buyES) return render_template( "strategy.html", strategyEchart=overlap.render_embed(), host=REMOTE_HOST, script_list=buyES.get_js_dependencies(), )
def __init__(self, path, ispage=True): self.page = Page() self.overlap = Overlap() self.ispage = ispage self.path = path self.range_color = [ "#313695", "#4575b4", "#74add1", "#abd9e9", "#e0f3f8", "#ffffbf", "#fee090", "#fdae61", "#f46d43", "#d73027", "#a50026", ]
def test_line_es(): v1 = [5, 20, 36, 10, 10, 100] line = Line("line-EffectScatter 示例") line.add("", CLOTHES, v1, is_random=True) es = EffectScatter() es.add("", CLOTHES, v1, effect_scale=8) overlap = Overlap() overlap.add(line) overlap.add(es) overlap.render()
def draw_chatrs(df, col): # 分组取离职情况 data = df.groupby([col])["Attrition"] # 由于0-1标签, 求和就是离职人数,求均值就是离职人数百分比 data_mean = data.mean() line = Line() line.add('离职率', data_mean.index, data_mean.values, mark_point=['max'], mark_line=['average'], yaxis_max=1.0) overlap = Overlap(width=900, height=400) overlap.add( line, is_add_yaxis=True, yaxis_index=1, ) return overlap
def render_add(self, path="test1.html"): overlap = Overlap( width=1600, height=800, ) # overlap.add(self.empty_line) overlap.add(self.kline) overlap.add(self.line, is_add_yaxis=True, yaxis_index=1) # overlap.add(self.line, yaxis_index=0) # overlap.add(self.kline, is_add_yaxis=True, yaxis_index=3) overlap.render(path=path)
def Longgang(longgang,price,add): overlap=Overlap() print(longgang) attr=['布吉关', '布吉大芬', '布吉水径', '坂田', '布吉街', '布吉南岭', '丹竹头', '大运新城', '横岗', '龙岗双龙', '龙岗中心城', '龙岗宝荷', '坪地', '平湖'] n1, n2, n3, n4, n5, n6,n7, n8, n9, n10, n11, n12,n13,n14 = [], [], [], [], [], [],[], [], [], [], [], [],[],[] for i in range(len(add)): if add[i] == longgang[0]: n1.append(price[i]) if add[i] == longgang[1]: n2.append(price[i]) if add[i] == longgang[2]: n3.append(price[i]) if add[i] == longgang[3]: n4.append(price[i]) if add[i] == longgang[4]: n5.append(price[i]) if add[i] == longgang[5]: n6.append(price[i]) if add[i] == longgang[6]: n7.append(price[i]) if add[i] == longgang[7]: n8.append(price[i]) if add[i] == longgang[8]: n9.append(price[i]) if add[i] == longgang[9]: n10.append(price[i]) if add[i] == longgang[10]: n11.append(price[i]) if add[i] == longgang[11]: n12.append(price[i]) if add[i] == longgang[12]: n13.append(price[i]) if add[i] == longgang[13]: n14.append(price[i]) l = [len(n1), len(n2), len(n3), len(n4), len(n5), len(n6), len(n7), len(n8), len(n9), len(n10),len(n11),len(n12),len(n13),len(n14)] ave = [round(numpy.mean(n1), 2), round(numpy.mean(n2), 2), round(numpy.mean(n3), 2), round(numpy.mean(n4), 2), round(numpy.mean(n5), 2), round(numpy.mean(n6), 2), round(numpy.mean(n7), 2), round(numpy.mean(n8), 2), round(numpy.mean(n9), 2), round(numpy.mean(n10), 2),round(numpy.mean(n11), 2), round(numpy.mean(n12), 2), round(numpy.mean(n13), 2),round(numpy.mean(n14), 2)] bar = Bar("龙岗区房屋数量_均价分布图", "", title_pos="left", width=1200, height=600) bar.add("", attr, ave, is_visualmap=True, visual_text_color='#fff', is_more_utils=True, is_label_show=True, is_datazoom_show=True, xaxis_rotate=45) overlap.add(bar) line = Line('龙岗区房屋数量_均价图', width=1200, height=600) line.add('数量', attr, l, is_stack=True, mark_point=['max', 'min'], line_color='lightblue', is_more_utils=True, visual_range=[0, 50]) overlap.add(line, is_add_yaxis=True, yaxis_index=1) overlap.render('龙岗区房屋数量_均价折线图.html') pie = Pie('龙岗区房屋数量面积占比', title_pos='center', width=1200, height=600) pie.add("", attr, l, label_text_color=None, is_label_show=True, legend_orient='vertical', is_more_utils=True, legend_pos='left') pie.render('龙岗区房屋数量占比Pie.html')
def test_overlap_bar_line(): attr = ["A", "B", "C", "D", "E", "F"] v1 = [10, 20, 30, 40, 50, 60] v2 = [38, 28, 58, 48, 78, 68] bar = Bar("Line-Bar 示例") bar.add("bar", attr, v1) line = Line() line.add("line", attr, v2) overlap = Overlap() overlap.add(bar) overlap.add(line) overlap.render()
def test_overlap_bar_line(): attr = ['A', 'B', 'C', 'D', 'E', 'F'] v1 = [10, 20, 30, 40, 50, 60] v2 = [38, 28, 58, 48, 78, 68] bar = Bar("Line - Bar 示例") bar.add("bar", attr, v1) line = Line() line.add("line", attr, v2) overlap = Overlap() overlap.add(bar) overlap.add(line) overlap.render()
def moneyflow_a_stock_all(date_start, date_end, save_path_moneyflow_ggt=''): # '000001.SH', '上证指数' # '399001.SZ', '深证成指' # '399006.SZ', '创业板指' # '399005.SZ', '中小板指' df1 = pro.index_daily( ts_code='000001.SH', start_date=date_start, end_date=date_last_trade_day).sort_index(ascending=False) df2 = pro.index_daily( ts_code='399001.SZ', start_date=date_start, end_date=date_last_trade_day).sort_index(ascending=False) # df3 = pro.index_daily(ts_code='399006.SZ', start_date=date_start, end_date=date_last_trade_day).sort_index(ascending=False) # df4 = pro.index_daily(ts_code='399005.SZ', start_date=date_start, end_date=date_last_trade_day).sort_index(ascending=False) # df5 = pro.index_daily(ts_code='399300.SZ', start_date=date_start, end_date=date_last_trade_day).sort_index(ascending=False) df0 = pd.DataFrame() df0['amount'] = df1['amount'] + df2['amount'] df0['trade_date'] = df1['trade_date'] df0 = df0.assign(amount=df0.amount.apply(lambda x: round(x / 100000, 0))) df1 = df1.assign(amount=df1.amount.apply(lambda x: round(x / 100000, 0))) df2 = df2.assign(amount=df2.amount.apply(lambda x: round(x / 100000, 0))) print(df0) title = ' 盘面资金 - A股(亿元)' subtitle = ' GZH: 摸鱼大佬' bar = Bar(title, subtitle, title_pos=0.1, subtitle_text_size=15, subtitle_color='#aa8') # bar.use_theme("macarons") bar.add("上证", df1['trade_date'], df1['amount'], bar_category_gap='40%') bar.add("深证", df2['trade_date'], df2['amount'], bar_category_gap='40%') line = Line() line.add("全市场", df0['trade_date'], df0['amount'], mark_line=['average'], mark_point=['min', 'max']) overlap = Overlap() overlap.add(bar) overlap.add(line, is_add_xaxis=False) #是否新增一个 x 坐标轴,默认为 False render_path = save_path + 'moneyflow_a_stock_all_' + date_end + '.png' # bar.render(path=render_path) overlap.render(path=render_path) # pic_zoom(render_path, save_path_tgbhotstock, 740) print('moneyflow_ggt done: ' + render_path) return render_path
def dataGet(self): """获取行情""" data = self.data #print "data1111=", data #data.sort_values('date', inplace=True) ochl = data[['openPrice', 'lastPrice', 'hightPrice', 'lowPrice']] ochl_tolist = [ochl.ix[i].tolist() for i in range(len(ochl))] close_df = data['lastPrice'] sma_N1 = talib.SMA(np.array(close_df), self.N1) sma_N2 = talib.SMA(np.array(close_df), self.N2) date_df = data.index kline = Candlestick() # datazoom_orient='vertical' dataZoom效果加到纵坐标上 kline.add(self.title, date_df, ochl_tolist, mark_point=['max', 'min'], is_datazoom_show=True, mark_point_symbolsize=80, mark_line_valuedim=['highest', 'lowest']) line = Line() line.add(u'{}日均线'.format(self.N1), date_df, sma_N1, is_fill=False, line_opacity=0.8, is_smooth=True, line_color='b') line.add(u'{}日均线'.format(self.N2), date_df, sma_N2, is_fill=False, line_opacity=0.8, is_smooth=True, line_color='g') overlap = Overlap(page_title=self.title, width=self.overWidth, height=self.overHeight) overlap.add(kline) overlap.add(line) KLine_path = r'KLine.html' overlap.render(KLine_path) # 自动打开HTML #self.driver = webdriver.Firefox() #self.driver.get(KLine_path) #if __name__ == '__main__': #PyechartsKLine()
def test_overlap_es_scatter(): v1 = [10, 20, 30, 40, 50, 60] v2 = [30, 30, 30, 30, 30, 30] v3 = [50, 50, 50, 50, 50, 50] v4 = [10, 10, 10, 10, 10, 10] es = EffectScatter("Scatter-EffectScatter 示例") es.add("es", v1, v2) scatter = Scatter() scatter.add("scatter", v1, v3) es_1 = EffectScatter() es_1.add("es_1", v1, v4, symbol='pin', effect_scale=5) overlap = Overlap() overlap.add(es) overlap.add(scatter) overlap.add(es_1) overlap.render()
def plotMACD(Symbol): path = './data/' + Symbol + 'MACD.csv' df = pd.read_csv(path) l1 = Line(background_color="#FFF", width=1500, height=680, is_datazoom_show=True, datazoom_type="both") l1.add('DIFF', df['date'], df['DIFF']) l1.add('DEA', df['date'], df['DEA']) b1 = Bar(is_datazoom_show=True, datazoom_type="both") b1.add('MACD', df['date'], df['MACD']) ov = Overlap() ov.add(l1) ov.add(b1) return ov
def forecastPlot(foreData, target, localPath): """ :param ismn_data: DataFrame. Merged dataset of ISMN :return: html file stored in paht './plot/ismn_ts' """ # create a new folder: plot/ismn_ts path = '../{}/predictionPlot'.format(localPath) if not os.path.exists(path): os.makedirs(path) foreData = foreData.copy() foreData['timeStamp'] = pd.to_datetime(foreData['timeStamp']) for station in foreData.station.unique(): line = Line("forecast of soil mosture at %i cm" % target, station) overlap = Overlap(width=1200, height=500) dataset = foreData[foreData.station == station] dataset.index = dataset.timeStamp fore_columns = list(dataset.filter(regex='fore|actual').columns) for forecastVar in fore_columns: x = dataset.index y = list(dataset.loc[:, [forecastVar]].values.reshape(-1)) line.add(forecastVar, x, y, is_datazoom_show=True) overlap.add(line) overlap.render(path=path + '/{0}_forecast_{1}cm.html'.format(station, target))
def test_overlap_bar_line(): attr = ['A', 'B', 'C', 'D', 'E', 'F'] v1 = [10, 20, 30, 40, 50, 60] v2 = [38, 28, 58, 48, 78, 68] bar = Bar("Line-Bar 示例") bar.add("bar", attr, v1) line = Line() line.add("line", attr, v2) overlap = Overlap() overlap.add(bar) overlap.add(line) overlap.render()
def test_overlap_kline_line(): import random v1 = [ [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], ] attr = ["2017/7/{}".format(i + 1) for i in range(31)] kline = Kline("Kline-Line 示例") kline.add("日K", attr, v1) line_1 = Line() line_1.add("line-1", attr, [random.randint(2400, 2500) for _ in range(31)]) line_2 = Line() line_2.add("line-2", attr, [random.randint(2400, 2500) for _ in range(31)]) overlap = Overlap() overlap.add(kline) overlap.add(line_1) overlap.add(line_2) overlap.render()
def test_overlap_two_yaxis(): attr = ["{}月".format(i) for i in range(1, 13)] v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] v3 = [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2] bar = Bar(width=1200, height=600) bar.add("蒸发量", attr, v1) bar.add("降水量", attr, v2, yaxis_formatter=" ml", yaxis_max=250) line = Line() line.add("平均温度", attr, v3, yaxis_formatter=" °C") overlap = Overlap() overlap.add(bar) overlap.add(line, yaxis_index=1, is_add_yaxis=True) overlap.render()
import numpy as np arr = np.array(data) # In[57]: from pyecharts import Bar, Line, Overlap bar = Bar("历年报考人数与录取率") bar.add("报考人数",arr[::-1,0] , arr[::-1,1]) bar.add("录取人数",arr[::-1,0] , arr[::-1,2]) line = Line() line.add("录取率",arr[::-1,0] , arr[::-1,3]*10, line_width=3, line_color='green') ol = Overlap() ol.add(bar) ol.add(line) ol # In[112]: data_born = [[124761, 123626, 122389, 121121, 119850, 118517, 117171, 115823, 114333, 112704, 111026, 109300, 107507, 105851, 104357, 103008, 101654, 100072, 98705, 97542, 96259, 94974, 93717, 92420, 90859, 89211, 87177, 85229, 82992, 80671, 78534, 76368, 74542, 72538, 70499, 69172, 67296, 65859, 66207, 67207, 65994], [14.64, 15.64, 16.57, 16.98, 17.12, 17.70, 18.09, 18.24, 19.68, 21.06, 21.58, 22.37, 23.33, 22.43, 21.04, 19.90, 20.19, 22.28, 20.91, 18.21, 17.82, 18.25, 19.03, 20.01, 23.13, 24.95, 28.07, 29.92, 30.74, 33.59, 34.25, 35.75, 34.12, 35.21, 38.00, 39.34, 43.60, 37.22, 18.13, 20.86, 24.78]] arr_born = np.array(data_born) list_born = list((arr_born[0]*arr_born[1]/1000)[::-1]) list_born
def graphpage(items,startdate,enddate,option,width1, height1): #labels:复权ork线or分笔 option:hfq, qfq or 15, 30, D, etc page = Page() for i in items:#generate numbers of graphs according to numbers of queries in treewidget j = re.split("-",i) if len(j)==3: a = generateline(j[1],j[2],startdate,enddate,option)#stock number, Type, startdate, enddate, 30 or 15 or days if a is None: continue time = [d[0] for d in a]#get time from returned dictionary if j[2]!="Kline": if len(a[0])==4 and a[0][2]=="bar": #for 分笔data overlap = Overlap() form = [e[1] for e in a] bar = Bar(j[0] + "-" + j[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items)) bar.add(j[0] + "-" + j[2], time, form, yaxis_min = "dataMin",yaxis_max = "dataMax",is_datazoom_show = True, datazoom_type = "slider") overlap.add(bar) line = Line(j[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items)) price = [e[3] for e in a] line.add(j[0] + "price", time, price, yaxis_min = "dataMin",yaxis_max = "dataMax", is_datazoom_show = True, datazoom_type = "slider", yaxis_type="value") overlap.add(line,yaxis_index=1, is_add_yaxis=True) page.add(overlap) if len(a[0])==5 and a[0][3]=="pie": overlap = Overlap() timeline = Timeline(is_auto_play=False, timeline_bottom=0) #zip(namearray,valuearray,quarter,flag,num) namearray = [c[0] for c in a] valuearray = [d[1] for d in a] quarter = [e[2] for e in a] num = a[0][4] for x in range(0, num / 10): list1 = valuearray[x] names = namearray[x] quarters = quarter[x][0] for idx, val in enumerate(list1): list1[idx] = float(val) pie = Pie(j[0]+"-"+"前十股东".decode("utf-8"),width=width1 * 10 / 11, height=(height1 * 10 / 11)) pie.add(j[0]+"-"+"前十股东".decode("utf-8"), names, list1, radius=[30, 55], is_legend_show=False, is_label_show=True, label_formatter = "{b}: {c}\n{d}%") # print list # print names # print quarterarray timeline.add(pie, quarters) # namearray = [y for y in namearray[x]] timeline.render() return #need more statement else: form = [e[1] for e in a]#for not分笔 data line = Line(j[0] + "-" + j[2], width=width1*10/11, height=(height1*10/11)/len(items)) line.add(j[0] + "-" + j[2], time, form, is_datazoom_show=True, datazoom_type="slider",yaxis_min="dataMin",yaxis_max="dataMax") page.add(line) else: overlap = Overlap()#for k线 close = zip(*a)[2] candle = [[x[1], x[2], x[3], x[4]] for x in a] candlestick = Kline(j[0] + "-" + j[2], width=width1*10/11, height = (height1*10/11) / len(items)) candlestick.add(j[0], time, candle, is_datazoom_show=True, datazoom_type="slider",yaxis_interval = 1) overlap.add(candlestick) if len(close)>10: ma10 = calculateMa(close, 10) line1 = Line(title_color="#C0C0C0") line1.add(j[0] + "-" + "MA10", time, ma10) overlap.add(line1) if len(close)>20: ma20 = calculateMa(close, 20) line2 = Line(title_color="#C0C0C0") line2.add(j[0] + "-" + "MA20", time, ma20) overlap.add(line2) if len(close)>30: ma30 = calculateMa(close, 30) line3 = Line(title_color="#C0C0C0") line3.add(j[0] + "-" + "MA30", time, ma30) overlap.add(line3) page.add(overlap) else: for k in range(1, len(j)/3):#if graphs are combined j[3*k-1] = re.sub("\n&","",j[3*k-1]) sizearray=[] #if j[1] != "Candlestick" layout = Overlap() for i in xrange(0, len(j),3): array = j[i:i +3] b = generateline(array[1],array[2],startdate,enddate,option) if b is None: continue btime = [d[0] for d in b] if array[2] != "Kline": if len(b[0])==4 and b[0][2]=="bar": form = [e[1] for e in b] bar = Bar(array[0] + "-" + array[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items)) bar.add(array[0] + "-" + array[2], btime, form, is_datazoom_show=True, datazoom_type="slider", yaxis_min="dataMin", yaxis_max="dataMax") layout.add(bar) line = Line(array[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(items)) price = [e[3] for e in b] line.add(array[0] + "price", btime, price, is_datazoom_show=True, datazoom_type="slider", yaxis_min="dataMin", yaxis_type="value") layout.add(line, yaxis_index=1, is_add_yaxis=True) else: line = Line(array[0] + "-" + array[2],width=width1*10/11, height=(height1*10/11) / len(items)) line.add(array[0]+"-"+array[2], btime, b, is_datazoom_show=True, yaxis_max = "dataMax", yaxis_min = "dataMin",datazoom_type="slider") layout.add(line) else: candle = [[x[1], x[2], x[3], x[4]] for x in b] candlestick = Kline(array[0] + "-" + array[1], width=width1*10/11, height=(height1*10/11) / len(items)) candlestick.add(array[0], btime, candle, is_datazoom_show=True, datazoom_type=["slider"]) #if i == 0: close = zip(*b)[2] if len(close)>10: ma10 = calculateMa(close, 10) line4 = Line(title_color="#C0C0C0") line4.add(array[0] + "-" + "MA10", btime, ma10) layout.add(line4) if len(close)>20: ma20 = calculateMa(close, 20) line5 = Line(title_color="#C0C0C0") line5.add(array[0] + "-" + "MA20", btime, ma20) layout.add(line5) if len(close)>30: ma30 = calculateMa(close, 30) line6 = Line(title_color="#C0C0C0") line6.add(array[0] + "-" + "MA30", btime, ma30) layout.add(line6) layout.add(candlestick) page.add(layout) page.render()
# In[239]: from pyecharts import Bar, Line, Overlap, Grid years = [str(i) for i in range(2008, 2018)] net_sales = data.loc['净销售额'].values net_income = data.loc['净利润'].values bar = Bar("盈利能力") bar.add("净销售额", years, net_sales) bar.add("净利润", years, net_income, bar_category_gap=25, yaxis_name='百万美元', yaxis_name_gap=60) gross = data.loc['毛利率'].values line = Line() line.add("毛利率", years, gross, line_width=3) ol = Overlap() ol.add(bar) ol.add(line, is_add_yaxis=True, yaxis_index=1) ol # In[241]: assets = data.loc['总资产'].values cash = data.loc['现金'].values bar = Bar("财务状况") bar.add("总资产", years, assets) bar.add("现金", years, cash, bar_category_gap=25, yaxis_name='百万美元', yaxis_name_gap=60) bar
avg_boxoffice = [] quantity = [] for i in sorted(genres.items(), key=lambda item:sum(item[1]['boxoffice_num']), reverse=True): styles.append(i[0]) boxoffice.append(round(sum(genres[i[0]]['boxoffice_num']), 2)) avg_boxoffice.append(round(np.mean(genres[i[0]]['boxoffice_num']), 2)) quantity.append(len(genres[i[0]]['boxoffice_num'])) grid = Grid() bar1 = Bar(title='类型-票房') # ,title_pos='40%' bar2 = Bar() bar1.add('总票房',styles, boxoffice, xaxis_name='类型', yaxis_name='总票房(亿)', yaxis_name_gap=40, is_toolbox_show=False) bar2.add('平均票房', styles, avg_boxoffice, xaxis_name='类型', yaxis_name='平均票房(亿)', is_toolbox_show=False) overlap = Overlap(width=1200, height=600) overlap.add(bar1) overlap.add(bar2, is_add_yaxis=True, yaxis_index=1) grid.add(overlap, grid_right="20%") grid#.render('类型-票房.html') # 上图为2018年不同类型电影的总票房和平均票房。由于一部电影一般会有多个类型,因此在计算票房时,分别考虑了该电影的每个类型。以‘红海行动’为例,‘红海行动’为动作片、战争片,因此在动作片和战争片中,都分别考虑了‘红海行动’的票房。 # # 可以看出,就总票房而言,动作片总票房最高,喜剧片紧随其后。而就平均票房而言,科幻和战争片的平均票房较高,这可能是由于这些类型的电影制作用了更大的成本,制作较好,因此也回收了更多的票房。 # In[16]: genres = {}
def test_page_grid_timeline_overlap(): # Grid v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] bar = Bar("柱状图示例", height=720, width=1200, title_pos="65%") bar.add("商家A", CLOTHES, v1, is_stack=True) bar.add("商家B", CLOTHES, v2, is_stack=True, legend_pos="80%") line = Line("折线图示例") line.add( "最高气温", WEEK, [11, 11, 15, 13, 12, 13, 10], mark_point=["max", "min"], mark_line=["average"], ) line.add( "最低气温", WEEK, [1, -2, 2, 5, 3, 2, 0], mark_point=["max", "min"], mark_line=["average"], legend_pos="20%", ) v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] scatter = Scatter("散点图示例", title_top="50%", title_pos="65%") scatter.add("scatter", v1, v2, legend_top="50%", legend_pos="80%") es = EffectScatter("动态散点图示例", title_top="50%") es.add( "es", [11, 11, 15, 13, 12, 13, 10], [1, -2, 2, 5, 3, 2, 0], effect_scale=6, legend_top="50%", legend_pos="20%", ) grid = Grid() grid.add(bar, grid_bottom="60%", grid_left="60%") grid.add(line, grid_bottom="60%", grid_right="60%") grid.add(scatter, grid_top="60%", grid_left="60%") grid.add(es, grid_top="60%", grid_right="60%") # Timeline bar_1 = Bar("2012 年销量", "数据纯属虚构") bar_1.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_1.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2 = Bar("2013 年销量", "数据纯属虚构") bar_2.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_2.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3 = Bar("2014 年销量", "数据纯属虚构") bar_3.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_3.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4 = Bar("2015 年销量", "数据纯属虚构") bar_4.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_4.add("冬季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5 = Bar("2016 年销量", "数据纯属虚构", height=720, width=1200) bar_5.add("春季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add("夏季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add("秋季", CLOTHES, [randint(10, 100) for _ in range(6)]) bar_5.add( "冬季", CLOTHES, [randint(10, 100) for _ in range(6)], is_legend_show=True, ) timeline = Timeline(is_auto_play=True, timeline_bottom=0) timeline.add(bar_1, "2012 年") timeline.add(bar_2, "2013 年") timeline.add(bar_3, "2014 年") timeline.add(bar_4, "2015 年") timeline.add(bar_5, "2016 年") # Overlap attr = ["{}月".format(i) for i in range(1, 13)] v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] v3 = [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2] bar = Bar(height=720, width=1200) bar.add("蒸发量", attr, v1) bar.add("降水量", attr, v2, yaxis_formatter=" ml", yaxis_max=250) line = Line() line.add("平均温度", attr, v3, yaxis_formatter=" °C") overlap = Overlap() overlap.add(bar) overlap.add(line, yaxis_index=1, is_add_yaxis=True) page = Page() page.add(grid) page.add(timeline) page.add(overlap) page.render()
def test_timeline_bar_line(): attr = ["{}月".format(i) for i in range(1, 7)] bar = Bar("1 月份数据", "数据纯属虚构") bar.add("bar", attr, [randint(10, 50) for _ in range(6)]) line = Line() line.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_0 = Overlap() overlap_0.add(bar) overlap_0.add(line) bar_1 = Bar("2 月份数据", "数据纯属虚构") bar_1.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_1 = Line() line_1.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_1 = Overlap() overlap_1.add(bar_1) overlap_1.add(line_1) bar_2 = Bar("3 月份数据", "数据纯属虚构") bar_2.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_2 = Line() line_2.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_2 = Overlap() overlap_2.add(bar_2) overlap_2.add(line_2) bar_3 = Bar("4 月份数据", "数据纯属虚构") bar_3.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_3 = Line() line_3.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_3 = Overlap() overlap_3.add(bar_3) overlap_3.add(line_3) bar_4 = Bar("5 月份数据", "数据纯属虚构") bar_4.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_4 = Line() line_4.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_4 = Overlap() overlap_4.add(bar_4) overlap_4.add(line_4) timeline = Timeline(timeline_bottom=0) timeline.add(overlap_0, "1 月") timeline.add(overlap_1, "2 月") timeline.add(overlap_2, "3 月") timeline.add(overlap_3, "4 月") timeline.add(overlap_4, "5 月") timeline.render()
def graphpage(labels,mode_combo,startdate,enddate,optInterval,width1, height1): #optInterval='D/W/M' labels startdate = startdate.replace("/","-")#convert to tushare readable date enddate = enddate.replace("/","-") page = Page() for label in labels: # generate numbers of graphs according to numbers of queries in treewidget label1 = re.split("-", label) overlap = Overlap() if label1[2]!="分笔" and label1[2]!="季度饼图": #"K线" "复权" "历史分钟" if mode_combo == "复权": #if optInterval == "qfq" or optInterval == "hfq":#复权 array = ts.get_h_data(label1[1], start=startdate, end=enddate, autype="qfq") array = array.sort_index() time = array.index.format() # 日期正是index elif mode_combo == "K线": #elif optInterval.isalnum() :#历史K线 array = ts.get_k_data(label1[1], start=startdate, end=enddate, ktype=optInterval) time = array['date'].tolist() # array.date elif mode_combo == "历史分钟": array_bfr = ts.get_tick_data(label1[1], date=startdate) array_bfr.sort_values("time") a = startdate + " " + array_bfr["time"] array_bfr["time"] = a array_bfr["time"] = pd.to_datetime(a) array_bfr = array_bfr.set_index("time") if label1[2] != "Volume" and label1[2] != "Amount": price_df = array_bfr["price"].resample(optInterval).ohlc() # resample重新取样,选出ohlc=open/high/low,提取除价格之外另外4列.close,tushare是ohcl price_df = price_df.dropna() array = price_df time = price_df.index.format() elif label1[2] == "Volume": vols = array_bfr["volume"].resample(optInterval).sum() #resample重新取样,累加间隔内数值 relevant data processing algorithm taken from Jimmy, Creator of Tushare vols = vols.dropna() vol_df = pd.DataFrame(vols, columns=["volume"]) array = vol_df time = vol_df.index.format() else: amounts = array_bfr["amount"].resample(optInterval).sum() amounts = amounts.dropna() amount_df = pd.DataFrame(amounts, columns=["amount"]) array = amount_df time = amount_df.index.format() #绘图方法 if label1[2] == 'Kline': re_array = array[['open', 'close', 'high', 'low']] data_li = list(row.tolist() for index, row in re_array.iterrows()) # data_list = list(re_array.as_matrix()) close = array['close'].tolist() kline = Kline(label1[0] + "-" + optInterval, width=width1*10/11, height = (height1*10/11) / len(labels)) kline.add(label1[0], time, data_li, is_datazoom_show=True, datazoom_type="slider", yaxis_interval=1) overlap.add(kline) if len(close) > 10: ma10 = calculateMa(close, 10) line1 = Line(title_color="#C0C0C0") line1.add(label1[0] + "-" + "MA10", time, ma10) overlap.add(line1) if len(close) > 20: ma20 = calculateMa(close, 20) line2 = Line(title_color="#C0C0C0") line2.add(label1[0] + "-" + "MA20", time, ma20) overlap.add(line2) if len(close) > 30: ma30 = calculateMa(close, 30) line3 = Line(title_color="#C0C0C0") line3.add(label1[0] + "-" + "MA30", time, ma30) overlap.add(line3) page.add(overlap) else:#When label1[2]==open/close/volume if label1[2] == 'Open': list_aft = array['open'].tolist() elif label1[2] == 'Close': list_aft = close elif label1[2] == 'High': list_aft = array['high'].tolist() elif label1[2] == 'Low': list_aft = array['low'].tolist() elif label1[2] == 'Volume':#volume list_aft = array['volume'].tolist() else:#amount list_aft = array['amount'].tolist() line = Line(label1[0] + "-" + label1[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels)) line.add(label1[0] + "-" + label1[2], time, list_aft, is_datazoom_show=True, yaxis_max="dataMax", yaxis_min="dataMin", datazoom_type="slider") overlap.add(line) page.add(overlap) elif label1[2]=="分笔": array = ts.get_tick_data(label1[1], date=startdate) array = array.sort_values("time") date = array["time"].tolist() amount = array["amount"].tolist() atype = array["type"].tolist() price = array["price"].tolist() flag = ["bar" for i in date] for idx, val in enumerate(atype): if val == "卖盘": amount[idx] = -amount[idx] if val == "中性盘": amount[idx] = 0 returnarray = list(zip(date, amount, flag, price)) form = [e[1] for e in returnarray] time = [d[0] for d in returnarray] bar = Bar(label1[0] + "-" + label1[2], width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels)) bar.add(label1[0] + "-" + label1[2], time, form, is_datazoom_show=True, datazoom_type="slider", yaxis_min="dataMin", yaxis_max="dataMax") overlap.add(bar) line = Line(label1[0] + "price", width=width1 * 10 / 11, height=(height1 * 10 / 11) / len(labels)) price = [e[3] for e in returnarray] line.add(label1[0] + "price", time, price, yaxis_min="dataMin", yaxis_max="dataMax", is_datazoom_show=True, datazoom_type="slider", yaxis_type="value") overlap.add(line, yaxis_index=1, is_add_yaxis=True) page.add(overlap) elif label1[2]=="季度饼图": datestr = startdate.split("-") thisyear = datestr[0] df2 = ts.top10_holders(code=label1[1], gdtype="1") test = df2[1]["quarter"].tolist() df_ready = df2[1] idxlist = [] for idx, val in enumerate(test): a = val.split("-") if a[0] == thisyear: # print a[0],idx idxlist.append(idx) thing = df_ready.loc[idxlist] thing = thing.sort_values(["quarter", "name"]) # print a[0],id name = thing["name"].tolist() value = thing["hold"].tolist() quarter = thing["quarter"].tolist() namearray = [name[i:i + 10] for i in range(0, len(name), 10)] valuearray = [value[j:j + 10] for j in range(0, len(value), 10)] quarterarray = [quarter[k:k + 10] for k in range(0, len(quarter), 10)] flag = ["pie" for i in namearray] num = [len(value) for k in namearray] returnarray = list(zip(namearray, valuearray, quarterarray, flag, num)) timeline = Timeline(is_auto_play=False, timeline_bottom=0) # zip(namearray,valuearray,quarter,flag,num) namearray = [c[0] for c in returnarray] valuearray = [d[1] for d in returnarray] quarter = [e[2] for e in returnarray] num = returnarray[0][4] for x in range(0, int(num / 10)): list1 = valuearray[x] names = namearray[x] quarters = quarter[x][0] for idx, val in enumerate(list1): list1[idx] = float(val) pie = Pie(label1[0] + "-" + "前十股东", width=width1 * 10 / 11, height=(height1 * 10 / 11)) pie.add(label1[0] + "-" + "前十股东", names, list1, radius=[30, 55], is_legend_show=False, is_label_show=True, label_formatter="{b}: {c}\n{d}%") timeline.add(pie, quarters) # namearray = [y for y in namearray[x]] timeline.render() page.render()