예제 #1
0
    def take_snapshot(self, file_html=None, width="1400px", height="580px"):
        """获取快照

        :param file_html: str
            交易快照保存的 html 文件名
        :param width: str
            图表宽度
        :param height: str
            图表高度
        :return:
        """
        tab = Tab(page_title="{}@{}".format(
            self.symbol, self.end_dt.strftime("%Y-%m-%d %H:%M")))
        for freq in self.freqs:
            chart = ka_to_echarts(self.kas[freq], width, height)
            tab.add(chart, freq)

        t1 = Table()
        t1.add(["名称", "数据"], [[k, v] for k, v in self.s.items() if "_" in k])
        t1.set_global_opts(
            title_opts=ComponentTitleOpts(title="缠中说禅信号表", subtitle=""))
        tab.add(t1, "信号表")

        t2 = Table()
        t2.add(["名称", "数据"],
               [[k, v] for k, v in self.s.items() if "_" not in k])
        t2.set_global_opts(
            title_opts=ComponentTitleOpts(title="缠中说禅因子表", subtitle=""))
        tab.add(t2, "因子表")

        if file_html:
            tab.render(file_html)
        else:
            return tab
예제 #2
0
파일: factors.py 프로젝트: yanding/czsc
    def take_snapshot(self, file_html=None, width="1400px", height="580px"):
        """获取快照

        :param file_html: str
            交易快照保存的 html 文件名
        :param width: str
            图表宽度
        :param height: str
            图表高度
        :return:
        """
        tab = Tab(page_title="{}@{}".format(self.symbol, self.end_dt.strftime("%Y-%m-%d %H:%M")))
        for freq in self.freqs:
            chart = self.kas[freq].to_echarts(width, height)
            tab.add(chart, freq)

        t1 = Table()
        t1.add(["名称", "数据"], [[k, v] for k, v in self.s.items()
                              if "_" in k and isinstance(v, str)
                              and v not in ["Other~其他", "向下", 'Y~是', 'N~否', '向上']])
        t1.set_global_opts(title_opts=ComponentTitleOpts(title="缠中说禅信号表", subtitle=""))
        tab.add(t1, "信号表")

        t2 = Table()
        ths_ = [["同花顺F10",  "http://basic.10jqka.com.cn/{}".format(self.symbol[:6])]]
        t2.add(["名称", "数据"], [[k, v] for k, v in self.s.items() if "_" not in k and v != "Other~其他"] + ths_)
        t2.set_global_opts(title_opts=ComponentTitleOpts(title="缠中说禅因子表", subtitle=""))
        tab.add(t2, "因子表")

        if file_html:
            tab.render(file_html)
        else:
            return tab
예제 #3
0
def getGuanjian():
    data =  pd.DataFrame(pd.read_excel(excel_dir,))
    mean = data.mean()
    print(type(mean))
    table = (Table().add(headers=['关键维度满意度得分','平均分'],rows=[['质量满意度','4.254902'],['包装满意度','4.078431'],['物流速度满意度','3.803922'],['售后满意度','4.117647'],['价格满意度','4.058824'],['支付满意度','4.117647'],]))
    table.render(path='keyScore.html')
    table1 = (Table().add(headers=['关键维度满意度比例','达到满意'],rows=[['质量满意度','0.86'],['包装满意度','0.76'],['物流速度满意度','0.70'],['售后满意度','0.80'],['价格满意度','0.76'],['支付满意度','0.84'],]))
    table1.render(path='keyScale.html')
