用Python写一个红利低波ETF网格策略回测

本文介绍了使用Python编程语言实现的一种基于网格交易的股票交易策略,通过读取CSV数据、处理日期、设置参数并模拟交易过程,最终计算总收益和最大占用资金,以及与持有策略的对比可视化。
import numpy as np
import pandas as pd
import feather
import quantstats as qs
import matplotlib.pyplot as plt
import time
from decimal import Decimal

# 定义一个日期解析器
date_parser = lambda x: pd.to_datetime(x, format='%Y/%m/%d')
# 读取数据
stock_code = "512890.SH"
data = pd.read_csv("D:/cfsworkfiles/myjupyternotebook/Mercury/512890.SH后复权.csv", parse_dates=['date'])
data = pd.DataFrame(data, columns=['date', 'open', 'high', 'low', 'close', 'volume'])
data.set_index('date', drop=True, inplace=True)
data.sort_index(inplace=True)  

# 设置开始日期和结束日期
start_date = '2021-09-01'
end_date = '2022-01-31'

# 筛选出开始日期和结束日期范围内的数据
filtered_data = data.loc[start_date:end_date]

# 获取筛选后数据的第一个交易日的开盘价作为收盘价
first_day_close_price = filtered_data.iloc[0]['close']
print("第一个交易日的收盘价:", first_day_close_price)

# 将benchmark设置为第一个交易日的收盘价格
benchmark = first_day_close_price
price = benchmark
# 初始化总资金
total_fund = 200000
# 计算初始持仓数量
position = int(total_fund /2/ first_day_close_price)
# 计算每份资金的数量
trade_quantity = 10000/price
# 设置网格参数
grid = 0.05
print("网格度:", grid)
# 初始化买入和卖出列表
opt_b = []
opt_s = []
# 初始化资金消耗和最大资金消耗
occupy_money = Decimal(0)
max_occupy_money = Decimal(0)
left_money = total_fund - occupy_money
# 初始化总收益
total_profit = 0
# 初始化成本价
cost_price = benchmark
# 第一日买入全部资金的一半进行建仓

occupy_money = Decimal(benchmark) * Decimal(position)
print("建仓成本", occupy_money)
max_occupy_money = max(max_occupy_money, occupy_money)  # 更新最大占用资金
opt_b.append([filtered_data.index[0], benchmark, position])  # 使用第一天的日期作为索引

for index, row in filtered_data.iterrows():
    open_price = row['open']
    high = row['high']
    low = row['low']

    # 如果最高价大于等于benchmark * (1+grid),则执行以benchmark * (1+grid)的价格卖出一份资金
    if high >= benchmark * (1+grid):
        price = benchmark * (1+grid)
        if position >= trade_quantity:  # 检查是否有足够的仓位进行卖出
            temp = (price - benchmark) * trade_quantity
            total_profit += temp  # 计算总收益
            opt_s.append([index, price, -trade_quantity])
            benchmark = benchmark * (1+grid)
            position -= trade_quantity  # 更新仓位
         

            print(index, "卖出", price, "收益", temp)

    # 如果最低价小于等于benchmark * (1-grid),则执行以benchmark * (1-grid)的价格买入一份资金
    elif low <= benchmark * (1-grid):
        price = benchmark * (1-grid)
        benchmark = benchmark * (1-grid)
        position += trade_quantity  # 更新仓位
        occupy_money = price * trade_quantity
        max_occupy_money = max(max_occupy_money, occupy_money)  # 更新最大占用资金
        opt_b.append([index, price, trade_quantity])
        print(index, "买入", price)

# 循环结束后,检查最后一天的收盘价是否大于成本价
last_day_close_price = filtered_data.iloc[-1]['close']
cost_pice = benchmark
if last_day_close_price > cost_price:
    # 计算最后一天卖出的收益
    final_sell_profit = (last_day_close_price - cost_price) * position
    total_profit += final_sell_profit
    # 更新总收益和仓位
    print(filtered_data.index[-1], "最后一天卖出", last_day_close_price, "收益", final_sell_profit)
    position = 0  # 清空仓位

# 打印总收益和最大占用资金
print("总收益:", total_profit)
print("最大占用资金:", max_occupy_money)
print("仓位", position)
# 计算总收益率
total_return_rate = (Decimal(total_profit) / max_occupy_money) * 100
print("网格总收益率:", total_return_rate, "%")
#计算buy&hold收益
buy_and_hold_return = (filtered_data['close'].iloc[-1]  / filtered_data['close'].iloc[0] - 1) * 100
print("持有卖出收益:", buy_and_hold_return, "%")


