Skip to content

智能 MA 算法加持!轻松锁定最佳盈利参数

作者:老余捞鱼

原创不易,转载请标明出处及原作者。

写在前面的话:你是不是已经厌倦了每次交易时都要在众多移动平均线中做出选择?今天,我将带你探讨如何借助算法的力量,自动调整和优化移动平均线交易策略的参数。我们会学习如何让这些策略灵活适应各种股票和市场的变化,以此来提升你的交易效率,并最大化收益。在文末我还将以特斯拉股票举例,并提供了全部源代码以及 Google Colab 笔记本的链接,以便您亲自进行尝试。

移动平均线(Moving Average,简称MA)是一种在技术分析领域广泛使用的技术指标。它是通过统计分析的方法,将一定时期内的证券价格进行平均计算,并将这些不同时间的平均值连接起来,形成一条平滑的曲线。

但问题来了,移动平均线的一定时期(日数)选择没有标准和规定,投资者需要根据自己的投资目标和市场特性来选择。而且在价格波动较大的市场中移动平均线会频繁信号;在价格波幅不大的市场中,平均线又可能会在价格之间上下交错,难以把握最佳交易时机。所有这些不同的选择都可能会影响移动平均线的敏感度和稳定性,从而影响投资者的决策。

而有没有一种算法能在任何时间段为任何股票自动找到最佳参数?

这种方法需要既可以满足高波动性科技股、又可以适应稳定的蓝筹股,在不同的市场周期和各种时间范围内都能根据您的情况找到专门优化的完美移动平均参数!

我们今天来探索实现它,直接上干货!

一、代码实现

1.1 数据收集和清理 

def get_clean_financial_data(ticker, start_date, end_date):
    # Download data using yfinance
    data = yf.download(ticker, start=start_date, end=end_date)
    
    # Clean structure and handle missing values
    data.columns = data.columns.get_level_values(0)
    data = data.ffill()
    
    # Standardize timezone
    data.index = data.index.tz_localize(None)
    
    return data

作用:

  • 使用 yfinance 下载股票数据;
  • 自动处理缺失值;
  • 确保数据结构简洁、一致。

1.2 核心战略实施

def ma_crossover_strategy(data, short_window=5, long_window=20):
    # Calculate moving averages
    data['SMA_Short'] = data['Close'].rolling(window=short_window).mean()
    data['SMA_Long'] = data['Close'].rolling(window=long_window).mean()
    
    # Generate signals
    data.loc[data['SMA_Short'] > data['SMA_Long'], 'Position'] = 1  # Buy
    data.loc[data['SMA_Short'] <= data['SMA_Long'], 'Position'] = 0  # Sell
    
    # Calculate returns
    data['Returns'] = data['Close'].pct_change()
    data['Strategy_Returns'] = data['Position'].shift(1) * data['Returns']
    
    return data

1.2.1 作用:

  • 计算短期和长期移动平均线
  • 在交叉点生成买入/卖出信号
  • 跟踪位置回报
data['Strategy_Returns'] = data['Position'].shift(1) * data['Returns']

1.2.2 战略回报(这一点至关重要):

  • Position.shift(1):使用昨天的位置计算今天的收益;
  • 将位置(1 或 0)乘以返回值;
  • 位置 = 1:获取全部收益;
  • 仓位 = 0:获得零收益(退出)。

1.2.3 要点说明:

位置 = 1 表示:空仓 → 买入 ,持仓 → 保持。

位置 = 0 表示:持仓 → 卖出 ,空仓 → 保持。

例如:

Day    Position    Returns    Strategy Returns
1      1          2%         0% (no previous position)
2      1          -1%        -1% (in market, full loss)
3      0          2%         2% (in market, full gain)
4      0          -1%        0% (out of market, no loss)

1.3 参数优化

def optimize_ma_windows(data):
    best_return = -np.inf
    best_params = None

    for short_window in range(3, 15):
        for long_window in range(short_window + 5, 200):
            result = ma_crossover_strategy(data.copy(), short_window, long_window)
            total_return = (1 + result['Strategy_Returns']).cumprod().iloc[-1] - 1

            if total_return > best_return:
                best_return = total_return
                best_params = (short_window, long_window)

    return best_params

作用:

  • 测试数百种 MA 组合;
  • 找到收益最大的一对;
  • 确保短 MA 始终短于长 MA。

1.4 着眼于现实的收益跟踪