예제 #4
0
def get_eventtable(rows) -> Table:
    table = Table()
    headers = ["序号", "日期", "举报内容", "所属区域", "维度", "经度"]
    for r in rows:
        c = r[2]
        cl = list(c)
        n_w = len(cl)
        idx = int((n_w - 1) / 30)  #每40个词分行
        if (idx < 1):
            continue
        for i in range(idx):
            cl.insert((i + 1) * 30, "\n")
        r[2] = "".join(cl)
    '''                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           
    headers = ["City name", "Area", "Population", "Annual Rainfall"]
    rows = [
        ["Brisbane", 5905, 1857594, 1146.4],
        ["Adelaide", 1295, 1158259, 600.5],
        ["Darwin", 112, 120900, 1714.7],
        ["Hobart", 1357, 205556, 619.5],
        ["Sydney", 2058, 4336374, 1214.8],
        ["Melbourne", 1566, 3806092, 646.9],
        ["Perth", 5386, 1554769, 869.4],
        ["Sydney", 2058, 4336374, 1214.8],
        ["Melbourne", 1566, 3806092, 646.9],
        ["Perth", 5386, 1554769, 869.4],
    ]
    '''
    table.add(headers, rows).set_global_opts(
        title_opts=ComponentTitleOpts(title="详细举报数据"), )
    return table
예제 #5
0
def image_info(root, path='image_info.html', show_original=False):
    """Show image visualize.
    
    Args:
        root: An image file root.
        path: result save a html file.
        show_original: whether show original image shape.
    Returns:
        A pyecharts polt object.
    """
    shape = read_image(root).shape
    info = PIL.Image.open(root).info
    width = '' if show_original else str(360)+'px'
    height = '' if show_original else str(int(360/shape[1]*shape[0]))+'px'
    image_charts = image_base(root, '', '', width, height)
    headers = ["Attribute", "Info"]
    rows = [['path', root],
            ['size', str(round(os.stat(root).st_size/1024/1024, 2))+'M'],
            ['shape', str(read_image(root).shape)],
            ['jfif', info['jfif']],
            ['jfif_version', info['jfif_version']],
            ['dpi', info['dpi']],
            ['jfif_unit', info['jfif_unit']],
            ['jfif_density', info['jfif_density']]
    ]
    table_charts = Table().add(headers, rows)
    page = Page(layout=Page.SimplePageLayout).add(*[image_charts, table_charts])
    return page.render(path)
           
           
예제 #6
0
def statistics(model,
               jupyter=True,
               path='Model Summary.html',
               title="Model Summary",
               subtitle=""):
    t = pd.DataFrame([[
        i.name, i.__class__.__name__, i.trainable, i.dtype, i.input_shape,
        i.output_shape,
        i.count_params()
    ] for i in model.layers],
                     columns=[
                         'layer_custom_name', 'layer_object_name', 'trainable',
                         'dtype', 'input_shape', 'output_shape', 'params'
                     ])
    #     t['output_memory(MB)'] = (t.output_shape.map(lambda x:sum([reduce(lambda y,z:y*z, i[1:]) for i in x]) if isinstance(x, list) else reduce(lambda y,z:y*z, x[1:]))
    #                        *t.dtype.map(lambda x:int(re.sub("\D", "", x))))/32#/1024/1024)
    t.loc['total'] = ['', '', '', '', '', '', t.params.sum()]
    t['input_shape'] = t.input_shape.map(
        lambda x: str(x).replace("),(", "),\n(") if isinstance(x, list) else x)
    t = t.reset_index().rename(columns={'index': ''})
    for i in t.columns:
        t[i] = t[i].astype(str)
    table = Table()
    headers = t.columns.tolist()
    rows = t.values.tolist()
    table.add(headers, rows).set_global_opts(
        title_opts=ComponentTitleOpts(title=title, subtitle=subtitle))
    return table.render_notebook() if jupyter else table.render(path)
예제 #7
0
    def table_picture(self, headers, data):
        '''
        数据类似
         headers = ["City name", "Area", "Population", "Annual Rainfall"]
        data = [
        ["Brisbane", 5905, 1857594, 1146.4],
        ["Adelaide", 1295, 1158259, 600.5],
        ["Darwin", 112, 120900, 1714.7],
        ["Hobart", 1357, 205556, 619.5],
        ["Sydney", 2058, 4336374, 1214.8],
        ["Melbourne", 1566, 3806092, 646.9],
        ["Perth", 5386, 1554769, 869.4],
    ]
        '''
        headers = [""]
        data = [
            []
        ]
        table = (
            Table()
                .add(headers=headers, rows=data)
                .set_global_opts(title_opts=ComponentTitleOpts(title=self.title, subtitle=self.subtitle),
                                 # 添加logo
                                 graphic_opts=self.logo
                                 )
        )

        return table
