更多精彩内容详见个人量化交易专辑索引
1. 回测框架
def trade_simulate(start, stop, initial_crash):
crash = initial_crash #设置初始资金
hold_dict = {} #持有的股票
hold_value = 0 #持有市值
# 获取有效交易日
trade_datetimes = my_trade_date(start, stop)
# 开始模拟交易
for today_datetime in trade_datetimes:
# 调整买入份额
single_limit = (crash+hold_value)/10
# 计算要买卖的股票
sale_list = my_sale_list(crash, hold_dict, today_datetime)
buy_list = my_buy_list(crash, hold_dict, today_datetime)
# 先卖股票
for to_sale in sale_list[:]:
result, crash, hold_dict = my_sale(crash, hold_dict, today_datetime, to_sale)
if result:
sale_list.remove(to_sale)
# 再买股票
for to_buy in buy_list[:]:
result, crash, hold_dict = my_buy(crash, hold_dict, today_datetime, to_buy, single_limit)
if result == True:
buy_list.remove(to_buy)
# 更新持有股票收盘信息
hold_value, hold_dict = my_update(hold_dict, today_datetime)
2. 获取有效交易日
def my_trade_date(start, stop):
# 读取本地数据库
# 添加代码
return trade_datetimes
3. 卖出策略
# 定时换仓策略
def my_sale_list(crash, hold_dict, today_datetime):
sale_list = []
for code in hold_dict:
# 计算持有时间
delta = today_datetime - datetime.datetime.strptime(hold_dict[code]['buy_date'], '%Y-%m-%d')
# 持有时间到
if delta > 7
sale_list.append([code])
return sale_list
4. 买入策略
# 均线策略
def my_buy_list(crash, hold_dict, today_datetime):
buy_list = []
# 读取数据库获取所有满足条件的股票
# 添加代码
# 从候选股票中选择
for candidate in candidates_list:
code = candidate[0]
closeing_price = candidate[1]
# 已经持有了,不再买入
if code in hold_dict:
continue
buy_list.append([code, closeing_price])
return buy_list
5. 模拟卖出
def my_sale(crash, hold_dict, today_datetime, to_sale):
code = to_sale[0]
sale_price = hold_dict[code]['last_closeing_price']
share = hold_dict[code]['share']
crash += sale_price*share*(1-selling_rate) #selling_rate是卖出交易费率
del hold_dict[code]
return True, crash, hold_dict
6. 模拟买入
def my_buy(crash, hold_dict, today_datetime, to_buy, single_limit):
code = to_buy[0]
closeing_price = to_buy[1]
crash -= single_limit*(1+buying_rate) #buying_rate是买入交易费率
share = single_limit/closeing_price
hold_dict[code] = {
'active':True,
'buy_date':today,
'last_date':today,
'buy_price':buy_price,
'share':share,
'last_closeing_price':closeing_price,
}
return True, crash, hold_dict
7. 更新持仓信息
def my_update(hold_dict, today_datetime):
for code in hold_dict:
# 读取数据库获取股票价格
# 添加代码
if not result:
hold_dict[code]['active'] = False
continue
hold_dict[code]['active'] = True
hold_dict[code]['last_date'] = today
hold_dict[code]['last_closeing_price'] = closeing_price
return hold_dict