【mindgo】 爱问财策略回测框架(分钟级回测)

# 爱问财策略回测框架(分钟级回测)

import datetime

# 初始化账户
def init(context):
    # 设置策略问句
    get_iwencai('非停牌;非st;业绩预增大于50%;市值排名后30%;市盈率小于120;总市值从小到大')
    # 设置持仓股票数量
    context.n = 4
    # 设置股票持有期
    context.holding_period = 5
    # 设置止盈涨幅
    context.stop_gain = 0.2
    # 设置止盈回撤
    context.stop_gain_drawdown = 0.05
    # 设置止损跌幅
    context.stop_loss = 0.05
    # 设置仓位比例
    context.position_pct = 1
    
    context.information = {}
    
    run_daily(market_open,'after_open',0,1,'000001.SZ')
    run_daily(market_close,'before_close',0,5,'000001.SZ')
    

class Information:
    # 记录买入股票的信息,作为position的补充
    def __init__(self, remain_days):
        self.remain_days = remain_days
        self.stop_gain = False
        self.today_high = 0

# 开盘时买入股票
def market_open(context, bar_dict):
    # 若持有天数到期则卖出(防止昨天未卖出)
    for stock in list(context.portfolio.positions):
        context.information[stock].today_high = 0
        if (not context.information[stock].stop_gain
                and context.information[stock].remain_days == 0):
            order_target(stock, 0)
            if stock not in list(context.portfolio.positions):
                del context.information[stock]
                log.info('持有天数到期,卖出%s' % stock)
                continue
    
    stocks_list = context.iwencai_securities
    number_of_buys = context.n-len(context.portfolio.positions)
    if number_of_buys == 0:
        return
    # 若持有股数不足设定值则买入
    cash_for_stock = context.portfolio.available_cash*context.position_pct/number_of_buys
    
    for stock in stocks_list:
        if stock in context.portfolio.positions:
            continue
        #current = data.current([stock])[stock]
        if not bar_dict[stock].open or not bar_dict[stock].close:
            continue
        # 开盘涨跌幅不小于-9%才买入
        if bar_dict[stock].open/bar_dict[stock].close-1 >= -0.09:
            order_value(stock, cash_for_stock)
            if stock in list(context.portfolio.positions):
                context.information[stock] = Information(context.holding_period)
                log.info('买入%s' % stock)
        number_of_buys -= 1
        if number_of_buys == 0:
            return

# 盘中止盈止损
def handle_bar(context, bar_dict):
    price_dict = history(list(context.portfolio.positions), ['close'], 2, '1m')
    for stock in price_dict:
        if price_dict[stock].empty:
            continue
        price = price_dict[stock].values[-1][0]
        # 更新今日最高价
        if price > context.information[stock].today_high:
            context.information[stock].today_high = price
        # 若刚买入则不进行操作
        if context.information[stock].remain_days == context.holding_period:
            continue
        # 若进入止盈状态,则根据要求止盈
        if context.information[stock].stop_gain:
            if price/context.information[stock].high-1 < -context.stop_gain_drawdown:
                order_target(stock, 0)
                if stock not in context.portfolio.positions:
                    del context.information[stock]
                    log.info('止盈,卖出%s' % stock)
        # 若未进入止盈状态,则根据要求止损
        else:
            if price/context.portfolio.positions[stock].cost_basis-1 < -context.stop_loss:
                order_target(stock, 0)
                if stock not in context.portfolio.positions:
                    del context.information[stock]
                    log.info('止损,卖出%s' % stock)

# 收盘时卖出到期股票、判断止盈
def market_close(context, bar_dict):
    for stock in list(context.portfolio.positions):
        today_high = context.information[stock].today_high
        # 若进入止盈状态,则更新最高价
        if context.information[stock].stop_gain:
            if today_high > context.information[stock].high:
                context.information[stock].high = today_high
        # 若未进入止盈状态,则卖出到期股票、判断止盈
        else:
            # 判断是否进入止盈状态
            if today_high/context.portfolio.positions[stock].cost_basis-1 >= context.stop_gain:
                context.information[stock].stop_gain = True
                context.information[stock].high = today_high
                log.info('%s进入止盈状态' % stock)
                continue
            # 若持有天数到期则卖出
            context.information[stock].remain_days -= 1
            if context.information[stock].remain_days == 0:
                order_target(stock, 0)
                if stock not in context.portfolio.positions:
                    del context.information[stock]
                    log.info('持有天数到期,卖出%s' % stock)
                    continue
  • 4
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是一个使用 Mindgo 平台编写的布林带策略的示例代码: ```python import numpy as np import pandas as pd def initialize(context): # 设置股票池和参数 context.symbols = ['AAPL', 'MSFT', 'AMZN'] context.n = 20 context.sigma = 2 def handle_data(context, data): # 获取股票数据 prices = data.history(context.symbols, 'close', context.n, '1d') # 计算布林带指标 ma = prices.mean() std = prices.std() upper = ma + context.sigma * std lower = ma - context.sigma * std # 获取当前仓位 positions = context.portfolio.positions # 根据布林带指标产生交易信号 for symbol in context.symbols: price = data.current(symbol, 'close') if price > upper[symbol] and symbol not in positions: order(symbol, 100) elif price < lower[symbol] and symbol in positions: order(symbol, -100) # 打印当前仓位 print(positions) ``` 这个代码使用了 Mindgo 平台提供的函数,包括 `initialize` 和 `handle_data`。在 `initialize` 函数中,我们设置了股票池和需要用到的参数。在 `handle_data` 函数中,我们首先获取了股票的历史价格,并计算了布林带指标。接着我们获取当前的仓位,并根据布林带指标产生交易信号。如果某个股票的价格突破了上轨线并且该股票目前没有持仓,则产生买入信号;如果某个股票的价格跌破了下轨线并且该股票目前有持仓,则产生卖出信号。最后我们打印当前的仓位情况,以便我们调试策略。 需要注意的是,这个代码只是示例,需要根据具体情况进行修改和完善。在实际使用中,我们还需要考虑交易成本、市场流动性等因素,以及如何设置止盈止损等风险管理措施。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

weixin_1985159637

感谢你的支持!!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值