优化与移动窗格检验
Here is a simple scenario that shows how to implement brute force optimization + walk-forward backtest on out-of-sample data interval. This scenario works with SMA crossover strategy.
以下代码演示了如何完成穷举优化和基于样本外数据间隔进行移动窗格检验回测。以下场景使用了SMA交叉策略。
- public class MyScenario : Scenario
- {
- public override void Run()
- {
- // set in-sample data interval
- Solution.StartDate = new DateTime(1995, 1, 1);
- Solution.StopDate = new DateTime(2001, 1, 1);
- // get reference to strategy project
- Project project = Solution.Projects[0];
- // define variables
- int best_length1 = 0;
- int best_length2 = 0;
- double best_objective = 0;
- // brute force optimization loop
- for (int length1 = 3;length1 <= 7;length1++)
- for (int length2 = 3;length2 <= 7;length2++)
- if (length2 > length1)
- {
- // set new parameters
- project.Parameters["Length1"].Value = length1;
- project.Parameters["Length2"].Value = length2;
- // print parameters
- Console.Write("Length1 = " + length1 + " Length2 = " + length2);
- // start backtest
- Start();
- // calculate objective function
- double objective = Solution.Portfolio.GetValue();
- // print objective
- Console.WriteLine(" Objective = " + objective);
- // check best objective
- if (objective > best_objective)
- {
- best_objective = objective;
- best_length1 = length1;
- best_length2 = length2;
- }
- }
- // print best parameters
- Console.WriteLine("BEST PARAMETERS");
- Console.WriteLine();
- Console.WriteLine("SMA1 Length = " + best_length1);
- Console.WriteLine("SMA2 Length = " + best_length2);
- Console.WriteLine("Objective = " + best_objective);
- // run strategy with the best parameters on out-of-sample data interval
- project.Parameters["Length1"].Value = best_length1;
- project.Parameters["Length2"].Value = best_length2;
- Solution.StartDate = new DateTime(2001, 1, 1);
- Solution.StopDate = new DateTime(2005, 1, 1);
- Start();
- }
- }