Ai全自动编写策略:SAR布林带多阶段策略(通达信&python双源码)

松鼠Quant
2025-11-05


图片
量化策略开发,高质量社群,交易思路分享等相关内容

工具推荐

👉· 参数筛选工具

👉 ·Ai帮你编写策略

👉· 订单流图表

👉· 加入2025俱乐部

👉· Ai投研助手课程


『正文』

ˇ

Ai编写策略是量化领域的新常态,松鼠Quant在早些时候推出了开源项目《gitee官方推荐,松鼠QuantAi+回测框架详细版教程(图文)让Ai自动编写策略,自动回测,给出总结和迭代意见。

现在我们将通达信指标:《买在起涨点》,让Ai自动完成python编写,然后自动回测总结。
图片
通达信源码:



























{指标介绍:黄金点三个时买入,蓝点出时毫不犹豫出半仓,加之和布林轨结合用,站稳中轨持半仓,直到第二波蓝点出就全止盈出第一蓝点时同时破中轨肯定是大阴线就全止盈出局}
VAR1:=1090630;喜来财:DRAWNULL,NODRAW;珍珠点:IF(DATE<=VAR1,SAR(4,2,20),MA(CLOSE,30)),NODRAW,COLORWHITE;彩虹带:MA(CLOSE,30),COLORWHITE,LINETHICK2;SMX:MA(CLOSE,30),COLORRED;A:=珍珠点,NODRAW;B:=(MA(CLOSE,30)-REF(MA(CLOSE,30),1))*100/REF(MA(CLOSE,30),1);{以下是在k线图上画sar指标线}IF(CLOSE>=A,A,DRAWNULL),POINTDOT,COLORRED,LINETHICK4;IF(CLOSE<A,A,DRAWNULL),POINTDOT,COLORGREEN,LINETHICK4;IF(MA(B,3)<0.1,MA(CLOSE,30),DRAWNULL),COLORGRAY,LINETHICK2;{划彩色k线}STICKLINE(C>=A AND C>=O,C,O,2.8,1),COLORRED;STICKLINE(C>=A AND C<O,C-0.003*C,O,2.8,0),COLORRED;STICKLINE(C>=A ,H,C,0,0),COLORRED;STICKLINE(C>=A ,O,L-0.003*C,0,0),COLORRED;STICKLINE((C<A AND C>=O),C,O,2.8,1),COLORGREEN;STICKLINE((C<A AND C<O),C-0.003*C,O,2.8,0),COLORGREEN;STICKLINE(C<A ,H,C,0,0),COLORGREEN;STICKLINE(C<A ,O,L-0.003*C,0,0),COLORGREEN;JJ:=(CLOSE+HIGH+LOW)/3;A8:=EMA(JJ,10);B8:=REF(A8,1);持股区域:STICKLINE(A8>B8,A8,B8,2,0),COLORYELLOW;持币区域:STICKLINE(A8<B8,A8,B8,2,0),COLORBLUE;
接下来让Ai帮我们转化到松鼠Quant回测框架内,我们不需要写一行代码!!!

github地址(国外):

https://github.com/songshuquant/ssquant-ai

gitee地址(国内):

https://gitee.com/ssquant/ssquant-ai

如何使用,手把手教程:《gitee官方推荐,松鼠QuantAi+回测框架详细版教程(图文)
提出需求:
图片
自动修复BUG:
图片
回测完成:
图片
图片
Ai给出改进意见:
图片
Python源码:















































































































































































































































































