quantproject-developers Mailing List for QuantProject (Page 76)
Brought to you by:
glauco_1
You can subscribe to this list here.
| 2003 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(7) |
Nov
(103) |
Dec
(67) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2004 |
Jan
(52) |
Feb
(9) |
Mar
(69) |
Apr
(53) |
May
(80) |
Jun
(23) |
Jul
(24) |
Aug
(112) |
Sep
(9) |
Oct
|
Nov
(58) |
Dec
(93) |
| 2005 |
Jan
(90) |
Feb
(93) |
Mar
(61) |
Apr
(56) |
May
(37) |
Jun
(61) |
Jul
(55) |
Aug
(68) |
Sep
(25) |
Oct
(46) |
Nov
(41) |
Dec
(37) |
| 2006 |
Jan
(33) |
Feb
(7) |
Mar
(19) |
Apr
(27) |
May
(73) |
Jun
(49) |
Jul
(83) |
Aug
(66) |
Sep
(45) |
Oct
(16) |
Nov
(15) |
Dec
(7) |
| 2007 |
Jan
(14) |
Feb
(33) |
Mar
|
Apr
(21) |
May
|
Jun
(34) |
Jul
(18) |
Aug
(100) |
Sep
(39) |
Oct
(55) |
Nov
(12) |
Dec
(2) |
| 2008 |
Jan
(120) |
Feb
(133) |
Mar
(129) |
Apr
(104) |
May
(42) |
Jun
(2) |
Jul
(52) |
Aug
(99) |
Sep
(134) |
Oct
|
Nov
(137) |
Dec
(48) |
| 2009 |
Jan
(48) |
Feb
(55) |
Mar
(61) |
Apr
(3) |
May
(2) |
Jun
(1) |
Jul
|
Aug
(51) |
Sep
|
Oct
(7) |
Nov
|
Dec
|
| 2010 |
Jan
(7) |
Feb
(1) |
Mar
(145) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(8) |
Dec
|
| 2011 |
Jan
(78) |
Feb
(1) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(88) |
Sep
(6) |
Oct
(1) |
Nov
|
Dec
|
| 2012 |
Jan
|
Feb
(1) |
Mar
|
Apr
(6) |
May
(5) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
| 2013 |
Jan
|
Feb
|
Mar
|
Apr
(1) |
May
(2) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(2) |
| 2014 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv6633/BiasedPVO Added Files: RunBiasedPVO.cs EndOfDayTimerHandlerBiasedPVO.cs Log Message: Added variations of Portfolio Value Oscillator strategy (some of these files have to be tested yet and will be re-written as soon as possible ...): - WeightedPVO: basic PVO (with thresholds); - weigthedBalancedPVO: the weighted PVO with 50% of portfolio invested in short positions and the remaining half in long ones; - biasedPVO: it is not simply chosen the genome with the highest fitness (as in the PVO base), but it is chosen the genome (from a given set of genomes with a good fitness) that has the highest degree of deviation from a threshold; - biasedPVO No Thresholds: as the biased, but the signal is just the highest gain or loss; - biasedOTC_PVONoThresholds: as the previous one, but with these differences: new positions are opened at market open, choosing the genome that opens with the highest gain or loss with respect to the last close All positions are closed at market close (at the moment ...tests are in progress ...) --- NEW FILE: RunBiasedPVO.cs --- /* QuantProject - Quantitative Finance Library RunBiasedPVO.cs Copyright (C) 2006 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using System.Data; using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Scripting; using QuantProject.Business.Strategies; using QuantProject.Business.Testing; using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; using QuantProject.ADT.FileManaging; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.BiasedPVO { /// <summary> /// Script that implements the PVO strategy, /// with this difference: /// when it is time to open new positions, /// it is not simply chosen the genome with the highest fitness /// (as in the PVO base), but it is chosen the genome (from a /// given set of genomes with a good fitness) that /// has the highest degree of deviation from a threshold /// </summary> [Serializable] public class RunBiasedPVO : RunPVO { private int numOfDifferentGenomesToEvaluateOutOfSample; private double minimumAcceptableGain; public RunBiasedPVO(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, int numOfDifferentGenomesToEvaluateOutOfSample, int numDaysForOscillatingPeriod, int minLevelForOversoldThreshold, int maxLevelForOversoldThreshold, int minLevelForOverboughtThreshold, int maxLevelForOverboughtThreshold, int divisorForThresholdComputation, bool symmetricalThresholds, bool overboughtMoreThanOversoldForFixedPortfolio, int numDaysBetweenEachOptimization, PortfolioType inSamplePortfolioType, double maxAcceptableCloseToCloseDrawdown, double minimumAcceptableGain, double maxRunningHours): base(tickerGroupID, maxNumOfEligibleTickersForOptimization, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, startDate, endDate, numDaysForOscillatingPeriod, minLevelForOversoldThreshold, maxLevelForOversoldThreshold, minLevelForOverboughtThreshold, maxLevelForOverboughtThreshold, divisorForThresholdComputation, symmetricalThresholds, overboughtMoreThanOversoldForFixedPortfolio, numDaysBetweenEachOptimization, inSamplePortfolioType, maxAcceptableCloseToCloseDrawdown, maxRunningHours) { this.numOfDifferentGenomesToEvaluateOutOfSample = numOfDifferentGenomesToEvaluateOutOfSample; this.minimumAcceptableGain = minimumAcceptableGain; this.ScriptName = "PVO_Biased_NoWeightsPriceSel"; } #region auxiliary overriden methods for Run protected override void run_initializeEndOfDayTimerHandler() { this.endOfDayTimerHandler = new EndOfDayTimerHandlerBiasedPVO(this.tickerGroupID, this.numberOfEligibleTickers, this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, this.account, this.generationNumberForGeneticOptimizer, this.populationSizeForGeneticOptimizer, this.benchmark, this.numOfDifferentGenomesToEvaluateOutOfSample, this.numDaysForOscillatingPeriod, this.minLevelForOversoldThreshold, this.maxLevelForOversoldThreshold, this.minLevelForOverboughtThreshold, this.maxLevelForOverboughtThreshold, this.divisorForThresholdComputation, this.symmetricalThresholds, this.overboughtMoreThanOversoldForFixedPortfolio, this.numDaysBetweenEachOptimization, this.portfolioType, this.maxAcceptableCloseToCloseDrawdown, this.minimumAcceptableGain); } public override void SaveScriptResults() { string fileName = DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + this.scriptName + "GenOS_" + this.numOfDifferentGenomesToEvaluateOutOfSample + "_OsDays_" + numDaysForOscillatingPeriod + "_From_" + this.tickerGroupID + "_" + this.numberOfEligibleTickers + "_DaysForOpt" + this.numDaysForOptimizationPeriod + "Tick" + this.numberOfTickersToBeChosen + "GenN°" + this.generationNumberForGeneticOptimizer + "PopSize" + this.populationSizeForGeneticOptimizer + Convert.ToString(this.portfolioType); string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.ScriptName + "\\"; string dirNameWhereToSaveTransactions = System.Configuration.ConfigurationSettings.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; string dirNameWhereToSaveBestGenomes = System.Configuration.ConfigurationSettings.AppSettings["GenomesArchive"] + "\\" + this.ScriptName + "\\"; this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); OptimizationOutput optimizationOutput = new OptimizationOutput(); foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) optimizationOutput.Add(genomeRepresentation); ObjectArchiver.Archive(optimizationOutput, dirNameWhereToSaveBestGenomes + fileName + ".bgn"); //default report with numIntervalDays = 1 AccountReport accountReport = this.account.CreateReport(fileName,1, this.endOfDayTimer.GetCurrentTime(), this.benchmark, new HistoricalAdjustedQuoteProvider()); this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ObjectArchiver.Archive(accountReport, dirNameWhereToSaveReports + fileName + ".qPr"); this.endOfDayTimer.Stop(); } #endregion } } --- NEW FILE: EndOfDayTimerHandlerBiasedPVO.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerBiasedPVO.cs Copyright (C) 2006 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.ADT; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.Strategies; using QuantProject.Data; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Data.DataTables; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.WeightedPVO.WeightedBalancedPVO; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.BiasedPVO { /// <summary> /// Implements MarketOpenEventHandler and MarketCloseEventHandler /// These handlers contain the core strategy for the Biased Portfolio Value /// Oscillator /// </summary> [Serializable] public class EndOfDayTimerHandlerBiasedPVO : EndOfDayTimerHandlerPVO { protected int numOfDifferentGenomesToEvaluateOutOfSample; protected double minimumAcceptableGain; protected int currentGenomeIndex = 0; protected double currentTickersGainOrLoss = 0.0; protected Hashtable genomesCollector; protected bool takeProfitConditionReached; new protected string[,] chosenTickers; new protected double[,] chosenTickersPortfolioWeights; new protected double[] currentOversoldThreshold; new protected double[] currentOverboughtThreshold; public EndOfDayTimerHandlerBiasedPVO(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, int numOfDifferentGenomesToEvaluateOutOfSample, int numDaysForOscillatingPeriod, int minLevelForOversoldThreshold, int maxLevelForOversoldThreshold, int minLevelForOverboughtThreshold, int maxLevelForOverboughtThreshold, int divisorForThresholdComputation, bool symmetricalThresholds, bool overboughtMoreThanOversoldForFixedPortfolio, int numDaysBetweenEachOptimization, PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown, double minimumAcceptableGain): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, numDaysForOscillatingPeriod, minLevelForOversoldThreshold, maxLevelForOversoldThreshold, minLevelForOverboughtThreshold, maxLevelForOverboughtThreshold, divisorForThresholdComputation, symmetricalThresholds, overboughtMoreThanOversoldForFixedPortfolio, numDaysBetweenEachOptimization, portfolioType, maxAcceptableCloseToCloseDrawdown) { this.numOfDifferentGenomesToEvaluateOutOfSample = numOfDifferentGenomesToEvaluateOutOfSample; this.minimumAcceptableGain = minimumAcceptableGain; this.chosenTickers = new string[numOfDifferentGenomesToEvaluateOutOfSample, numberOfTickersToBeChosen]; this.chosenTickersPortfolioWeights = new double[numOfDifferentGenomesToEvaluateOutOfSample, numberOfTickersToBeChosen]; this.currentOversoldThreshold = new double[numOfDifferentGenomesToEvaluateOutOfSample]; this.currentOverboughtThreshold = new double[numOfDifferentGenomesToEvaluateOutOfSample]; this.genomesCollector = new Hashtable(); } #region MarketCloseEventHandler protected virtual double getCurrentChosenTickersGainOrLoss(IndexBasedEndOfDayTimer timer, int indexForChosenTickers) { double returnValue = 999.0; try { DateTime initialDate = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForOscillatingPeriod + 2]["quDate"]; //so to replicate exactly in sample scheme, where only numOscillatingDay - 1 returns //are computed DateTime finalDate = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; string[] tickers = new string[this.numberOfTickersToBeChosen]; double[] tickerWeights = new double[this.numberOfTickersToBeChosen]; for(int i = 0; i < this.numberOfTickersToBeChosen; i++) { tickers[i] = this.chosenTickers[indexForChosenTickers,i]; tickerWeights[i] = this.chosenTickersPortfolioWeights[indexForChosenTickers,i]; } returnValue = SignedTicker.GetCloseToClosePortfolioReturn( tickers, tickerWeights, initialDate,finalDate) + 1.0; } catch(MissingQuotesException ex) { ex = ex; } return returnValue; } private void marketCloseEventHandler_reverseOrClose(IndexBasedEndOfDayTimer timer) { double currentChosenTickersGainOrLoss = this.getCurrentChosenTickersGainOrLoss(timer, this.currentGenomeIndex); this.marketCloseEventHandler_updateStopLossAndTakeProfitConditions(); if(currentChosenTickersGainOrLoss != 999.0) //currentChosenTickersValue has been properly computed { if(currentChosenTickersGainOrLoss >= 1.0 + currentOverboughtThreshold[this.currentGenomeIndex] && this.portfolioHasBeenOversold) //open positions derive from an overSold period but now //the overbought threshold has been reached { this.reversePositions(); this.portfolioHasBeenOversold = false; this.portfolioHasBeenOverbought = true; } else if(currentChosenTickersGainOrLoss <= 1.0 - currentOversoldThreshold[this.currentGenomeIndex] && this.portfolioHasBeenOverbought) //open positions derive from an overBought period but now //the overSold threshold has been reached { this.reversePositions(); this.portfolioHasBeenOversold = true; this.portfolioHasBeenOverbought = false; } else if(this.stopLossConditionReached || this.takeProfitConditionReached || this.numDaysElapsedSinceLastOptimization + 1 == this.numDaysBetweenEachOptimization ) //reversal conditions have not been reached but //stop loss or take profit conditions yes //or after the close it is necessary to run //another optimization { base.closePositions(); this.orders.Clear(); this.portfolioHasBeenOverbought = false; this.portfolioHasBeenOversold = false; } } } private void marketCloseEventHandler_closeIfItIsTimeToClose() { this.marketCloseEventHandler_updateStopLossAndTakeProfitConditions(); if(this.stopLossConditionReached || this.takeProfitConditionReached || this.numDaysElapsedSinceLastOptimization + 1 == this.numDaysBetweenEachOptimization ) //reversal conditions have not been reached but //stop loss or take profit conditions yes //or after the close it is necessary to run //another optimization { base.closePositions(); this.orders.Clear(); this.portfolioHasBeenOverbought = false; this.portfolioHasBeenOversold = false; } } //sets currentGenomeIndex with the genome's index that crosses an overbought/oversold threshold with the //highest degree and sets currentTickersGainOrLoss accordingly private void marketCloseEventHandler_openPositions_chooseBestGenome(IndexBasedEndOfDayTimer timer) { //default index is the first //genome (with the highest plain fitness), if no other genome //has crossed the threshold with a higher degree than the first genome double currentMaxDegreeOfCrossingThreshold = 0.0; double currentDegreeOfCrossingThreshold = 0.0; for(int i = 0; i < this.numOfDifferentGenomesToEvaluateOutOfSample; i++) { double currentChosenTickersGainOrLoss = this.getCurrentChosenTickersGainOrLoss(timer, i); if(currentChosenTickersGainOrLoss != 999.0) //currentChosenTickersValue has been properly computed { //computing degree of crossing threshold if(currentChosenTickersGainOrLoss >= 1.0 + this.currentOverboughtThreshold[i]) { currentDegreeOfCrossingThreshold = (currentChosenTickersGainOrLoss - 1.0 - this.currentOverboughtThreshold[i])/ (1 + this.currentOverboughtThreshold[i]); } else if (currentChosenTickersGainOrLoss <= 1.0 - this.currentOversoldThreshold[i]) { currentDegreeOfCrossingThreshold = (1.0 - this.currentOversoldThreshold[i] - currentChosenTickersGainOrLoss)/ (1.0 - this.currentOversoldThreshold[i]); } if(currentDegreeOfCrossingThreshold > currentMaxDegreeOfCrossingThreshold) { currentMaxDegreeOfCrossingThreshold = currentDegreeOfCrossingThreshold; this.currentGenomeIndex = i; this.currentTickersGainOrLoss = currentChosenTickersGainOrLoss; } } } } private void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) { this.currentTickersGainOrLoss = 999.0; // this.marketCloseEventHandler_openPositions_chooseBestGenome(timer); if(this.currentTickersGainOrLoss != 999.0) //currentChosenTickersValue has been properly computed { string[] tickers = new string[this.numberOfTickersToBeChosen]; for(int i = 0; i < this.numberOfTickersToBeChosen; i++) tickers[i] = this.chosenTickers[this.currentGenomeIndex,i]; if(this.currentTickersGainOrLoss >= 1.0 + currentOverboughtThreshold[this.currentGenomeIndex] && this.portfolioType == PortfolioType.ShortAndLong) { SignedTicker.ChangeSignOfEachTicker(tickers); base.openPositions(tickers); this.portfolioHasBeenOverbought = true; this.portfolioHasBeenOversold = false; } else if (this.currentTickersGainOrLoss <= 1.0 - currentOversoldThreshold[this.currentGenomeIndex]) { base.openPositions(tickers); this.portfolioHasBeenOverbought = false; this.portfolioHasBeenOversold = true; } this.currentAccountValue = this.account.GetMarketValue(); } } private void marketCloseEventHandler_updateStopLossAndTakeProfitConditions() { this.previousAccountValue = this.currentAccountValue; this.currentAccountValue = this.account.GetMarketValue(); double portfolioGainOrLoss = (this.currentAccountValue - this.previousAccountValue) /this.previousAccountValue; if( portfolioGainOrLoss < -this.maxAcceptableCloseToCloseDrawdown ) { this.stopLossConditionReached = true; this.takeProfitConditionReached = false; } else if (portfolioGainOrLoss >= this.minimumAcceptableGain) { this.stopLossConditionReached = false; this.takeProfitConditionReached = true; } else { this.stopLossConditionReached = false; this.takeProfitConditionReached = false; } } public override void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { if(this.account.Portfolio.Count > 0) //this.marketCloseEventHandler_reverseOrClose((IndexBasedEndOfDayTimer)sender); this.marketCloseEventHandler_closeIfItIsTimeToClose(); else if ( this.account.Portfolio.Count == 0 && this.chosenTickers[0,0] != null ) //portfolio is empty and optimization has been already launched this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); } #endregion #region OneHourAfterMarketCloseEventHandler private void setTickers_updateTickersWeightsAndThresholdsAndAddGenomesForLog(GeneticOptimizer GO, int eligibleTickersForGO) { int addedGenomes = 0; int counter = 0; Genome currentGenome = null; this.genomesCollector.Clear(); while(addedGenomes < this.numOfDifferentGenomesToEvaluateOutOfSample && counter < GO.PopulationSize) { currentGenome = (Genome)GO.CurrentGeneration[GO.PopulationSize - 1 - counter]; if(counter == 0 || !this.genomesCollector.ContainsKey(currentGenome.Fitness) ) //it is the first genome to be added or no genome with the current // fitness has been added to the hashtable yet { for(int i = 0; i<this.numberOfTickersToBeChosen; i++) { this.chosenTickers[addedGenomes,i] = ((GenomeMeaningPVO)currentGenome.Meaning).Tickers[i]; this.chosenTickersPortfolioWeights[addedGenomes,i] = ((GenomeMeaningPVO)currentGenome.Meaning).TickersPortfolioWeights[i]; } this.currentOversoldThreshold[addedGenomes] = ((GenomeMeaningPVO)currentGenome.Meaning).OversoldThreshold; this.currentOverboughtThreshold[addedGenomes] = ((GenomeMeaningPVO)currentGenome.Meaning).OverboughtThreshold; this.genomesCollector.Add(currentGenome.Fitness, null); this.addPVOGenomeToBestGenomes(currentGenome,((GenomeManagerForEfficientPortfolio)this.iGenomeManager).FirstQuoteDate, ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate, eligibleTickersForGO, this.numDaysForOscillatingPeriod, this.portfolioType, GO.GenerationCounter, this.currentOversoldThreshold[addedGenomes], this.currentOverboughtThreshold[addedGenomes]); addedGenomes ++ ; } counter ++ ; } } protected override void setTickers(DateTime currentDate, bool setGenomeCounter) { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); this.iGenomeManager = new GenomeManagerPVO(setOfTickersToBeOptimized, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, this.numDaysForOscillatingPeriod, this.minLevelForOversoldThreshold, this.maxLevelForOversoldThreshold, this.minLevelForOverboughtThreshold, this.maxLevelForOverboughtThreshold, this.divisorForThresholdComputation, this.symmetricalThresholds, this.overboughtMoreThanOversoldForFixedPortfolio, this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer, this.seedForRandomGenerator); if(setGenomeCounter) this.genomeCounter = new GenomeCounter(GO); GO.MutationRate = 0.4; GO.Run(false); this.setTickers_updateTickersWeightsAndThresholdsAndAddGenomesForLog(GO, setOfTickersToBeOptimized.Rows.Count); } #endregion } } |
|
From: Marco M. <mi...@us...> - 2007-02-27 22:52:45
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/WeightedPVO In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv6633/WeightedPVO Added Files: RunWeightedPVO.cs GenomeManagerWeightedPVO.cs EndOfDayTimerHandlerWeightedPVO.cs Log Message: Added variations of Portfolio Value Oscillator strategy (some of these files have to be tested yet and will be re-written as soon as possible ...): - WeightedPVO: basic PVO (with thresholds); - weigthedBalancedPVO: the weighted PVO with 50% of portfolio invested in short positions and the remaining half in long ones; - biasedPVO: it is not simply chosen the genome with the highest fitness (as in the PVO base), but it is chosen the genome (from a given set of genomes with a good fitness) that has the highest degree of deviation from a threshold; - biasedPVO No Thresholds: as the biased, but the signal is just the highest gain or loss; - biasedOTC_PVONoThresholds: as the previous one, but with these differences: new positions are opened at market open, choosing the genome that opens with the highest gain or loss with respect to the last close All positions are closed at market close (at the moment ...tests are in progress ...) --- NEW FILE: EndOfDayTimerHandlerWeightedPVO.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerWeightedPVO.cs Copyright (C) 2006 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.ADT; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.Strategies; using QuantProject.Data; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Data.DataTables; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.WeightedPVO { /// <summary> /// Implements MarketOpenEventHandler and MarketCloseEventHandler /// These handlers contain the core strategy for the Portfolio Value /// Oscillator using weights for tickers /// </summary> [Serializable] public class EndOfDayTimerHandlerWeightedPVO : EndOfDayTimerHandlerPVO { public EndOfDayTimerHandlerWeightedPVO(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, int numDaysForOscillatingPeriod, int minLevelForOversoldThreshold, int maxLevelForOversoldThreshold, int minLevelForOverboughtThreshold, int maxLevelForOverboughtThreshold, int divisorForThresholdComputation, bool symmetricalThresholds, bool overboughtMoreThanOversoldForFixedPortfolio, int numDaysBetweenEachOptimization, PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, numDaysForOscillatingPeriod, minLevelForOversoldThreshold, maxLevelForOversoldThreshold, minLevelForOverboughtThreshold, maxLevelForOverboughtThreshold, divisorForThresholdComputation, symmetricalThresholds, overboughtMoreThanOversoldForFixedPortfolio, numDaysBetweenEachOptimization, portfolioType, maxAcceptableCloseToCloseDrawdown) { } protected override DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); int numOfTickersInGroupAtCurrentDate = tickersFromGroup.Rows.Count; SelectorByAverageRawOpenPrice byPrice = new SelectorByAverageRawOpenPrice(tickersFromGroup,false,currentDate.AddDays(-30), currentDate, numOfTickersInGroupAtCurrentDate, 20,500, 0.0001,100); SelectorByLiquidity mostLiquidSelector = new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfEligibleTickers); // SelectorByCloseToCloseCorrelationToBenchmark byCorrelationToBenchmark = // new SelectorByCloseToCloseCorrelationToBenchmark(mostLiquidSelector.GetTableOfSelectedTickers(), // "^GSPC",false, // currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, // this.numberOfEligibleTickers/2,false); // SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromLastSelection = new SelectorByQuotationAtEachMarketDay(mostLiquidSelector.GetTableOfSelectedTickers(), false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfEligibleTickers, this.benchmark); return quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(); } protected override void setTickers(DateTime currentDate, bool setGenomeCounter) { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); if(setOfTickersToBeOptimized.Rows.Count > this.chosenTickers.Length*2) //the optimization process is meaningful only if the initial set of tickers is //larger than the number of tickers to be chosen { this.iGenomeManager = new GenomeManagerWeightedPVO(setOfTickersToBeOptimized, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, this.numDaysForOscillatingPeriod, this.minLevelForOversoldThreshold, this.maxLevelForOversoldThreshold, this.minLevelForOverboughtThreshold, this.maxLevelForOverboughtThreshold, this.divisorForThresholdComputation, this.symmetricalThresholds, this.overboughtMoreThanOversoldForFixedPortfolio, this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer, this.seedForRandomGenerator); if(setGenomeCounter) this.genomeCounter = new GenomeCounter(GO); GO.MutationRate = 0.2; GO.Run(false); this.chosenTickers = ((GenomeMeaningPVO)GO.BestGenome.Meaning).Tickers; this.chosenTickersPortfolioWeights = ((GenomeMeaningPVO)GO.BestGenome.Meaning).TickersPortfolioWeights; this.currentOversoldThreshold = ((GenomeMeaningPVO)GO.BestGenome.Meaning).OversoldThreshold; this.currentOverboughtThreshold = ((GenomeMeaningPVO)GO.BestGenome.Meaning).OverboughtThreshold; this.addPVOGenomeToBestGenomes(GO.BestGenome,((GenomeManagerForEfficientPortfolio)this.iGenomeManager).FirstQuoteDate, ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate, setOfTickersToBeOptimized.Rows.Count, this.numDaysForOscillatingPeriod, this.portfolioType, GO.GenerationCounter, this.currentOversoldThreshold, this.currentOverboughtThreshold); } //else it will be buyed again the previous optimized portfolio //that's it the actual chosenTickers member } } } --- NEW FILE: RunWeightedPVO.cs --- /* QuantProject - Quantitative Finance Library RunWeightedPVO.cs Copyright (C) 2006 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using System.Data; using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Scripting; using QuantProject.Business.Strategies; using QuantProject.Business.Testing; using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; using QuantProject.ADT.FileManaging; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.WeightedPVO { /// <summary> /// Script that implements an oscillating strategy using weights for tickers, /// based on the classical technical indicator /// RelativeStrengthIndex - RSI /// </summary> [Serializable] public class RunWeightedPVO : RunEfficientPortfolio { protected int minLevelForOversoldThreshold; protected int maxLevelForOversoldThreshold; protected int minLevelForOverboughtThreshold; protected int maxLevelForOverboughtThreshold; protected int divisorForThresholdComputation; //to be used by the optimizer protected int numDaysBetweenEachOptimization; protected double maxAcceptableCloseToCloseDrawdown; protected int numDaysForOscillatingPeriod; protected bool symmetricalThresholds = false; protected bool overboughtMoreThanOversoldForFixedPortfolio = false; public RunWeightedPVO(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, int numDaysForOscillatingPeriod, int minLevelForOversoldThreshold, int maxLevelForOversoldThreshold, int minLevelForOverboughtThreshold, int maxLevelForOverboughtThreshold, int divisorForThresholdComputation, bool symmetricalThresholds, bool overboughtMoreThanOversoldForFixedPortfolio, int numDaysBetweenEachOptimization, PortfolioType inSamplePortfolioType, double maxAcceptableCloseToCloseDrawdown, double maxRunningHours): base(tickerGroupID, maxNumOfEligibleTickersForOptimization, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, startDate, endDate, 0.0, inSamplePortfolioType, maxRunningHours) { this.ScriptName = "PVO_SR_WithWeights_PriceSel"; this.minLevelForOversoldThreshold = minLevelForOversoldThreshold; this.maxLevelForOversoldThreshold = maxLevelForOversoldThreshold; this.minLevelForOverboughtThreshold = minLevelForOverboughtThreshold; this.maxLevelForOverboughtThreshold = maxLevelForOverboughtThreshold; this.divisorForThresholdComputation = divisorForThresholdComputation; this.symmetricalThresholds = symmetricalThresholds; this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } #region auxiliary overriden methods for Run protected override void run_initializeEndOfDayTimerHandler() { this.endOfDayTimerHandler = new EndOfDayTimerHandlerWeightedPVO(this.tickerGroupID, this.numberOfEligibleTickers, this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, this.account, this.generationNumberForGeneticOptimizer, this.populationSizeForGeneticOptimizer, this.benchmark, this.numDaysForOscillatingPeriod, this.minLevelForOversoldThreshold, this.maxLevelForOversoldThreshold, this.minLevelForOverboughtThreshold, this.maxLevelForOverboughtThreshold, this.divisorForThresholdComputation, this.symmetricalThresholds, this.overboughtMoreThanOversoldForFixedPortfolio, this.numDaysBetweenEachOptimization, this.portfolioType, this.maxAcceptableCloseToCloseDrawdown); } protected override void run_initializeHistoricalQuoteProvider() { this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); } protected override void run_addEventHandlers() { this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.endOfDayTimerHandler.MarketCloseEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); this.endOfDayTimer.OneHourAfterMarketClose += new OneHourAfterMarketCloseEventHandler( this.endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler); } public override void SaveScriptResults() { string fileName = DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + this.scriptName + "OsDays_" + numDaysForOscillatingPeriod + "_From_" + this.tickerGroupID + "_" + this.numberOfEligibleTickers + "_DaysForOpt" + this.numDaysForOptimizationPeriod + "Tick" + this.numberOfTickersToBeChosen + "GenN°" + this.generationNumberForGeneticOptimizer + "PopSize" + this.populationSizeForGeneticOptimizer + Convert.ToString(this.portfolioType); string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.ScriptName + "\\"; string dirNameWhereToSaveTransactions = System.Configuration.ConfigurationSettings.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; string dirNameWhereToSaveBestGenomes = System.Configuration.ConfigurationSettings.AppSettings["GenomesArchive"] + "\\" + this.ScriptName + "\\"; this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); OptimizationOutput optimizationOutput = new OptimizationOutput(); foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) optimizationOutput.Add(genomeRepresentation); ObjectArchiver.Archive(optimizationOutput, dirNameWhereToSaveBestGenomes + fileName + ".bgn"); //default report with numIntervalDays = 1 AccountReport accountReport = this.account.CreateReport(fileName,1, this.endOfDayTimer.GetCurrentTime(), this.benchmark, new HistoricalAdjustedQuoteProvider()); this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ObjectArchiver.Archive(accountReport, dirNameWhereToSaveReports + fileName + ".qPr"); this.endOfDayTimer.Stop(); } #endregion } } --- NEW FILE: GenomeManagerWeightedPVO.cs --- /* QuantProject - Quantitative Finance Library GenomeManagerWeightedPVO.cs Copyright (C) 2003 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.ADT; using QuantProject.ADT.Statistics; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Data; using QuantProject.Data.DataTables; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.WeightedPVO { /// <summary> /// Implements what needed to use the Genetic Optimizer /// for finding the portfolio that best suites /// the Portfolio Value Oscillator strategy /// </summary> [Serializable] public class GenomeManagerWeightedPVO : GenomeManagerForEfficientPortfolio { protected int minLevelForOversoldThreshold; protected int maxLevelForOversoldThreshold; protected int minLevelForOverboughtThreshold; protected int maxLevelForOverboughtThreshold; protected int divisorForThresholdComputation; protected bool symmetricalThresholds = false; protected bool overboughtMoreThanOversoldForFixedPortfolio = false; protected int numOfGenesDedicatedToThresholds; protected double currentOversoldThreshold = 0.0; protected double currentOverboughtThreshold = 0.0; protected int numDaysForOscillatingPeriod; protected int[] genePositionsPointingToTickers; protected double[] portfolioValues;//the values for each unit, invested //at the beginning of the optimization period, //throughout the period itself protected bool genePositionPointsToATicker(int genePosition) { return ( genePosition >= this.numOfGenesDedicatedToThresholds && ( (this.numOfGenesDedicatedToThresholds == 1 && genePosition%2 == 0) || (this.numOfGenesDedicatedToThresholds == 2 && genePosition%2 != 0) ) ); } protected bool genePositionPointsToAWeight(int genePosition) { return ( genePosition >= this.numOfGenesDedicatedToThresholds && ( (this.numOfGenesDedicatedToThresholds == 1 && genePosition%2 != 0) || (this.numOfGenesDedicatedToThresholds == 2 && genePosition%2 == 0) ) ); } protected bool genePositionPointsToATreshold(int genePosition) { return ( genePosition < this.numOfGenesDedicatedToThresholds ); } public int[] GetGenePositionsPointingToTickers(Genome genome) { int i = 0; for(int genePosition = this.numOfGenesDedicatedToThresholds; genePosition < genome.Size; genePosition++) { if(this.genePositionPointsToATicker(genePosition) ) { this.genePositionsPointingToTickers[i] = genePosition; i++; } } return this.genePositionsPointingToTickers; } private void genomeManagerWeightedPVO_checkParametersForThresholdsComputation() { if(this.maxLevelForOverboughtThreshold < this.minLevelForOverboughtThreshold || this.maxLevelForOversoldThreshold < this.minLevelForOversoldThreshold || this.divisorForThresholdComputation < this.maxLevelForOverboughtThreshold || this.divisorForThresholdComputation < this.maxLevelForOversoldThreshold || (this.symmetricalThresholds && (this.minLevelForOversoldThreshold != this.minLevelForOverboughtThreshold || this.maxLevelForOversoldThreshold != this.maxLevelForOverboughtThreshold) ) || (this.overboughtMoreThanOversoldForFixedPortfolio && (this.minLevelForOverboughtThreshold > Convert.ToInt32(Convert.ToDouble(this.minLevelForOversoldThreshold)* Convert.ToDouble(this.divisorForThresholdComputation) / (Convert.ToDouble(this.divisorForThresholdComputation) - Convert.ToDouble(this.minLevelForOversoldThreshold) ) ) || this.maxLevelForOverboughtThreshold < Convert.ToInt32(Convert.ToDouble(this.maxLevelForOversoldThreshold) * Convert.ToDouble(this.divisorForThresholdComputation) / (Convert.ToDouble(this.divisorForThresholdComputation) - Convert.ToDouble(this.maxLevelForOversoldThreshold) ) ) ) ) ) throw new Exception("Bad parameters for thresholds computation!"); } public GenomeManagerWeightedPVO(DataTable setOfInitialTickers, DateTime firstQuoteDate, DateTime lastQuoteDate, int numberOfTickersInPortfolio, int numDaysForOscillatingPeriod, int minLevelForOversoldThreshold, int maxLevelForOversoldThreshold, int minLevelForOverboughtThreshold, int maxLevelForOverboughtThreshold, int divisorForThresholdComputation, bool symmetricalThresholds, bool overboughtMoreThanOversoldForFixedPortfolio, PortfolioType inSamplePortfolioType) : base(setOfInitialTickers, firstQuoteDate, lastQuoteDate, numberOfTickersInPortfolio, 0.0, inSamplePortfolioType) { this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; this.divisorForThresholdComputation = divisorForThresholdComputation; this.minLevelForOversoldThreshold = minLevelForOversoldThreshold; this.maxLevelForOversoldThreshold = maxLevelForOversoldThreshold; this.minLevelForOverboughtThreshold = minLevelForOverboughtThreshold; this.maxLevelForOverboughtThreshold = maxLevelForOverboughtThreshold; this.symmetricalThresholds = symmetricalThresholds; this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; if(this.symmetricalThresholds)//value for thresholds must be unique numOfGenesDedicatedToThresholds = 1; else numOfGenesDedicatedToThresholds = 2; this.genePositionsPointingToTickers = new int[(this.GenomeSize - this.numOfGenesDedicatedToThresholds)/2]; this.genomeManagerWeightedPVO_checkParametersForThresholdsComputation(); this.retrieveData(); } public override int GenomeSize { get{return this.genomeSize * 2 + this.numOfGenesDedicatedToThresholds;} } #region Get Min and Max Value private int getMinValueForGenes_getMinValueForTicker() { int returnValue; switch (this.portfolioType) { case PortfolioType.OnlyLong : returnValue = 0; break; default://For ShortAndLong or OnlyShort portfolios returnValue = - this.originalNumOfTickers; break; } return returnValue; } public override int GetMinValueForGenes(int genePosition) { int returnValue; switch (genePosition) { case 0 ://gene for oversold threshold returnValue = this.minLevelForOversoldThreshold; break; case 1 ://gene for overbought threshold if thresholds are asymmetrical if(this.numOfGenesDedicatedToThresholds == 2) returnValue = this.minLevelForOverboughtThreshold; else returnValue = this.getMinValueForGenes_getMinValueForTicker(); break; default://gene for ticker or weight returnValue = this.getMinValueForGenes_getMinValueForTicker(); break; } return returnValue; } private int getMaxValueForGenes_getMaxValueForTicker() { int returnValue; switch (this.portfolioType) { case PortfolioType.OnlyShort : returnValue = - 1; break; default ://For ShortAndLong or OnlyLong portfolios returnValue = this.originalNumOfTickers - 1; break; } return returnValue; } public override int GetMaxValueForGenes(int genePosition) { int returnValue; switch (genePosition) { case 0 ://gene for oversold threshold returnValue = this.maxLevelForOversoldThreshold; break; case 1 ://gene for overbought threshold when thresholds are asymmetrical if(this.numOfGenesDedicatedToThresholds == 2) returnValue = this.maxLevelForOverboughtThreshold; else returnValue = this.getMaxValueForGenes_getMaxValueForTicker(); break; default://gene for ticker returnValue = this.getMaxValueForGenes_getMaxValueForTicker(); break; } return returnValue; } #endregion protected override float[] getArrayOfRatesOfReturn(string ticker) { float[] returnValue = null; Quotes tickerQuotes = new Quotes(ticker, this.firstQuoteDate, this.lastQuoteDate); tickerQuotes.RecalculateCloseToCloseRatios(); returnValue = QuantProject.ADT.ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuotes, Quotes.AdjustedCloseToCloseRatio); for(int i = 0; i<returnValue.Length; i++) returnValue[i] = returnValue[i] - 1.0f; this.numberOfExaminedReturns = returnValue.Length; return returnValue; } //starting from this.numDaysForOscillatingPeriod day, //it computes for each day ahead the value of the //portfolio opened numDaysForOscillatingPeriod days ago private double[] getPortfolioMovingValues() { double[] returnValue = new double[this.portfolioRatesOfReturn.Length]; double[] valuesInOscillatingPeriod = new double[this.numDaysForOscillatingPeriod]; valuesInOscillatingPeriod[0] = 1.0; for(int i = this.numDaysForOscillatingPeriod; i<returnValue.Length; i++) { for(int j = 1; j < this.numDaysForOscillatingPeriod; j++) valuesInOscillatingPeriod[j] = valuesInOscillatingPeriod[j - 1] + valuesInOscillatingPeriod[j - 1] * this.portfolioRatesOfReturn[i-this.numDaysForOscillatingPeriod+j]; returnValue[i-1] = valuesInOscillatingPeriod[this.numDaysForOscillatingPeriod -1]; } return returnValue; } private void getFitnessValue_setCurrentThresholds(Genome genome) { this.currentOversoldThreshold = Convert.ToDouble(genome.Genes()[0])/ Convert.ToDouble(this.divisorForThresholdComputation); if(this.symmetricalThresholds) this.currentOverboughtThreshold = this.currentOversoldThreshold; else this.currentOverboughtThreshold = Convert.ToDouble(genome.Genes()[1])/ Convert.ToDouble(this.divisorForThresholdComputation); } private int getFitnessValue_getDaysOnTheMarket(double[] equityLine) { int returnValue = 0; foreach(double equityReturn in equityLine) if(equityReturn != 0.0) //the applied strategy gets positions on the market returnValue++; return returnValue; } //fitness is a sharpe-ratio based indicator for the equity line resulting //from applying the strategy public override double GetFitnessValue(Genome genome) { double returnValue = -1.0; this.portfolioRatesOfReturn = this.getPortfolioRatesOfReturn(genome.Genes()); this.portfolioValues = this.getPortfolioMovingValues(); this.getFitnessValue_setCurrentThresholds(genome); double[] equityLine = this.getFitnessValue_getEquityLineRates(); double fitness = Double.NaN; if(this.getFitnessValue_getDaysOnTheMarket(equityLine) > equityLine.Length / 2) //if the genome represents a portfolio that stays on the market //at least half of the theoretical days fitness = AdvancedFunctions.GetSharpeRatio(equityLine); if(!double.IsNaN(fitness) && !double.IsInfinity(fitness)) returnValue = fitness; return returnValue; } private double[] getFitnessValue_getEquityLineRates() { double[] returnValue = new double[this.PortfolioRatesOfReturn.Length]; double coefficient = 0.0; for(int i = 0; i<this.PortfolioRatesOfReturn.Length - 1;i++) { if(this.portfolioValues[i] >= 1.0 + this.currentOverboughtThreshold) //portfolio is overbought coefficient = -1.0; else if(this.portfolioValues[i] <= 1.0 - this.currentOversoldThreshold && this.portfolioValues[i] > 0.0) //portfolio is oversold coefficient = 1.0; returnValue[i + 1] = coefficient * this.PortfolioRatesOfReturn[i + 1]; } return returnValue; } protected override double getTickerWeight(int[] genes, int tickerPositionInGenes) { int numOfGenesDedicatedToWeights = this.genePositionsPointingToTickers.Length; double minimumWeight = (1.0 - ConstantsProvider.AmountOfVariableWeightToBeAssignedToTickers)/ numOfGenesDedicatedToWeights; double totalOfValuesForWeightsInGenes = 0.0; for(int j = this.numOfGenesDedicatedToThresholds; j<genes.Length; j++) { if(this.numOfGenesDedicatedToThresholds == 2 && j%2==0) //ticker weight is contained in genes at even position when //thresholds are asymmetrical totalOfValuesForWeightsInGenes += Math.Abs(genes[j]) + 1.0; //0 has to be avoided ! else if (this.numOfGenesDedicatedToThresholds == 1 && j%2!=0) //ticker weight is contained in genes at odd position when //thresholds are symmetrical totalOfValuesForWeightsInGenes += Math.Abs(genes[j]) + 1.0; //0 has to be avoided ! } double freeWeight = (Math.Abs(genes[tickerPositionInGenes-1]) + 1.0)/totalOfValuesForWeightsInGenes; return minimumWeight + freeWeight * (1.0 - minimumWeight * numOfGenesDedicatedToWeights); } protected override double[] getPortfolioRatesOfReturn(int[] genes) { double[] returnValue = new double[this.numberOfExaminedReturns]; for(int i = 0; i<returnValue.Length; i++) { for(int genePosition=this.numOfGenesDedicatedToThresholds; genePosition<genes.Length; genePosition++)//the first numOfGenesDedicatedToThresholds are for thresholds { if( this.genePositionPointsToATicker(genePosition) ) returnValue[i] += this.getPortfolioRatesOfReturn_getRateOfTickerToBeAddedToTheArray(genes,genePosition,i); } } return returnValue; } public override object Decode(Genome genome) { string[] arrayOfTickers = new string[this.genePositionsPointingToTickers.Length]; double[] arrayOfTickerWeights = new double[this.genePositionsPointingToTickers.Length]; int geneForTicker; GenomeMeaningPVO meaning; int i = 0;//for the arrayOfTickers and the arrayOfWeights for(int genePosition = this.numOfGenesDedicatedToThresholds; genePosition < genome.Genes().Length; genePosition++) { if( this.genePositionPointsToATicker(genePosition) ) { geneForTicker = (int)genome.Genes().GetValue(genePosition); arrayOfTickers[i] = this.decode_getTickerCodeForLongOrShortTrade(geneForTicker); arrayOfTickerWeights[i] = this.getTickerWeight(genome.Genes(), genePosition); i++; } }// end of for cycle inside genome if(this.symmetricalThresholds) meaning = new GenomeMeaningPVO( arrayOfTickers, arrayOfTickerWeights, Convert.ToDouble(genome.Genes()[0])/Convert.ToDouble(this.divisorForThresholdComputation), Convert.ToDouble(genome.Genes()[0])/Convert.ToDouble(this.divisorForThresholdComputation), this.numDaysForOscillatingPeriod); else meaning = new GenomeMeaningPVO( arrayOfTickers, arrayOfTickerWeights, Convert.ToDouble(genome.Genes()[0])/Convert.ToDouble(this.divisorForThresholdComputation), Convert.ToDouble(genome.Genes()[1])/Convert.ToDouble(this.divisorForThresholdComputation), this.numDaysForOscillatingPeriod); return meaning; } public override Genome[] GetChilds(Genome parent1, Genome parent2) { //in this simple implementation //child have the tickers of one parent //and the thresholds of the other Genome[] childs = new Genome[2]; childs[0] = parent1.Clone(); childs[1] = parent2.Clone(); //exchange of genes coding thresholds if(this.symmetricalThresholds)//unique value for thresholds { childs[0].SetGeneValue(parent2.GetGeneValue(0),0); childs[1].SetGeneValue(parent1.GetGeneValue(0),0); } else//two different values for thresholds { childs[0].SetGeneValue(parent2.GetGeneValue(0),0); childs[1].SetGeneValue(parent1.GetGeneValue(0),0); childs[0].SetGeneValue(parent2.GetGeneValue(1),1); childs[1].SetGeneValue(parent1.GetGeneValue(1),1); } return childs; } private int getNewGeneValue_getGeneValue(Genome genome, int genePosition) { int returnValue; int minValueForGene = genome.GetMinValueForGenes(genePosition); int maxValueForGene = genome.GetMaxValueForGenes(genePosition); if(this.numOfGenesDedicatedToThresholds == 2 && this.overboughtMoreThanOversoldForFixedPortfolio && genePosition == 1) //genePosition points to overbought threshold, //dipendent from the oversold one such that the portfolio tends to be fix returnValue = Convert.ToInt32( Convert.ToDouble( genome.GetGeneValue(0) ) * Convert.ToDouble(this.divisorForThresholdComputation) / ( Convert.ToDouble(this.divisorForThresholdComputation) - Convert.ToDouble( genome.GetGeneValue(0) ) ) ); else returnValue = GenomeManagement.RandomGenerator.Next(minValueForGene, maxValueForGene + 1); return returnValue; } public override int GetNewGeneValue(Genome genome, int genePosition) { // in this implementation only new gene values pointing to tickers // must be different from the others already stored int returnValue = this.getNewGeneValue_getGeneValue(genome,genePosition); while( this.genePositionPointsToATicker(genePosition) && GenomeManipulator.IsTickerContainedInGenome(returnValue, genome, this.GetGenePositionsPointingToTickers(genome) ) ) //while in the given position has to be stored //a new gene pointing to a ticker and //the proposed returnValue points to a ticker //already stored in the given genome, at the given genePositionsPointingToTickers returnValue = this.getNewGeneValue_getGeneValue(genome,genePosition); return returnValue; } //OLD VERSION // public override void Mutate(Genome genome, double mutationRate) // { // // in this implementation only one gene is mutated // int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); // int minValueForGene = genome.GetMinValueForGenes(genePositionToBeMutated); // int maxValueForGene = genome.GetMaxValueForGenes(genePositionToBeMutated); // int newValueForGene = GenomeManagement.RandomGenerator.Next(minValueForGene, // maxValueForGene +1); // // if( this.genePositionPointsToATicker(genePositionToBeMutated) ) // { // while(GenomeManipulator.IsTickerContainedInGenome(newValueForGene, // genome, this.genePositionsPointingToTickers) ) // //while the proposed newValueForGene points to a ticker // //already stored in the given genome, at the given genePositionsPointingToTickers // newValueForGene = GenomeManagement.RandomGenerator.Next(minValueForGene, // maxValueForGene +1); // GenomeManagement.MutateOneGene(genome, mutationRate, // genePositionToBeMutated, newValueForGene); // } // else if( this.genePositionPointsToAWeight(genePositionToBeMutated) ) // { // double partOfGeneToSubtractOrAdd = 0.25; // int geneValue = Math.Abs(genome.GetGeneValue(genePositionToBeMutated)); // int subtractOrAdd = GenomeManagement.RandomGenerator.Next(2); // if(subtractOrAdd == 1)//subtract a part of the gene value from the gene value itself // newValueForGene = geneValue - Convert.ToInt32(partOfGeneToSubtractOrAdd*geneValue); // else // newValueForGene = Math.Min(genome.GetMaxValueForGenes(genePositionToBeMutated), // geneValue + Convert.ToInt32(partOfGeneToSubtractOrAdd*geneValue)); // // GenomeManagement.MutateOneGene(genome, mutationRate, // genePositionToBeMutated, newValueForGene); // } // else if ( this.numOfGenesDedicatedToThresholds == 2 && // this.overboughtMoreThanOversoldForFixedPortfolio && // genePositionToBeMutated == 0 ) // // genePositionToBeMutated points to the oversold threshold and the // //the overbought one is determined // { // if (GenomeManagement.RandomGenerator.Next(0,101) < (int)(mutationRate*100)) // { // genome.SetGeneValue(newValueForGene, genePositionToBeMutated); // genome.SetGeneValue(Convert.ToInt32(Convert.ToDouble(newValueForGene) * Convert.ToDouble(this.divisorForThresholdComputation) / // (Convert.ToDouble(this.divisorForThresholdComputation) - Convert.ToDouble(newValueForGene))), 1); // } // } // else if ( this.numOfGenesDedicatedToThresholds == 2 && // this.overboughtMoreThanOversoldForFixedPortfolio && // genePositionToBeMutated == 1 ) // // genePositionToBeMutated points to the overbought threshold and, as the // //the overbought one is determined, the oversold one depends from the overbought // { // if (GenomeManagement.RandomGenerator.Next(0,101) < (int)(mutationRate*100)) // { // genome.SetGeneValue(newValueForGene, genePositionToBeMutated); // genome.SetGeneValue(Convert.ToInt32(Convert.ToDouble(newValueForGene) * Convert.ToDouble(this.divisorForThresholdComputation) / // (Convert.ToDouble(this.divisorForThresholdComputation) + Convert.ToDouble(newValueForGene))), 0); // } // } // } private int mutate_MutateOnlyOneWeight_getNewWeight(Genome genome, int genePositionToBeMutated) { int returnValue; double partOfGeneToSubtractOrAdd = 0.25; int geneValue = Math.Abs( genome.GetGeneValue(genePositionToBeMutated) ); int subtractOrAdd = GenomeManagement.RandomGenerator.Next(2); if(subtractOrAdd == 1)//subtract a part of the gene value from the gene value itself returnValue = geneValue - Convert.ToInt32(partOfGeneToSubtractOrAdd*geneValue); else returnValue = Math.Min(genome.GetMaxValueForGenes(genePositionToBeMutated), geneValue + Convert.ToInt32(partOfGeneToSubtractOrAdd*geneValue)); return returnValue; } private void mutate_MutateOnlyOneWeight(Genome genome) { int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); while( this.genePositionPointsToAWeight(genePositionToBeMutated) == false ) //while the proposed genePositionToBeMutated doesn't point to a weight genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); int newValueForGene = this.mutate_MutateOnlyOneWeight_getNewWeight(genome, genePositionToBeMutated); GenomeManagement.MutateOneGene(genome, genePositionToBeMutated, newValueForGene); } private void mutate_MutateAllGenes(Genome genome) { for(int genePositionToBeMutated = 0; genePositionToBeMutated < genome.Genes().Length; genePositionToBeMutated ++) { int newValueForGene = this.GetNewGeneValue(genome, genePositionToBeMutated); genome.SetGeneValue(newValueForGene, genePositionToBeMutated); } } public override void Mutate(Genome genome) { int mutateOnlyOneWeight = GenomeManagement.RandomGenerator.Next(2); if(mutateOnlyOneWeight == 1) this.mutate_MutateOnlyOneWeight(genome); else//mutate all genome's genes this.mutate_MutateAllGenes(genome); } } } |
|
From: Marco M. <mi...@us...> - 2007-02-27 22:34:55
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/WeightedPVO/WeightedBalancedPVO In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv29277/WeightedBalancedPVO Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/WeightedPVO/WeightedBalancedPVO added to the repository |
|
From: Marco M. <mi...@us...> - 2007-02-27 22:34:44
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/WeightedPVO In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv29228/WeightedPVO Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/WeightedPVO added to the repository |
|
From: Marco M. <mi...@us...> - 2007-02-27 22:34:30
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/BiasedPVONoThresholds In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv29161/BiasedPVONoThresholds Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/BiasedPVONoThresholds added to the repository |
|
From: Marco M. <mi...@us...> - 2007-02-27 22:34:18
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/BiasedOTC_PVONoThresholds In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv29115/BiasedOTC_PVONoThresholds Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/BiasedOTC_PVONoThresholds added to the repository |
|
From: Marco M. <mi...@us...> - 2007-02-27 22:25:32
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv24666/BiasedPVO Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO added to the repository |
|
From: Marco M. <mi...@us...> - 2007-02-27 22:19:55
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv21691 Modified Files: RunPVO.cs EndOfDayTimerHandlerPVO.cs Log Message: Updated PVO script (minor changes) Index: RunPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/RunPVO.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RunPVO.cs 19 Jan 2007 16:47:55 -0000 1.3 --- RunPVO.cs 27 Feb 2007 22:19:51 -0000 1.4 *************** *** 129,133 **** protected override void run_addEventHandlers() { ! this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( --- 129,136 ---- protected override void run_addEventHandlers() { ! this.endOfDayTimer.MarketOpen += ! new MarketOpenEventHandler( ! this.endOfDayTimerHandler.MarketOpenEventHandler); ! this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( Index: EndOfDayTimerHandlerPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/EndOfDayTimerHandlerPVO.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** EndOfDayTimerHandlerPVO.cs 3 Jan 2007 23:02:58 -0000 1.3 --- EndOfDayTimerHandlerPVO.cs 27 Feb 2007 22:19:51 -0000 1.4 *************** *** 214,227 **** else if (currentChosenTickersValue <= 1.0 - currentOversoldThreshold) { ! try ! { ! base.openPositions(this.chosenTickers); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = true; ! } ! catch(Exception ex) ! { ! ex = ex; ! } } } --- 214,220 ---- else if (currentChosenTickersValue <= 1.0 - currentOversoldThreshold) { ! base.openPositions(this.chosenTickers); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = true; } } |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:34:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv17095 Added Files: WFLagNewChosenPositionsEventArgs.cs Log Message: EventArgs for new chosen positions for the walk forward Lag Strategy --- NEW FILE: WFLagNewChosenPositionsEventArgs.cs --- /* QuantProject - Quantitative Finance Library WFLagNewChosenPositionsEventArgs.cs Copyright (C) 2003 Glauco Siliprandi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using QuantProject.Scripts.WalkForwardTesting.WalkForwardLag.WFLagDebugger; namespace QuantProject.Scripts.WalkForwardTesting.WalkForwardLag { /// <summary> /// EventArgs for new chosen positions for the walk forward /// Lag Strategy /// </summary> public class WFLagNewChosenPositionsEventArgs : EventArgs { private WFLagChosenPositions wFLagChosenPositions; public WFLagChosenPositions WFLagChosenPositions { get { return this.wFLagChosenPositions; } } public WFLagNewChosenPositionsEventArgs( WFLagChosenPositions wFLagChosenPositions ) { this.wFLagChosenPositions = wFLagChosenPositions; } } } |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:34:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv13334/b7_Scripts/WalkForwardTesting/WalkForwardLag Modified Files: RunWalkForwardLag.cs Log Message: Better OO approach now: an IWFLagWeightedPositionChooser interface has been introduced. Now it will be easier to move both from a strategy to another, and from an optimization technique to another Index: RunWalkForwardLag.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/RunWalkForwardLag.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** RunWalkForwardLag.cs 3 Nov 2006 16:41:26 -0000 1.7 --- RunWalkForwardLag.cs 18 Feb 2007 01:04:59 -0000 1.8 *************** *** 45,50 **** private string tickerGroupID; private int numberEligibleTickers; ! private int numberOfDrivingPositions; ! private int numberOfPortfolioPositions; private int numberDaysForInSampleOptimization; private int numDaysBetweenEachOptimization; --- 45,52 ---- private string tickerGroupID; private int numberEligibleTickers; ! private IWFLagWeightedPositionsChooser ! wFLagWeightedPositionsChooser; ! // private int numberOfDrivingPositions; ! // private int numberOfPortfolioPositions; private int numberDaysForInSampleOptimization; private int numDaysBetweenEachOptimization; *************** *** 69,94 **** public RunWalkForwardLag( string tickerGroupID , ! int numberEligibleTickers , ! int numberOfDrivingPositions , ! int numberOfPortfolioPositions , ! int numberDaysForInSampleOptimization , int numDaysBetweenEachOptimization , - int generationNumberForGeneticOptimizer , - int populationSizeForGeneticOptimizer , - string benchmark , DateTime firstDateTime , DateTime lastDateTime , - IEquityEvaluator equityEvaluator , double maxRunningHours ) { this.tickerGroupID = tickerGroupID; ! this.numberEligibleTickers = numberEligibleTickers; ! this.numberOfDrivingPositions = numberOfDrivingPositions; ! this.numberOfPortfolioPositions = numberOfPortfolioPositions; ! this.numberDaysForInSampleOptimization = numberDaysForInSampleOptimization; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; ! this.benchmark = benchmark; this.firstDateTime = firstDateTime; this.lastDateTime = lastDateTime; --- 71,91 ---- public RunWalkForwardLag( string tickerGroupID , ! int maxNumberOfEligibleTickers , ! IWFLagWeightedPositionsChooser wFLagWeightedPositionsChooser , int numDaysBetweenEachOptimization , DateTime firstDateTime , DateTime lastDateTime , double maxRunningHours ) { this.tickerGroupID = tickerGroupID; ! this.numberEligibleTickers = maxNumberOfEligibleTickers; ! this.wFLagWeightedPositionsChooser = wFLagWeightedPositionsChooser; ! this.numberDaysForInSampleOptimization = ! wFLagWeightedPositionsChooser.NumberDaysForInSampleOptimization; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; ! this.benchmark = ! this.wFLagWeightedPositionsChooser.Benchmark; this.firstDateTime = firstDateTime; this.lastDateTime = lastDateTime; *************** *** 130,141 **** this.benchmark , this.numberEligibleTickers , ! this.numberOfPortfolioPositions , ! this.numberOfDrivingPositions , ! this.numberDaysForInSampleOptimization , this.numDaysBetweenEachOptimization , ! this.account , ! this.generationNumberForGeneticOptimizer , ! this.populationSizeForGeneticOptimizer , ! this.equityEvaluator ); } public static void WriteToTextLog( string message ) --- 127,133 ---- this.benchmark , this.numberEligibleTickers , ! this.wFLagWeightedPositionsChooser , this.numDaysBetweenEachOptimization , ! this.account ); } public static void WriteToTextLog( string message ) *************** *** 212,217 **** this.getLongStringForDateTime( DateTime.Now ) + "_" + "Group_" + this.tickerGroupID + "_" + ! "DrvPstns_" + this.numberOfDrivingPositions + "_" + ! "PrtfPstns_" + this.numberOfPortfolioPositions + "_" + "GenNum_" + this.generationNumberForGeneticOptimizer + "_" + "PopSize_" + this.populationSizeForGeneticOptimizer + "_" + --- 204,211 ---- this.getLongStringForDateTime( DateTime.Now ) + "_" + "Group_" + this.tickerGroupID + "_" + ! "DrvPstns_" + ! this.wFLagWeightedPositionsChooser.NumberOfDrivingPositions + "_" + ! "PrtfPstns_" + ! this.wFLagWeightedPositionsChooser.NumberOfPortfolioPositions + "_" + "GenNum_" + this.generationNumberForGeneticOptimizer + "_" + "PopSize_" + this.populationSizeForGeneticOptimizer + "_" + *************** *** 286,296 **** } #endregion ! private void newChosenTickersEventHandler( object sender , ! WFLagNewChosenTickersEventArgs eventArgs ) { ! WFLagChosenPositions wFLagChosenPositions = ! new WFLagChosenPositions( eventArgs.WFLagChosenTickers , ! this.endOfDayTimer.GetCurrentTime().DateTime ); ! this.wFLagLog.Add( wFLagChosenPositions ); } private void run_addEventHandlers() --- 280,290 ---- } #endregion ! private void newChosenPositionsEventHandler( object sender , ! WFLagNewChosenPositionsEventArgs eventArgs ) { ! // WFLagChosenPositions wFLagChosenPositions = ! // new WFLagChosenPositions( eventArgs.WFLagChosenTickers , ! // this.endOfDayTimer.GetCurrentTime().DateTime ); ! this.wFLagLog.Add( eventArgs.WFLagChosenPositions ); } private void run_addEventHandlers() *************** *** 307,313 **** new MarketCloseEventHandler( this.marketCloseEventHandler ); ! this.endOfDayTimerHandler.NewChosenTickers += ! new NewChosenTickersEventHandler( ! this.newChosenTickersEventHandler ); } public override void Run() --- 301,307 ---- new MarketCloseEventHandler( this.marketCloseEventHandler ); ! this.endOfDayTimerHandler.NewChosenPositions += ! new NewChosenPositionsEventHandler( ! this.newChosenPositionsEventHandler ); } public override void Run() |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:34:38
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv12505/b7_Scripts/WalkForwardTesting/WalkForwardLag Modified Files: WFLagEligibleTickers.cs Log Message: An exception is rised if a constructor's parameter contains an unexpected value. This approach should be extended to all constructors and methods... Index: WFLagEligibleTickers.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagEligibleTickers.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** WFLagEligibleTickers.cs 8 Oct 2006 16:06:32 -0000 1.4 --- WFLagEligibleTickers.cs 18 Feb 2007 01:02:24 -0000 1.5 *************** *** 58,61 **** --- 58,64 ---- IEndOfDayTimer endOfDayTimer ) { + this.checkParametersForWFLagEligibleTickers( tickerGroupID , benchmark , + numberEligibleTickersToBeChosen , numberDaysForPerformanceCalculation , + endOfDayTimer ); this.tickerGroupID = tickerGroupID; this.benchmark = benchmark; *************** *** 65,68 **** --- 68,82 ---- this.eligibleTickers = new DataTable(); } + private void checkParametersForWFLagEligibleTickers( + string tickerGroupID , + string benchmark , + int numberEligibleTickersToBeChosen , + int numberDaysForPerformanceCalculation , + IEndOfDayTimer endOfDayTimer ) + { + if ( numberDaysForPerformanceCalculation <= 0 ) + throw new Exception( "numberDaysForPerformanceCalculation value is " + + numberDaysForPerformanceCalculation + "\nIt must be > 0" ); + } #region setTickers private DataTable setTickers_build_getSelectedTickers() |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:34:38
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv11381/b7_Scripts/WalkForwardTesting/WalkForwardLag Modified Files: WFLagEndOfDayTimerHandler.cs Log Message: Better OO approach now: an IWFLagWeightedPositionChooser interface has been introduced. Now it will be easier to move both from a strategy to another, and from an optimization technique to another Index: WFLagEndOfDayTimerHandler.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagEndOfDayTimerHandler.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** WFLagEndOfDayTimerHandler.cs 3 Nov 2006 16:38:47 -0000 1.6 --- WFLagEndOfDayTimerHandler.cs 18 Feb 2007 01:00:11 -0000 1.7 *************** *** 36,41 **** namespace QuantProject.Scripts.WalkForwardTesting.WalkForwardLag { ! public delegate void NewChosenTickersEventHandler( ! Object sender , WFLagNewChosenTickersEventArgs eventArgs ); /// <summary> --- 36,41 ---- namespace QuantProject.Scripts.WalkForwardTesting.WalkForwardLag { ! public delegate void NewChosenPositionsEventHandler( ! Object sender , WFLagNewChosenPositionsEventArgs eventArgs ); /// <summary> *************** *** 49,63 **** private string benchmark; private int numberEligibleTickers; ! private int numberOfPositionsToBeChosen; ! private int numberOfDrivingPositions; ! private int inSampleWindowDays; private int outOfSampleWindowDays; private Account account; ! private int generationNumberForGeneticOptimizer; ! private int populationSizeForGeneticOptimizer; ! private IEquityEvaluator equityEvaluator; private WFLagEligibleTickers eligibleTickers; ! private WFLagChosenTickers chosenTickers; private HistoricalAdjustedQuoteProvider historicalAdjustedQuoteProvider; --- 49,59 ---- private string benchmark; private int numberEligibleTickers; ! IWFLagWeightedPositionsChooser wFLagWeightedPositionsChooser; private int outOfSampleWindowDays; private Account account; ! // private IEquityEvaluator equityEvaluator; private WFLagEligibleTickers eligibleTickers; ! // private WFLagChosenTickers chosenTickers; private HistoricalAdjustedQuoteProvider historicalAdjustedQuoteProvider; *************** *** 67,71 **** public event InSampleNewProgressEventHandler InSampleNewProgress; ! public event NewChosenTickersEventHandler NewChosenTickers; public WFLagEndOfDayTimerHandler( --- 63,67 ---- public event InSampleNewProgressEventHandler InSampleNewProgress; ! public event NewChosenPositionsEventHandler NewChosenPositions; public WFLagEndOfDayTimerHandler( *************** *** 73,97 **** string benchmark , int numberEligibleTickers , ! int numberOfPositionsToBeChosen , ! int numberOfDrivingPositions , ! int inSampleWindowDays , int outOfSampleWindowDays , ! Account account , ! int generationNumberForGeneticOptimizer , ! int populationSizeForGeneticOptimizer , ! IEquityEvaluator equityEvaluator ) { this.tickerGroupID = tickerGroupID; this.benchmark = benchmark; this.numberEligibleTickers = numberEligibleTickers; ! this.numberOfPositionsToBeChosen = numberOfPositionsToBeChosen; ! this.numberOfDrivingPositions = numberOfDrivingPositions; ! this.inSampleWindowDays = inSampleWindowDays; this.outOfSampleWindowDays = outOfSampleWindowDays; this.account = account; - this.generationNumberForGeneticOptimizer = - generationNumberForGeneticOptimizer; - this.populationSizeForGeneticOptimizer = - populationSizeForGeneticOptimizer; - this.equityEvaluator = equityEvaluator; this.eligibleTickers = new WFLagEligibleTickers( --- 69,82 ---- string benchmark , int numberEligibleTickers , ! IWFLagWeightedPositionsChooser wFLagWeightedPositionsChooser , ! int outOfSampleWindowDays , ! Account account ) { this.tickerGroupID = tickerGroupID; this.benchmark = benchmark; this.numberEligibleTickers = numberEligibleTickers; ! this.wFLagWeightedPositionsChooser = wFLagWeightedPositionsChooser; this.outOfSampleWindowDays = outOfSampleWindowDays; this.account = account; this.eligibleTickers = new WFLagEligibleTickers( *************** *** 99,114 **** this.benchmark , this.numberEligibleTickers , ! this.inSampleWindowDays , this.account.EndOfDayTimer ); ! this.chosenTickers = new WFLagChosenTickers( ! this.numberOfDrivingPositions , ! this.numberOfPositionsToBeChosen , ! this.inSampleWindowDays , ! this.account.EndOfDayTimer , ! this.generationNumberForGeneticOptimizer , ! this.populationSizeForGeneticOptimizer , ! this.equityEvaluator ); ! this.chosenTickers.NewProgress += new NewProgressEventHandler( this.bestPerformingNewProgress ); --- 84,93 ---- this.benchmark , this.numberEligibleTickers , ! this.wFLagWeightedPositionsChooser.NumberDaysForInSampleOptimization , this.account.EndOfDayTimer ); ! // this.chosenTickers = new WFLagChosenTickers( ! // this.wFLagWeightedPositionsChooser ); ! this.wFLagWeightedPositionsChooser.NewProgress += new NewProgressEventHandler( this.bestPerformingNewProgress ); *************** *** 177,181 **** double totalReturn = 0; foreach ( WeightedPosition weightedPosition in ! this.chosenTickers.DrivingWeightedPositions.Values ) totalReturn += this.getTodayReturn( weightedPosition ); return totalReturn < 0; --- 156,160 ---- double totalReturn = 0; foreach ( WeightedPosition weightedPosition in ! this.wFLagWeightedPositionsChooser.WFLagChosenPositions.DrivingWeightedPositions.Values ) totalReturn += this.getTodayReturn( weightedPosition ); return totalReturn < 0; *************** *** 207,211 **** weightedPosition , isToReverse ); double maxPositionValue = this.account.GetMarketValue() / ! this.numberOfPositionsToBeChosen; long sharesToBeTraded = this.getMaxBuyableShares( weightedPosition ); this.account.AddOrder( new Order( orderType , --- 186,190 ---- weightedPosition , isToReverse ); double maxPositionValue = this.account.GetMarketValue() / ! this.wFLagWeightedPositionsChooser.NumberOfPortfolioPositions; long sharesToBeTraded = this.getMaxBuyableShares( weightedPosition ); this.account.AddOrder( new Order( orderType , *************** *** 216,220 **** bool isToReverse = this.isToReverse(); foreach ( WeightedPosition weightedPosition ! in this.chosenTickers.PortfolioWeightedPositions.Values ) this.fiveMinutesBeforeMarketCloseEventHandler_openPosition( weightedPosition , isToReverse ); --- 195,199 ---- bool isToReverse = this.isToReverse(); foreach ( WeightedPosition weightedPosition ! in this.wFLagWeightedPositionsChooser.WFLagChosenPositions.PortfolioWeightedPositions.Values ) this.fiveMinutesBeforeMarketCloseEventHandler_openPosition( weightedPosition , isToReverse ); *************** *** 223,227 **** private void fiveMinutesBeforeMarketCloseEventHandler_openPositions() { ! if ( this.chosenTickers.DrivingWeightedPositions != null ) this.fiveMinutesBeforeMarketCloseEventHandler_openPositions_actually(); } --- 202,206 ---- private void fiveMinutesBeforeMarketCloseEventHandler_openPositions() { ! if ( this.wFLagWeightedPositionsChooser.WFLagChosenPositions != null ) this.fiveMinutesBeforeMarketCloseEventHandler_openPositions_actually(); } *************** *** 230,234 **** double totalReturn = 0; foreach ( WeightedPosition weightedPosition in ! this.chosenTickers.DrivingWeightedPositions.Values ) totalReturn += this.getTodayReturn( weightedPosition ); return totalReturn; --- 209,213 ---- double totalReturn = 0; foreach ( WeightedPosition weightedPosition in ! this.wFLagWeightedPositionsChooser.WFLagChosenPositions.DrivingWeightedPositions.Values ) totalReturn += this.getTodayReturn( weightedPosition ); return totalReturn; *************** *** 317,321 **** private WeightedPosition getWeightedPosition( string ticker ) { ! return this.chosenTickers.PortfolioWeightedPositions.GetWeightedPosition( ticker ); } --- 296,300 ---- private WeightedPosition getWeightedPosition( string ticker ) { ! return this.wFLagWeightedPositionsChooser.WFLagChosenPositions.PortfolioWeightedPositions.GetWeightedPosition( ticker ); } *************** *** 398,405 **** // Console.WriteLine( "Number of Eligible tickers: " + // this.eligibleTickers.EligibleTickers.Rows.Count ); ! this.chosenTickers.SetWeightedPositions( this.eligibleTickers ); this.arePositionsUpToDateWithChosenTickers = false; ! this.NewChosenTickers( this , ! new WFLagNewChosenTickersEventArgs( this.chosenTickers ) ); this.lastOptimizationDate = this.now().DateTime; } --- 377,390 ---- // Console.WriteLine( "Number of Eligible tickers: " + // this.eligibleTickers.EligibleTickers.Rows.Count ); ! // this.chosenTickers.SetWeightedPositions( this.eligibleTickers , ! // this.account.EndOfDayTimer.GetCurrentTime() ); ! this.wFLagWeightedPositionsChooser.ChosePositions( ! this.eligibleTickers , ! this.eligibleTickers , ! this.account.EndOfDayTimer.GetCurrentTime() ); this.arePositionsUpToDateWithChosenTickers = false; ! this.NewChosenPositions( this , ! new WFLagNewChosenPositionsEventArgs( ! this.wFLagWeightedPositionsChooser.WFLagChosenPositions ) ); this.lastOptimizationDate = this.now().DateTime; } |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:34:38
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv10431/b7_Scripts/WalkForwardTesting/WalkForwardLag Modified Files: WFLagMain.cs Log Message: Better OO approach now: an IWFLagWeightedPositionChooser interface has been introduced. Now it will be easier to move both from a strategy to another, and from an optimization technique to another Index: WFLagMain.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagMain.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** WFLagMain.cs 3 Nov 2006 16:32:53 -0000 1.6 --- WFLagMain.cs 18 Feb 2007 00:57:34 -0000 1.7 *************** *** 136,146 **** // XLF vs SMH // QQQQ vs SPY ! new RunWalkForwardLag( "DrvPstns" , 500 , ! 4 , 2 , 200 , 13 , 9 , 100 , "EWQ" , ! new DateTime( 2002 , 1 , 1 ) , ! new DateTime( 2003 , 12 , 31 ) , ! new QuantProject.Business.Strategies.EquityEvaluation.WinningPeriods() , ! 8.5 ).Run(); // new RunWalkForwardLag( "ib_etf" , 500 , // 4 , 4 , 250 , 2 , 15 , 30000 , "EWQ" , --- 136,156 ---- // XLF vs SMH // QQQQ vs SPY ! IWFLagWeightedPositionsChooser wFLagWeightedPositionsChooser = ! new WFLagBruteForceFixedPortfolioWeightedPositionsChooser( ! 4 , new string[]{ "IWM" , "SPY" } , 100 , "EWQ" , ! new QuantProject.Business.Strategies.EquityEvaluation.WinningPeriods() ); ! new RunWalkForwardLag( "DrvPstns" , 200 , ! wFLagWeightedPositionsChooser , 9 , ! new DateTime( 2001 , 1 , 1 ) , ! new DateTime( 2001 , 6 , 1 ) , ! 0.5 ).Run(); + // new RunWalkForwardLag( "DrvPstns" , 500 , + // 4 , 2 , 365 , 13 , 9 , 100 , "EWQ" , + // new DateTime( 2002 , 1 , 1 ) , + // new DateTime( 2003 , 12 , 31 ) , + // new QuantProject.Business.Strategies.EquityEvaluation.WinningPeriods() , + // 13 ).Run(); + // // new RunWalkForwardLag( "ib_etf" , 500 , // 4 , 4 , 250 , 2 , 15 , 30000 , "EWQ" , |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:34:34
|
Update of /cvsroot/quantproject/QuantProject/b5_Presentation In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv8830/b5_Presentation Modified Files: b5_Presentation.csproj Log Message: Minor VSNet automatic changes Index: b5_Presentation.csproj =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b5_Presentation/b5_Presentation.csproj,v retrieving revision 1.33 retrieving revision 1.34 diff -C2 -d -r1.33 -r1.34 *** b5_Presentation.csproj 6 Dec 2006 16:07:17 -0000 1.33 --- b5_Presentation.csproj 18 Feb 2007 00:53:13 -0000 1.34 *************** *** 169,173 **** <File RelPath = "Charting\Chart.cs" ! SubType = "Code" BuildAction = "Compile" /> --- 169,173 ---- <File RelPath = "Charting\Chart.cs" ! SubType = "UserControl" BuildAction = "Compile" /> |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:34:33
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagDebugger In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv12915/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagDebugger Modified Files: WFLagChosenPositions.cs Log Message: A new constructor has been added Index: WFLagChosenPositions.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagDebugger/WFLagChosenPositions.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** WFLagChosenPositions.cs 8 Aug 2006 09:45:27 -0000 1.3 --- WFLagChosenPositions.cs 18 Feb 2007 01:03:36 -0000 1.4 *************** *** 92,96 **** this.portfolioWeightedPositions = wFLagChosenTickers.PortfolioWeightedPositions; this.lastOptimizationDate = lastOptimizationDate; ! this.generation = wFLagChosenTickers.Generation; } --- 92,107 ---- this.portfolioWeightedPositions = wFLagChosenTickers.PortfolioWeightedPositions; this.lastOptimizationDate = lastOptimizationDate; ! } ! ! public WFLagChosenPositions( WeightedPositions drivingWeightedPositions , ! WeightedPositions portfolioWeightedPositions , DateTime lastOptimizationDate ) ! { ! // this.drivingPositions = ! // this.copy( wFLagChosenTickers.DrivingWeightedPositions ); ! // this.portfolioPositions = ! // this.copy( wFLagChosenTickers.PortfolioWeightedPositions ); ! this.drivingWeightedPositions = drivingWeightedPositions; ! this.portfolioWeightedPositions = portfolioWeightedPositions; ! this.lastOptimizationDate = lastOptimizationDate; } |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:34:33
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv16688 Removed Files: WFLagNewChosenTickersEventArgs.cs Log Message: It has been replaced by WFLagNewChosenPositionsEventArgs --- WFLagNewChosenTickersEventArgs.cs DELETED --- |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:34:33
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv17495/WeightedPositionsChoosers Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers added to the repository |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:34:33
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv17956 Added Files: IWFLagWeightedPositionsChooser.cs Log Message: Interface to be implemented by any object used to chose in sample WeghtedPositions --- NEW FILE: IWFLagWeightedPositionsChooser.cs --- /* QuantProject - Quantitative Finance Library IWFLagWeightedPositionsChooser.cs Copyright (C) 2006 Glauco Siliprandi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using QuantProject.ADT; using QuantProject.Business.Timing; using QuantProject.Scripts.WalkForwardTesting.WalkForwardLag.WFLagDebugger; namespace QuantProject.Scripts.WalkForwardTesting.WalkForwardLag { /// <summary> /// Interface to be implemented by any object used to chose in /// sample WeghtedPositions. /// </summary> public interface IWFLagWeightedPositionsChooser : IProgressNotifier { void ChosePositions( WFLagEligibleTickers eligibleTickersForDrivingPositions , WFLagEligibleTickers eligibleTickersForPortfolioPositions , EndOfDayDateTime now ); WFLagChosenPositions WFLagChosenPositions { get; } int NumberOfDrivingPositions { get; } int NumberOfPortfolioPositions { get; } int NumberDaysForInSampleOptimization { get; } string Benchmark { get; } // TO DO: remove this one from the interface } } |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:34:32
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv18356 Added Files: WFLagBruteForceFixedPortfolioWeightedPositionsChooser.cs Log Message: Computes the best driving positions, for the given portfolio tickers, with respect to the lag strategy, using the brute force optimization method. --- NEW FILE: WFLagBruteForceFixedPortfolioWeightedPositionsChooser.cs --- /* QuantProject - Quantitative Finance Library WFLagBruteForceFixedPortfolioWeightedPositionsChooser.cs Copyright (C) 2003 Glauco Siliprandi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using QuantProject.ADT; //using QuantProject.ADT.Collections; using QuantProject.ADT.Optimizing.BruteForce; //using QuantProject.ADT.Optimizing.Genetic; //using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.EquityEvaluation; using QuantProject.Business.Timing; using QuantProject.Scripts.WalkForwardTesting.WalkForwardLag.WFLagDebugger; namespace QuantProject.Scripts.WalkForwardTesting.WalkForwardLag { /// <summary> /// Computes the best driving positions, for the given portfolio /// tickers, with respect to the lag strategy, using /// the brute force optimization method. /// </summary> [Serializable] public class WFLagBruteForceFixedPortfolioWeightedPositionsChooser : IWFLagWeightedPositionsChooser { public event NewProgressEventHandler NewProgress; protected int numberOfDrivingPositions; protected string[] portfolioPositionTickers; protected int inSampleDays; protected string benchmark; protected IEquityEvaluator equityEvaluator; private WFLagChosenPositions wFLagChosenPositions; private WeightedPositions drivingWeightedPositions; private WeightedPositions portfolioWeightedPositions; private DateTime firstOptimizationDate; private DateTime lastOptimizationDate; public int NumberOfDrivingPositions { get { return this.numberOfDrivingPositions; } } public int NumberOfPortfolioPositions { get { return this.portfolioPositionTickers.Length; } } public int NumberDaysForInSampleOptimization { get { return this.inSampleDays; } } public string Benchmark { get { return this.benchmark; } } public WeightedPositions DrivingWeightedPositions { get { return this.drivingWeightedPositions; } } public WeightedPositions PortfolioWeightedPositions { get { return this.portfolioWeightedPositions; } } public DateTime FirstOptimizationDate { get { return this.firstOptimizationDate; } } public DateTime LastOptimizationDate { get { return this.lastOptimizationDate; } } public WFLagChosenPositions WFLagChosenPositions { get { return this.wFLagChosenPositions; } } public WFLagBruteForceFixedPortfolioWeightedPositionsChooser( int numberOfDrivingPositions , string[] portfolioPositionTickers , int inSampleDays , string benchmark , IEquityEvaluator equityEvaluator ) { this.numberOfDrivingPositions = numberOfDrivingPositions; this.portfolioPositionTickers = portfolioPositionTickers; this.inSampleDays = inSampleDays; this.benchmark = benchmark; this.equityEvaluator = equityEvaluator; } #region SetWeightedPositions // private void setSignedTickers_clearPositions() // { // this.drivingPositions.Clear(); // this.portfolioPositions.Clear(); // } // #region setWeightedPositions_usingTheGeneticOptimizer // private void newGenerationEventHandler( // object sender , NewGenerationEventArgs e ) // { // this.NewProgress( sender , // new NewProgressEventArgs( e.GenerationCounter , e.GenerationNumber ) ); // } private void setWeightedPositions( WFLagWeightedPositions wFLagWeightedPositions ) { this.drivingWeightedPositions = wFLagWeightedPositions.DrivingWeightedPositions; this.portfolioWeightedPositions = wFLagWeightedPositions.PortfolioWeightedPositions; } // private void setSignedTickers_setTickersFromGenome( // IGenomeManager genomeManager , // Genome genome ) // { // WFLagWeightedPositions wFLagWeightedPositions = // ( WFLagWeightedPositions )genomeManager.Decode( genome ); // this.setWeightedPositions( wFLagWeightedPositions ); //// this.drivingWeightedPositions = //// wFLagWeightedPositions.DrivingWeightedPositions; //// this.portfolioWeightedPositions = //// wFLagWeightedPositions.PortfolioWeightedPositions; // } // public virtual void setWeightedPositions_usingTheGeneticOptimizer( // WFLagEligibleTickers eligibleTickers ) // { // this.firstOptimizationDate = // this.endOfDayTimer.GetCurrentTime().DateTime.AddDays( // -( this.inSampleDays - 1 ) ); // this.lastOptimizationDate = // this.endOfDayTimer.GetCurrentTime().DateTime; // // WFLagGenomeManager genomeManager = // new WFLagGenomeManager( // eligibleTickers.EligibleTickers , // eligibleTickers.EligibleTickers , // this.firstOptimizationDate , // this.lastOptimizationDate , // this.numberOfDrivingPositions , // this.numberOfPositionsToBeChosen , // this.equityEvaluator , // QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator ); // // GeneticOptimizer geneticOptimizer = new GeneticOptimizer( // 0.85 , // 0.02 , // 0.001 , // this.populationSizeForGeneticOptimizer , // this.generationNumberForGeneticOptimizer , // genomeManager , // ConstantsProvider.SeedForRandomGenerator ); // // geneticOptimizer.NewGeneration += // new NewGenerationEventHandler( this.newGenerationEventHandler ); // // geneticOptimizer.Run( false ); // // this.setSignedTickers_setTickersFromGenome( // genomeManager , geneticOptimizer.BestGenome ); // // this.generation = geneticOptimizer.BestGenome.Generation; // // } // #endregion // #region setWeightedPositions_usingTheBruteForceOptimizer // private void newBruteForceOptimizerProgressEventHandler( // object sender , NewProgressEventArgs e ) // { // this.NewProgress( sender , e ); // } // public virtual void setWeightedPositions_usingTheBruteForceOptimizer( // WFLagEligibleTickers eligibleTickers ) // { // this.firstOptimizationDate = // this.endOfDayTimer.GetCurrentTime().DateTime.AddDays( // -( this.inSampleDays - 1 ) ); // this.lastOptimizationDate = // this.endOfDayTimer.GetCurrentTime().DateTime; // // WFLagBruteForceOptimizableParametersManager // wFLagBruteForceOptimizableItemManager= // new WFLagBruteForceOptimizableParametersManager( // eligibleTickers.EligibleTickers , // eligibleTickers.EligibleTickers , // this.firstOptimizationDate , // this.lastOptimizationDate , // this.numberOfDrivingPositions , // this.numberOfPositionsToBeChosen , // this.equityEvaluator ); // // BruteForceOptimizer bruteForceOptimizer = new BruteForceOptimizer( // wFLagBruteForceOptimizableItemManager ); // // bruteForceOptimizer.NewProgress += // new NewProgressEventHandler( // this.newBruteForceOptimizerProgressEventHandler ); // // bruteForceOptimizer.Run(); // // BruteForceOptimizableParameters bestParameters = // bruteForceOptimizer.BestParameters; // // WFLagWeightedPositions wFLagWeightedPositions = // ( WFLagWeightedPositions )wFLagBruteForceOptimizableItemManager.Decode( // bestParameters ); // // this.setWeightedPositions( wFLagWeightedPositions ); // } // #endregion #region setWeightedPositions_withFixedPortfolio // private void newBruteForceOptimizerProgressEventHandler( // object sender , NewProgressEventArgs e ) // { // this.NewProgress( sender , e ); // } private void newBruteForceOptimizerProgressEventHandler( object sender , NewProgressEventArgs e ) { this.NewProgress( sender , e ); } public virtual void setWeightedPositions_withFixedPortfolio( WFLagEligibleTickers eligibleTickers , string longPortfolioTicker , string shortPortfolioTicker , EndOfDayDateTime now ) { this.firstOptimizationDate = now.DateTime.AddDays( -( this.inSampleDays - 1 ) ); this.lastOptimizationDate = now.DateTime; // WFLagFixedPortfolioBruteForceOptimizableParametersManager // wFLagFixedPortfolioBruteForceOptimizableParametersManager= // new WFLagFixedPortfolioBruteForceOptimizableParametersManager( // eligibleTickers.EligibleTickers , // longPortfolioTicker , // shortPortfolioTicker , // this.firstOptimizationDate , // this.lastOptimizationDate , // this.numberOfDrivingPositions ); // // WFLagFixedPortfolioBruteForceOptParamManagerWithPortfolioNormalizedVolatility // wFLagFixedPortfolioBruteForceOptimizableParametersManager= // new WFLagFixedPortfolioBruteForceOptParamManagerWithNormalizedVolatility( // eligibleTickers.EligibleTickers , // longPortfolioTicker , // shortPortfolioTicker , // this.firstOptimizationDate , // this.lastOptimizationDate , // this.numberOfDrivingPositions ); WFLagFixedPortfolioBruteForceOptParamManagerWithNormalizedVolatility wFLagFixedPortfolioBruteForceOptimizableParametersManager= new WFLagFixedPortfolioBruteForceOptParamManagerWithNormalizedVolatility( eligibleTickers.EligibleTickers , longPortfolioTicker , shortPortfolioTicker , this.firstOptimizationDate , this.lastOptimizationDate , this.numberOfDrivingPositions , this.equityEvaluator ); BruteForceOptimizer bruteForceOptimizer = new BruteForceOptimizer( wFLagFixedPortfolioBruteForceOptimizableParametersManager ); bruteForceOptimizer.NewProgress += new NewProgressEventHandler( this.newBruteForceOptimizerProgressEventHandler ); bruteForceOptimizer.Run( 100000 , wFLagFixedPortfolioBruteForceOptimizableParametersManager.TotalIterations ); BruteForceOptimizableParameters bestParameters = bruteForceOptimizer.BestParameters; WFLagWeightedPositions wFLagWeightedPositions = ( WFLagWeightedPositions )wFLagFixedPortfolioBruteForceOptimizableParametersManager.Decode( bestParameters ); this.setWeightedPositions( wFLagWeightedPositions ); } #endregion public virtual void ChosePositions( WFLagEligibleTickers eligibleTickersForDrivingPositions , WFLagEligibleTickers eligibleTickersForPortfolioPositions , EndOfDayDateTime now ) { this.setWeightedPositions_withFixedPortfolio( eligibleTickersForDrivingPositions , "SPY" , "IWM" , now ); this.wFLagChosenPositions = new WFLagChosenPositions( this.drivingWeightedPositions , this.portfolioWeightedPositions , now.DateTime ); } #endregion } } |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:34:32
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv19196/b7_Scripts Modified Files: b7_Scripts.csproj Log Message: WalkForwardTesting\WalkForwardLag\WFLagNewChosenTickersEventArgs.cs has been removed WalkForwardTesting\WalkForwardLag\WFLagNewChosenPositionsEventArgs.cs has been added WalkForwardTesting\WalkForwardLag\WeightedPositionsChoosers\IWFLagWeightedPositionsChooser.cs has been added WalkForwardTesting\WalkForwardLag\WeightedPositionsChoosers\WFLagBruteForceFixedPortfolioWeightedPositionsChooser.cs has been added Index: b7_Scripts.csproj =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/b7_Scripts.csproj,v retrieving revision 1.66 retrieving revision 1.67 diff -C2 -d -r1.66 -r1.67 *** b7_Scripts.csproj 8 Oct 2006 15:58:49 -0000 1.66 --- b7_Scripts.csproj 18 Feb 2007 01:18:42 -0000 1.67 *************** *** 679,683 **** /> <File ! RelPath = "WalkForwardTesting\WalkForwardLag\WFLagNewChosenTickersEventArgs.cs" SubType = "Code" BuildAction = "Compile" --- 679,683 ---- /> <File ! RelPath = "WalkForwardTesting\WalkForwardLag\WFLagNewChosenPositionsEventArgs.cs" SubType = "Code" BuildAction = "Compile" *************** *** 700,703 **** --- 700,713 ---- /> <File + RelPath = "WalkForwardTesting\WalkForwardLag\WeightedPositionsChoosers\IWFLagWeightedPositionsChooser.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File + RelPath = "WalkForwardTesting\WalkForwardLag\WeightedPositionsChoosers\WFLagBruteForceFixedPortfolioWeightedPositionsChooser.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "WalkForwardTesting\WalkForwardLag\WFLagBruteForceOptimizableItemManager\WFLagBruteForceOptimizableParametersManager.cs" SubType = "Code" |
|
From: Glauco S. <gla...@us...> - 2007-02-18 01:24:24
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv21700 Modified Files: b7_Scripts.csproj Log Message: The folder WalkForwardTesting\WalkForwardLag\EligibleTickers\ has been removed Index: b7_Scripts.csproj =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/b7_Scripts.csproj,v retrieving revision 1.67 retrieving revision 1.68 diff -C2 -d -r1.67 -r1.68 *** b7_Scripts.csproj 18 Feb 2007 01:18:42 -0000 1.67 --- b7_Scripts.csproj 18 Feb 2007 01:24:19 -0000 1.68 *************** *** 693,697 **** BuildAction = "Compile" /> - <Folder RelPath = "WalkForwardTesting\WalkForwardLag\EligibleTickers\" /> <File RelPath = "WalkForwardTesting\WalkForwardLag\GeneticOptimizerTesting\WFLagGOTester.cs" --- 693,696 ---- |
|
From: Marco M. <mi...@us...> - 2007-01-19 16:48:01
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv6724/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator Modified Files: RunPVO.cs Log Message: Updated RunPVO file Index: RunPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/RunPVO.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunPVO.cs 22 Oct 2006 18:49:20 -0000 1.2 --- RunPVO.cs 19 Jan 2007 16:47:55 -0000 1.3 *************** *** 63,67 **** protected int numDaysForOscillatingPeriod; protected bool symmetricalThresholds = false; ! public RunPVO(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, --- 63,68 ---- protected int numDaysForOscillatingPeriod; protected bool symmetricalThresholds = false; ! protected bool overboughtMoreThanOversoldForFixedPortfolio = false; ! public RunPVO(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, *************** *** 76,79 **** --- 77,81 ---- int divisorForThresholdComputation, bool symmetricalThresholds, + bool overboughtMoreThanOversoldForFixedPortfolio, int numDaysBetweenEachOptimization, PortfolioType inSamplePortfolioType, double maxAcceptableCloseToCloseDrawdown, *************** *** 93,96 **** --- 95,99 ---- this.divisorForThresholdComputation = divisorForThresholdComputation; this.symmetricalThresholds = symmetricalThresholds; + this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; *************** *** 114,117 **** --- 117,121 ---- this.divisorForThresholdComputation, this.symmetricalThresholds, + this.overboughtMoreThanOversoldForFixedPortfolio, this.numDaysBetweenEachOptimization, this.portfolioType, this.maxAcceptableCloseToCloseDrawdown); |
|
From: Marco M. <mi...@us...> - 2007-01-03 23:20:49
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv4394/b7_Scripts/TickerSelectionTesting Modified Files: GenomeManipulator.cs GenomeManagerForWeightedEfficientPortfolio.cs GenomeManagerForEfficientPortfolio.cs GenomeManagerForEfficientOTCCTOPortfolio.cs Log Message: Deleted the mutationRate parameter from the IGenomeManager's Mutate method. Now classes implementing Mutate method just need to pass only the genome that has to be mutated to the method. As the mutationRate is now used only by the GeneticOptimizer, all the methods that effectively mutate genes of a given genome don't need anymore the mutation rate parameter. Index: GenomeManagerForEfficientPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/GenomeManagerForEfficientPortfolio.cs,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** GenomeManagerForEfficientPortfolio.cs 22 Oct 2006 18:30:18 -0000 1.26 --- GenomeManagerForEfficientPortfolio.cs 3 Jan 2007 23:20:14 -0000 1.27 *************** *** 295,299 **** } ! public virtual void Mutate(Genome genome, double mutationRate) { // in this implementation only one gene is mutated --- 295,299 ---- } ! public virtual void Mutate(Genome genome) { // in this implementation only one gene is mutated *************** *** 312,316 **** genome.GetMaxValueForGenes(genePositionToBeMutated) + 1); } ! GenomeManagement.MutateOneGene(genome, mutationRate, genePositionToBeMutated, newValueForGene); } --- 312,316 ---- genome.GetMaxValueForGenes(genePositionToBeMutated) + 1); } ! GenomeManagement.MutateOneGene(genome, genePositionToBeMutated, newValueForGene); } Index: GenomeManagerForEfficientOTCCTOPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/GenomeManagerForEfficientOTCCTOPortfolio.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** GenomeManagerForEfficientOTCCTOPortfolio.cs 17 Sep 2006 21:48:39 -0000 1.2 --- GenomeManagerForEfficientOTCCTOPortfolio.cs 3 Jan 2007 23:20:14 -0000 1.3 *************** *** 38,42 **** /// </summary> [Serializable] ! public class GenomeManagerForEfficientOTCCTOPortfolio : GenomeManagerForEfficientPortfolio { --- 38,42 ---- /// </summary> [Serializable] ! public class GenomeManagerForEfficientOTCCTOPortfolio : GenomeManagerForWeightedEfficientPortfolio { Index: GenomeManagerForWeightedEfficientPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/GenomeManagerForWeightedEfficientPortfolio.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** GenomeManagerForWeightedEfficientPortfolio.cs 7 Aug 2006 21:03:24 -0000 1.5 --- GenomeManagerForWeightedEfficientPortfolio.cs 3 Jan 2007 23:20:13 -0000 1.6 *************** *** 143,167 **** return returnValue; } ! ! public override void Mutate(Genome genome, double mutationRate) { - // in this implementation only one gene is mutated int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); ! int newValueForGene = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePositionToBeMutated), ! genome.GetMaxValueForGenes(genePositionToBeMutated) +1); ! ! while(genePositionToBeMutated%2 == 1 && ! GenomeManipulator.IsTickerContainedInGenome(newValueForGene,genome)) ! //while in the proposed genePositionToBeMutated has to be stored ! //a new gene pointing to a ticker and ! //the proposed newValueForGene points to a ticker ! //already stored in the given genome { ! newValueForGene = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePositionToBeMutated), ! genome.GetMaxValueForGenes(genePositionToBeMutated) +1); } - GenomeManagement.MutateOneGene(genome, mutationRate, - genePositionToBeMutated, newValueForGene); } } --- 143,233 ---- return returnValue; } ! ! #region override Mutate ! ! //OLD VERSION ! // public override void Mutate(Genome genome, double mutationRate) ! // { ! // // in this implementation only one gene is mutated ! // int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); ! // int newValueForGene = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePositionToBeMutated), ! // genome.GetMaxValueForGenes(genePositionToBeMutated) +1); ! // ! // while(genePositionToBeMutated%2 == 1 && ! // GenomeManipulator.IsTickerContainedInGenome(newValueForGene,genome)) ! // //while in the proposed genePositionToBeMutated has to be stored ! // //a new gene pointing to a ticker and ! // //the proposed newValueForGene points to a ticker ! // //already stored in the given genome ! // { ! // newValueForGene = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePositionToBeMutated), ! // genome.GetMaxValueForGenes(genePositionToBeMutated) +1); ! // } ! // GenomeManagement.MutateOneGene(genome, mutationRate, ! // genePositionToBeMutated, newValueForGene); ! // } ! ! private int mutate_MutateOnlyOneWeight_getNewWeight(Genome genome, int genePositionToBeMutated) ! { ! int returnValue; ! double partOfGeneToSubtractOrAdd = 0.25; ! int geneValue = Math.Abs(genome.GetGeneValue(genePositionToBeMutated)); ! int subtractOrAdd = GenomeManagement.RandomGenerator.Next(2); ! if(subtractOrAdd == 1)//subtract a part of the gene value from the gene value itself ! returnValue = geneValue - Convert.ToInt32(partOfGeneToSubtractOrAdd*geneValue); ! else ! returnValue = Math.Min(genome.GetMaxValueForGenes(genePositionToBeMutated), ! geneValue + Convert.ToInt32(partOfGeneToSubtractOrAdd*geneValue)); ! return returnValue; ! } ! ! private void mutate_MutateOnlyOneWeight(Genome genome) { int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); ! while(genePositionToBeMutated%2 == 1 ) ! //while the proposed genePositionToBeMutated points to a ticker ! genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); ! ! int newValueForGene = this.mutate_MutateOnlyOneWeight_getNewWeight(genome, genePositionToBeMutated); ! ! GenomeManagement.MutateOneGene(genome, genePositionToBeMutated, newValueForGene); ! } ! ! private void mutate_MutateAllGenes(Genome genome) ! { ! for(int genePositionToBeMutated = 0; ! genePositionToBeMutated < genome.Genes().Length; ! genePositionToBeMutated ++) { ! int newValueForGene = ! GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePositionToBeMutated), ! genome.GetMaxValueForGenes(genePositionToBeMutated) + 1); ! while(genePositionToBeMutated%2 == 1 ! && GenomeManipulator.IsTickerContainedInGenome(newValueForGene,genome)) ! //while in the given position has to be stored ! //a new gene pointing to a ticker and ! //the proposed newValueForGene points to a ticker ! //already stored in the given genome ! // a new newalueForGene has to be generated ! newValueForGene = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePositionToBeMutated), ! genome.GetMaxValueForGenes(genePositionToBeMutated) + 1); ! ! genome.SetGeneValue(newValueForGene, genePositionToBeMutated); } } + + //new version + //mutation means just a change in one single weight + //or in a complete new genome (with a probability of 50%) + public override void Mutate(Genome genome) + { + int mutateOnlyOneWeight = GenomeManagement.RandomGenerator.Next(2); + if(mutateOnlyOneWeight == 1) + this.mutate_MutateOnlyOneWeight(genome); + else//mutate all genome's genes + this.mutate_MutateAllGenes(genome); + } + + #endregion } Index: GenomeManipulator.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/GenomeManipulator.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** GenomeManipulator.cs 22 Aug 2006 19:09:35 -0000 1.8 --- GenomeManipulator.cs 3 Jan 2007 23:20:12 -0000 1.9 *************** *** 261,265 **** } ! } } --- 261,293 ---- } ! ! /// <summary> ! /// Returns true if a given gene, when decoded by the ! /// GenomeManagerForEfficientPortfolio, refers to a ! /// ticker already contained in a given genome ! /// </summary> ! /// <param name="geneValueCorrespondingToATicker">Gene, corresponding to a certain ticker, that has to be checked</param> ! /// <param name="genome">Genome containing or not the ticker geneCorrespondingToATicker refers to</param> ! /// <param name="genesPointingToTickers">The int array that contains positions of genes pointing ! /// to tickers inside genome</param> ! public static bool IsTickerContainedInGenome(int geneValueCorrespondingToATicker, ! Genome genome, int[] genePositionsPointingToTickers) ! { ! bool returnValue = false; ! for(int i = 0; i<genePositionsPointingToTickers.Length; i++) ! { ! returnValue = (genome.HasGene(geneValueCorrespondingToATicker, ! genePositionsPointingToTickers[i]) || ! (geneValueCorrespondingToATicker < 0 && ! genome.HasGene(Math.Abs(geneValueCorrespondingToATicker)-1, ! genePositionsPointingToTickers[i]) ) || ! (geneValueCorrespondingToATicker >= 0 && ! genome.HasGene(- Math.Abs(geneValueCorrespondingToATicker)- 1, ! genePositionsPointingToTickers[i])) ); ! if(returnValue) ! i = genePositionsPointingToTickers.Length;//exit from FOR ! } ! return returnValue; ! } } } |
|
From: Marco M. <mi...@us...> - 2007-01-03 23:20:48
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv4394/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator Modified Files: GenomeManagerPVO.cs Log Message: Deleted the mutationRate parameter from the IGenomeManager's Mutate method. Now classes implementing Mutate method just need to pass only the genome that has to be mutated to the method. As the mutationRate is now used only by the GeneticOptimizer, all the methods that effectively mutate genes of a given genome don't need anymore the mutation rate parameter. Index: GenomeManagerPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/GenomeManagerPVO.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** GenomeManagerPVO.cs 22 Oct 2006 18:49:20 -0000 1.2 --- GenomeManagerPVO.cs 3 Jan 2007 23:20:14 -0000 1.3 *************** *** 47,50 **** --- 47,51 ---- private int divisorForThresholdComputation; private bool symmetricalThresholds = false; + private bool overboughtMoreThanOversoldForFixedPortfolio = false; private int numOfGenesDedicatedToThresholds; private double currentOversoldThreshold = 0.0; *************** *** 63,67 **** this.divisorForThresholdComputation < this.maxLevelForOversoldThreshold || (this.symmetricalThresholds && (this.minLevelForOversoldThreshold != this.minLevelForOverboughtThreshold || ! this.maxLevelForOversoldThreshold != this.maxLevelForOverboughtThreshold) ) ) throw new Exception("Bad parameters for thresholds computation!"); --- 64,73 ---- this.divisorForThresholdComputation < this.maxLevelForOversoldThreshold || (this.symmetricalThresholds && (this.minLevelForOversoldThreshold != this.minLevelForOverboughtThreshold || ! this.maxLevelForOversoldThreshold != this.maxLevelForOverboughtThreshold) ) || ! (this.overboughtMoreThanOversoldForFixedPortfolio && ! (this.minLevelForOverboughtThreshold > Convert.ToInt32(Convert.ToDouble(this.minLevelForOversoldThreshold)* Convert.ToDouble(this.divisorForThresholdComputation) / ! (Convert.ToDouble(this.divisorForThresholdComputation) - Convert.ToDouble(this.minLevelForOversoldThreshold) ) ) || ! this.maxLevelForOverboughtThreshold < Convert.ToInt32(Convert.ToDouble(this.maxLevelForOversoldThreshold) * Convert.ToDouble(this.divisorForThresholdComputation) / ! (Convert.ToDouble(this.divisorForThresholdComputation) - Convert.ToDouble(this.maxLevelForOversoldThreshold) ) ) ) ) ) throw new Exception("Bad parameters for thresholds computation!"); *************** *** 79,82 **** --- 85,89 ---- int divisorForThresholdComputation, bool symmetricalThresholds, + bool overboughtMoreThanOversoldForFixedPortfolio, PortfolioType inSamplePortfolioType) : *************** *** 97,100 **** --- 104,108 ---- this.maxLevelForOverboughtThreshold = maxLevelForOverboughtThreshold; this.symmetricalThresholds = symmetricalThresholds; + this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; if(this.symmetricalThresholds)//value for thresholds must be unique numOfGenesDedicatedToThresholds = 1; *************** *** 364,391 **** int minValueForGene = genome.GetMinValueForGenes(genePosition); int maxValueForGene = genome.GetMaxValueForGenes(genePosition); ! int returnValue = minValueForGene; ! if( minValueForGene != maxValueForGene) ! { ! returnValue = GenomeManagement.RandomGenerator.Next(minValueForGene, ! maxValueForGene + 1); ! while(genePosition > this.numOfGenesDedicatedToThresholds - 1 ! && GenomeManipulator.IsTickerContainedInGenome(returnValue, ! genome, ! this.numOfGenesDedicatedToThresholds, ! genome.Size - 1)) ! //while in the given position has to be stored ! //a new gene pointing to a ticker and ! //the proposed returnValue points to a ticker ! //already stored in the given genome ! { ! // a new returnValue has to be generated ! returnValue = GenomeManagement.RandomGenerator.Next(minValueForGene, ! maxValueForGene + 1); ! } ! } return returnValue; } ! public override void Mutate(Genome genome, double mutationRate) { // in this implementation only one gene is mutated --- 372,401 ---- int minValueForGene = genome.GetMinValueForGenes(genePosition); int maxValueForGene = genome.GetMaxValueForGenes(genePosition); ! int returnValue = GenomeManagement.RandomGenerator.Next(minValueForGene, ! maxValueForGene + 1); ! ! if(this.numOfGenesDedicatedToThresholds == 2 && ! this.overboughtMoreThanOversoldForFixedPortfolio && genePosition == 1) ! //genePosition points to overbought threshold, ! //dipendent from the oversold one such that the portfolio tends to be fix ! returnValue = Convert.ToInt32(Convert.ToDouble(genome.GetGeneValue(0)) * Convert.ToDouble(this.divisorForThresholdComputation) / ! (Convert.ToDouble(this.divisorForThresholdComputation) - Convert.ToDouble(genome.GetGeneValue(0)))); ! ! while(genePosition > this.numOfGenesDedicatedToThresholds - 1 ! && GenomeManipulator.IsTickerContainedInGenome(returnValue, ! genome, ! this.numOfGenesDedicatedToThresholds, ! genome.Size - 1)) ! //while in the given position has to be stored ! //a new gene pointing to a ticker and ! //the proposed returnValue points to a ticker ! //already stored in the given genome ! returnValue = GenomeManagement.RandomGenerator.Next(minValueForGene, ! maxValueForGene + 1); ! return returnValue; } ! public override void Mutate(Genome genome) { // in this implementation only one gene is mutated *************** *** 393,417 **** int minValueForGene = genome.GetMinValueForGenes(genePositionToBeMutated); int maxValueForGene = genome.GetMaxValueForGenes(genePositionToBeMutated); ! if(minValueForGenes != maxValueForGenes) ! { ! int newValueForGene = GenomeManagement.RandomGenerator.Next(minValueForGene, ! maxValueForGene + 1); ! ! while(genePositionToBeMutated > this.numOfGenesDedicatedToThresholds - 1 && ! GenomeManipulator.IsTickerContainedInGenome(newValueForGene, ! genome, ! this.numOfGenesDedicatedToThresholds, ! genome.Size - 1)) ! //while in the proposed genePositionToBeMutated has to be stored ! //a new gene pointing to a ticker and ! //the proposed newValueForGene points to a ticker ! //already stored in the given genome ! { ! newValueForGene = GenomeManagement.RandomGenerator.Next(minValueForGene, ! maxValueForGene +1); ! } ! GenomeManagement.MutateOneGene(genome, mutationRate, ! genePositionToBeMutated, newValueForGene); ! } } } --- 403,424 ---- int minValueForGene = genome.GetMinValueForGenes(genePositionToBeMutated); int maxValueForGene = genome.GetMaxValueForGenes(genePositionToBeMutated); ! int newValueForGene = GenomeManagement.RandomGenerator.Next(minValueForGene, ! maxValueForGene +1); ! while(genePositionToBeMutated > this.numOfGenesDedicatedToThresholds - 1 && ! GenomeManipulator.IsTickerContainedInGenome(newValueForGene, ! genome, ! this.numOfGenesDedicatedToThresholds, ! genome.Size - 1)) ! //while in the proposed genePositionToBeMutated has to be stored ! //a new gene pointing to a ticker and ! //the proposed newValueForGene points to a ticker ! //already stored in the given genome ! newValueForGene = GenomeManagement.RandomGenerator.Next(minValueForGene, ! maxValueForGene +1); ! //TODO add if when it is mutated a threshold ! //(just a single threshold or the pair of thresholds) ! if(genePositionToBeMutated > this.numOfGenesDedicatedToThresholds - 1) ! GenomeManagement.MutateOneGene(genome, ! genePositionToBeMutated, newValueForGene); } } |
|
From: Marco M. <mi...@us...> - 2007-01-03 23:20:47
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv4394/b1_ADT/Optimizing/Genetic Modified Files: IGenomeManager.cs GenomeManagerTest.cs GenomeManagement.cs GeneticOptimizer.cs Log Message: Deleted the mutationRate parameter from the IGenomeManager's Mutate method. Now classes implementing Mutate method just need to pass only the genome that has to be mutated to the method. As the mutationRate is now used only by the GeneticOptimizer, all the methods that effectively mutate genes of a given genome don't need anymore the mutation rate parameter. Index: GenomeManagerTest.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic/GenomeManagerTest.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** GenomeManagerTest.cs 7 Aug 2006 21:03:24 -0000 1.6 --- GenomeManagerTest.cs 3 Jan 2007 23:20:11 -0000 1.7 *************** *** 77,83 **** } ! public void Mutate(Genome genome, double mutationRate) { ! GenomeManagement.MutateAllGenes(genome, mutationRate); } --- 77,83 ---- } ! public void Mutate(Genome genome) { ! GenomeManagement.MutateAllGenes(genome); } Index: GeneticOptimizer.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic/GeneticOptimizer.cs,v retrieving revision 1.22 retrieving revision 1.23 diff -C2 -d -r1.22 -r1.23 *** GeneticOptimizer.cs 22 Aug 2006 19:05:50 -0000 1.22 --- GeneticOptimizer.cs 3 Jan 2007 23:20:11 -0000 1.23 *************** *** 489,493 **** { foreach(Genome g in this.nextGeneration) ! this.genomeManager.Mutate(g,this.MutationRate); } --- 489,496 ---- { foreach(Genome g in this.nextGeneration) ! { ! if( GenomeManagement.RandomGenerator.Next(0,101) < (int)(this.mutationRate*100) ) ! this.genomeManager.Mutate(g); ! } } Index: IGenomeManager.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic/IGenomeManager.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** IGenomeManager.cs 7 Aug 2006 21:03:24 -0000 1.4 --- IGenomeManager.cs 3 Jan 2007 23:20:10 -0000 1.5 *************** *** 49,53 **** object Decode(Genome genome); Genome[] GetChilds(Genome parent1, Genome parent2); ! void Mutate(Genome genome, double mutationRate); } } --- 49,53 ---- object Decode(Genome genome); Genome[] GetChilds(Genome parent1, Genome parent2); ! void Mutate(Genome genome); } } Index: GenomeManagement.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic/GenomeManagement.cs,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** GenomeManagement.cs 7 Aug 2006 21:03:24 -0000 1.10 --- GenomeManagement.cs 3 Jan 2007 23:20:11 -0000 1.11 *************** *** 173,204 **** } ! static public void MutateAllGenes(Genome genome, double mutationRate) { for (int pos = 0 ; pos < genome.Size; pos++) { ! if (GenomeManagement.RandomGenerator.Next(0,101) < (int)(mutationRate*100)) ! genome.SetGeneValue(GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(pos), ! genome.GetMaxValueForGenes(pos) + 1), pos); } } ! static public void MutateOneGene(Genome genome, double mutationRate, ! int genePosition) { ! ! if (GenomeManagement.RandomGenerator.Next(0,101) < (int)(mutationRate*100)) ! genome.SetGeneValue(GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePosition), genome.GetMaxValueForGenes(genePosition) + 1), genePosition); - } ! static public void MutateOneGene(Genome genome, double mutationRate, ! int genePosition, int newValueOfGene) { ! if (GenomeManagement.RandomGenerator.Next(0,101) < (int)(mutationRate*100)) ! genome.SetGeneValue(newValueOfGene, genePosition); ! } #region MixGenesWithoutDuplicates --- 173,212 ---- } ! static public void MutateAllGenes(Genome genome) { for (int pos = 0 ; pos < genome.Size; pos++) { ! genome.SetGeneValue( GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(pos), ! genome.GetMaxValueForGenes(pos) + 1), pos ); } } ! static public void MutateOneGene(Genome genome, int genePosition) { ! genome.SetGeneValue(GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePosition), genome.GetMaxValueForGenes(genePosition) + 1), genePosition); } ! static public void MutateOneGene(Genome genome, ! int genePosition, int newValueOfGene) { ! genome.SetGeneValue(newValueOfGene, genePosition); } + static public void MutateGenes(Genome genome, + int[] positionsOfGenesToBeMutated, + int[] newValuesForGenes) + { + if(positionsOfGenesToBeMutated.Length > genome.Size || + positionsOfGenesToBeMutated.Length != newValuesForGenes.Length) + throw new Exception("Bad parameters: too many positions of genes to be mutated or " + + "newValueForGenes' length is different from positionsOfGenesToBeMutated's lenght"); + + for(int i = 0; i<positionsOfGenesToBeMutated.Length; i++) + genome.SetGeneValue(newValuesForGenes[i], positionsOfGenesToBeMutated[i]); + + } + + #region MixGenesWithoutDuplicates |