作者:被爱的小花花_ | 来源:互联网 | 2023-09-18 15:26
1.读取excel文件。由列变成行。每个item是一个字典 importpandasaspdfromjinja2importEnvironment,FileSystemLoade
1. 读取excel文件。由列变成行。每个item是一个字典
![](https://img2.php1.cn/3cdc5/3b70/807/f18f159654afa63f.png)
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 reporttitle>
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>
![](https://img2.php1.cn/3cdc5/3b70/807/361b17b1345f5c76.png)
用一个例子来演示会更加清晰