
等级: 新手上路
- 注册:
- 2025-3-7
- 曾用名:
|
import pandas as pd
def pyramid_trading_strategy(df, initial_capital=100000):
"""
金字塔决策交易策略
策略逻辑:
1. 当5日均线上穿10日均线时,使用总资金的10%开多仓
2. 平仓条件:
a) 收盘价跌破5日均线
b) 持仓期间最高价较开仓价上涨10%后,回撤超过5%
"""
# ========== 指标计算 ==========
# 计算移动平均线
df['MA5'] = df['close'].rolling(window=5).mean()
df['MA10'] = df['close'].rolling(window=10).mean()
# 生成金叉信号(5日线上穿10日线)
df['MA5_prev'] = df['MA5'].shift(1)
df['MA10_prev'] = df['MA10'].shift(1)
df['golden_cross'] = (df['MA5'] > df['MA10']) & (df['MA5_prev'] <= df['MA10_prev'])
# ========== 初始化交易账户 ==========
cash = initial_capital # 可用资金
position = 0.0 # 持仓数量
entry_price = 0.0 # 开仓价格
max_price = 0.0 # 持仓期间最高价
hold = False # 持仓状态
# 记录账户信息
df['cash'] = 0.0
df['position'] = 0.0
df['total_asset'] = 0.0
df['signal'] = 0 # 1: 买入,-1: 卖出
# ========== 策略执行 ==========
for i in range(len(df)):
current = df.iloc[i]
# 更新账户总资产(用于后续信号生成)
df.at[i, 'cash'] = cash
df.at[i, 'position'] = position
df.at[i, 'total_asset'] = cash + position * current['close']
# 未持仓时检测买入信号
if not hold:
if current['golden_cross']:
# 计算可投入资金(总资产的10%)
total_asset = cash + position * current['close']
investment = total_asset * 0.1
if current['close'] > 0 and investment > 0:
# 计算买入数量
shares = investment / current['close']
# 执行买入
cash -= shares * current['close']
position += shares
entry_price = current['close'] # 记录开仓价
max_price = current['high'] # 初始化最高价
hold = True
df.at[i, 'signal'] = 1 # 标记买入信号
# 持仓时检测平仓信号
else:
# 更新持仓期间最高价
if current['high'] > max_price:
max_price = current['high']
# 平仓条件1:收盘价跌破5日均线
condition1 = current['close'] < current['MA5']
# 平仓条件2:最高价上涨10%后回撤5%
price_increase = max_price >= entry_price * 1.1
price_drawdown = current['close'] <= max_price * 0.95
condition2 = price_increase and price_drawdown
# 执行平仓
if condition1 or condition2:
# 计算平仓收益
cash += position * current['close']
# 重置持仓状态
position = 0.0
entry_price = 0.0
max_price = 0.0
hold = False
df.at[i, 'signal'] = -1 # 标记卖出信号
return df
# 使用示例(需包含open,high,low,close列的DataFrame)
# df = pd.read_csv('your_stock_data.csv')
# result_df = pyramid_trading_strategy(df)
# result_df[['date','close','MA5','MA10','signal','total_asset']].tail() |
|