python + jinja2 + pandas 输出HTML报告
1. 读取excel文件。由列变成行。每个item是一个字典
import pandas as pd from jinja2 import Environment, FileSystemLoader df = pd.read_excel('回测指标汇总.xlsx') df['消耗本金'] = df['消耗本金'].astype(str) + ' 元' df['最大回撤率'] = df['最大回撤率'].astype(str) + '%' df['总收益率'] = df['总收益率'].astype(str) + '%' data = df.to_dict('records') results = {} results.update({'strategy_name': '第一个策略', 'start_time': '2020-01-01', 'end_time': '2021-06-01', 'money': 20000, 'items': data}) env = Environment(loader=FileSystemLoader('./')) template = env.get_template('template_table.html') indicator = 'images/' + '回测指标.png' with open("out.html", 'w+', encoding='utf-8') as f: out = template.render(strategy_name=results['strategy_name'], start_time=results['start_time'], end_time=results['end_time'], money=results['money'], items = results['items'], indicator = indicator) f.write(out) f.close()
2. html模板
<html> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>beautified tified report</title> </head> <style type="text/css"> h1 {margin-left: 20px} h2 {margin-left: 20px; font-size: 19px; font-weight: bold; display: inline-block; padding-left: 10px; border-left: 5px solid #916dd5;} h3 {margin-left: 20px} h4 {margin-left: 20px; margin-bottom: -5px} table {margin-left: 20px; margin-top: 5px; margin-bottom: 5px} p {margin-left: 20px} a {margin-top: 200px;} </style> <h1>基金策略回测报告</h1> <body> <h2>一、策略详情</h2> <p>策略描述:{{ strategy_name }}</p> <p>回测时间段:{{ start_time }} --> {{ end_time }} </p> <p>初始本金:{{ money }}</p> </body> </html> <h2>二、回测结果</h2> <table border="1" width = "40%" cellspacing='0' cellpadding='0'> <tr> <th>基金名称</th> <th>总投入本金</th> <th>总收益率</th> <th>最大回测率</th> </tr> {% for item in items %} <tr align='center'> <td>{{ item.基金名称 }}</td> <td>{{ item.消耗本金 }}</td> <td>{{ item.总收益率 }}</td> <td>{{ item.最大回撤率 }}</td> </tr> {% endfor%} </table> <a name="{{ 回测指标 }}"> <img src="{{ indicator }}" width="850"></a>
用一个例子来演示会更加清晰
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
2021-09-17 文 - 阻塞 postgresql 锁 理解
2021-09-17 zh-Hans_CF@calendar=japanese 403 error_code: InvalidAccessKeyId - 图片上传失败 get 404
2020-09-17 prometheus pushgateway-简单-脚本-自定义 - EOF 运维神器 federate + 多instances聚合
2019-09-17 hbase增量和全量备份