原创内容第962篇,专注量化投资,AGI和智能体落地、个人成长与财富自由。
今天来说说“交易系统”。
海龟策略大家应该都听过,甚至用过。唐奇安通道,突破做多,向下突破做空。但如果你只是这么看,那就把海龟系统想简单?
其实它本质是是一个交易系统:
它有完整的多空信号,多减仓逻辑,止盈止损逻辑。
风控逻辑:通过ATR和资金比例1%管理,让波动控制在一定的范围内:
下面是完整的backtrader的海龟系统的代码:
import backtrader as bt
class TurtleStrategy(bt.Strategy):
"""海龟交易策略 - Backtrader 优化版"""
params = (
('entry_window', 20),
('exit_window', 10),
('atr_window', 20),
('risk_percent', 0.01), # 风险资本比例
('size', 5), # 合约乘数
)
def __init__(self):
# 初始化策略状态
self.order = None
self.open_price = 0.0
self.short_price = 0.0
# 使用Backtrader内置指标计算ATR
self.atr = bt.indicators.ATR(self.data, period=self.p.atr_window)
def log(self, txt, dt=None):
"""日志记录函数"""
dt = dt or self.datas[0].datetime.date(0)
print(f'{dt.isoformat()}, {txt}')
def notify_order(self, order):
"""处理订单状态变化"""
if order.status in [order.Submitted, order.Accepted]:
return # 订单已提交/接受 - 无需操作
if order.status in [order.Completed]:
# 记录开仓价格
if order.isbuy():
self.open_price = order.executed.price
elif order.issell() and not order.info.get('closing', False):
self.short_price = order.executed.price
elif order.status in [order.Canceled, order.Margin, order.Rejected]:
self.log(f'订单取消/保证金不足/拒绝: {order.getstatusname()}')
self.order = None
def next(self):
"""主策略逻辑"""
# 取消所有未完成订单
if self.order:
self.cancel(self.order)
# 检查数据长度是否足够
if len(self.data) < max(self.p.entry_window, self.p.exit_window, self.p.atr_window) + 1:
return
# 计算唐奇安通道
self.entry_up = max(self.data.high.get(size=self.p.entry_window, ago=-1))
self.entry_down = min(self.data.low.get(size=self.p.entry_window, ago=-1))
self.exit_up = max(self.data.high.get(size=self.p.exit_window, ago=-1))
self.exit_down = min(self.data.low.get(size=self.p.exit_window, ago=-1))
# 获取当前价格和ATR
price = self.data.close[0]
atr_value = self.atr[0] if self.atr[0] > 0 else 1 # 防止除零错误
# 计算交易单位 - 使用当前净资产计算
risk_capital = self.broker.getvalue() * self.p.risk_percent
risk_per_contract = atr_value * self.p.size
self.unit = max(1, int(risk_capital / risk_per_contract))
# 无持仓时的开仓逻辑
if not self.position:
if price > self.entry_up:
self.order = self.buy(size=self.unit)
elif price < self.entry_down:
self.order = self.sell(size=self.unit)
# 多头持仓管理
elif self.position.size > 0:
# 加仓逻辑
open_low = self.open_price + atr_value * 0.5
open_high = self.open_price + atr_value * 2
if open_low < price < open_high and self.position.size < 4 * self.unit:
unit_num = min(
int((price - self.open_price) / (atr_value * 0.5)),
4 - self.position.size // self.unit
)
if unit_num > 0:
self.order = self.buy(size=unit_num * self.unit)
# 止损/止盈逻辑
if price < (self.open_price - atr_value * 2) or price < self.exit_down:
self.order = self.sell(size=abs(self.position.size), closing=True)
# 空头持仓管理
elif self.position.size < 0:
# 加仓逻辑
open_low = self.short_price - atr_value * 2
open_high = self.short_price - atr_value * 0.5
if open_low < price < open_high and abs(self.position.size) < 4 * self.unit:
unit_num = min(
int((self.short_price - price) / (atr_value * 0.5)),
4 - abs(self.position.size) // self.unit
)
if unit_num > 0:
self.order = self.sell(size=unit_num * self.unit)
# 止损/止盈逻辑
if price > (self.short_price + atr_value * 2) or price > self.exit_up:
self.order = self.buy(size=abs(self.position.size), closing=True, short=True)
def stop(self):
"""策略结束时打印结果"""
self.log(f'期末净资产: {self.broker.getvalue():.2f}')
海龟策略完整notebook在如下位置:
天勤量化tqsdk的期货数据下载:
大类资产配置的角度,一般我们使用order_target_percent就是指定目标仓位。
等权分配、风险平价等来分配仓位。
但这里有一个核心逻辑,就是满仓,只是组合里不同的标的分配不同的权重罢了。
从量化的角度,一个策略符合入场条件,你就会全仓all in吗?似乎不妥。
更常见的情况是投入一定比例的资金,比如《以交易为生》里提及的2%的仓位,然后根据变化,再决定加仓还是减仓等。
实盘中的几个问题,大家可以思考一下:
1、卖空的仓位,在backtrader的self.get_broker().getvalue如何计算当前市值?
2、backtrader里的现金如何获取?self.broker.get_cash()
3、国内期货是否允许同时持有多仓和空仓?
逻辑上是可以的,但对于策略没有意义。比如像海龟这样的策略,当前持有多仓,而策略发出卖出信号,应该先平多仓,然后如何还需要持空仓可以再卖出。
择时交易的交易系统,本质其实是“应对而非预测”。——这是符合逻辑的。
预测市场很难,而应对是指,承认自己无法预测,但不意味着就没事可作,而是顺应市场去操作。比如发现市场往上走,就加点仓位,回调多少就止损等等。
在做好风控的基础上,胜率*赔率为正,就是一个可以执行的系统。
多因子的逻辑,从这个本质看,尤其是机器学习,反而有“预测”的意味,选择好的因子(特征),使用未来收益率的label来预测哪个股票会上涨,然后把它纳入组合持有,定期去筛选。——这是预测逻辑。
股票和期货是两种不同的思路。
股票本质是有内生增长动力,本质上是好企业融资,发展的逻辑,所以,优质股票是可以长期持有。这是本质。
期货就是一个定价,一份合约。就是看价格变化,多空都可,而且可以上杠杆,本质是为了锁定价格,对冲风险。
这是不一样的。
另外,从实盘的角度,哪怕不做日内,也是需要日内数据的。比如你需要在收盘前5分钟完成交易,那就需要5分钟数据,或者是分钟线数据才能完成相应的策略。
免费的数据里,日频的数据获取相对还容易一些,但要到分钟线或者tick,那是需要一定的成本的。
吾日三省吾身
今天看一个视频,关于财务自由,讲得挺好,分享一下:
她按年化3.5%(其实按4%没问题的)的“保守”计算,有多少钱“花不完”。
1、生存财务自由:300万本金,每月开销8K,花不完。
在三线及以下城市,你就躺着,月8K确实差不多。
2、真正财务自由(大家理解的): 3000万本金。每天花2700,只要不作,确实花不了这么多钱。
年化收益548%,回撤才6%,夏普比5.72,这个策略一直很稳定,附python代码