|
|
#【JoinQuant】策略名称:浦发银行T0回测-模拟交易 链接:https://www.joinquant.com/algori ... ad08649038ef32facc5 密码:h0y4f4
# 导入聚宽函数库
import jqdata
import pandas as pd
import numpy as np
def initialize(context):
# 设定要操作的股票:浦发银行
g.security = '600000.XSHG'
# 设定基准
set_benchmark('000300.XSHG')
# 开启动态复权模式(真实价格)
set_option('use_real_price', True)
# 【关键】开启 T+0 模式,允许当天买入的股票当天卖出
set_option('t0_mode', True)
# 设置交易成本:佣金万2.5,印花税千0.5(卖出),最低佣金5元
set_order_cost(OrderCost(
open_tax=0,
close_tax=0.0005,
open_commission=0.00025,
close_commission=0.00025,
min_commission=5
), type='stock')
# 策略参数
g.init_cash = 50000
g.base_ratio = 0.5 # 底仓占50%
g.t_ratio = 0.3 # 每次做T动用底仓的30%
g.max_trades_per_day = 2
g.buy_threshold = 0.003
g.sell_threshold = 0.005
# 状态变量
g.base_built = False # 底仓是否已建立
g.base_shares = 0 # 底仓股数
g.t_shares = 0 # T仓持股数
g.t_price = 0
g.day_trade_count = 0
# 【修正】按分钟频率运行策略,并显式调度收盘处理函数
run_daily(market_open, time='every_bar')
run_daily(after_trading_end, time='14:55') # 收盘前5分钟执行平仓检查
def build_base_position(context):
"""建立底仓:用50%资金买入,只在第一天执行一次"""
security = g.security
current_price = get_current_data()[security].last_price
if current_price <= 0:
return
# 计算底仓股数(整手)
base_shares = int(g.init_cash * g.base_ratio / current_price / 100) * 100
if base_shares < 100:
log.warn("资金不足,无法建立底仓")
return
order(security, base_shares)
g.base_shares = base_shares
g.base_built = True
log.info("【建底仓】价格 %.2f,股数 %d" % (current_price, base_shares))
def market_open(context):
security = g.security
current_dt = context.current_dt
current_time = current_dt.strftime('%H:%M')
# ========== 每日重置(开盘后第一分钟) ==========
if current_time == '09:31':
g.t_shares = 0
g.t_price = 0
g.day_trade_count = 0
log.info("=== 新交易日开始,重置T仓状态 ===")
# 【修正】第一天开盘时建立底仓
if not g.base_built:
build_base_position(context)
return
# 跳过开盘前30分钟,让VWAP稳定
if current_time < '10:00':
return
# ========== 获取当日分钟数据并计算 VWAP ==========
try:
day_start = current_dt.replace(hour=9, minute=30, second=0, microsecond=0)
minute_df = get_price(
security,
start_date=day_start,
end_date=current_dt,
frequency='1m',
fields=['close', 'high', 'low', 'volume', 'money'],
skip_paused=False,
fq='pre'
)
except Exception as e:
log.error("获取分钟数据失败: %s" % str(e))
return
if minute_df is None or len(minute_df) < 6:
return
cumulative_money = minute_df['money'].sum()
cumulative_volume = minute_df['volume'].sum()
if cumulative_volume == 0:
return
vwap = cumulative_money / cumulative_volume
current_price = minute_df['close'].iloc[-1]
# T仓股数:基于底仓的30%
t_shares_max = int(g.base_shares * g.t_ratio / 100) * 100
if t_shares_max < 100:
return
# ========== 正T逻辑 ==========
# 买入
if g.t_shares == 0 and g.day_trade_count < g.max_trades_per_day:
if current_price < vwap * (1 - g.buy_threshold):
cash = context.portfolio.available_cash
buy_amount = t_shares_max * current_price
if cash >= buy_amount:
order(security, t_shares_max)
g.t_shares = t_shares_max
g.t_price = current_price
log.info("【正T买入】价格 %.2f,VWAP %.2f,股数 %d" % (current_price, vwap, t_shares_max))
# 卖出
elif g.t_shares > 0:
if current_price >= g.t_price * (1 + g.sell_threshold):
order(security, -g.t_shares) # 只卖出T仓,不动底仓
pnl = (current_price - g.t_price) * g.t_shares
log.info("【正T卖出】价格 %.2f,买入价 %.2f,盈亏 %.2f" % (current_price, g.t_price, pnl))
g.t_shares = 0
g.t_price = 0
g.day_trade_count += 1
def after_trading_end(context):
"""收盘前平掉未完成的T仓,底仓保持不动"""
security = g.security
if g.t_shares > 0:
current_price = get_current_data()[security].last_price
order(security, -g.t_shares)
pnl = (current_price - g.t_price) * g.t_shares
log.info("【收盘平仓】价格 %.2f,买入价 %.2f,盈亏 %.2f" % (current_price, g.t_price, pnl))
g.t_shares = 0
g.t_price = 0 |
|