예제 #8
0
    def _plot_txt_time(self, stats, ax=None, **kwargs):
        """
        Outputs the statistics for various time frames.
        """
        returns = stats['returns']

        mly_ret = perf.aggregate_returns(returns, 'monthly')
        yly_ret = perf.aggregate_returns(returns, 'yearly')

        mly_pct = mly_ret[mly_ret >= 0].shape[0] / float(mly_ret.shape[0])
        mly_avg_win_pct = np.mean(mly_ret[mly_ret >= 0])
        mly_avg_loss_pct = np.mean(mly_ret[mly_ret < 0])
        mly_max_win_pct = np.max(mly_ret)
        mly_max_loss_pct = np.min(mly_ret)
        yly_pct = yly_ret[yly_ret >= 0].shape[0] / float(yly_ret.shape[0])
        yly_max_win_pct = np.max(yly_ret)
        yly_max_loss_pct = np.min(yly_ret)

        header = ["Performance", "Value"]
        rows = [["Winning Months %", "{:.0%}".format(mly_pct)],
                ["Average Winning Month %", "{:.2%}".format(mly_avg_win_pct)],
                ["Average Losing Month %", "{:.2%}".format(mly_avg_loss_pct)],
                ["Best Month %", "{:.2%}".format(mly_max_win_pct)],
                ["Worst Month %", "{:.2%}".format(mly_max_loss_pct)],
                ["Winning Years %", '{:.0%}'.format(yly_pct)],
                ["Best Year %", '{:.2%}'.format(yly_max_win_pct)],
                ["Worst Year %", '{:.2%}'.format(yly_max_loss_pct)]]

        table = (Table().add(header, rows).set_global_opts(
            title_opts=opts.ComponentTitleOpts(title="Time")))
        return table
예제 #9
0
def table_traces(rows) -> Table:
    table = Table()
    headers = ["设备名", "MonkeyError", "条数"]
    table.add(
        headers,
        rows).set_global_opts(title_opts=ComponentTitleOpts(title="错误日志收集"))
    return table
예제 #10
0
	def plot_portfolio(self):
		# 持仓
		total_value = glovar.context.portfolio.total_value	
		if len(glovar.context.value_history)==0:			
			day_return = total_value/glovar.context.portfolio.starting_cash-1
		else:
			day_return = total_value/glovar.context.value_history[-1][-1]-1

		headers = ['股票代码','股票名称','持仓数量','开仓时间','收益率','资金占比']
		rows = []
		value_count = 0
		for security in glovar.context.portfolio.positions.index:
			position = glovar.context.portfolio.positions.loc[security,:]
			if security in self.stock_info.index.values:
				name = self.stock_info.loc[security, 'display_name']
			else:
				name = security[:-5]
			position_amount = position.amount
			position_value = position.value
			profit = (position.price-position.avg_cost)*position.amount*position.multiplier*position.side
			init_time = position.init_time.strftime('%Y-%m-%d %H:%M:%S')
			returns_rate = '{:.2%}'.format(profit/position_value)
			position_rate = '{:.2%}'.format(position_value/total_value)
			value_count += position_value			
			rows.append([security, name, position_amount, init_time, returns_rate, position_rate])
		total_position_rate = value_count/total_value
		title = '{}  当天收益率:{:.2%} 总资产:{:.0f} 持仓比率:{:.2%} 持股{}只'.format(glovar.context.current_dt.strftime('%Y-%m-%d %H:%M:%S'), 
			day_return, total_value, total_position_rate, len(glovar.context.portfolio.positions))
		(
		    Table()
		    .add(headers, rows)
		    .set_global_opts(title_opts=opts.ComponentTitleOpts(title=title))
		    .render(sys.path[0]+'/img/{}/{}/持仓.html'.format(self.run_params['mode'], self.run_params['strategy']))
		)
