vectorbt 案例 --策略参数优化

vectorbt 案例 --策略参数优化 vectorBT的一个突出特点是能够轻松优化策略参数。例如我们优化交叉策略中的移动平均长度以找到表现最佳的参数。import vectorbt as vbt import pandas as pd import numpy as np # Download historical data data vbt.YFData.download(AAPL, start2020-01-01, end2021-12-31).get(Close) # Define ranges for fast and slow moving averages fast_ma_range range(10, 100, 10) # Short moving averages from 10 to 90 in steps of 10 slow_ma_range range(100, 300, 20) # Long moving averages from 100 to 280 in steps of 20 # Store the results results {} # Loop over all combinations of fast and slow MA values for fast_ma in fast_ma_range: for slow_ma in slow_ma_range: if fast_ma slow_ma: continue # Fast MA should always be less than slow MA to make sense # Calculate moving averages fast_ma_values data.rolling(windowfast_ma).mean() slow_ma_values data.rolling(windowslow_ma).mean() # Define entry and exit signals entries fast_ma_values slow_ma_values exits fast_ma_values slow_ma_values # Run backtesting portfolio vbt.Portfolio.from_signals(data, entries, exits) # Store total return for each combination of fast_ma and slow_ma results[(fast_ma, slow_ma)] portfolio.total_return() # Convert results to a DataFrame for better visualization results_df pd.DataFrame.from_dict(results, orientindex, columns[Total Return]) # Find the best combination best_params results_df[Total Return].idxmax() best_return results_df[Total Return].max() print(fBest MA combination: Fast MA {best_params[0]}, Slow MA {best_params[1]}) print(fBest Total Return: {best_return})我在这里获得了以下信息最佳MA组合快速MA 50慢MA 100 最佳总回报1.1302656073899642解释在这里我们测试各种短期和长期移动平均线的组合并对每种数据进行回溯测试。vectorBT并行运行所有回测效率极高。最后我们找到基于总回报的最佳参数。