def calculate_performance(data, initial_capital=10000, transaction_fee=10):
    # Track trades and capital
    trade_details = []
    capital = initial_capital

    for buy_date, buy_row in buys.iterrows():
        # Find next sell signal
        sell = sells[sells.index > buy_date].iloc[0]
        
        # Calculate position size and costs
        num_shares = (capital - transaction_fee) // buy_row['Close']
        profit = (sell['Close'] - buy_row['Close']) / buy_row['Close']
        
        # Update capital
        capital += profit_after_fee
        
        # Track trade details...

作用:

  • 精确跟踪每笔交易;
  • 交易费用;
  • 保持基本建设收支平衡。

二、实际应用

让我们用特斯拉股票为例,来看看它的实际效果:

# Get the data
TSLA = get_clean_financial_data('TSLA', '2023-01-01', datetime.now().strftime('%Y-%m-%d'))

# Find optimal parameters
optimal_short, optimal_long = optimize_ma_windows(TSLA)

# Run strategy with optimal parameters
result = ma_crossover_strategy(TSLA.copy(), optimal_short, optimal_long)

# Calculate performance
performance = calculate_performance(result)

Performance Metrics (Trade Details):
Buy Date     Buy Price    Sell Date    Sell Price   Number of Shares  Profit   Transaction Fee Capital Change  Running Total Capital
2023-01-18   128.78       2023-02-23   202.07       77                56.91%   $10             $5633.33         $15633.33            
2023-03-20   183.25       2023-04-10   184.51       85                0.69%    $10             $97.1            $15730.43            
2023-05-04   161.2        2023-06-27   250.21       97                55.22%   $10             $8623.97         $24354.4             
2023-07-03   279.82       2023-07-24   269.06       87                -3.85%   $10             $-946.12         $23408.28            
2023-08-25   238.59       2023-09-22   244.88       98                2.64%    $10             $606.42          $24014.7             
2023-10-04   261.16       2023-10-17   254.85       91                -2.42%   $10             $-584.21         $23430.49            
2023-11-06   219.27       2023-12-06   239.37       106               9.17%    $10             $2120.6          $25551.09            
2023-12-11   239.74       2023-12-12   237.01       106               -1.14%   $10             $-299.38         $25251.71            
2023-12-13   239.29       2024-01-03   238.45       105               -0.35%   $10             $-98.2           $25153.51            
2024-02-12   188.13       2024-03-05   180.74       133               -3.93%   $10             $-992.87         $24160.64            
2024-03-22   170.83       2024-04-03   168.38       141               -1.43%   $10             $-355.45         $23805.19            
2024-04-12   171.05       2024-04-16   157.11       139               -8.15%   $10             $-1947.66        $21857.53            
2024-04-26   168.29       2024-05-09   171.97       129               2.19%    $10             $464.72          $22322.25            
2024-05-20   174.95       2024-05-29   176.19       127               0.71%    $10             $147.48          $22469.73            
2024-06-17   187.44       2024-07-17   248.5        119               32.58%   $10             $7256.14         $29725.87            
2024-08-15   214.14       2024-08-28   205.75       138               -3.92%   $10             $-1167.82        $28558.05            
2024-09-05   230.17       2024-10-04   250.08       124               8.65%    $10             $2458.84         $31016.89            

Initial Capital: $10000
Final Capital: $31016.89
Total Profit: 210.17%

三、观点总结

为什么这种算法能用且好用?我的总结如下:

3.1 适应性

  • 根据每只股票的独特性调整参数;
  • 战略随市场情况而变化;
  • 没有放之四海而皆准的假设。

3.2 客观性

  • 消除人为偏见;
  • 数据驱动决策;
  • 系统方法。

3.3 效率

  • 即时测试数百种组合;
  • 优化以获得最大收益;
  • 考虑交易成本。

3.4 实用性

我提供了实际的代码示例和 Google Colab 笔记本,方便您加深理解和立刻实践。

地址如下:https://colab.research.google.com/drive/1zBZdXYf7tOpJFDL8w0PoNldlTzbuo9my?usp=sharing

最后我想对您说:Gone are the days of using standard moving average periods for every stock. Let the data tell you what works best…

感谢您阅读到最后,希望本文能给您带来新的收获。祝您投资顺利!如果对文中的内容有任何疑问,请给我留言,必复。


本文内容仅仅是技术探讨和学习,并不构成任何投资建议。

Published inAI&Invest专栏

Be First to Comment

    发表回复