public void Start(StrategyContext context) { this.context = context; String strategyName = context.BacktestParam.StrategyName; if (strategyName == null || strategyName == "") { logger.Warn("无效的策略名称,请确保回测参数中定义了策略名称"); return; } meta = context.GetStrategyMeta(strategyName); if (meta == null) { logger.Warn("无效的策略名称:" + strategyName); return; } PropertyDescriptorCollection pdc = meta.Parameters; if (pdc == null || pdc.Count <= 0) { logger.Warn("策略" + strategyName + "没有定义所需的参数类型"); return; } //生成策略参数 List <Properties> currentParamPopulations = createParamPopulation(pdc, initPopulation); int sn = 100; currentParamPopulations.ForEach(x => computeFitness(sn++, x)); int iteratorCount = 1; double maxProfilt = 0; while (iteratorCount <= pMaxIteratorCount || maxProfilt < pMaxProfile) { logger.Info("第" + iteratorCount.ToString() + "代种群生成..."); //按照适应度排序 Comparison <Properties> comparsion = (x, y) => { double x1 = x.Get <double>("fitness"); double y1 = y.Get <double>("fitness"); if (x1 < y1) { return(1); } else if (x1 > y1) { return(-1); } else { return(0); } }; currentParamPopulations.Sort(comparsion); double[] P = currentParamPopulations.ConvertAll(x => x.Get <double>("fitness")).ToArray(); maxProfilt = currentParamPopulations[0].Get <double>("fitness"); logger.Info("本次迭代得到的最大收益:" + maxProfilt.ToString("F3")); List <Properties> nextParamPopulations = new List <Properties>(); //下一代 for (int i = 0; i < currentParamPopulations.Count; i += 2) //逐步生成新一代群体,每次生成两个 { int select1 = roulette(P); int select2 = select1; while (select1 == select2) { select2 = roulette(P); } Properties c1 = currentParamPopulations[select1].Clone(); Properties c2 = currentParamPopulations[select2].Clone(); double t1 = new Random().NextDouble(); if (t1 < pCrossOver) { doCross(c1, c2); } t1 = new Random().NextDouble(); if (t1 < pMutation) { doMutate(c1); doMutate(c2); } computeFitness(sn++, c1); computeFitness(sn++, c2); nextParamPopulations.Add(c1); nextParamPopulations.Add(c2); } currentParamPopulations = nextParamPopulations; iteratorCount += 1; } Properties maxParam = currentParamPopulations[0]; maxProfilt = maxParam.Get <double>("fitness"); logger.Info("得到的最优收益:" + maxProfilt.ToString("F3")); logger.Info("得到的最优参数组合:"); logger.Info(pdc.ToString(maxParam)); }