量化交易文档处理 - PDF、DOCX、PPTX 用于交易报告、策略文档、演示文稿
55
35%
Does it follow best practices?
Impact
88%
1.18xAverage score across 3 eval scenarios
Passed
No known issues
Optimize this skill with Tessl
npx tessl skill review --optimize ./.trae/skills/quant-docs/SKILL.md此技能使 Claude 能够处理 PDF、Word (.docx) 和 PowerPoint (.pptx) 文档,用于生成交易报告、策略文档和演示文稿。
import PyPDF2
import pandas as pd
# 提取 PDF 中的交易数据
def extract_trades_from_pdf(pdf_path):
text = ""
with open(pdf_path, 'rb') as file:
reader = PyPDF2.PdfReader(file)
for page in reader.pages:
text += page.extract_text()
# 解析交易数据
trades = parse_trade_data(text)
return pd.DataFrame(trades)from reportlab.lib.pagesizes import letter
from reportlab.lib import colors
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle
def generate_trading_report(trades, output_path):
doc = SimpleDocTemplate(output_path, pagesize=letter)
# 创建数据表格
data = [['Ticket', 'Symbol', 'Type', 'Lots', 'PnL']]
for _, trade in trades.iterrows():
data.append([
trade['ticket'],
trade['symbol'],
trade['type'],
trade['lots'],
f"${trade['pnl']:.2f}"
])
table = Table(data)
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.grey),
('TEXTCOLOR', (0, 0), (-1, 0), colors.whitesmoke),
('ALIGN', (0, 0), (-1, -1), 'CENTER'),
]))
doc.build([table])from docx import Document
from docx.shared import Pt, Inches
from docx.enum.text import WD_ALIGN_PARAGRAPH
def create_strategy_document(strategy_name, params, performance):
doc = Document()
# 标题
title = doc.add_heading(f'{strategy_name} Strategy Document', 0)
title.alignment = WD_ALIGN_PARAGRAPH.CENTER
# 概述
doc.add_heading('Overview', level=1)
doc.add_paragraph(f"This document describes the {strategy_name} trading strategy.")
# 参数表
doc.add_heading('Parameters', level=1)
table = doc.add_table(rows=len(params)+1, cols=2)
table.style = 'Light Grid Accent 1'
table.rows[0].cells[0].text = 'Parameter'
table.rows[0].cells[1].text = 'Value'
for i, (key, value) in enumerate(params.items(), 1):
table.rows[i].cells[0].text = key
table.rows[i].cells[1].text = str(value)
# 性能数据
doc.add_heading('Performance', level=1)
perf_para = doc.add_paragraph()
perf_para.add_run(f"Total Return: {performance['total_return']}%\n")
perf_para.add_run(f"Win Rate: {performance['win_rate']}%\n")
perf_para.add_run(f"Sharpe Ratio: {performance['sharpe']}").bold = True
doc.save(f'{strategy_name}_strategy.docx')def generate_weekly_report(week_trades, equity_curve):
doc = Document()
# 页眉
doc.add_heading('Weekly Trading Report', 0)
# 摘要
summary = doc.add_heading('Summary', level=1)
table = doc.add_table(rows=5, cols=2)
table.rows[0].cells[0].text = 'Total Trades'
table.rows[0].cells[1].text = str(len(week_trades))
table.rows[1].cells[0].text = 'Win Rate'
table.rows[1].cells[1].text = f"{win_rate:.2f}%"
table.rows[2].cells[0].text = 'Total PnL'
table.rows[2].cells[1].text = f"${total_pnl:.2f}"
# 详细交易列表
doc.add_heading('Trade Details', level=1)
for trade in week_trades:
p = doc.add_paragraph()
p.add_run(f"#{trade['ticket']} ").bold = True
p.add_run(f"{trade['symbol']} {trade['type']} ")
p.add_run(f"PnL: ${trade['pnl']:.2f}", color='00FF00' if trade['pnl'] > 0 else 'FF0000')
doc.save('weekly_report.docx')from pptx import Presentation
from pptx.util import Inches, Pt
from pptx.dml.color import RgbColor
def create_trading_presentation(data):
prs = Presentation()
# 标题页
title_slide = prs.slides.add_slide(prs.slide_layouts[0])
title = title_slide.shapes.title
subtitle = title_slide.placeholders[1]
title.text = "Trading Performance Analysis"
subtitle.text = f"Period: {data['period']}"
# 摘要页
summary_slide = prs.slides.add_slide(prs.slide_layouts[1])
content = summary_slide.placeholders[1]
content.text = f"""
• Total Trades: {data['total_trades']}
• Win Rate: {data['win_rate']}%
• Total PnL: ${data['total_pnl']}
• Max Drawdown: {data['max_drawdown']}%
• Sharpe Ratio: {data['sharpe']}
"""
# 权益曲线页
chart_slide = prs.slides.add_slide(prs.slide_layouts[5])
title = chart_slide.shapes.title
title.text = "Equity Curve"
# 添加图片(预生成的图表)
chart_slide.shapes.add_picture(
'equity_curve.png',
Inches(1), Inches(1),
width=Inches(8)
)
# 货币对表现页
symbol_slide = prs.slides.add_slide(prs.slide_layouts[5])
symbol_slide.shapes.title.text = "Symbol Performance"
# 添加表格
x, y, cx, cy = Inches(0.5), Inches(1.5), Inches(9), Inches(5)
shape = symbol_slide.shapes.add_table(
rows=len(data['symbols'])+1, cols=4,
left=x, top=y, width=cx, height=cy
)
table = shape.table
# 表头
for col, text in enumerate(['Symbol', 'Trades', 'Win Rate', 'PnL']):
table.cell(0, col).text = text
table.cell(0, col).fill.solid()
table.cell(0, col).fill.fore_color.rgb = RgbColor(59, 130, 246)
# 数据行
for row, symbol_data in enumerate(data['symbols'], 1):
table.cell(row, 0).text = symbol_data['symbol']
table.cell(row, 1).text = str(symbol_data['trades'])
table.cell(row, 2).text = f"{symbol_data['win_rate']}%"
pnl_cell = table.cell(row, 3)
pnl_cell.text = f"${symbol_data['pnl']:.2f}"
if symbol_data['pnl'] > 0:
pnl_cell.fill.solid()
pnl_cell.fill.fore_color.rgb = RgbColor(16, 185, 129)
prs.save('trading_presentation.pptx')def create_strategy_presentation(strategy_name, config, backtest_results):
prs = Presentation()
# 策略概述
overview = prs.slides.add_slide(prs.slide_layouts[1])
overview.shapes.title.text = f"{strategy_name} Strategy"
overview.placeholders[1].text = f"""
{strategy_name} is a trend-following strategy using:
• SMC (Smart Money Concepts) for entry signals
• Martingale for position scaling
• Multi-timeframe analysis (H1 + M15)
Risk Management:
• Max Drawdown: {config['max_dd']}%
• Position Sizing: {config['risk_per_trade']}% per trade
"""
# 参数页
params_slide = prs.slides.add_slide(prs.slide_layouts[5])
params_slide.shapes.title.text = "Strategy Parameters"
table = params_slide.shapes.add_table(
rows=len(config)+1, cols=2,
left=Inches(2), top=Inches(2),
width=Inches(6), height=Inches(4)
)
# ... 填充参数表
# 回测结果页
results_slide = prs.slides.add_slide(prs.slide_layouts[5])
results_slide.shapes.title.text = "Backtest Results"
# 添加结果图表
results_slide.shapes.add_picture(
'backtest_chart.png',
Inches(1), Inches(1.5),
width=Inches(8)
)
prs.save(f'{strategy_name}_presentation.pptx')生成本周交易报告:
1. Word 文档格式
2. 包含:总交易数、胜率、盈亏、最大回撤
3. 按货币对分组统计
4. 添加 equity chart 截图
5. 生成 PDF 版本为 SMC 马丁格尔策略创建完整文档:
1. Word 格式
2. 包含:策略概述、参数说明、入场规则、出场规则、风险控制
3. 添加回测结果截图
4. 生成 PDF 和 PPTX 版本为客户创建投资演示:
1. PPTX 格式,10-15 页
2. 包含:策略介绍、历史表现、风险分析、预期收益
3. 使用专业配色方案
4. 添加动画和图表生成监管要求的交易报告:
1. PDF 格式
2. 包含:所有交易明细、持仓快照、风险指标
3. 符合监管格式要求
4. 添加电子签名区# 使用标准化模板
TEMPLATES = {
'weekly_report': 'templates/weekly_report.docx',
'monthly_report': 'templates/monthly_report.docx',
'strategy_doc': 'templates/strategy.docx'
}# 定义品牌样式
STYLES = {
'primary_color': (59, 130, 246), # 蓝色
'success_color': (16, 185, 129), # 绿色
'danger_color': (239, 68, 68), # 红色
'heading_font': 'Arial',
'heading_size': Pt(16),
'body_font': 'Arial',
'body_size': Pt(11)
}document_name_v1.0_2025-02-23.docx
document_name_v1.1_2025-02-25.docx# PDF 处理
pip install PyPDF2 reportlab
# Word 文档
pip install python-docx
# PowerPoint
pip install python-pptx生成本周交易报告:
1. 读取 trading_logs.xlsx 提取本周交易
2. 计算统计指标
3. 生成 Word 文档
4. 转换为 PDF为 SMC 策略创建文档:
1. 描述策略原理
2. 列出所有参数
3. 添加回测结果
4. 生成 Word、PDF、PPTX 三种格式为客户创建投资演示:
1. 创建 12 页 PPTX
2. 包含策略介绍、历史表现、风险分析
3. 使用专业配色和图表版本历史:
3069d33
If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.