在每年四次调仓和交易费用为千分之1.3%的要求下,你可以修改 handle_data
函数中的逻辑来实现:
import numpy as np
import pandas as pd
def initialize(context):
context.index = 'HS300'
context.start_date = '2010-01-01'
context.end_date = '2022-12-31'
# 设置调仓频率为每年四次
schedule_function(rebalance_portfolio,
date_rule=date_rules.month_start(days_offset=0),
time_rule=time_rules.market_open())
def handle_data(context, data):
components = get_index_stocks('000300.XSHG')
df = get_fundamentals(query(valuation, indicator), date=context.current_dt)
avg_market_cap = df['market_cap'].mean()
avg_dividend_yield = df['dividend_ratio'].mean()
avg_debt_to_asset_ratio = df['debt_to_assets'].mean()
avg_pe_ratio_lyr = df['pe_ratio_lyr'].mean()
avg_cash_flow_per_share_ttm = df['cash_flow_per_share_ttm'].mean()
selected_stocks = []
for stock in components:
if (df.loc[stock, 'market_cap'] > avg_market_cap and
df.loc[stock, 'dividend_ratio'] > avg_dividend_yield * 1.5 and
df.loc[stock, 'debt_to_assets'] < avg_debt_to_asset_ratio and
df.loc[stock, 'pe_ratio_lyr'] < avg_pe_ratio_lyr and
df.loc[stock, 'cash_flow_per_share_ttm'] > avg_cash_flow_per_share_ttm):
selected_stocks.append(stock)
selected_stocks = sorted(selected_stocks,
key=lambda x: df.loc[x, 'dividend_ratio'],
reverse=True)[:10]
rebalance_portfolio(context, data, selected_stocks)
def rebalance_portfolio(context, data, stocks):
num_stocks = len(stocks)
# 卖出持仓中不在选股列表的股票
for stock in context.portfolio.positions:
if stock not in stocks and context.portfolio.positions[stock].closeable_amount > 0:
order_target_percent(stock, 0)
# 买入新选股列表中的股票
for stock in stocks:
if stock not in context.portfolio.positions:
order_target_percent(stock, 1/num_stocks)
# 计算每个股票需要调整的权重
target_weight = 1 / num_stocks
# 调整现有持仓中的股票权重
for stock in context.portfolio.positions:
if stock in stocks:
position_value = context.portfolio.positions[stock].value
target_value = context.portfolio.total_value * target_weight
if position_value < target_value:
cash_to_invest = target_value - position_value
order_value(stock, cash_to_invest)
elif position_value > target_value:
cash_to_withdraw = position_value - target_value
order_target_percent(stock, target_weight)
order_cash(-cash_to_withdraw)
# 在Supermind量化平台上配置策略和参数
if __name__ == '__main__':
from jqalpha.api import *
log_level = "info"
set_token('你的聚宽账号', '你的聚宽密码')
set_benchmark('000300.XSHG')
run_func(init=initialize, handle_data=handle_data, config=config)
上述代码中,我们使用 schedule_function
函数来设置调仓频率为每年四次,在每次调仓时根据选股结果进行买卖操作。在买入和卖出操作时,我们需要注意交易费用,并且按照千分之1.3的比例进行扣除。请确保在Supermind量化平台上正确配置和运行该回测代码,并根据需要进行参数调整和其他逻辑编写。同样,请替换代码中的”你的聚宽账号”和”你的聚宽密码”为你自己的聚宽账号信息。
内容由零声教学AI助手提供,问题来源于学员提问