예제 #11
0
def create_base_table(title, x_list, data_list):
    headers = [" "] + x_list
    rows = []
    for key in data_list.keys():
        #print(key)
        row = []
        row.append(key)
        for x in data_list[key]:
            row.append(x)
        #print(row)
        rows.append(row)
    table = Table()
    table.add(headers, rows)
    table.set_global_opts(
        title_opts=opts.ComponentTitleOpts(title=title)
    )
    src_path = "./test/"
    html_file_name = src_path + title + ".html"
    img_file_name = src_path + title + ".png"
    table.render(html_file_name)
    path_wkimg = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe'  # 工具路径
    cfg = imgkit.config(wkhtmltoimage=path_wkimg)
    imgkit.from_file(html_file_name, img_file_name, config=cfg)
    #make_snapshot(snapshot, table.render(html_file_name), img_file_name)
    print(img_file_name+"生成完毕...")
예제 #12
0
파일: views.py 프로젝트: grand-zz/epos
def table_base(sql, titl) -> Table:
    table = Table()
    # engine = create_engine("mysql+pymysql://root:root@localhost:3306/mysql", encoding="utf-8")
    # session = sessionmaker(bind=engine)
    # df = pd.read_sql(sql, engine)
    # rows=df.values.tolist()
    # headers=df.columns.tolist()
    with SQLPoll() as db:
        students = db.fetch_all(sql, None)
    headers = []
    for student in students:
        headers = list(student.keys())
        break
    c = []
    rows = []
    for student in students:
        c = list(student.values())
        rows += [c]
    if len(rows) == 0:
        headers = ['记录', '数量']
        rows = [['无', 0]]
    table.add(
        headers,
        rows).set_global_opts(title_opts=opts.ComponentTitleOpts(title=titl))
    return table
예제 #13
0
def table_base(data) -> Table:
    table = Table()
    level = ['较低:0~3k', '一般:3k~5k', '中等:5k~8k', '较高:8k~12k', '优秀:12k以上']
    city = ['beijing', "shanghai", 'guang', 'shen', 'cheng']
    table.add(level, data[1]).set_global_opts(
        title_opts=opts.ComponentTitleOpts(title="表格", subtitle="城市"))
    return table
예제 #14
0
def table_base() -> Table:
    table = Table()
    heardes = [
        "课题名称", "课题编号", "年份", "负责人", "负责单位", "课题类型", "领域", "课题方向", "关键词", "URL"
    ]
    res_file = "..\\000LocalData\\caict_k\\research_subject_intergrate.csv"
    res_file_read = open(res_file, 'r', encoding='utf-8')
    res_list = []
    temp_list = []
    res_name_list = []
    for line in res_file_read.readlines():
        line = line.strip().split("|")
        if line[1] not in res_name_list:
            temp_list.append(line[0])
            temp_list.append(line[1].replace("--", "-", 10))
            temp_list.append(line[2])
            temp_list.append(line[3])
            temp_list.append(line[4])
            temp_list.append(line[5])
            temp_list.append(line[6])
            temp_list.append(line[7])
            temp_list.append(line[8])
            temp_list.append(line[10])
            # print(temp_list)
            res_list.append(temp_list)
            temp_list = []
            res_name_list.append(line[1])
    table.add(heardes, res_list).set_global_opts(
        title_opts=opts.ComponentTitleOpts(title="院软课题知识数据表(2010-2019)"))
    return table
예제 #15
0
 def getDeatils(self, num):
     if num <= 0:
         exit("[+] 所取条数必须大于0,默认为20!")
     YearRank = {}
     for i in range(1, self.month + 1):
         global MonthRank
         MonthRank = {}
         url = self.baseurl + "&month=%d" % i
         res = requests.get(url)
         maxPage = int(re.findall(re.compile(r'(?<=page=)\d*(?=\D)'), res.text)[-2]) if re.findall(re.compile(r'(?<=page=)\d*(?=\D)'), res.text) else 1
         pagelist = [_ for _ in range(1,maxPage + 1)]
         threads = [GetList(pagelist[i:i+3], url) for i in range(0,maxPage + 1,3)]
         for t in threads:
             t.start()
         for t in threads:
             t.join()
         YearRank = dict(Counter(YearRank) + Counter(MonthRank))
     YearRank = sorted(YearRank.items(), key = lambda x:x[1], reverse=True)
     if num > len(YearRank):
         num = len(YearRank)
         YearRank = dict(YearRank)
     else:
         YearRank = dict(YearRank[0:num])
     table = Table(page_title = "edusrc%d 年度榜单 TOP %d" % (time.localtime().tm_year,num))
     YearRankKeys= [_ for _ in YearRank.keys()]
     YearRankValues = [_ for _ in YearRank.values()]
     headers = ["排名", "用户名", "Rank"]
     rows = []
     for i in range(len(YearRank)):
         row = [i + 1, YearRankKeys[i], YearRankValues[i]]
         rows.append(row)
     table.add(headers, rows)
     table.render("result.html")
     os.system("result.html")
