quant-platform/strategies/strategy_a.py

38 lines
1.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import pandas as pd
import numpy as np
def run():
"""
简单均线策略示例:
- 买入条件:收盘价 > 5 日均线
- 卖出条件:收盘价 < 5 日均线
"""
# 模拟历史行情数据
dates = pd.date_range(start='2026-01-01', periods=20)
prices = pd.Series(np.random.uniform(100, 200, size=20), index=dates)
# 计算 5 日均线
ma5 = prices.rolling(window=5).mean()
# 策略信号1 买入,-1 卖出
signal = (prices > ma5).astype(int) - (prices < ma5).astype(int)
# 简单净值计算
capital = 10000
position = 0
nav = []
for i in range(len(prices)):
if signal[i] == 1: # 买入
position = capital / prices[i]
elif signal[i] == -1: # 卖出
capital = position * prices[i]
position = 0
nav.append(capital + position * prices[i])
result = pd.DataFrame({
'date': dates,
'price': prices,
'signal': signal,
'nav': nav
})
return result