# 可视化买入和卖出点
df_b = pd.DataFrame(opt_b, columns=['timestamp', 'price', 'opt'])
df_b.set_index('timestamp', drop=True, inplace=True)

df_s = pd.DataFrame(opt_s, columns=['timestamp', 'price', 'opt'])
df_s.set_index('timestamp', drop=True, inplace=True)

plt.figure(figsize=(10, 5))
plt.plot(filtered_data.index, filtered_data['close'], label=stock_code, color='b')
plt.scatter(df_b.index, df_b['price'], color='r', label='Buy')
plt.scatter(df_s.index, df_s['price'], color='g', label='Sell')
plt.xlabel('日期')
plt.ylabel(stock_code)
plt.legend()
plt.title(stock_code)
plt.show()

【资源说明】 基于Python实现的简单网格策略交易源码+使用说明.zip 策略说明 开仓:在盘口挂出买N和卖N,当你的买单或卖单完成后,再重新开启相应的仓位,保持你始终有买N和卖N的订单。 **KuCoin**拥有**level3交易数据、强大的撮合引擎、针对api用户提供的手续费折扣**,同时提供**sandbox环境**作为数据试支撑,帮助你规避风险。 我们仅提供一个简单且不完备的交易策略,使用时**请注意规避风险**,我们希望你能够**在sandbox环境配合其他参数或是策略进行试调整,我们也不想你成为一个慈善家!!! 如何使用 * 安装Python * Windows系统请前往[Python](https://www.python.org/downloads/windows/)官网自行安装,64位请选择1,32位请选择2。 <img src="./img/python_download.png" style="zoom:50%" /> * 在开始安装时请注意将以下选项勾选: <img src="./img/python_win.png" style="zoom:40%" /> * MAC OS X安装 * 打开命令终端,输入以下命令安装Homebrew(安装过程中需要输入**电脑密码**): ```shell /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" ``` * 在命令终端输入以下命令,安装Python3: ```shell brew install python ``` * 在命令终端输入以下命令,确认是否安装成功: ```shell python3 --version ``` Mac/Linux **在项目目录下**打开命令终端: ```shell cd simple-grid ``` * 用以下命令让你的合约策略运行起来: ```shell ./simple_grid_future.py ``` * 用以下命令让你的现货策略运行起来: ```shell ./simple_grid_kucoin.py ``` * Windows **在项目目录下**打开命令终端: ```shell cd simple-grid ``` * 用以下命令让你的合约策略运行起来: ```shell py simple_grid_future.py ``` * 用以下命令让你的现货策略运行起来: ```shell py simple_grid_kucoin.py ``` 【备注】 1、该资源内项目代码都经过试运行成功,功能ok的情况下才上传的,请放心下载使用! 2、本项目适合计算机相关专业(如计科、人工智能、通信工程、自动化、电子信息等)的在校学生、老师或者企业员工下载使用,也适合小白学习进阶,当然也可作为毕设项目、课程设计、作业、项目初期立项演示等。 3、如果基础还行,也可在此代码基础上进行修改,以实现其他功能,也可直接用于毕设、课设、作业等。 欢迎下载,沟通交流,互相学习,共同进步!
<think>嗯,用户想要在Ptrade软件上进行ETF网格交易策略,需要示例代码。首先,我得忆一下Ptrade支持的API和语法。Ptrade用的是Python,所以代码应该是Python的。网格交易的基本逻辑是设定价格区间,分成多个网格,价格动时自动买卖。 首先,需要确定ETF代码,比如510050.SH。然后设置网格参数,比如基准价、网格间距、数量。初始化的时候,可能需要获取历史数据来计算基准价,比如过去20天的均价。然后,在每天开盘前取消未成交的订单,避免重复下单。 接下来,在每次的定时任务里,比如每30分钟执行一次,获取当前持仓和最新价。计算当前价与基准价的偏离百分比,决定买入或卖出。比如,偏离-3%时买入一格,偏离+3%时卖出一格。这里可能需要用round函数来确保网格的间距正确。 还需要处理下单逻辑,检查是否有可用资金或持仓,避免无效操作。比如,买入时要确保资金足够,卖出时要确保有足够的持仓。每次下单后,记录基准价到context变量,避免重复触发。 然后,用户可能需要结果的分析,比如年化收益率、最大撤等指标。Ptrade的报告会自动生成这些数据,所以代码里不需要额外处理,但用户可能需要知道如何查看报告。 还要考虑一些常见问题,比如网格间距调整、止盈止损、不同时间段的参数优化。比如,用户可能想知道如何修改网格间距,或者在策略中加入止盈条件。这时候可以提供一些修改建议,比如调整grid_percent或者添加止损逻辑。 另外,引用中的信息提到Ptrade支持算法交易网格策略,所以代码示例需要符合这些功能。确保代码中使用了正确的API,比如order_target和get_position。还要注意Ptrade的定时任务设置,比如schedule_daily和schedule_timer。 最后,代码是否存在语法错误,比如变量名是否正确,函数调用是否恰当。例如,get_history的正确参数,order_target的用法是否正确。确保用户可以直接复制代码进行,并根据需要调整参数。 总结一下,步骤是:初始化参数,定时任务处理订单,计算网格触发条件,执行买卖操作,记录状态。同时,提供优化方向和常见问题解答,帮助用户进一步调整策略。</think>以下是为Ptrade平台设计的ETF网格交易策略示例代码,包含完整逻辑和注释说明: ```python # 导入Ptrade量化交易API from ptrade.api import * import numpy as np # 初始化函数 def initialize(context): # 设置标的为上证50ETF context.symbol = "510050.SH" # 网格参数设置 context.benchmark_price = 0 # 基准价格 context.grid_interval = 0.03 # 3%网格间距 context.grid_qty = 1000 # 每格交易数量 # 定时任务设置 schedule_daily(reset_benchmark, time="09:30") # 每日开盘重置基准价 schedule_timer(check_grid, frequency="30m") # 每30分钟检查网格 # 重置基准价函数 def reset_benchmark(context): # 获取前20日收盘价计算基准 hist = get_history(20, "1d", "close", [context.symbol]) context.benchmark_price = np.mean(hist[context.symbol]) cancel_all_orders() # 取消前日未成交订单 # 网格检查函数 def check_grid(context): price = get_price(context.symbol) # 获取实时价格 position = get_position(context.symbol) # 获取持仓 # 计算价格偏离百分比 deviation = (price - context.benchmark_price)/context.benchmark_price # 向下突破网格 if deviation <= -context.grid_interval: buy_qty = context.grid_qty * round(abs(deviation)/context.grid_interval) if context.cash >= buy_qty * price: order_target(context.symbol, position + buy_qty) context.benchmark_price = price # 更新基准价 # 向上突破网格 elif deviation >= context.grid_interval: sell_qty = min(position, context.grid_qty * round(deviation/context.grid_interval)) if sell_qty > 0: order_target(context.symbol, position - sell_qty) context.benchmark_price = price # 更新基准价 # 获取价格函数 def get_price(symbol): bars = get_latest_bars(symbol, 1) return bars[-1]["close"] # 策略参数设置 def backtest_setting(): return { "start": "2020-01-01", "end": "2023-12-31", "cash": 1000000, "commission": 0.0002, "slippage": 0.001 } ``` §§代码说明与优化方向§§ 1. **参数优化方向**: - 网格间距$grid\_interval$可调整为动态参数,根据动率指标ATR动态计算[^4] - 加入止盈止损机制,当累计收益率超过$15\%$时平仓[^2] 2. **风险控制模块**: ```python # 可添加最大撤控制 if context.portfolio.max_drawdown > 0.2: order_target(context.symbol, 0) print("触发最大撤20%止损") ``` 3. **进阶功能扩展**: - 支持多ETF轮动配置,通过夏普比率动态选择标的[^1] - 添加盘口流动性检,避免大单冲击成本[^3] 4. **结果分析**: Ptrade报告将自动生成以下指标: - 年化收益率$R_{annual} = \frac{P_{end} - P_{start}}{P_{start}} \times \frac{365}{days}$ - 最大撤$MDD = \max_{0≤i<j≤n}( \frac{P_i - P_j}{P_i} )$ - 胜率$WR = \frac{\sum profitable\ trades}{\sum total\ trades}$ §§常见问题解答§§ 1. **如何修改网格间距**? 调整`context.grid_interval`参数,建议保持$0.01≤interval≤0.05$,过小会增加交易频率和摩擦成本[^2] 2. **如何处理分红除权**? Ptrade已自动处理复权价格,使用`get_history()`获取的是后复权数据 3. **如何添加交易信号提醒**? 可在订单函数后添加: ```python send_message(f"已下单{quantity}股{context.symbol} @ {price}") ``` 4. **策略容量评估**: 建议单策略资金规模不超过$2000$万元,避免在流动性ETF上产生显著冲击成本[^1]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值