예제 #16
0
    def take_snapshot(self, file_html=None, width="1400px", height="580px"):
        """获取快照

        :param file_html: str
            交易快照保存的 html 文件名
        :param width: str
            图表宽度
        :param height: str
            图表高度
        :return:
        """
        tab = Tab(page_title="{}@{}".format(
            self.symbol, self.end_dt.strftime("%Y-%m-%d %H:%M")))
        for freq in self.freqs:
            chart = self.kas[freq].to_echarts(width, height)
            tab.add(chart, freq)

        for freq in self.freqs:
            t1 = Table()
            t1.add(["名称", "数据"], [[k, v] for k, v in self.s.items()
                                  if k.startswith("{}_".format(freq))])
            t1.set_global_opts(
                title_opts=ComponentTitleOpts(title="缠中说禅信号表", subtitle=""))
            tab.add(t1, "{}信号表".format(freq))

        t2 = Table()
        ths_ = [[
            "同花顺F10", "http://basic.10jqka.com.cn/{}".format(self.symbol[:6])
        ]]
        t2.add(["名称", "数据"],
               [[k, v] for k, v in self.s.items() if "_" not in k] + ths_)
        t2.set_global_opts(
            title_opts=ComponentTitleOpts(title="缠中说禅因子表", subtitle=""))
        tab.add(t2, "因子表")

        t3 = Table()
        t3.add(["本级别", "次级别"],
               [[k, v] for k, v in eval(self.s['级别映射']).items()])
        t3.set_global_opts(
            title_opts=ComponentTitleOpts(title="缠中说禅级别映射表", subtitle=""))
        tab.add(t3, "级别映射表")

        if file_html:
            tab.render(file_html)
        else:
            return tab
예제 #17
0
파일: test.py 프로젝트: klmtldh/python_oas
def table_base(header,row) -> Table:
    table = Table(page_title='未完成项',js_host=r"D:\JGY\600-Data\004-auxiliary辅助文件\\")
    headers = header
    rows = row
    table.add(headers, rows).set_global_opts(
        title_opts=opts.ComponentTitleOpts(title="Table")
    )
    return table
예제 #18
0
def _gen_table() -> Table:
    table = Table()

    headers = ["City name", "Area", "Population", "Annual Rainfall"]
    rows = [["Brisbane", 5905, 1857594, 1146.4],
            ["Perth", 5386, 1554769, 869.4]]
    table.add(headers, rows)
    return table
예제 #19
0
def table_base(header,row) -> Table:
    table = Table()
    headers = header
    rows = row
    table.add(headers, rows).set_global_opts(
        title_opts=opts.ComponentTitleOpts(title="Table")
    )
    return table
def test_table_base(fake_writer):
    table = Table()

    headers = ["City name", "Area", "Population", "Annual Rainfall"]
    rows = [["Brisbane", 5905, 1857594, 1146.4],
            ["Perth", 5386, 1554769, 869.4]]
    table.add(headers, rows).render()
    _, content = fake_writer.call_args[0]
    assert_in("fl-table", content)
예제 #21
0
def createtable(data):

    # 生成pyecharts表格
    table = Table()
    headers = ["提交日期","仪器编号","板号","样品数量","结果均值","ISD"]
    # rows = [[localtime(d.upload_time).strftime("%Y-%m-%d %X"), d.instrument, d.platenum, d.num, d.mean, d.sd] for d in data]
    rows = [[d.upload_time.strftime("%Y-%m-%d %X"), d.instrument, d.platenum, d.num, d.mean, d.sd] for d in data]
    table.add(headers, rows).set_global_opts(title_opts=ComponentTitleOpts(title="结果分布表"))
    return table