import pandas as pdimport numpy as npfrom ssquant.backtest.multi_source_backtest import MultiSourceBacktesterfrom ssquant.api.strategy_api import StrategyAPI# 使用全局变量来存储策略状态,避免API对象属性问题gold_points = 0blue_point_occurred = Falsefirst_blue_exit = Falsedef initialize(api: StrategyAPI):    """策略初始化函数"""    global gold_points, blue_point_occurred, first_blue_exit        api.log("SAR布林带多阶段策略初始化")        # 重置全局状态变量    gold_points = 0   # 黄金点计数    blue_point_occurred = False   # 是否出现过蓝点    first_blue_exit = False   # 是否执行过第一次蓝点减仓def strategy_function(api: StrategyAPI):    """    SAR布林带多阶段策略    策略逻辑:    1. 黄金点三个时买入开仓    2. 蓝点出现时毫不犹豫出半仓    3. 结合布林轨:站稳中轨持半仓,直到第二波蓝点出就全止盈    4. 出第一蓝点时同时破中轨(大阴线)就全止盈出局    """    global gold_points, blue_point_occurred, first_blue_exit        # 数据验证 - 增强版    current_idx = api.get_idx()    if current_idx is None:        return            # 需要足够的数据计算指标    if current_idx < 30:        return            close = api.get_close()    high = api.get_high()   # 修复:使用正确的API方法    low = api.get_low()    # 修复:使用正确的API方法    open_price = api.get_open()        # 增强数据验证    if (close is None or len(close) == 0 or         high is None or len(high) == 0 or         low is None or len(low) == 0 or         open_price is None or len(open_price) == 0):        api.log("警告: 数据为空或数据源异常")        return        # 检查索引是否在有效范围内    if current_idx >= len(close):        api.log(f"警告: 索引 {current_idx} 超出数据范围 {len(close)}")        return        # 获取策略参数    sar_step = api.get_param('sar_step', 0.02)    sar_max = api.get_param('sar_max', 0.2)    boll_period = api.get_param('boll_period', 20)    boll_std = api.get_param('boll_std', 2)        # 计算SAR指标 - 修复版    def calculate_sar(high_series, low_series, acceleration=0.02, maximum=0.2):        """计算抛物线转向指标SAR"""        length = len(high_series)        if length == 0:            return pd.Series([], dtype=float)                    sar = np.zeros(length)        ep = np.zeros(length)        af = np.zeros(length)        trend = np.zeros(length)                # 初始化        sar[0] = low_series.iloc[0]        ep[0] = high_series.iloc[0]        af[0] = acceleration        trend[0] = 1                for i in range(1, length):            # 保存前一个值            prev_sar = sar[i-1]            prev_ep = ep[i-1]            prev_af = af[i-1]            prev_trend = trend[i-1]                        # 反转情况            if prev_trend == 1:   # 上升趋势                sar[i] = prev_sar + prev_af * (prev_ep - prev_sar)                if high_series.iloc[i] > prev_ep:                    ep[i] = high_series.iloc[i]                    af[i] = min(prev_af + acceleration, maximum)                else:                    ep[i] = prev_ep                    af[i] = prev_af                                    if low_series.iloc[i] < sar[i]:                    trend[i] = -1                    sar[i] = prev_ep                    ep[i] = low_series.iloc[i]                    af[i] = acceleration                else:                    trend[i] = 1                                else:   # 下降趋势                sar[i] = prev_sar + prev_af * (prev_ep - prev_sar)                if low_series.iloc[i] < prev_ep:                    ep[i] = low_series.iloc[i]                    af[i] = min(prev_af + acceleration, maximum)                else:                    ep[i] = prev_ep                    af[i] = prev_af                                    if high_series.iloc[i] > sar[i]:                    trend[i] = 1                    sar[i] = prev_ep                    ep[i] = high_series.iloc[i]                    af[i] = acceleration                else:                    trend[i] = -1                            return pd.Series(sar, index=high_series.index)        # 计算布林带 - 修复版    def calculate_bollinger_bands(close_series, period=20, std_dev=2):        """计算布林带指标"""        if len(close_series) < period:            return pd.Series([], dtype=float), pd.Series([], dtype=float), pd.Series([], dtype=float)                    middle_band = close_series.rolling(window=period, min_periods=1).mean()        std = close_series.rolling(window=period, min_periods=1).std()        upper_band = middle_band + (std * std_dev)        lower_band = middle_band - (std * std_dev)        return upper_band, middle_band, lower_band        try:        # 计算指标        sar_values = calculate_sar(high, low, sar_step, sar_max)        boll_upper, boll_middle, boll_lower = calculate_bollinger_bands(close, boll_period, boll_std)                # 检查指标计算结果        if (len(sar_values) == 0 or len(boll_middle) == 0 or             current_idx >= len(sar_values) or current_idx >= len(boll_middle)):            return                    current_close = close.iloc[current_idx]        current_sar = sar_values.iloc[current_idx]        prev_sar = sar_values.iloc[current_idx-1] if current_idx > 0 else current_sar        current_boll_middle = boll_middle.iloc[current_idx]                # 判断黄金点(价格上穿SAR且SAR转势向上)        is_gold_point = False        if current_idx >= 2:            is_gold_point = (current_close > current_sar and                             current_sar > prev_sar and                             prev_sar <= sar_values.iloc[current_idx-2])                # 判断蓝点(价格下穿SAR)        is_blue_point = (current_close < current_sar and                         current_close <= prev_sar)                # 判断是否破中轨(大阴线情况)        break_middle_band = (current_close < current_boll_middle and                             open_price.iloc[current_idx] > current_boll_middle)                current_pos = api.get_pos()                # 策略逻辑执行        if is_gold_point:            gold_points += 1            api.log(f"检测到黄金点 #{gold_points}, 价格: {current_close:.2f}, SAR: {current_sar:.2f}")                        # 三个黄金点买入            if gold_points >= 3 and current_pos == 0:                api.buy(volume=1, order_type='next_bar_open')                api.log(f"三个黄金点确认,买入开仓,价格: {current_close:.2f}")                gold_points = 0   # 重置计数                blue_point_occurred = False                first_blue_exit = False                elif is_blue_point:            api.log(f"检测到蓝点,价格: {current_close:.2f}, SAR: {current_sar:.2f}")            blue_point_occurred = True                        # 第一蓝点处理            if not first_blue_exit and current_pos > 0:                if break_middle_band:                    # 蓝点+破中轨(大阴线)- 全止盈                    api.close_all(order_type='next_bar_open')                    api.log(f"蓝点+破中轨大阴线,全止盈出局,价格: {current_close:.2f}")                    first_blue_exit = True                    gold_points = 0                else:                    # 蓝点出现 - 出半仓                    exit_volume = current_pos // 2                    if exit_volume > 0:                        api.sell(volume=exit_volume, order_type='next_bar_open')                        api.log(f"蓝点出现,减半仓 {exit_volume}手,价格: {current_close:.2f}")                        first_blue_exit = True                        # 第二蓝点处理 - 全止盈            elif first_blue_exit and current_pos > 0:                api.close_all(order_type='next_bar_open')                api.log(f"第二蓝点出现,全止盈出局,价格: {current_close:.2f}")                first_blue_exit = False                gold_points = 0                # 布林带中轨支撑检查(持半仓情况下)        if (first_blue_exit and current_pos > 0 and             current_close >= current_boll_middle and             not is_blue_point):            # 站稳中轨,保持半仓            api.log(f"价格站稳布林带中轨 {current_boll_middle:.2f},保持半仓状态")                except Exception as e:        api.log(f"策略执行异常: {str(e)}")        returnif __name__ == "__main__":    # 导入API认证信息    try:        from ssquant.config.auth_config import get_api_auth        API_USERNAME, API_PASSWORD = get_api_auth()    except ImportError:        print("警告:未找到 auth_config.py 文件,请在下方填写您的认证信息:API_USERNAME和API_PASSWORD")        API_USERNAME = ""        API_PASSWORD = ""    # 创建多数据源回测器    backtester = MultiSourceBacktester()        # 设置基础配置    backtester.set_base_config({        'username': API_USERNAME,       # 使用配置文件中的用户名        'password': API_PASSWORD,       # 使用配置文件中的密码        'use_cache': True,              # 是否使用缓存数据        'save_data': True,              # 是否保存数据        'align_data': False,            # 是否对齐数据        'fill_method': 'ffill',         # 填充方法        'debug': True                   # 启用调试模式    })        # 添加品种配置(黄金期货)    backtester.add_symbol_config(        symbol='au888',        config={            'start_date': '2024-01-01',      # 回测开始日期            'end_date': '2025-12-31',        # 回测结束日期            'initial_capital': 100000.0,     # 初始资金,单位:元            'commission': 0.0003,            # 手续费率            'margin_rate': 0.1,              # 保证金率            'contract_multiplier': 1000,     # 黄金期货合约乘数:1000克/手            'periods': [                {'kline_period': '1d', 'adjust_type': '1'},   # 日线,后复权            ]        }    )        # 设置策略参数    strategy_params = {        'sar_step': 0.02,      # SAR加速因子初始值        'sar_max': 0.2,        # SAR加速因子最大值        'boll_period': 20,     # 布林带周期        'boll_std': 2          # 布林带标准差倍数    }        # 运行回测    results = backtester.run(        strategy=strategy_function,        initialize=initialize,        strategy_params=strategy_params,    )
没错,整个开发过程我们没有手写一行代码,松鼠QuantAi助手会编写,回测,分析,修改。基于松鼠Quant的MCP服务器+Deepseek开启全新量化学习的路径,即使0基础也能完成策略的编写与验证!
如果你喜欢这个系列,请点赞,转发,在看三连。我们根据受欢迎程度决定是否继续更新,感谢您的支持。

github地址(国外):

https://github.com/songshuquant/ssquant-ai

gitee地址(国内):

https://gitee.com/ssquant/ssquant-ai

如何使用,手把手教程:《gitee官方推荐,松鼠QuantAi+回测框架详细版教程(图文)

防迷路


           图片

微   信|小松鼠-松鼠Quant

微信号|viquant01

25俱乐部源码VIP27》

加入2025量化俱乐部


分享