Tortoise/tests/test_strategy_indicators.py
2026-06-24 16:50:59 +08:00

71 lines
2.3 KiB
Python

"""策略通用技术指标工具测试。"""
import pytest
from strategy.indicators import calculate_ema, calculate_kdj, calculate_ma, calculate_macd
def test_6_1_calculate_ma() -> None:
"""
功能说明:验证简单移动平均线会在样本不足时返回 None。
参数说明:无。
返回值说明:无返回值。
注意事项:用例编号 6-1。
"""
assert calculate_ma([1, 2, 3, 4], 3) == [None, None, 2.0, 3.0]
def test_6_2_calculate_ema() -> None:
"""
功能说明:验证指数移动平均线按首个值初始化并递推。
参数说明:无。
返回值说明:无返回值。
注意事项:用例编号 6-2。
"""
assert calculate_ema([1, 2, 3], 2) == pytest.approx([1.0, 1.6666666667, 2.5555555556])
def test_6_3_calculate_macd() -> None:
"""
功能说明:验证 MACD 返回 DIF、DEA 和柱值三个等长序列。
参数说明:无。
返回值说明:无返回值。
注意事项:用例编号 6-3。
"""
dif, dea, macd = calculate_macd([1, 2, 3, 4], fast_period=2, slow_period=3, signal_period=2)
assert len(dif) == 4
assert len(dea) == 4
assert len(macd) == 4
assert dif == pytest.approx([0.0, 0.1666666667, 0.3055555556, 0.3935185185])
assert dea == pytest.approx([0.0, 0.1111111111, 0.2407407407, 0.3425925926])
assert macd == pytest.approx([0.0, 0.1111111111, 0.1296296296, 0.1018518519])
def test_6_4_calculate_kdj() -> None:
"""
功能说明:验证 KDJ 在样本足够后计算 K、D、J 值。
参数说明:无。
返回值说明:无返回值。
注意事项:用例编号 6-4。
"""
k_values, d_values, j_values = calculate_kdj([3, 4, 5], [1, 1, 1], [2, 3, 4], period=3)
assert k_values[:2] == [None, None]
assert d_values[:2] == [None, None]
assert j_values[:2] == [None, None]
assert k_values[2] == pytest.approx(58.3333333333)
assert d_values[2] == pytest.approx(52.7777777778)
assert j_values[2] == pytest.approx(69.4444444444)
def test_6_5_indicator_period_validation() -> None:
"""
功能说明:验证通用指标工具会拒绝非法周期参数。
参数说明:无。
返回值说明:无返回值。
注意事项:用例编号 6-5。
"""
with pytest.raises(ValueError):
calculate_ma([1], 0)