예제 #22
0
def table_base(data):

    data = data.reset_index().round(4)
    headers = data.columns.tolist()
    cont = data.values.tolist()
    table = Table().add(headers, cont).set_global_opts(
        title_opts=ComponentTitleOpts(title="", subtitle="数据来源:WIND")
    ).set_global_opts()
    return table
예제 #23
0
def table_base(rows) -> Table:
    table = Table()
    headers = [
        "设备名", "设备号", "CPU", "总内存", "分辨率", "网络", "耗时(s)", "CPU峰值", "CPU均值",
        "内存峰值", "内存均值", "fps峰值", "fps均值", "开始电量", "结束电量", "上行流量峰值", "上行流量均值",
        "下行流量峰值", "下行流量均值"
    ]
    table.add(headers, rows).set_global_opts(
        title_opts=ComponentTitleOpts(title="手机汇总信息", subtitle=""))
    return table
예제 #24
0
def table_base():
    table = Table()

    headers = ["地区", "现有确诊", "累计死亡", "累计治愈"]

    rows = []
    table.add(headers, rows).set_global_opts(
        title_opts=ComponentTitleOpts(title="Table", subtitle="副标题"))
    # table.render("table_base.html")
    return rows
예제 #25
0
def table_base() -> Table:
    table = Table()

    headers = ["国家", "2012", "2013", "2014", "2015", "2016", "2017", "2018"]
    rows = [
        ["中国", 3.867, 4.158, 4.301, 3.953, 3.685, 4.107, 4.622],
    ]
    table.add(headers, rows).set_global_opts(
        title_opts=opts.ComponentTitleOpts(title="近年中国贸易总额/万亿美元"))
    return table
예제 #26
0
def _create_table() -> Table:
    table = Table()
    headers = ["City name", "Area", "Population", "Annual Rainfall"]
    rows = [
        ["Brisbane", 5905, 1857594, 1146.4],
        ["Adelaide", 1295, 1158259, 600.5],
        ["Darwin", 112, 120900, 1714.7],
    ]
    table.add(headers, rows)
    return table
예제 #27
0
def mapper_table():
    headers = [user_name, 'achievement']
    rows = [["Mapping Age", mapping_age_str],
            ["Map Set", map_set_count],
            ["Rank", rank_set_count],
            ["Playcount", rank_set_playcount],
            ["Favourite", int(favourite_count)]]
    mapper_table = (Table().add(headers, rows))

    return mapper_table
예제 #28
0
def table_base():
    table = Table()

    headers = ["地区", "确诊", "死亡", "治愈"]
    rows = [["湖北", 13522, 414, 397], ["浙江", 829, 0, 60], ["广东", 813, 0, 24],
            ["河南", 675, 2, 20], ["湖南", 593, 0, 29], ["安徽", 480, 0, 20],
            ["江西", 476, 2, 19], ["重庆", 344, 2, 9]]
    table.add(headers, rows).set_global_opts(
        title_opts=ComponentTitleOpts(title="Table", subtitle="副标题"))
    # table.render("table_base.html")
    return rows
예제 #29
0
def table_base(feeds: typing.List) -> Table:
    table = Table()
    headers = ['user', 'action', 'time', 'question', 'vote']
    rows = []
    for f in feeds:
        info = [f.user, f.action, f.time, f.question, f.vote]
        rows.append(info)
        table.add(headers, rows).set_global_opts(title_opts=ComponentTitleOpts(
            title='爬取一天的关注动态', subtitle='利用无头浏览器爬取异步加载页面'))
    table.render('zhihu.html')
    return table
예제 #30
0
파일: geo_map.py 프로젝트: sucre111/novice
 def get_table_base(self, _data):
     '''
     plot geo-detail
     :param _data: gps对应的城市分布(dataframe)
     :return: 数据示例
     '''
     table = Table()
     headers = ["City name", "Number"]
     rows = _data
     table.add(headers, rows).set_global_opts(
         title_opts=opts.ComponentTitleOpts(title="Table-Details"))
     return table