TAMath transform
数学变换实用指南
本文档介绍数学变换函数在量化交易中的实际应用。
常用变换函数
1. 对数变换 (LN / LOG10)
用途:
- 收益率计算
- 价格数据平滑
- 消除异方差性
示例:
python
def log_returns():
"""对数收益率"""
records = exchange.GetRecords()
closes = [r.Close for r in records]
# 方法1:使用Python内置
import math
log_returns = []
for i in range(1, len(closes)):
log_ret = math.log(closes[i] / closes[i-1])
log_returns.append(log_ret)
# 对数收益率的优势:可加性
cumulative_return = sum(log_returns[-20:])
Log(f"20日累计对数收益: {cumulative_return*100:.2f}%")
return log_returns2. 平方根 (SQRT)
用途:
- 波动率计算(方差→标准差)
- 时间调整(时间平方根法则)
- 数据压缩
示例:
python
def volatility_calc():
"""波动率计算"""
records = exchange.GetRecords()
# 方差
variance = TA.VAR(records, 20)
# 标准差 = 方差的平方根
import math
std_dev = math.sqrt(variance[-1])
# 年化波动率(假设日线数据)
annual_vol = std_dev * math.sqrt(365)
Log(f"日波动率: {std_dev*100:.2f}%")
Log(f"年化波动率: {annual_vol*100:.2f}%")
return annual_vol3. 指数函数 (EXP)
用途:
- 对数的反变换
- 指数加权
- 复利计算
示例:
python
def compound_return():
"""复利计算"""
import math
# 假设日收益率
daily_returns = [0.01, 0.02, -0.01, 0.015, 0.008]
# 对数收益率求和
log_sum = sum([math.log(1 + r) for r in daily_returns])
# 指数还原得到总收益率
total_return = math.exp(log_sum) - 1
Log(f"总收益率: {total_return*100:.2f}%")
return total_return4. 取整函数 (CEIL / FLOOR)
用途:
- 价格取整
- 网格交易
- 订单量规范化
示例:
python
def grid_trading_levels():
"""网格交易价格取整"""
import math
ticker = exchange.GetTicker()
current_price = ticker.Last
# 网格间距
grid_size = 100
# 向下取整到最近的网格
lower_grid = math.floor(current_price / grid_size) * grid_size
# 向上取整到最近的网格
upper_grid = math.ceil(current_price / grid_size) * grid_size
Log(f"当前价格: {current_price}")
Log(f"下方网格: {lower_grid}")
Log(f"上方网格: {upper_grid}")
return lower_grid, upper_grid实战案例
案例1:标准化价格
python
def normalize_price():
"""使用对数标准化价格数据"""
import math
records = exchange.GetRecords()
closes = [r.Close for r in records]
# 对数变换
log_prices = [math.log(p) for p in closes]
# 标准化(Z-score)
mean = sum(log_prices) / len(log_prices)
variance = sum([(x - mean)**2 for x in log_prices]) / len(log_prices)
std = math.sqrt(variance)
z_scores = [(x - mean) / std for x in log_prices]
Log(f"当前价格Z-score: {z_scores[-1]:.2f}")
if z_scores[-1] > 2:
Log("价格偏高")
elif z_scores[-1] < -2:
Log("价格偏低")案例2:网格交易机器人
python
def grid_bot():
"""使用取整函数的网格交易"""
import math
ticker = exchange.GetTicker()
current_price = ticker.Last
# 网格参数
grid_size = 100 # 每格100美元
grid_amount = 0.01 # 每格交易0.01 BTC
# 价格取整到网格
price_grid = math.floor(current_price / grid_size) * grid_size
# 检查是否触发网格
position = exchange.GetPosition()
# 价格下穿网格,买入
if current_price <= price_grid:
Log(f"触发网格{price_grid},买入")
exchange.SetDirection("buy")
exchange.Buy(price_grid, grid_amount)
# 价格上穿网格,卖出
elif current_price >= price_grid + grid_size:
Log(f"触发网格{price_grid + grid_size},卖出")
exchange.SetDirection("sell")
exchange.Sell(price_grid + grid_size, grid_amount)案例3:波动率锥
python
def volatility_cone():
"""使用SQRT计算不同周期的波动率"""
import math
records = exchange.GetRecords()
periods = [5, 10, 20, 60]
volatilities = []
for period in periods:
if len(records) >= period:
var = TA.VAR(records, period)[-1]
vol = math.sqrt(var)
# 年化(假设日线)
annual_vol = vol * math.sqrt(365)
volatilities.append({
'period': period,
'volatility': annual_vol
})
Log(f"{period}日波动率: {annual_vol*100:.2f}%")
return volatilitiesPython内置数学函数
大多数数学变换可以使用Python的math模块:
python
import math
# 常用函数
math.sqrt(x) # 平方根
math.log(x) # 自然对数
math.log10(x) # 常用对数
math.exp(x) # e^x
math.pow(x, y) # x^y
math.sin(x) # 正弦
math.cos(x) # 余弦
math.tan(x) # 正切
math.ceil(x) # 向上取整
math.floor(x) # 向下取整
math.trunc(x) # 截断小数
# 常数
math.pi # π
math.e # e最佳实践
-
优先使用Python内置函数
- 性能更好
- 更灵活
- 更易调试
-
注意数值范围
- 对数:输入必须>0
- 平方根:输入必须≥0
- 除法:除数不能为0
-
单位一致性
- 角度 vs 弧度(三角函数)
- 日收益 vs 年收益
- 价格单位统一