TAMath ops
MULT - 向量乘法
TA.MULT() - 数组元素相乘
语法
python
result = TA.MULT(array1, array2)参数
| 参数 | 类型 | 说明 |
|---|---|---|
| array1 | array | 第一个数组 |
| array2 | array | 第二个数组 |
返回值
返回一个新数组,每个元素是 array1[i] * array2[i]。
计算方法
plaintext
result[i] = array1[i] * array2[i]使用场景
- 成交量加权:价格乘以成交量
- 仓位计算:价格乘以数量
- 指标缩放:调整指标数值范围
基础示例
python
def onTick():
exchange.SetContractType("swap")
records = exchange.GetRecords()
if len(records) < 30:
return
# 计算成交额(价格 × 成交量)
closes = [r.Close for r in records]
volumes = [r.Volume for r in records]
turnover = TA.MULT(closes, volumes)
Log("最新成交额:", turnover[-1])高级应用
1. 成交量加权平均价
python
def onTick():
records = exchange.GetRecords()
closes = [r.Close for r in records[-20:]]
volumes = [r.Volume for r in records[-20:]]
# 价格 × 成交量
price_volume = TA.MULT(closes, volumes)
# 成交量加权平均价 = Σ(价格×成交量) / Σ成交量
total_pv = sum(price_volume)
total_v = sum(volumes)
vwap = total_pv / total_v
Log("成交量加权平均价(VWAP):", vwap)
# 当前价格偏离VWAP
current_price = records[-1].Close
deviation = (current_price - vwap) / vwap
if deviation < -0.02: # 低于VWAP 2%
Log("价格被低估,考虑买入")
exchange.SetDirection("buy")
exchange.Buy(-1, 1)
elif deviation > 0.02: # 高于VWAP 2%
Log("价格被高估,考虑卖出")2. 仓位价值计算
python
def onTick():
records = exchange.GetRecords()
# 假设持有不同价格点买入的仓位
buy_prices = [50000, 51000, 52000] # 买入价
buy_amounts = [1, 0.5, 0.3] # 对应数量
# 计算每笔仓位的成本
position_costs = TA.MULT(buy_prices, buy_amounts)
total_cost = sum(position_costs)
total_amount = sum(buy_amounts)
avg_price = total_cost / total_amount
current_price = records[-1].Close
profit_pct = (current_price - avg_price) / avg_price * 100
Log(f"平均成本: {avg_price}, 当前盈亏: {profit_pct:.2f}%")3. 波动率权重
python
def onTick():
records = exchange.GetRecords()
# 计算ATR(波动率)
atr = TA.ATR(records, 14)
# 基础仓位
base_size = 1.0
# 根据波动率调整仓位(波动率越大,仓位越小)
avg_atr = sum(atr[-20:]) / 20
volatility_factor = TA.DIV([avg_atr] * len(atr), atr)
# 调整后的仓位大小
adjusted_size = TA.MULT([base_size] * len(volatility_factor), volatility_factor)
Log("当前建议仓位:", adjusted_size[-1])4. 指标信号强度
python
def onTick():
records = exchange.GetRecords()
# RSI信号(0-1范围)
rsi = TA.RSI(records, 14)
rsi_signal = TA.DIV(TA.SUB(rsi, [50] * len(rsi)), [50] * len(rsi))
# MACD信号
macd = TA.MACD(records, 12, 26, 9)
macd_hist = TA.SUB(macd[0], macd[1])
# 标准化MACD
macd_max = max([abs(m) for m in macd_hist[-20:]])
macd_signal = TA.DIV(macd_hist, [macd_max] * len(macd_hist))
# 组合信号强度 = RSI信号 × MACD信号
combo_strength = TA.MULT(rsi_signal, macd_signal)
if combo_strength[-1] > 0.5:
Log("强烈看涨信号,强度:", combo_strength[-1])
exchange.SetDirection("buy")
exchange.Buy(-1, 1)
elif combo_strength[-1] < -0.5:
Log("强烈看跌信号,强度:", combo_strength[-1])
exchange.SetDirection("sell")
exchange.Sell(-1, 1)注意事项
- 数组长度:两个数组长度必须相同
- 数值溢出:注意大数相乘可能溢出
- 零值处理:任何数乘以0结果为0