我写了一个网格交易策略,但是编译完了,看不到交易数据。

用户头像韭菜来割
2025-02-06 发布

初始化函数

def initialize(context):

设置初始参数

context.investment = 1000000 # 投资金额100万元
context.position = 20000 # 当前持仓数量
context.cash = context.investment # 当前现金
context.security = '513050.SH' # 交易标的
context.base_price = 1.0 # 基准价1元
context.max_position = context.investment * 0.90 # 最大仓位90%

数据处理函数

def handle_data(context, data):

获取当前价格

current_price = data.current(context.security, 'close')

计算20日均线和20日波动率

history_data = data.history(context.security, 'close', 20)
ma20 = history_data.mean() # 20日均线
volatility = history_data.std() # 20日波动率

动态阈值:根据波动率控制在2%-5%

threshold = max(min(volatility * 2, 0.05), 0.02)

卖出条件:当前价格高于20日均线3%

if current_price > ma20 * (1 + threshold) and context.position > 0:
sell_amount = context.position * 0.10 # 卖出10%持仓
context.position -= sell_amount
context.cash += sell_amount * current_price
print("Sell {:.2f} shares at {:.2f}".format(sell_amount, current_price)) # 使用 .format() 方法

买入条件:当前价格低于20日均线3%

if current_price < ma20 * (1 - threshold) and context.cash > 0:
buy_amount = min(context.cash * 0.12 / current_price, (context.max_position - context.position)) # 买入12%资金,且不超过最大仓位
context.position += buy_amount
context.cash -= buy_amount * current_price
print("Buy {:.2f} shares at {:.2f}".format(buy_amount, current_price)) # 使用 .format() 方法

计算当前投资组合价值

portfolio_value = context.position * current_price + context.cash
print("Portfolio Value: {:.2f} CNY".format(portfolio_value)) # 使用 .format() 方法

主函数(同花顺平台要求)

def run():
pass

我自己做了一个网格交易策略,在编译成功以后,看不到交易数据,不知道是哪里写错了?

有人能指导一下吗?

评论