quantproject-developers Mailing List for QuantProject (Page 86)
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
|
|
From: Marco M. <mi...@us...> - 2006-07-02 19:51:39
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv13547/b1_ADT/Optimizing/Genetic Modified Files: GenomeManagement.cs Log Message: Added MixGenesWithoutDuplicates method to the class (it is a general method that can be used in general by IGenomeManager objects) Index: GenomeManagement.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic/GenomeManagement.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** GenomeManagement.cs 7 Aug 2005 08:20:53 -0000 1.7 --- GenomeManagement.cs 2 Jul 2006 19:51:36 -0000 1.8 *************** *** 43,47 **** static GenomeManagement() { ! RandomGenerator = new Random((int)DateTime.Now.Ticks); childs = new Genome[2]; } --- 43,47 ---- static GenomeManagement() { ! RandomGenerator = new Random(ConstantsProvider.SeedForRandomGenerator); childs = new Genome[2]; } *************** *** 54,57 **** --- 54,64 ---- //the two childs now points to their parents maskForChilds = new int[childs.Length, genomeSize]; + for(int i = 0; i<genomeSize; i++) + { + maskForChilds[0,i]=1; + maskForChilds[1,i]=2; + } + //maskForChilds has been set in order to re-create + //a copy of parents by using setChildsUsingMaskForChilds() } *************** *** 190,193 **** --- 197,285 ---- } + + #region MixGenesWithoutDuplicates + + private static int[] genePositionsOfParent1NotPresentInParent2(Genome parent1, + Genome parent2) + { + int[] returnValue = new int[parent1.Size]; + for(int i = 0; i < returnValue.Length; i++) + { + returnValue[i] = - 1; + int geneValue = parent1.GetGeneValue(i); + if(geneValue >= 0) + { + if(!parent2.HasGene(geneValue) && + !parent2.HasGene(-Math.Abs(geneValue) - 1)) + returnValue[i] = i; + } + else + { + if(!parent2.HasGene(geneValue) && + !parent2.HasGene(Math.Abs(geneValue) - 1)) + returnValue[i] = i; + } + } + return returnValue; + } + + private static void setMaskForChildsForMixingWithoutDuplicates(Genome parent1, Genome parent2) + + { + int[] genePlacesOfParent1NotPresentInParent2 = + genePositionsOfParent1NotPresentInParent2(parent1, parent2); + int[] genePlacesOfParent2NotPresentInParent1 = + genePositionsOfParent1NotPresentInParent2(parent2, parent1); + bool justExchangedAtPreviousPosition = false; + for(int i = 0;i<parent1.Size;i++) + { + if(!justExchangedAtPreviousPosition) + //exchanges between genes of parents in childs + //must follow an alternate pattern, in order to + //avoid plain copy of parents in childs when all genes + //of the first parent are not in the second one (and viceversa) + { + if(genePlacesOfParent2NotPresentInParent1[i]!= - 1) + { + maskForChilds[0, i] = 2; + justExchangedAtPreviousPosition = true; + } + if(genePlacesOfParent1NotPresentInParent2[i]!= - 1) + { + maskForChilds[1, i] = 1; + justExchangedAtPreviousPosition = true; + } + } + else + justExchangedAtPreviousPosition = false; + } + } + + /// <summary> + /// This method returns an array of genomes based on + /// a mix of the genes of parents, such that the 2 childs, + /// if possible, are different from parents and, at + /// the same time, childs' genes are not duplicated + /// </summary> + /// <param name="parent1">First genome parent from which genes are to be mixed in offspring</param> + /// <param name="parents">Second genome parent from which genes are to be mixed in offspring</param> + /// <param name="constToDiscoverGenesDuplicates">Gene y is a duplicate of gene x iff y = |x| - 1 + /// or y = -|x| -1</param> + public static Genome[] MixGenesWithoutDuplicates(Genome parent1, Genome parent2) + { + initializeStaticMembers(parent1, parent2); + if(parent1.Size > (parent1.MaxValueForGenes - parent1.MinValueForGenes + 1)) + //it is impossible not to duplicate genes if size is too + // large for the range of variation of each gene + throw new Exception("Impossible to avoid duplicates with the given size!"); + if(parent1.Size != parent2.Size) + throw new Exception("Genomes must have the same size!"); + + setMaskForChildsForMixingWithoutDuplicates(parent1, parent2); + setChildsUsingMaskForChilds(parent1, parent2); + //throwExcIfAChildHasDuplicateGenes(); //just for debugging purposes + return childs; + } + #endregion } } |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:42:18
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/TestingOTCTypes In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv9856/b7_Scripts/TickerSelectionTesting/TestingOTCTypes Modified Files: RunEfficientOTCTypes.cs Log Message: Updated RunEfficientOTCTypes Index: RunEfficientOTCTypes.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/TestingOTCTypes/RunEfficientOTCTypes.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RunEfficientOTCTypes.cs 14 May 2006 18:21:47 -0000 1.3 --- RunEfficientOTCTypes.cs 2 Jul 2006 19:42:15 -0000 1.4 *************** *** 72,76 **** portfolioType, maxRunningHours) { ! this.ScriptName = "OTC_Types_SharpeRatioCombinedNoCoeff"; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.accounts = new Account[4]; --- 72,76 ---- portfolioType, maxRunningHours) { ! this.ScriptName = "OTC_Types_ExpScoreWithCoeff"; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.accounts = new Account[4]; |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:41:53
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv9454/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend Modified Files: RunExtremeCounterTrend.cs Log Message: Improved names of the files that are saved on disk (reports, accounts or genomes). Index: RunExtremeCounterTrend.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend/RunExtremeCounterTrend.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunExtremeCounterTrend.cs 14 May 2006 15:33:37 -0000 1.1 --- RunExtremeCounterTrend.cs 2 Jul 2006 19:41:46 -0000 1.2 *************** *** 57,61 **** private int numDaysBetweenEachOptimization; ! public RunExtremeCounterTrend(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, --- 57,61 ---- private int numDaysBetweenEachOptimization; ! public RunExtremeCounterTrend(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, *************** *** 66,70 **** PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown, double maxRunningHours): ! base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, generationNumberForGeneticOptimizer, --- 66,70 ---- PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown, double maxRunningHours): ! base(tickerGroupID, maxNumOfEligibleTickersForOptimization, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, generationNumberForGeneticOptimizer, *************** *** 73,77 **** portfolioType, maxRunningHours) { ! this.ScriptName = "ExtremeCounterTrendScriptWithSharpe"; this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; --- 73,77 ---- portfolioType, maxRunningHours) { ! this.ScriptName = "ExtremeCounterTrendScriptWithExpScoreWeighted"; this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; *************** *** 116,121 **** public override void SaveScriptResults() { ! string fileName = "From"+this.numberOfEligibleTickers + ! "OptDays" + this.numDaysForOptimizationPeriod + "Portfolio" + this.numberOfTickersToBeChosen + "GenNum" + this.generationNumberForGeneticOptimizer + --- 116,121 ---- public override void SaveScriptResults() { ! string fileName = "From"+ this.tickerGroupID + "_" + this.numberOfEligibleTickers + ! "_DaysForOpt" + this.numDaysForOptimizationPeriod + "Tickers" + this.numberOfTickersToBeChosen + "GenNum" + this.generationNumberForGeneticOptimizer + |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:36:16
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/TechnicalAnalysis In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv6845/b7_Scripts/EvaluatingOptimizationTechnique/TechnicalAnalysis Modified Files: RunTestingOptimizationExtremeCounterTrend.cs Log Message: Updated files for testing optimization on OTC and ExtremeCounterTrend strategies. Index: RunTestingOptimizationExtremeCounterTrend.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/TechnicalAnalysis/RunTestingOptimizationExtremeCounterTrend.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunTestingOptimizationExtremeCounterTrend.cs 14 May 2006 18:07:46 -0000 1.1 --- RunTestingOptimizationExtremeCounterTrend.cs 2 Jul 2006 19:36:12 -0000 1.2 *************** *** 30,33 **** --- 30,34 ---- using QuantProject.Data.DataTables; using QuantProject.ADT.Statistics; + using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.ExtremeCounterTrend; *************** *** 46,55 **** private int numberOfEligibleTickers; private int numberOfTickersToBeChosen; ! private int numDaysForOptimization; private int populationSizeForGeneticOptimizer; private int generationNumberForGeneticOptimizer; private string benchmark; private DateTime marketDate; ! private double targetReturn; private PortfolioType portfolioType; private int numDaysAfterLastOptimizationDay; --- 47,56 ---- private int numberOfEligibleTickers; private int numberOfTickersToBeChosen; ! private int numDaysForOptimizationPeriod; private int populationSizeForGeneticOptimizer; private int generationNumberForGeneticOptimizer; private string benchmark; private DateTime marketDate; ! private int numDaysForReturnCalculation; private PortfolioType portfolioType; private int numDaysAfterLastOptimizationDay; *************** *** 59,66 **** public RunTestingOptimizationExtremeCounterTrend(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimization, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, ! DateTime marketDate, double targetReturn, PortfolioType portfolioType, int numDaysAfterLastOptimizationDay, int numberOfSubsets, int numberOfGenomesToTest) --- 60,67 ---- public RunTestingOptimizationExtremeCounterTrend(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, ! DateTime marketDate, int numDaysForReturnCalculation, PortfolioType portfolioType, int numDaysAfterLastOptimizationDay, int numberOfSubsets, int numberOfGenomesToTest) *************** *** 73,82 **** this.numberOfEligibleTickers = numberOfEligibleTickers; this.numberOfTickersToBeChosen = numberOfTickersToBeChosen; ! this.numDaysForOptimization = numDaysForOptimization; this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; this.benchmark = benchmark; this.marketDate = marketDate; ! this.targetReturn = targetReturn; this.portfolioType = portfolioType; this.numDaysAfterLastOptimizationDay = numDaysAfterLastOptimizationDay; --- 74,83 ---- this.numberOfEligibleTickers = numberOfEligibleTickers; this.numberOfTickersToBeChosen = numberOfTickersToBeChosen; ! this.numDaysForOptimizationPeriod = numDaysForOptimizationPeriod; this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; this.benchmark = benchmark; this.marketDate = marketDate; ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.portfolioType = portfolioType; this.numDaysAfterLastOptimizationDay = numDaysAfterLastOptimizationDay; *************** *** 84,101 **** } ! private DataTable getSetOfTickersToBeOptimized(DateTime date) { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! date); ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketFromTemporized = new SelectorByQuotationAtEachMarketDay(temporizedGroup.GetTableOfSelectedTickers(), ! false, date.AddDays(-this.numDaysForOptimization), date, ! this.numberOfEligibleTickers, this.benchmark); ! ! return quotedAtEachMarketFromTemporized.GetTableOfSelectedTickers(); } private double setFitnesses_setFitnessesActually_getFitnessOutOfSample(Genome genome) --- 85,137 ---- } ! private DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromTemporized = new SelectorByQuotationAtEachMarketDay(temporizedGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! 600, this.benchmark); ! // filter to be used with plain stocks ! // DataTable tickersQuotedAtEachMarketDay = quotedAtEachMarketDayFromTemporized.GetTableOfSelectedTickers(); ! // SelectorByLiquidity mostLiquid = ! // new SelectorByLiquidity(tickersQuotedAtEachMarketDay, ! // false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // tickersQuotedAtEachMarketDay.Rows.Count/2); ! // ! // DataTable mostLiquidTickers = mostLiquid.GetTableOfSelectedTickers(); ! // ! // SelectorByCloseToCloseVolatility lessVolatile = ! // new SelectorByCloseToCloseVolatility(mostLiquidTickers, ! // true,currentDate.AddDays(-30), currentDate, ! // Math.Min(this.numberOfEligibleTickers, mostLiquidTickers.Rows.Count/2)); ! //// return mostLiquid.GetTableOfSelectedTickers(); ! // return lessVolatile.GetTableOfSelectedTickers(); ! // ! return quotedAtEachMarketDayFromTemporized.GetTableOfSelectedTickers(); } + private double setFitnesses_setFitnessesActually_getFitnessOutOfSample_PortfolioClose(Genome portfolioGenome, DateTime date) + + { + double returnValue = 0.0; + foreach(string tickerCode in ((GenomeMeaning)portfolioGenome.Meaning).Tickers) + { + double coefficient = 1.0; + string ticker = tickerCode; + if(ticker.StartsWith("-")) + { + ticker = ticker.Substring(1,ticker.Length -1); + coefficient = -1.0; + } + Quotes tickerQuotes = new Quotes(ticker, date, + date); + returnValue += (tickerQuotes.GetFirstValidCloseToCloseRatio(date) - 1.0)*coefficient; + } + return returnValue/portfolioGenome.Size; + } + private double setFitnesses_setFitnessesActually_getFitnessOutOfSample(Genome genome) *************** *** 111,151 **** coefficient = -1.0; } ! DateTime dateOutOfSample = this.marketDate.AddDays(this.numDaysAfterLastOptimizationDay); ! //returnValue is the single return for the numDaysAfterLastOptimizationDay - th day ! //after the given market date ! ! //Quotes tickerQuotes = new Quotes(ticker, dateOutOfSample, ! // dateOutOfSample); ! //returnValue += ! // (tickerQuotes.GetFirstValidRawClose(dateOutOfSample)/ ! // tickerQuotes.GetFirstValidRawOpen(dateOutOfSample) - 1.0)*coefficient; ! ! //returnValue is the average return for the interval between ! //the given market date and the numDaysAfterLastOptimizationDay - th ! //day after the given market date ! //Quotes tickerQuotes = new Quotes(ticker, this.marketDate, ! // dateOutOfSample); ! //double close, open; ! //for(int i = 0; i<this.numDaysAfterLastOptimizationDay; i++) ! //{ ! //close = tickerQuotes.GetFirstValidRawClose(this.marketDate.AddDays(i)); ! //open = tickerQuotes.GetFirstValidRawOpen(this.marketDate.AddDays(i)); ! //returnValue += ! //(close/open - 1.0)*coefficient/this.numDaysAfterLastOptimizationDay; ! ! //} - //returnValue is the sharpe ratio for the interval between - //the given market date and the numDaysAfterLastOptimizationDay - th - //day after the given market date Quotes tickerQuotes = new Quotes(ticker, this.marketDate, ! dateOutOfSample); ! double close, open; ! double[] returns = new double[this.numDaysAfterLastOptimizationDay]; ! for(int i = 0; i<this.numDaysAfterLastOptimizationDay; i++) { ! close = tickerQuotes.GetFirstValidRawClose(this.marketDate.AddDays(i)); ! open = tickerQuotes.GetFirstValidRawOpen(this.marketDate.AddDays(i)); ! returns[i] = (close/open - 1.0)*coefficient; } returnValue += BasicFunctions.SimpleAverage(returns) / BasicFunctions.StdDev(returns); --- 147,162 ---- coefficient = -1.0; } ! DateTime endDateOutOfSample = this.marketDate.AddDays(this.numDaysAfterLastOptimizationDay); Quotes tickerQuotes = new Quotes(ticker, this.marketDate, ! endDateOutOfSample); ! double[] returns = new double[tickerQuotes.Rows.Count]; ! for(int i = 1; i<returns.Length; i++) { ! if(this.setFitnesses_setFitnessesActually_getFitnessOutOfSample_PortfolioClose( ! genome, (DateTime)tickerQuotes.Rows[i-1]["quDate"])>0.0) ! coefficient = -1.0 * coefficient; ! returns[i] = (tickerQuotes.GetFirstValidCloseToCloseRatio( ! (DateTime)tickerQuotes.Rows[i]["quDate"] ) - 1.0)*coefficient; } returnValue += BasicFunctions.SimpleAverage(returns) / BasicFunctions.StdDev(returns); *************** *** 251,263 **** DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(this.marketDate); ! IGenomeManager genManEfficientOTCTypes = ! new GenomeManagerForEfficientOTCTypes(setOfTickersToBeOptimized, ! this.marketDate.AddDays(-this.numDaysForOptimization), ! this.marketDate, ! this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType); ! this.setFitnesses_setFitnessesActually(genManEfficientOTCTypes); } --- 262,275 ---- DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(this.marketDate); ! ! IGenomeManager genManExtremeCounterTrend = ! new GenomeManagerECT(setOfTickersToBeOptimized, ! this.marketDate.AddDays(-this.numDaysForOptimizationPeriod), ! this.marketDate, ! this.numberOfTickersToBeChosen, ! this.numDaysForReturnCalculation, ! this.portfolioType); ! this.setFitnesses_setFitnessesActually(genManExtremeCounterTrend); } *************** *** 292,297 **** StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); ! w.Write("\r\nNew Test for Evaluation of Open To Close Optimization {0}\r", DateTime.Now.ToLongDateString()+ " " +DateTime.Now.ToLongTimeString()); ! w.Write("\r\nNum days for optimization {0}\r", this.numDaysForOptimization.ToString()); w.Write("\r\nOptimizing market date {0}\r", this.marketDate.ToLongDateString()); w.Write("\r\nMarket date for test out of sample (sharpe ratio as fitness OS){0}\r", --- 304,309 ---- StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); ! w.Write("\r\nNew Test for Evaluation of Extreme Counter Trend Optimization {0}\r", DateTime.Now.ToLongDateString()+ " " +DateTime.Now.ToLongTimeString()); ! w.Write("\r\nNum days for optimization {0}\r", this.numDaysForOptimizationPeriod.ToString()); w.Write("\r\nOptimizing market date {0}\r", this.marketDate.ToLongDateString()); w.Write("\r\nMarket date for test out of sample (sharpe ratio as fitness OS){0}\r", |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:36:16
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv6845/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio Modified Files: RunTestingOptimizationOpenToCloseFitnessCombined.cs Log Message: Updated files for testing optimization on OTC and ExtremeCounterTrend strategies. Index: RunTestingOptimizationOpenToCloseFitnessCombined.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio/RunTestingOptimizationOpenToCloseFitnessCombined.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunTestingOptimizationOpenToCloseFitnessCombined.cs 14 May 2006 18:06:39 -0000 1.1 --- RunTestingOptimizationOpenToCloseFitnessCombined.cs 2 Jul 2006 19:36:12 -0000 1.2 *************** *** 84,124 **** } ! private DataTable getSetOfTickersToBeOptimized(DateTime date) { ! /* ! SelectorByAverageRawOpenPrice selectorByOpenPrice = ! new SelectorByAverageRawOpenPrice(this.tickerGroupID, false, ! currentDate.AddDays(-this.numDaysForOptimization), currentDate, ! this.numberOfEligibleTickers, this.minPriceForMinimumCommission, ! this.maxPriceForMinimumCommission, 0, 2); ! DataTable tickersByPrice = selectorByOpenPrice.GetTableOfSelectedTickers(); ! */ ! ! SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! date); ! ! SelectorByOpenCloseCorrelationToBenchmark lessCorrelatedFromTemporizedGroup = ! new SelectorByOpenCloseCorrelationToBenchmark(temporizedGroup.GetTableOfSelectedTickers(), ! this.benchmark,true, ! date.AddDays(-this.numDaysForOptimization ), ! date, ! this.numberOfEligibleTickers); ! DataTable eligibleTickers; ! eligibleTickers = lessCorrelatedFromTemporizedGroup.GetTableOfSelectedTickers(); ! //eligibleTickers = temporizedGroup.GetTableOfSelectedTickers(); ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromEligible = ! new SelectorByQuotationAtEachMarketDay( eligibleTickers, ! false, date.AddDays(-this.numDaysForOptimization), ! date, this.numberOfEligibleTickers, this.benchmark); ! //SelectorByWinningOpenToClose winners = ! //new SelectorByWinningOpenToClose(quotedAtEachMarketDayFromEligible.GetTableOfSelectedTickers(), ! // false, date.AddDays(-1), ! // date.AddDays(-1), this.numberOfEligibleTickers/2, ! // true); ! //return winners.GetTableOfSelectedTickers(); ! return quotedAtEachMarketDayFromEligible.GetTableOfSelectedTickers(); ! //return lessCorrelated.GetTableOfSelectedTickers(); } --- 84,102 ---- } ! private DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { ! SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! SelectorByLiquidity mostLiquid = ! new SelectorByLiquidity(tickersFromGroup, ! false,currentDate.AddDays(-this.numDaysForOptimization), currentDate, ! this.numberOfEligibleTickers); ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromMostLiquid = ! new SelectorByQuotationAtEachMarketDay(mostLiquid.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimization), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! return quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(); } *************** *** 276,281 **** DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(this.marketDate); ! IGenomeManager genManEfficientOTCTypes = ! new GenomeManagerForEfficientOTCTypes(setOfTickersToBeOptimized, this.marketDate.AddDays(-this.numDaysForOptimization), this.marketDate, --- 254,259 ---- DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(this.marketDate); ! IGenomeManager genManEfficientOTC_CTO = ! new GenomeManagerForEfficientOTCCTOPortfolio(setOfTickersToBeOptimized, this.marketDate.AddDays(-this.numDaysForOptimization), this.marketDate, *************** *** 284,288 **** this.portfolioType); ! this.setFitnesses_setFitnessesActually(genManEfficientOTCTypes); } --- 262,266 ---- this.portfolioType); ! this.setFitnesses_setFitnessesActually(genManEfficientOTC_CTO); } |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:31:21
|
Update of /cvsroot/quantproject/QuantProject/b3_Data/Selectors In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv4685/b3_Data/Selectors Modified Files: SelectorByCloseToCloseCorrelationToBenchmark.cs Log Message: The selector has been simplified, and some bugs have been fixed. Index: SelectorByCloseToCloseCorrelationToBenchmark.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b3_Data/Selectors/SelectorByCloseToCloseCorrelationToBenchmark.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** SelectorByCloseToCloseCorrelationToBenchmark.cs 20 Dec 2005 19:29:57 -0000 1.2 --- SelectorByCloseToCloseCorrelationToBenchmark.cs 2 Jul 2006 19:31:18 -0000 1.3 *************** *** 22,30 **** using System; - using System.Collections; using System.Data; - using System.Windows.Forms; using QuantProject.DataAccess.Tables; ! using QuantProject.Data.DataTables; namespace QuantProject.Data.Selectors --- 22,28 ---- using System; using System.Data; using QuantProject.DataAccess.Tables; ! using QuantProject.ADT.Statistics; namespace QuantProject.Data.Selectors *************** *** 41,49 **** { private string benchmark; ! private int numDaysBetweenEachClose; /// <summary> /// Creates a new instance of the selector /// </summary> ! /// <param name="setOfTickersToBeSelected">The data table containing in the first column the tickers that have to be ordered</param> /// <param name="benchmark">Benchmark code</param> /// <param name="orderInASCmode">Ordering mode</param> --- 39,49 ---- { private string benchmark; ! private bool addBenchmarkToTheGivenSetOfTickers; /// <summary> /// Creates a new instance of the selector /// </summary> ! /// <param name="setOfTickersToBeSelected">The data table containing ! /// in the first column the tickers that have to be ordered by pearson correlation ! /// coefficient to a given benchmark</param> /// <param name="benchmark">Benchmark code</param> /// <param name="orderInASCmode">Ordering mode</param> *************** *** 51,73 **** /// <param name="lastQuoteDate">The last date for the interval</param> /// <param name="maxNumOfReturnedTickers">Max number of tickers to be returned</param> - /// <param name="numDaysBetweenEachClose">Number of days between closes to be studied. NOTE that - /// close values are grouped in pairs and the first close value in each group is - /// not the last close in the previous group. There is, in other words, a discontinuity - /// between each group, with length equal to the group's length </param> public SelectorByCloseToCloseCorrelationToBenchmark(DataTable setOfTickersToBeSelected, ! string benchmark, ! bool orderInASCmode, ! DateTime firstQuoteDate, ! DateTime lastQuoteDate, ! long maxNumOfReturnedTickers, ! int numDaysBetweenEachClose): ! base(setOfTickersToBeSelected, ! orderInASCmode, ! firstQuoteDate, ! lastQuoteDate, ! maxNumOfReturnedTickers) { this.benchmark = benchmark; ! this.numDaysBetweenEachClose = numDaysBetweenEachClose; } --- 51,69 ---- /// <param name="lastQuoteDate">The last date for the interval</param> /// <param name="maxNumOfReturnedTickers">Max number of tickers to be returned</param> public SelectorByCloseToCloseCorrelationToBenchmark(DataTable setOfTickersToBeSelected, ! string benchmark, ! bool orderInASCmode, ! DateTime firstQuoteDate, ! DateTime lastQuoteDate, ! long maxNumOfReturnedTickers, ! bool addBenchmarkToTheGivenSetOfTickers): ! base(setOfTickersToBeSelected, ! orderInASCmode, ! firstQuoteDate, ! lastQuoteDate, ! maxNumOfReturnedTickers) { this.benchmark = benchmark; ! this.addBenchmarkToTheGivenSetOfTickers = addBenchmarkToTheGivenSetOfTickers; } *************** *** 76,80 **** /// </summary> /// <param name="groupID">The group ID containing the tickers that have to be ordered</param> ! /// <param name="benchmark">Benchmark code</param> /// <param name="orderInASCmode">Ordering mode</param> /// <param name="firstQuoteDate">The first date for the interval</param> --- 72,76 ---- /// </summary> /// <param name="groupID">The group ID containing the tickers that have to be ordered</param> ! /// <param name="benchmark">Benchmark</param> /// <param name="orderInASCmode">Ordering mode</param> /// <param name="firstQuoteDate">The first date for the interval</param> *************** *** 86,103 **** /// between each group, with length equal to the group's length </param> public SelectorByCloseToCloseCorrelationToBenchmark(string groupID, ! string benchmark, ! bool orderInASCmode, ! DateTime firstQuoteDate, ! DateTime lastQuoteDate, ! long maxNumOfReturnedTickers, ! int numDaysBetweenEachClose): ! base(groupID, ! orderInASCmode, ! firstQuoteDate, ! lastQuoteDate, ! maxNumOfReturnedTickers) { this.benchmark = benchmark; ! this.numDaysBetweenEachClose = numDaysBetweenEachClose; } --- 82,99 ---- /// between each group, with length equal to the group's length </param> public SelectorByCloseToCloseCorrelationToBenchmark(string groupID, ! string benchmark, ! bool orderInASCmode, ! DateTime firstQuoteDate, ! DateTime lastQuoteDate, ! long maxNumOfReturnedTickers, ! bool addBenchmarkToTheGivenSetOfTickers): ! base(groupID, ! orderInASCmode, ! firstQuoteDate, ! lastQuoteDate, ! maxNumOfReturnedTickers) { this.benchmark = benchmark; ! this.addBenchmarkToTheGivenSetOfTickers = addBenchmarkToTheGivenSetOfTickers; } *************** *** 106,124 **** { if(this.setOfTickersToBeSelected == null) ! return QuantProject.Data.DataTables.Quotes.GetTickersByCloseToCloseCorrelationToBenchmark(this.isOrderedInASCMode, this.groupID,this.benchmark, this.firstQuoteDate, this.lastQuoteDate, ! this.maxNumOfReturnedTickers, this.numDaysBetweenEachClose); else ! return QuantProject.Data.DataTables.Quotes.GetTickersByCloseToCloseCorrelationToBenchmark(this.isOrderedInASCMode, this.setOfTickersToBeSelected,this.benchmark, this.firstQuoteDate, this.lastQuoteDate, ! this.maxNumOfReturnedTickers, this.numDaysBetweenEachClose); } public void SelectAllTickers() { ; ! } } } --- 102,174 ---- { if(this.setOfTickersToBeSelected == null) ! return this.getTickersByCloseToCloseCorrelationToBenchmark(this.isOrderedInASCMode, this.groupID,this.benchmark, this.firstQuoteDate, this.lastQuoteDate, ! this.maxNumOfReturnedTickers); else ! return this.getTickersByCloseToCloseCorrelationToBenchmark(this.isOrderedInASCMode, this.setOfTickersToBeSelected,this.benchmark, this.firstQuoteDate, this.lastQuoteDate, ! this.maxNumOfReturnedTickers); } public void SelectAllTickers() { ; ! } ! ! private DataTable getTickersByCloseToCloseCorrelationToBenchmark( bool orderByASC, ! DataTable setOfTickers, string benchmark, ! DateTime firstQuoteDate, ! DateTime lastQuoteDate, ! long maxNumOfReturnedTickers) ! { ! if(!setOfTickers.Columns.Contains("CloseToCloseCorrelationToBenchmark")) ! setOfTickers.Columns.Add("CloseToCloseCorrelationToBenchmark", System.Type.GetType("System.Double")); ! float[] benchmarkQuotes = QuantProject.Data.DataTables.Quotes.GetArrayOfAdjustedCloseQuotes(benchmark, firstQuoteDate, lastQuoteDate); ! foreach(DataRow row in setOfTickers.Rows) ! { ! float[] tickerQuotes = QuantProject.Data.DataTables.Quotes.GetArrayOfAdjustedCloseQuotes((string)row[0], ! firstQuoteDate, lastQuoteDate); ! if(tickerQuotes.Length == benchmarkQuotes.Length) ! { ! if((string)row[0] == benchmark) ! row["CloseToCloseCorrelationToBenchmark"] = 1; ! else ! row["CloseToCloseCorrelationToBenchmark"] = ! BasicFunctions.PearsonCorrelationCoefficient(benchmarkQuotes, tickerQuotes); ! } ! ! } ! DataTable tableToReturn = ExtendedDataTable.CopyAndSort(setOfTickers, ! "CloseToCloseCorrelationToBenchmark>=0.0 OR " + ! "CloseToCloseCorrelationToBenchmark<0.0", ! "CloseToCloseCorrelationToBenchmark", ! orderByASC); ! ExtendedDataTable.DeleteRows(tableToReturn, maxNumOfReturnedTickers); ! if(this.addBenchmarkToTheGivenSetOfTickers) ! { ! DataRow newRow = tableToReturn.NewRow(); ! newRow[0] = benchmark; ! tableToReturn.Rows.Add(newRow); ! } ! return tableToReturn; ! } ! ! private DataTable getTickersByCloseToCloseCorrelationToBenchmark( bool orderByASC, ! string groupID, string benchmark, ! DateTime firstQuoteDate, ! DateTime lastQuoteDate, ! long maxNumOfReturnedTickers) ! { ! DataTable tickersOfGroup = Tickers_tickerGroups.GetTickers(groupID); ! return this.getTickersByCloseToCloseCorrelationToBenchmark(orderByASC, ! tickersOfGroup, benchmark, ! firstQuoteDate, ! lastQuoteDate, ! maxNumOfReturnedTickers); ! } ! ! } } |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:29:58
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT/Statistics In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv3845/b1_ADT/Statistics Modified Files: BasicFunctions.cs Log Message: Pearson correlation coefficient is computed within a unique FOR loop (and it should be faster, so) Index: BasicFunctions.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/Statistics/BasicFunctions.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** BasicFunctions.cs 3 Sep 2005 23:53:17 -0000 1.6 --- BasicFunctions.cs 2 Jul 2006 19:29:52 -0000 1.7 *************** *** 172,195 **** double[] secondDataVariable ) { BasicFunctions.checkLengthOfDataVariables(firstDataVariable, secondDataVariable); ! ! double stdDevOfFirst = BasicFunctions.StdDev(firstDataVariable); ! double stdDevOfSecond = BasicFunctions.StdDev(secondDataVariable); ! double coVariance = BasicFunctions.CoVariance(firstDataVariable, ! secondDataVariable); ! ! return (coVariance)/(stdDevOfFirst*stdDevOfSecond); } static public double PearsonCorrelationCoefficient( float[] firstDataVariable, float[] secondDataVariable ) { BasicFunctions.checkLengthOfDataVariables(firstDataVariable, secondDataVariable); ! double stdDevOfFirst = BasicFunctions.StdDev(firstDataVariable); ! double stdDevOfSecond = BasicFunctions.StdDev(secondDataVariable); ! double coVariance = BasicFunctions.CoVariance(firstDataVariable, ! secondDataVariable); ! ! return (coVariance)/(stdDevOfFirst*stdDevOfSecond); } --- 172,229 ---- double[] secondDataVariable ) { + // BasicFunctions.checkLengthOfDataVariables(firstDataVariable, secondDataVariable); + // + // double stdDevOfFirst = BasicFunctions.StdDev(firstDataVariable); + // double stdDevOfSecond = BasicFunctions.StdDev(secondDataVariable); + // double coVariance = BasicFunctions.CoVariance(firstDataVariable, + // secondDataVariable); + // + // return (coVariance)/(stdDevOfFirst*stdDevOfSecond); BasicFunctions.checkLengthOfDataVariables(firstDataVariable, secondDataVariable); ! int n = firstDataVariable.Length; ! double sumOfProduct = 0.0, sumOfFirst = 0.0, sumOfSecond = 0.0, ! sumOfSquaredFirst = 0.0, sumOfSquaredSecond = 0.0; ! for(int i = 0; i < n; i++) ! { ! sumOfFirst += firstDataVariable[i]; ! sumOfSecond += secondDataVariable[i]; ! sumOfProduct += firstDataVariable[i]*secondDataVariable[i]; ! sumOfSquaredFirst += firstDataVariable[i]*firstDataVariable[i]; ! sumOfSquaredSecond += secondDataVariable[i]*secondDataVariable[i]; ! } ! return (n*sumOfProduct - sumOfFirst*sumOfSecond)/ ! Math.Sqrt( (n*sumOfSquaredFirst - sumOfFirst*sumOfFirst)* ! (n*sumOfSquaredSecond - sumOfSecond*sumOfSecond) ); ! } static public double PearsonCorrelationCoefficient( float[] firstDataVariable, float[] secondDataVariable ) { + // OLD Computation way + // BasicFunctions.checkLengthOfDataVariables(firstDataVariable, secondDataVariable); + // + // double stdDevOfFirst = BasicFunctions.StdDev(firstDataVariable); + // double stdDevOfSecond = BasicFunctions.StdDev(secondDataVariable); + // double coVariance = BasicFunctions.CoVariance(firstDataVariable, + // secondDataVariable); + // + // return (coVariance)/(stdDevOfFirst*stdDevOfSecond); BasicFunctions.checkLengthOfDataVariables(firstDataVariable, secondDataVariable); + int n = firstDataVariable.Length; + double sumOfProduct = 0.0, sumOfFirst = 0.0, sumOfSecond = 0.0, + sumOfSquaredFirst = 0.0, sumOfSquaredSecond = 0.0; + for(int i = 0; i < n; i++) + { + sumOfFirst += firstDataVariable[i]; + sumOfSecond += secondDataVariable[i]; + sumOfProduct += firstDataVariable[i]*secondDataVariable[i]; + sumOfSquaredFirst += firstDataVariable[i]*firstDataVariable[i]; + sumOfSquaredSecond += secondDataVariable[i]*secondDataVariable[i]; + } + return (n*sumOfProduct - sumOfFirst*sumOfSecond)/ + Math.Sqrt( (n*sumOfSquaredFirst - sumOfFirst*sumOfFirst)* + (n*sumOfSquaredSecond - sumOfSecond*sumOfSecond) ); ! } |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:27:36
|
Update of /cvsroot/quantproject/QuantProject/b2_DataAccess In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv2880/b2_DataAccess Modified Files: ConnectionProvider.cs Log Message: Added a try catch block for a better error management Index: ConnectionProvider.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b2_DataAccess/ConnectionProvider.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** ConnectionProvider.cs 21 Mar 2004 16:16:51 -0000 1.4 --- ConnectionProvider.cs 2 Jul 2006 19:27:32 -0000 1.5 *************** *** 56,62 **** @";Jet OLEDB:Registry Path="""";Jet OLEDB:Database Password="""";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password="""";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False"; oleDbConnection = new OleDbConnection( connectionString ); ! oleDbConnection.Open(); ! DataBaseVersionManager dataBaseVersionManager = new DataBaseVersionManager(oleDbConnection); ! dataBaseVersionManager.UpdateDataBaseStructure(); } return oleDbConnection; --- 56,70 ---- @";Jet OLEDB:Registry Path="""";Jet OLEDB:Database Password="""";Jet OLEDB:Engine Type=5;Jet OLEDB:Database Locking Mode=1;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password="""";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don't Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False"; oleDbConnection = new OleDbConnection( connectionString ); ! try{ ! oleDbConnection.Open(); ! } ! catch(Exception ex) ! { ! System.Windows.Forms.MessageBox.Show(ex.ToString()); ! oleDbConnection = null; ! } ! DataBaseVersionManager dataBaseVersionManager = new DataBaseVersionManager(oleDbConnection); ! dataBaseVersionManager.UpdateDataBaseStructure(); ! } return oleDbConnection; |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:26:06
|
Update of /cvsroot/quantproject/QuantProject/b2_DataAccess In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv2038/b2_DataAccess Modified Files: DataBaseLocator.cs Log Message: Now the database.xml file is deleted automatically when path is not valid Index: DataBaseLocator.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b2_DataAccess/DataBaseLocator.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** DataBaseLocator.cs 10 Aug 2005 16:46:59 -0000 1.4 --- DataBaseLocator.cs 2 Jul 2006 19:26:02 -0000 1.5 *************** *** 62,68 **** //gets full path of the file that contains the database this.Path = xmlTextReader.GetAttribute(0); ! if(!File.Exists(this.path)) ! throw new Exception("Specified file in DataBase.xml doesn't exist!\n" + ! "Delete Database.xml and retry!"); } } --- 62,73 ---- //gets full path of the file that contains the database this.Path = xmlTextReader.GetAttribute(0); ! if(!File.Exists(this.path)) ! { ! xmlTextReader.Close(); ! stream.Close(); ! File.Delete(xmlPath); ! MessageBox.Show("Specified file in DataBase.xml doesn't exist!\n\n" + ! "Retry and select again Database.mdb."); ! } } } *************** *** 74,79 **** { MessageBox.Show(ex.ToString()); ! xmlTextReader.Close(); ! stream.Close(); } } --- 79,86 ---- { MessageBox.Show(ex.ToString()); ! if(xmlTextReader != null) ! xmlTextReader.Close(); ! if(this.stream != null) ! stream.Close(); } } |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:24:37
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv1485/b7_Scripts/WalkForwardTesting/LinearCombination Modified Files: OpenToCloseDailyStrategy.cs Log Message: The strategy now keeps on count tickers' weights Index: OpenToCloseDailyStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/OpenToCloseDailyStrategy.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** OpenToCloseDailyStrategy.cs 2 Aug 2005 23:08:32 -0000 1.1 --- OpenToCloseDailyStrategy.cs 2 Jul 2006 19:24:33 -0000 1.2 *************** *** 40,67 **** private Account account; private string[] signedTickers; public OpenToCloseDailyStrategy( Account account , ! string[] signedTickers) { this.account = account; this.signedTickers = signedTickers; } private long marketOpenEventHandler_addOrder_getQuantity( ! string ticker ) { double accountValue = this.account.GetMarketValue(); double currentTickerAsk = ! this.account.DataStreamer.GetCurrentAsk( ticker ); double maxPositionValueForThisTicker = ! accountValue/this.signedTickers.Length; long quantity = Convert.ToInt64( Math.Floor( maxPositionValueForThisTicker / currentTickerAsk ) ); return quantity; } ! private void marketOpenEventHandler_addOrder( string signedTicker ) { ! OrderType orderType = GenomeRepresentation.GetOrderType( signedTicker ); ! string ticker = GenomeRepresentation.GetTicker( signedTicker ); ! long quantity = marketOpenEventHandler_addOrder_getQuantity( ticker ); Order order = new Order( orderType , new Instrument( ticker ) , quantity ); --- 40,69 ---- private Account account; private string[] signedTickers; + private double[] weightsForSignedTickers; public OpenToCloseDailyStrategy( Account account , ! string[] signedTickers, double[] weightsForSignedTickers) { this.account = account; this.signedTickers = signedTickers; + this.weightsForSignedTickers = weightsForSignedTickers; } private long marketOpenEventHandler_addOrder_getQuantity( ! int indexForSignedTicker ) { double accountValue = this.account.GetMarketValue(); double currentTickerAsk = ! this.account.DataStreamer.GetCurrentAsk( SignedTicker.GetTicker(this.signedTickers[indexForSignedTicker]) ); double maxPositionValueForThisTicker = ! accountValue*this.weightsForSignedTickers[indexForSignedTicker]; long quantity = Convert.ToInt64( Math.Floor( maxPositionValueForThisTicker / currentTickerAsk ) ); return quantity; } ! private void marketOpenEventHandler_addOrder( int indexForSignedTicker ) { ! OrderType orderType = GenomeRepresentation.GetOrderType( this.signedTickers[indexForSignedTicker] ); ! string ticker = GenomeRepresentation.GetTicker( this.signedTickers[indexForSignedTicker] ); ! long quantity = marketOpenEventHandler_addOrder_getQuantity( indexForSignedTicker ); Order order = new Order( orderType , new Instrument( ticker ) , quantity ); *************** *** 70,75 **** private void marketOpenEventHandler_addOrders() { ! foreach ( string signedTicker in this.signedTickers ) ! marketOpenEventHandler_addOrder( signedTicker ); } public void MarketOpenEventHandler( --- 72,77 ---- private void marketOpenEventHandler_addOrders() { ! for(int i = 0; i<this.signedTickers.Length; i++) ! marketOpenEventHandler_addOrder( i ); } public void MarketOpenEventHandler( |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:22:16
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv521/b7_Scripts/WalkForwardTesting/LinearCombination Modified Files: TestDisplayer.cs StrategyType.cs LinearCombinationTest.cs GenomeRepresentation.cs FixedPeriodOscillatorStrategy.cs ExtremeCounterTrendStrategy.cs Added Files: OTC_CTODailyStrategy.cs Log Message: Added OTC_CTO strategy for the genome form displayer. Updated other file strategies for the displayer. Index: ExtremeCounterTrendStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/ExtremeCounterTrendStrategy.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ExtremeCounterTrendStrategy.cs 14 May 2006 18:13:17 -0000 1.1 --- ExtremeCounterTrendStrategy.cs 2 Jul 2006 19:22:12 -0000 1.2 *************** *** 43,46 **** --- 43,47 ---- private Account account; private string[] signedTickers; + private double[] weightsForSignedTickers; private int numDaysForReturnCalculation; private int numOfClosesElapsed = 0; *************** *** 48,56 **** public ExtremeCounterTrendStrategy( Account account , ! string[] signedTickers, int numDaysForReturnCalculation) { this.account = account; this.signedTickers = signedTickers; this.numDaysForReturnCalculation = numDaysForReturnCalculation; } --- 49,59 ---- public ExtremeCounterTrendStrategy( Account account , ! string[] signedTickers, ! double[] weightsForSignedTickers, int numDaysForReturnCalculation) { this.account = account; this.signedTickers = signedTickers; + this.weightsForSignedTickers = weightsForSignedTickers; this.numDaysForReturnCalculation = numDaysForReturnCalculation; } *************** *** 67,86 **** private long marketCloseEventHandler_addOrder_getQuantity( ! string ticker ) { double accountValue = this.account.GetMarketValue(); double currentTickerAsk = ! this.account.DataStreamer.GetCurrentAsk( ticker ); double maxPositionValueForThisTicker = ! accountValue/this.signedTickers.Length; long quantity = Convert.ToInt64( Math.Floor( maxPositionValueForThisTicker / currentTickerAsk ) ); return quantity; } ! private void marketCloseEventHandler_addOrder( string signedTicker ) { ! OrderType orderType = GenomeRepresentation.GetOrderType( signedTicker ); ! string ticker = GenomeRepresentation.GetTicker( signedTicker ); ! long quantity = marketCloseEventHandler_addOrder_getQuantity( ticker ); Order order = new Order( orderType , new Instrument( ticker ) , quantity ); --- 70,89 ---- private long marketCloseEventHandler_addOrder_getQuantity( ! int indexForSignedTicker) { double accountValue = this.account.GetMarketValue(); double currentTickerAsk = ! this.account.DataStreamer.GetCurrentAsk( SignedTicker.GetTicker(this.signedTickers[indexForSignedTicker]) ); double maxPositionValueForThisTicker = ! accountValue*this.weightsForSignedTickers[indexForSignedTicker]; long quantity = Convert.ToInt64( Math.Floor( maxPositionValueForThisTicker / currentTickerAsk ) ); return quantity; } ! private void marketCloseEventHandler_addOrder( int indexForSignedTicker ) { ! OrderType orderType = GenomeRepresentation.GetOrderType( this.signedTickers[indexForSignedTicker] ); ! string ticker = GenomeRepresentation.GetTicker( this.signedTickers[indexForSignedTicker] ); ! long quantity = marketCloseEventHandler_addOrder_getQuantity( indexForSignedTicker ); Order order = new Order( orderType , new Instrument( ticker ) , quantity ); *************** *** 89,94 **** private void marketCloseEventHandler_addOrders() { ! foreach ( string signedTicker in this.signedTickers ) ! marketCloseEventHandler_addOrder( signedTicker ); } --- 92,97 ---- private void marketCloseEventHandler_addOrders() { ! for(int i = 0; i<this.signedTickers.Length; i++) ! marketCloseEventHandler_addOrder( i ); } --- NEW FILE: OTC_CTODailyStrategy.cs --- /* QuantProject - Quantitative Finance Library OTC_CTODailyStrategy.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.Collections; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Strategies; using QuantProject.Business.Timing; namespace QuantProject.Scripts.WalkForwardTesting.LinearCombination { /// <summary> /// Open to close - Close to open daily strategy /// </summary> [Serializable] public class OTC_CTODailyStrategy : IEndOfDayStrategy { private Account account; private string[] signedTickers; private double[] weightsForSignedTickers; public OTC_CTODailyStrategy( Account account , string[] signedTickers, double[] weightsForSignedTickers) { this.account = account; this.signedTickers = signedTickers; this.weightsForSignedTickers = weightsForSignedTickers; } private long addOrders_addOrder_getQuantity( int indexForSignedTicker ) { double accountValue = this.account.GetMarketValue(); double currentTickerAsk = this.account.DataStreamer.GetCurrentAsk( SignedTicker.GetTicker(this.signedTickers[indexForSignedTicker]) ); double maxPositionValueForThisTicker = accountValue*this.weightsForSignedTickers[indexForSignedTicker]; long quantity = Convert.ToInt64( Math.Floor( maxPositionValueForThisTicker / currentTickerAsk ) ); return quantity; } private void addOrders_addOrder( int indexForSignedTicker ) { OrderType orderType = GenomeRepresentation.GetOrderType( this.signedTickers[indexForSignedTicker] ); string ticker = GenomeRepresentation.GetTicker( this.signedTickers[indexForSignedTicker] ); long quantity = addOrders_addOrder_getQuantity( indexForSignedTicker ); Order order = new Order( orderType , new Instrument( ticker ) , quantity ); this.account.AddOrder( order ); } private void addOrders() { for(int i = 0; i<this.signedTickers.Length; i++) this.addOrders_addOrder( i ); } public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { this.closePositions(); if ( ( this.account.CashAmount == 0 ) && ( this.account.Transactions.Count == 0 ) ) // cash has not been added yet this.account.AddCash( 30000 ); this.addOrders(); } private void closePositions() { ArrayList tickers = new ArrayList(); foreach ( Position position in this.account.Portfolio.Positions ) tickers.Add( position.Instrument.Key ); foreach ( string ticker in tickers ) this.account.ClosePosition( ticker ); } public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { } public void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { this.closePositions(); SignedTicker.ChangeSignOfEachTicker(this.signedTickers); this.addOrders(); SignedTicker.ChangeSignOfEachTicker(this.signedTickers); } public void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { } } } Index: FixedPeriodOscillatorStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/FixedPeriodOscillatorStrategy.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** FixedPeriodOscillatorStrategy.cs 14 May 2006 18:13:17 -0000 1.1 --- FixedPeriodOscillatorStrategy.cs 2 Jul 2006 19:22:12 -0000 1.2 *************** *** 41,44 **** --- 41,45 ---- private Account account; private string[] signedTickers; + private double[] weightsForSignedTickers; private int daysForRightPeriod; private int daysForReversalPeriod; *************** *** 51,55 **** public FixedPeriodOscillatorStrategy( Account account , ! string[] signedTickers, int daysForRightPeriod, int daysForReversalPeriod) --- 52,57 ---- public FixedPeriodOscillatorStrategy( Account account , ! string[] signedTickers, ! double[] weightsForSignedTickers, int daysForRightPeriod, int daysForReversalPeriod) *************** *** 57,80 **** this.account = account; this.signedTickers = signedTickers; this.daysForRightPeriod = daysForRightPeriod; this.daysForReversalPeriod = daysForReversalPeriod; } private long marketCloseEventHandler_addOrder_getQuantity( ! string ticker ) { double accountValue = this.account.GetMarketValue(); double currentTickerAsk = ! this.account.DataStreamer.GetCurrentAsk( ticker ); double maxPositionValueForThisTicker = ! accountValue/this.signedTickers.Length; long quantity = Convert.ToInt64( Math.Floor( maxPositionValueForThisTicker / currentTickerAsk ) ); return quantity; } ! private void marketCloseEventHandler_addOrder( string signedTicker ) { ! OrderType orderType = GenomeRepresentation.GetOrderType( signedTicker ); ! string ticker = GenomeRepresentation.GetTicker( signedTicker ); ! long quantity = marketCloseEventHandler_addOrder_getQuantity( ticker ); Order order = new Order( orderType , new Instrument( ticker ) , quantity ); --- 59,83 ---- this.account = account; this.signedTickers = signedTickers; + this.weightsForSignedTickers = weightsForSignedTickers; this.daysForRightPeriod = daysForRightPeriod; this.daysForReversalPeriod = daysForReversalPeriod; } private long marketCloseEventHandler_addOrder_getQuantity( ! int indexForSignedTicker) { double accountValue = this.account.GetMarketValue(); double currentTickerAsk = ! this.account.DataStreamer.GetCurrentAsk( SignedTicker.GetTicker(this.signedTickers[indexForSignedTicker]) ); double maxPositionValueForThisTicker = ! accountValue*this.weightsForSignedTickers[indexForSignedTicker]; long quantity = Convert.ToInt64( Math.Floor( maxPositionValueForThisTicker / currentTickerAsk ) ); return quantity; } ! private void marketCloseEventHandler_addOrder( int indexForSignedTicker ) { ! OrderType orderType = GenomeRepresentation.GetOrderType( this.signedTickers[indexForSignedTicker] ); ! string ticker = GenomeRepresentation.GetTicker( this.signedTickers[indexForSignedTicker] ); ! long quantity = marketCloseEventHandler_addOrder_getQuantity( indexForSignedTicker ); Order order = new Order( orderType , new Instrument( ticker ) , quantity ); *************** *** 83,88 **** private void marketCloseEventHandler_addOrders() { ! foreach ( string signedTicker in this.signedTickers ) ! marketCloseEventHandler_addOrder( signedTicker ); } --- 86,91 ---- private void marketCloseEventHandler_addOrders() { ! for(int i = 0; i<this.signedTickers.Length; i++) ! marketCloseEventHandler_addOrder( i ); } Index: StrategyType.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/StrategyType.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** StrategyType.cs 14 May 2006 18:18:23 -0000 1.2 --- StrategyType.cs 2 Jul 2006 19:22:12 -0000 1.3 *************** *** 33,36 **** --- 33,37 ---- OpenToCloseWeekly, CloseToOpenDaily, + OpenToCloseCloseToOpenDaily, FixedPeriodOscillator, ExtremeCounterTrend Index: GenomeRepresentation.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/GenomeRepresentation.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** GenomeRepresentation.cs 23 Oct 2005 19:09:04 -0000 1.4 --- GenomeRepresentation.cs 2 Jul 2006 19:22:12 -0000 1.5 *************** *** 23,26 **** --- 23,27 ---- using System; + using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Business.Financial.Ordering; *************** *** 68,76 **** } ! public static string[] GetSignedTickers( string signedTickers ) { ! string[] returnValue = signedTickers.Split( ";".ToCharArray() ); return returnValue; } public static OrderType GetOrderType( string signedTicker ) { --- 69,117 ---- } ! // public static string[] GetSignedTickers( string signedTickers ) ! // { ! // string[] returnValue = signedTickers.Split( ";".ToCharArray()); ! // return returnValue; ! // } ! ! public static string[] GetSignedTickers( string signedTickersWithWeights ) { ! string[] returnValue = ! signedTickersWithWeights.Split( ConstantsProvider.SeparatorForTickers.ToCharArray()); ! if( signedTickersWithWeights.Split( ConstantsProvider.SeparatorForWeights.ToCharArray() ).Length > 1 ) ! //the separator char for tickers is contained in signedTickersWithWeights: ! //so weights have been saved within tickers, separated by this special char ! { ! for(int i = 0; i<returnValue.Length; i++) ! { ! returnValue[i] = ! returnValue[i].Split( ConstantsProvider.SeparatorForWeights.ToCharArray() )[0]; ! } ! } ! return returnValue; ! } ! ! public static double[] GetWeightsForSignedTickers( string signedTickersWithWeights ) ! { ! string[] signedTickersWithWeightsArray = ! signedTickersWithWeights.Split( ConstantsProvider.SeparatorForTickers.ToCharArray() ); ! double[] returnValue = ! new double[signedTickersWithWeightsArray.Length]; ! for(int i = 0; i<returnValue.Length; i++) ! returnValue[i] = 1.0/returnValue.Length; ! ! if((signedTickersWithWeights.Split(ConstantsProvider.SeparatorForWeights.ToCharArray())).Length > 1) ! //the separator for weights is contained in signedTickersWithWeights: ! //so weights have been saved within tickers, separated by this char ! { ! for(int i = 0; i<returnValue.Length; i++) ! { ! returnValue[i] = ! Convert.ToDouble( signedTickersWithWeightsArray[i].Split( ConstantsProvider.SeparatorForWeights.ToCharArray() )[1] ); ! } ! } return returnValue; } + public static OrderType GetOrderType( string signedTicker ) { *************** *** 91,94 **** --- 132,136 ---- return returnValue; } + private string getSignedTickers( Genome genome ) { *************** *** 100,103 **** --- 142,162 ---- return signedTickers; } + private string getSignedTickersWithWeights( Genome genome ) + { + string signedTickersWithWeights = ""; + for ( int i = 0; i<((GenomeMeaning)genome.Meaning).Tickers.Length; i++ ) + { + signedTickersWithWeights += + ((GenomeMeaning)genome.Meaning).Tickers[i] + + ConstantsProvider.SeparatorForWeights + + ((GenomeMeaning)genome.Meaning).TickersPortfolioWeights[i] + + ConstantsProvider.SeparatorForTickers; + } + signedTickersWithWeights = signedTickersWithWeights.Substring( 0 , + signedTickersWithWeights.Length - 1 ); + + return signedTickersWithWeights; + } + private void genomeRepresentation( Genome genome , DateTime firstOptimizationDate , DateTime lastOptimizationDate , *************** *** 105,109 **** { this.fitness = genome.Fitness; ! this.signedTickers = this.getSignedTickers( genome ); this.firstOptimizationDate = firstOptimizationDate; this.lastOptimizationDate = lastOptimizationDate; --- 164,169 ---- { this.fitness = genome.Fitness; ! this.signedTickers = this.getSignedTickersWithWeights( genome ); ! //this.signedTickers = this.getSignedTickers( genome ); this.firstOptimizationDate = firstOptimizationDate; this.lastOptimizationDate = lastOptimizationDate; Index: LinearCombinationTest.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/LinearCombinationTest.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** LinearCombinationTest.cs 14 May 2006 18:18:23 -0000 1.6 --- LinearCombinationTest.cs 2 Jul 2006 19:22:12 -0000 1.7 *************** *** 94,102 **** string[] signedTickers = GenomeRepresentation.GetSignedTickers( this.genomeRepresentation.SignedTickers ); switch (this.strategyType) { case StrategyType.OpenToCloseDaily: this.endOfDayStrategy = new OpenToCloseDailyStrategy( ! this.account , signedTickers ); break; case StrategyType.OpenToCloseWeekly: --- 94,105 ---- string[] signedTickers = GenomeRepresentation.GetSignedTickers( this.genomeRepresentation.SignedTickers ); + double[] weightsForSignedTickers = GenomeRepresentation.GetWeightsForSignedTickers( + this.genomeRepresentation.SignedTickers ); switch (this.strategyType) { case StrategyType.OpenToCloseDaily: this.endOfDayStrategy = new OpenToCloseDailyStrategy( ! this.account , signedTickers, ! weightsForSignedTickers ); break; case StrategyType.OpenToCloseWeekly: *************** *** 109,120 **** break; case StrategyType.FixedPeriodOscillator: this.endOfDayStrategy = new FixedPeriodOscillatorStrategy( ! this.account , signedTickers , this.numDaysForOscillatorStrategy , this.numDaysForOscillatorStrategy ); break; case StrategyType.ExtremeCounterTrend: this.endOfDayStrategy = new ExtremeCounterTrendStrategy( ! this.account , signedTickers , this.numDaysForOscillatorStrategy ); break; } --- 112,130 ---- break; + case StrategyType.OpenToCloseCloseToOpenDaily: + this.endOfDayStrategy = new OTC_CTODailyStrategy( + this.account , signedTickers , weightsForSignedTickers); + break; + case StrategyType.FixedPeriodOscillator: this.endOfDayStrategy = new FixedPeriodOscillatorStrategy( ! this.account , signedTickers , weightsForSignedTickers, ! this.numDaysForOscillatorStrategy , ! this.numDaysForOscillatorStrategy ); break; case StrategyType.ExtremeCounterTrend: this.endOfDayStrategy = new ExtremeCounterTrendStrategy( ! this.account , signedTickers , weightsForSignedTickers, this.numDaysForOscillatorStrategy ); break; } Index: TestDisplayer.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/TestDisplayer.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** TestDisplayer.cs 14 May 2006 18:18:23 -0000 1.7 --- TestDisplayer.cs 2 Jul 2006 19:22:12 -0000 1.8 *************** *** 36,46 **** { private System.Windows.Forms.Label labelDays; ! private System.Windows.Forms.TextBox textBoxDaysFPOscillatorAndRevOneRank; ! private System.Windows.Forms.Label label1; private System.Windows.Forms.RadioButton radioButtonOpenToCloseDaily; private System.Windows.Forms.RadioButton radioButtonReversalOneRank; private System.Windows.Forms.DateTimePicker dtpLastDate; private System.Windows.Forms.DateTimePicker dtpFirstDate; ! private System.Windows.Forms.RadioButton radioButtonFixedPeriodOscillator; private System.Windows.Forms.RadioButton radioButtonOpenToCloseWeekly; private System.Windows.Forms.RadioButton radioButtonCloseToOpenDaily; --- 36,46 ---- { private System.Windows.Forms.Label labelDays; ! private System.Windows.Forms.RadioButton radioButtonFixedPeriodOscillator; private System.Windows.Forms.RadioButton radioButtonOpenToCloseDaily; private System.Windows.Forms.RadioButton radioButtonReversalOneRank; private System.Windows.Forms.DateTimePicker dtpLastDate; + private System.Windows.Forms.Label label1; private System.Windows.Forms.DateTimePicker dtpFirstDate; ! private System.Windows.Forms.TextBox textBoxDaysFPOscillatorAndRevOneRank; private System.Windows.Forms.RadioButton radioButtonOpenToCloseWeekly; private System.Windows.Forms.RadioButton radioButtonCloseToOpenDaily; *************** *** 54,57 **** --- 54,58 ---- private ArrayList bestGenomes; private GenomeRepresentation lastSelectedGenomeRepresentation; + private System.Windows.Forms.RadioButton radioButtonOTCCTODaily; private StrategyType selectedStrategyType = StrategyType.OpenToCloseDaily; *************** *** 103,234 **** /// </summary> private void InitializeComponent() { ! this.dgBestGenomes = new System.Windows.Forms.DataGrid(); ! this.radioButtonCloseToOpenDaily = new System.Windows.Forms.RadioButton(); ! this.radioButtonOpenToCloseWeekly = new System.Windows.Forms.RadioButton(); ! this.radioButtonFixedPeriodOscillator = new System.Windows.Forms.RadioButton(); ! this.dtpFirstDate = new System.Windows.Forms.DateTimePicker(); ! this.dtpLastDate = new System.Windows.Forms.DateTimePicker(); ! this.radioButtonReversalOneRank = new System.Windows.Forms.RadioButton(); ! this.radioButtonOpenToCloseDaily = new System.Windows.Forms.RadioButton(); ! this.label1 = new System.Windows.Forms.Label(); ! this.textBoxDaysFPOscillatorAndRevOneRank = new System.Windows.Forms.TextBox(); ! this.labelDays = new System.Windows.Forms.Label(); ! ((System.ComponentModel.ISupportInitialize)(this.dgBestGenomes)).BeginInit(); ! this.SuspendLayout(); ! // ! // dgBestGenomes ! // ! this.dgBestGenomes.DataMember = ""; ! this.dgBestGenomes.Dock = System.Windows.Forms.DockStyle.Bottom; ! this.dgBestGenomes.HeaderForeColor = System.Drawing.SystemColors.ControlText; ! this.dgBestGenomes.Location = new System.Drawing.Point(0, 205); ! this.dgBestGenomes.Name = "dgBestGenomes"; ! this.dgBestGenomes.Size = new System.Drawing.Size(584, 168); ! this.dgBestGenomes.TabIndex = 0; ! this.dgBestGenomes.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dgBestGenomes_MouseUp); ! // ! // radioButtonCloseToOpenDaily ! // ! this.radioButtonCloseToOpenDaily.Location = new System.Drawing.Point(64, 120); ! this.radioButtonCloseToOpenDaily.Name = "radioButtonCloseToOpenDaily"; ! this.radioButtonCloseToOpenDaily.Size = new System.Drawing.Size(144, 24); ! this.radioButtonCloseToOpenDaily.TabIndex = 6; ! this.radioButtonCloseToOpenDaily.Text = "Close To Open Daily"; ! this.radioButtonCloseToOpenDaily.CheckedChanged += new System.EventHandler(this.radioButtonCloseToOpenDaily_CheckedChanged); ! // ! // radioButtonOpenToCloseWeekly ! // ! this.radioButtonOpenToCloseWeekly.Location = new System.Drawing.Point(64, 144); ! this.radioButtonOpenToCloseWeekly.Name = "radioButtonOpenToCloseWeekly"; ! this.radioButtonOpenToCloseWeekly.Size = new System.Drawing.Size(144, 24); ! this.radioButtonOpenToCloseWeekly.TabIndex = 5; ! this.radioButtonOpenToCloseWeekly.Text = "Open To Close Weekly"; ! this.radioButtonOpenToCloseWeekly.CheckedChanged += new System.EventHandler(this.radioButtonOpenToCloseWeekly_CheckedChanged); ! // ! // radioButtonFixedPeriodOscillator ! // ! this.radioButtonFixedPeriodOscillator.Location = new System.Drawing.Point(232, 96); ! this.radioButtonFixedPeriodOscillator.Name = "radioButtonFixedPeriodOscillator"; ! this.radioButtonFixedPeriodOscillator.Size = new System.Drawing.Size(192, 24); ! this.radioButtonFixedPeriodOscillator.TabIndex = 7; ! this.radioButtonFixedPeriodOscillator.Text = "Fixed Period n-days oscillator"; ! this.radioButtonFixedPeriodOscillator.CheckedChanged += new System.EventHandler(this.radioButtonFixedPeriodOscillator_CheckedChanged); ! // ! // dtpFirstDate ! // ! this.dtpFirstDate.Location = new System.Drawing.Point(16, 24); ! this.dtpFirstDate.Name = "dtpFirstDate"; ! this.dtpFirstDate.TabIndex = 1; ! // ! // dtpLastDate ! // ! this.dtpLastDate.Location = new System.Drawing.Point(264, 24); ! this.dtpLastDate.Name = "dtpLastDate"; ! this.dtpLastDate.Size = new System.Drawing.Size(208, 21); ! this.dtpLastDate.TabIndex = 2; ! // ! // radioButtonReversalOneRank ! // ! this.radioButtonReversalOneRank.Location = new System.Drawing.Point(232, 120); ! this.radioButtonReversalOneRank.Name = "radioButtonReversalOneRank"; ! this.radioButtonReversalOneRank.Size = new System.Drawing.Size(192, 24); ! this.radioButtonReversalOneRank.TabIndex = 10; ! this.radioButtonReversalOneRank.Text = "Extreme counter trend"; ! this.radioButtonReversalOneRank.CheckedChanged += new System.EventHandler(this.radioButtonReversalOneRank_CheckedChanged); ! // ! // radioButtonOpenToCloseDaily ! // ! this.radioButtonOpenToCloseDaily.Location = new System.Drawing.Point(64, 96); ! this.radioButtonOpenToCloseDaily.Name = "radioButtonOpenToCloseDaily"; ! this.radioButtonOpenToCloseDaily.Size = new System.Drawing.Size(144, 24); ! this.radioButtonOpenToCloseDaily.TabIndex = 4; ! this.radioButtonOpenToCloseDaily.Text = "Open To Close Daily"; ! this.radioButtonOpenToCloseDaily.CheckedChanged += new System.EventHandler(this.radioButtonOpenToCloseDaily_CheckedChanged); ! // ! // label1 ! // ! this.label1.Location = new System.Drawing.Point(32, 64); ! this.label1.Name = "label1"; ! this.label1.Size = new System.Drawing.Size(400, 40); ! this.label1.TabIndex = 3; ! this.label1.Text = "Left click data grid rows to reset dates to the optimization period. Right click " + ! "to preserve date displacements and backtest."; ! // ! // textBoxDaysFPOscillatorAndRevOneRank ! // ! this.textBoxDaysFPOscillatorAndRevOneRank.Location = new System.Drawing.Point(320, 152); ! this.textBoxDaysFPOscillatorAndRevOneRank.Name = "textBoxDaysFPOscillatorAndRevOneRank"; ! this.textBoxDaysFPOscillatorAndRevOneRank.Size = new System.Drawing.Size(56, 21); ! this.textBoxDaysFPOscillatorAndRevOneRank.TabIndex = 8; ! this.textBoxDaysFPOscillatorAndRevOneRank.Text = ""; ! // ! // labelDays ! // ! this.labelDays.Location = new System.Drawing.Point(272, 152); ! this.labelDays.Name = "labelDays"; ! this.labelDays.Size = new System.Drawing.Size(40, 16); ! this.labelDays.TabIndex = 9; ! this.labelDays.Text = "days"; ! // ! // TestDisplayer ! // ! this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); ! this.ClientSize = new System.Drawing.Size(584, 373); ! this.Controls.Add(this.radioButtonReversalOneRank); ! this.Controls.Add(this.labelDays); ! this.Controls.Add(this.textBoxDaysFPOscillatorAndRevOneRank); ! this.Controls.Add(this.radioButtonFixedPeriodOscillator); ! this.Controls.Add(this.radioButtonCloseToOpenDaily); ! this.Controls.Add(this.radioButtonOpenToCloseWeekly); ! this.Controls.Add(this.radioButtonOpenToCloseDaily); ! this.Controls.Add(this.label1); ! this.Controls.Add(this.dtpLastDate); ! this.Controls.Add(this.dtpFirstDate); ! this.Controls.Add(this.dgBestGenomes); ! this.Name = "TestDisplayer"; ! this.Text = "TestDisplayer"; ! ((System.ComponentModel.ISupportInitialize)(this.dgBestGenomes)).EndInit(); ! this.ResumeLayout(false); ! } #endregion --- 104,247 ---- /// </summary> private void InitializeComponent() { ! this.dgBestGenomes = new System.Windows.Forms.DataGrid(); ! this.radioButtonCloseToOpenDaily = new System.Windows.Forms.RadioButton(); ! this.radioButtonOpenToCloseWeekly = new System.Windows.Forms.RadioButton(); ! this.textBoxDaysFPOscillatorAndRevOneRank = new System.Windows.Forms.TextBox(); ! this.dtpFirstDate = new System.Windows.Forms.DateTimePicker(); ! this.label1 = new System.Windows.Forms.Label(); ! this.dtpLastDate = new System.Windows.Forms.DateTimePicker(); ! this.radioButtonReversalOneRank = new System.Windows.Forms.RadioButton(); ! this.radioButtonOpenToCloseDaily = new System.Windows.Forms.RadioButton(); ! this.radioButtonFixedPeriodOscillator = new System.Windows.Forms.RadioButton(); ! this.labelDays = new System.Windows.Forms.Label(); ! this.radioButtonOTCCTODaily = new System.Windows.Forms.RadioButton(); ! ((System.ComponentModel.ISupportInitialize)(this.dgBestGenomes)).BeginInit(); ! this.SuspendLayout(); ! // ! // dgBestGenomes ! // ! this.dgBestGenomes.DataMember = ""; ! this.dgBestGenomes.Dock = System.Windows.Forms.DockStyle.Bottom; ! this.dgBestGenomes.HeaderForeColor = System.Drawing.SystemColors.ControlText; ! this.dgBestGenomes.Location = new System.Drawing.Point(0, 205); ! this.dgBestGenomes.Name = "dgBestGenomes"; ! this.dgBestGenomes.Size = new System.Drawing.Size(584, 168); ! this.dgBestGenomes.TabIndex = 0; ! this.dgBestGenomes.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dgBestGenomes_MouseUp); ! // ! // radioButtonCloseToOpenDaily ! // ! this.radioButtonCloseToOpenDaily.Location = new System.Drawing.Point(64, 120); ! this.radioButtonCloseToOpenDaily.Name = "radioButtonCloseToOpenDaily"; ! this.radioButtonCloseToOpenDaily.Size = new System.Drawing.Size(144, 24); ! this.radioButtonCloseToOpenDaily.TabIndex = 6; ! this.radioButtonCloseToOpenDaily.Text = "Close To Open Daily"; ! this.radioButtonCloseToOpenDaily.CheckedChanged += new System.EventHandler(this.radioButtonCloseToOpenDaily_CheckedChanged); ! // ! // radioButtonOpenToCloseWeekly ! // ! this.radioButtonOpenToCloseWeekly.Location = new System.Drawing.Point(64, 144); ! this.radioButtonOpenToCloseWeekly.Name = "radioButtonOpenToCloseWeekly"; ! this.radioButtonOpenToCloseWeekly.Size = new System.Drawing.Size(144, 24); ! this.radioButtonOpenToCloseWeekly.TabIndex = 5; ! this.radioButtonOpenToCloseWeekly.Text = "Open To Close Weekly"; ! this.radioButtonOpenToCloseWeekly.CheckedChanged += new System.EventHandler(this.radioButtonOpenToCloseWeekly_CheckedChanged); ! // ! // textBoxDaysFPOscillatorAndRevOneRank ! // ! this.textBoxDaysFPOscillatorAndRevOneRank.Location = new System.Drawing.Point(320, 152); ! this.textBoxDaysFPOscillatorAndRevOneRank.Name = "textBoxDaysFPOscillatorAndRevOneRank"; ! this.textBoxDaysFPOscillatorAndRevOneRank.Size = new System.Drawing.Size(56, 20); ! this.textBoxDaysFPOscillatorAndRevOneRank.TabIndex = 8; ! this.textBoxDaysFPOscillatorAndRevOneRank.Text = "1"; ! // ! // dtpFirstDate ! // ! this.dtpFirstDate.Location = new System.Drawing.Point(16, 24); ! this.dtpFirstDate.Name = "dtpFirstDate"; ! this.dtpFirstDate.TabIndex = 1; ! // ! // label1 ! // ! this.label1.Location = new System.Drawing.Point(32, 64); ! this.label1.Name = "label1"; ! this.label1.Size = new System.Drawing.Size(400, 40); ! this.label1.TabIndex = 3; ! this.label1.Text = "Left click data grid rows to reset dates to the optimization period. Right click " + ! "to preserve date displacements and backtest."; ! // ! // dtpLastDate ! // ! this.dtpLastDate.Location = new System.Drawing.Point(264, 24); ! this.dtpLastDate.Name = "dtpLastDate"; ! this.dtpLastDate.Size = new System.Drawing.Size(208, 20); ! this.dtpLastDate.TabIndex = 2; ! // ! // radioButtonReversalOneRank ! // ! this.radioButtonReversalOneRank.Location = new System.Drawing.Point(232, 120); ! this.radioButtonReversalOneRank.Name = "radioButtonReversalOneRank"; ! this.radioButtonReversalOneRank.Size = new System.Drawing.Size(192, 24); ! this.radioButtonReversalOneRank.TabIndex = 10; ! this.radioButtonReversalOneRank.Text = "Extreme counter trend"; ! this.radioButtonReversalOneRank.CheckedChanged += new System.EventHandler(this.radioButtonReversalOneRank_CheckedChanged); ! // ! // radioButtonOpenToCloseDaily ! // ! this.radioButtonOpenToCloseDaily.Location = new System.Drawing.Point(64, 96); ! this.radioButtonOpenToCloseDaily.Name = "radioButtonOpenToCloseDaily"; ! this.radioButtonOpenToCloseDaily.Size = new System.Drawing.Size(144, 24); ! this.radioButtonOpenToCloseDaily.TabIndex = 4; ! this.radioButtonOpenToCloseDaily.Text = "Open To Close Daily"; ! this.radioButtonOpenToCloseDaily.CheckedChanged += new System.EventHandler(this.radioButtonOpenToCloseDaily_CheckedChanged); ! // ! // radioButtonFixedPeriodOscillator ! // ! this.radioButtonFixedPeriodOscillator.Location = new System.Drawing.Point(232, 96); ! this.radioButtonFixedPeriodOscillator.Name = "radioButtonFixedPeriodOscillator"; ! this.radioButtonFixedPeriodOscillator.Size = new System.Drawing.Size(192, 24); ! this.radioButtonFixedPeriodOscillator.TabIndex = 7; ! this.radioButtonFixedPeriodOscillator.Text = "Fixed Period n-days oscillator"; ! this.radioButtonFixedPeriodOscillator.CheckedChanged += new System.EventHandler(this.radioButtonFixedPeriodOscillator_CheckedChanged); ! // ! // labelDays ! // ! this.labelDays.Location = new System.Drawing.Point(272, 152); ! this.labelDays.Name = "labelDays"; ! this.labelDays.Size = new System.Drawing.Size(40, 16); ! this.labelDays.TabIndex = 9; ! this.labelDays.Text = "days"; ! // ! // radioButtonOTCCTODaily ! // ! this.radioButtonOTCCTODaily.Location = new System.Drawing.Point(64, 168); ! this.radioButtonOTCCTODaily.Name = "radioButtonOTCCTODaily"; ! this.radioButtonOTCCTODaily.Size = new System.Drawing.Size(144, 24); ! this.radioButtonOTCCTODaily.TabIndex = 11; ! this.radioButtonOTCCTODaily.Text = "OTC - CTO Daily"; ! // ! // TestDisplayer ! // ! this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); ! this.ClientSize = new System.Drawing.Size(584, 373); ! this.Controls.AddRange(new System.Windows.Forms.Control[] { ! this.radioButtonOTCCTODaily, ! this.radioButtonReversalOneRank, ! this.labelDays, ! this.textBoxDaysFPOscillatorAndRevOneRank, ! this.radioButtonFixedPeriodOscillator, ! this.radioButtonCloseToOpenDaily, ! this.radioButtonOpenToCloseWeekly, ! this.radioButtonOpenToCloseDaily, ! this.label1, ! this.dtpLastDate, ! this.dtpFirstDate, ! this.dgBestGenomes}); ! this.Name = "TestDisplayer"; ! this.Text = "TestDisplayer"; ! ((System.ComponentModel.ISupportInitialize)(this.dgBestGenomes)).EndInit(); ! this.ResumeLayout(false); ! ! } #endregion *************** *** 323,326 **** --- 336,341 ---- else if(this.radioButtonReversalOneRank.Checked) this.selectedStrategyType = StrategyType.ExtremeCounterTrend; + else if(this.radioButtonOTCCTODaily.Checked) + this.selectedStrategyType = StrategyType.OpenToCloseCloseToOpenDaily; } |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:18:17
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv31166/b7_Scripts/TickerSelectionTesting Added Files: GenomeManagerForEfficientOTCCTOPortfolio.cs Log Message: Added GenomeManagerForEfficientOTCCTOPortfolio --- NEW FILE: GenomeManagerForEfficientOTCCTOPortfolio.cs --- /* QuantProject - Quantitative Finance Library GenomeManagerForEfficientOTCCTOPortfolio.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.Statistics; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Data; using QuantProject.Data.DataTables; namespace QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios { /// <summary> /// This class implements IGenomeManager, in order to find efficient /// portfolios based on the OTC and CTO strategy, using the /// GeneticOptimizer /// </summary> [Serializable] public class GenomeManagerForEfficientOTCCTOPortfolio : GenomeManagerForWeightedEfficientPortfolio { public GenomeManagerForEfficientOTCCTOPortfolio(DataTable setOfInitialTickers, DateTime firstQuoteDate, DateTime lastQuoteDate, int numberOfTickersInPortfolio, double targetPerformance, PortfolioType portfolioType) :base(setOfInitialTickers, firstQuoteDate, lastQuoteDate, numberOfTickersInPortfolio, targetPerformance, portfolioType) { this.retrieveData(); } protected override float[] getArrayOfRatesOfReturn(string ticker) { Quotes tickerQuotes = new Quotes(ticker, this.firstQuoteDate, this.lastQuoteDate); float[] returnValue = new float[2*tickerQuotes.Rows.Count - 1]; int j = 0; for(int i = 0;i<tickerQuotes.Rows.Count; i++) { //open to close returnValue[j] = (float)tickerQuotes.Rows[i]["quClose"]/ (float)tickerQuotes.Rows[i]["quOpen"] - 1; //close to open if(i<tickerQuotes.Rows.Count-1) { returnValue[j+1] = -(( (float)tickerQuotes.Rows[i+1]["quOpen"]* (float)tickerQuotes.Rows[i+1]["quAdjustedClose"]/ (float)tickerQuotes.Rows[i+1]["quClose"] ) /(float)tickerQuotes.Rows[i]["quAdjustedClose"] - 1); } j += 2 ; } this.numberOfExaminedReturns = returnValue.Length; return returnValue; } protected override double getFitnessValue_calculate() { //return this.RateOfReturn/Math.Sqrt(this.Variance); return AdvancedFunctions.GetExpectancyScore(this.PortfolioRatesOfReturn); } } } |
Update of /cvsroot/quantproject/QuantProject/b3_Data/Selectors/ByLinearIndipendence In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv30792/b3_Data/Selectors/ByLinearIndipendence Added Files: SelectorByMaxLinearIndipendence.cs GenomeManagerForMaxLinearIndipendenceSelector.cs Candidate.cs Log Message: Added SimpleScriptsContainer, used mainly for debugging purposes --- NEW FILE: Candidate.cs --- /* QuantProject - Quantitative Finance Library Candidate.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.Collections; namespace QuantProject.Data.Selectors.ByLinearIndipendence { /// <summary> /// This is the class containing basic information /// for each candidate to be evaluated /// </summary> [Serializable] public class Candidate { protected string ticker; protected float[] arrayOfRatesOfReturn; protected float[] oppositeArrayOfRatesOfReturn; protected bool longRatesOfReturn; public Candidate(string ticker, float[] arrayOfRatesOfReturn) { this.ticker = ticker; this.longRatesOfReturn = true; this.arrayOfRatesOfReturn = arrayOfRatesOfReturn; } private float[] arrayOfRatesOfReturn_getOppositeArrayOfRatesOfReturn() { if(this.oppositeArrayOfRatesOfReturn == null) //opposite array of rates of returns not set yet { this.oppositeArrayOfRatesOfReturn = new float[this.arrayOfRatesOfReturn.Length]; for(int i = 0; i<this.arrayOfRatesOfReturn.Length; i++) oppositeArrayOfRatesOfReturn[i] = -this.arrayOfRatesOfReturn[i]; } return this.oppositeArrayOfRatesOfReturn; } public float[] ArrayOfRatesOfReturn { get { float[] returnValue = this.arrayOfRatesOfReturn; if(!this.longRatesOfReturn) returnValue = this.arrayOfRatesOfReturn_getOppositeArrayOfRatesOfReturn(); return returnValue; } } public bool LongRatesOfReturn { set{this.longRatesOfReturn = value;} get{return this.longRatesOfReturn;} } public string Ticker { get{return this.ticker;} } public float GetReturn( int arrayElementPosition , bool isLong ) { float returnValue = this.arrayOfRatesOfReturn[ arrayElementPosition ]; if ( !isLong ) // a reverse position return is requested returnValue = -returnValue; return returnValue; } } } --- NEW FILE: SelectorByMaxLinearIndipendence.cs --- /* QuantProject - Quantitative Finance Library SelectorByMaxLinearIndipendence.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.Collections; using System.Data; using System.Windows.Forms; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.DataAccess.Tables; using QuantProject.Data.DataTables; namespace QuantProject.Data.Selectors.ByLinearIndipendence { /// <summary> /// Class for selection of a given number of tickers /// that are mostly linear indipendent (two by two) /// </summary> public class SelectorByMaxLinearIndipendence : TickerSelector , ITickerSelector { private int numOfGenerationForGeneticOptimizer; private int populationSizeForGeneticOptimizer; private string marketIndex; public SelectorByMaxLinearIndipendence(DataTable setOfTickersToBeSelected, DateTime firstQuoteDate, DateTime lastQuoteDate, long indipendentTickersToBeReturned, int numOfGenerationForGeneticOptimizer, int populationSizeForGeneticOptimizer, string marketIndex): base(setOfTickersToBeSelected, false, firstQuoteDate, lastQuoteDate, indipendentTickersToBeReturned) { this.numOfGenerationForGeneticOptimizer = numOfGenerationForGeneticOptimizer; this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; this.marketIndex = marketIndex; } public SelectorByMaxLinearIndipendence(string groupID, DateTime firstQuoteDate, DateTime lastQuoteDate, long indipendentTickersToBeReturned, int numOfGenerationForGeneticOptimizer, int populationSizeForGeneticOptimizer, string marketIndex): base(QuantProject.DataAccess.Tables.Tickers_tickerGroups.GetTickers(groupID), false, firstQuoteDate, lastQuoteDate, indipendentTickersToBeReturned) { this.numOfGenerationForGeneticOptimizer = numOfGenerationForGeneticOptimizer; this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; this.marketIndex = marketIndex; } public DataTable GetTableOfSelectedTickers() { DataTable returnValue = new DataTable(); returnValue.Columns.Add("ticker", Type.GetType("System.String")); SelectorByQuotationAtEachMarketDay selectorByQuotation = new SelectorByQuotationAtEachMarketDay(this.setOfTickersToBeSelected,false,this.firstQuoteDate, this.lastQuoteDate,this.setOfTickersToBeSelected.Rows.Count, this.marketIndex); GeneticOptimizer GO = new GeneticOptimizer( new GenomeManagerForMaxLinearIndipendenceSelector( selectorByQuotation.GetTableOfSelectedTickers(),this.firstQuoteDate, this.lastQuoteDate,(int)this.MaxNumOfReturnedTickers), this.populationSizeForGeneticOptimizer,this.numOfGenerationForGeneticOptimizer); GO.Run(false); string[] bestTickers = (string[])GO.BestGenome.Meaning; for(int i = 0; i< (int)this.maxNumOfReturnedTickers; i++) { DataRow newRow = returnValue.NewRow(); newRow[0] = bestTickers[i]; returnValue.Rows.Add(newRow); } return returnValue; } public void SelectAllTickers() { ; } } } --- NEW FILE: GenomeManagerForMaxLinearIndipendenceSelector.cs --- /* QuantProject - Quantitative Finance Library GenomeManagerForMaxLinearIndipendenceSelector.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.Statistics; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Data; using QuantProject.Data.DataTables; namespace QuantProject.Data.Selectors.ByLinearIndipendence { /// <summary> /// IGenomeManager used by SelectorByMaxLinearIndipendence /// </summary> [Serializable] public class GenomeManagerForMaxLinearIndipendenceSelector : IGenomeManager { private DataTable setOfInitialTickers; private Candidate[] candidates; private DateTime firstQuoteDate; private DateTime lastQuoteDate; private int genomeSize; private int minValueForGenes; private int maxValueForGenes; private GeneticOptimizer currentGeneticOptimizer; private double[,] correlationMatrix; //IGenomeManager implementation for properties public int GenomeSize { get{return this.genomeSize;} } public int MinValueForGenes { get{return this.minValueForGenes;} } public int MaxValueForGenes { get{return this.maxValueForGenes;} } public GeneticOptimizer CurrentGeneticOptimizer { get{return this.currentGeneticOptimizer;} set{this.currentGeneticOptimizer = value;} } //end of interface implementation for properties public GenomeManagerForMaxLinearIndipendenceSelector(DataTable setOfInitialTickers, DateTime firstQuoteDate, DateTime lastQuoteDate, int numOfIndipendentTickersToBeReturned) { this.genomeSize = numOfIndipendentTickersToBeReturned; this.setOfInitialTickers = setOfInitialTickers; this.setMinAndMaxValueForGenes(); this.firstQuoteDate = firstQuoteDate; this.lastQuoteDate = lastQuoteDate; this.candidates = new Candidate[this.setOfInitialTickers.Rows.Count]; this.retrieveData(); } private void setMinAndMaxValueForGenes() { this.minValueForGenes = 0; this.maxValueForGenes = this.setOfInitialTickers.Rows.Count - 1; } private float[] retrieveData_getArrayOfAdjustedCloseQuotes(string ticker) { float[] returnValue = null; Quotes tickerQuotes = new Quotes(ticker, this.firstQuoteDate, this.lastQuoteDate); returnValue = ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuotes,"quAdjustedClose"); return returnValue; } private void retrieveData_setCorrelationMatrix() { this.correlationMatrix = new double[this.candidates.Length,this.candidates.Length]; for(int i = 0;i<this.candidates.Length;i++) { for(int j = 0; j<i; j++) //matrix is symmetric, only the lower half is computed this.correlationMatrix[i,j] = BasicFunctions.PearsonCorrelationCoefficient(this.candidates[i].ArrayOfRatesOfReturn, this.candidates[j].ArrayOfRatesOfReturn); } } private void retrieveData() { for(int i = 0; i<this.setOfInitialTickers.Rows.Count; i++) { string ticker = (string)setOfInitialTickers.Rows[i][0]; this.candidates[i] = new Candidate(ticker, this.retrieveData_getArrayOfAdjustedCloseQuotes(ticker)); } this.retrieveData_setCorrelationMatrix(); } public Genome[] GetChilds(Genome parent1, Genome parent2) { return GenomeManagement.MixGenesWithoutDuplicates(parent1, parent2); } public int GetNewGeneValue(Genome genome, int genePosition) { int returnValue = GenomeManagement.RandomGenerator.Next(genome.MinValueForGenes, genome.MaxValueForGenes + 1); while( genome.HasGene(returnValue) ) //the genome to be examined shouldn't have a duplicate { returnValue = GenomeManagement.RandomGenerator.Next(genome.MinValueForGenes, genome.MaxValueForGenes + 1); } return returnValue; } public void Mutate(Genome genome, double mutationRate) { int newValueForGene = GenomeManagement.RandomGenerator.Next(genome.MinValueForGenes, genome.MaxValueForGenes +1); int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); while( genome.HasGene(newValueForGene) ) //genome shouldn't have a duplicated gene { newValueForGene = GenomeManagement.RandomGenerator.Next(genome.MinValueForGenes, genome.MaxValueForGenes + 1); } GenomeManagement.MutateOneGene(genome, mutationRate, genePositionToBeMutated, newValueForGene); } public object Decode(Genome genome) { string[] returnValue = new string[genome.Size]; for(int i = 0; i<genome.Size; i++) returnValue[i] = (string)this.setOfInitialTickers.Rows[genome.GetGeneValue(i)][0]; return returnValue; } private double getFitnessValue_getCorrelationCoefficient(int i, int j) { int row = i; int column = j; if( i < j ) { row = j; column = i; } return this.correlationMatrix[row,column]; } public virtual double GetFitnessValue(Genome genome) { double maximumCorrelation = 0.0; for( int i = 0; i <= genome.Size - 2; i++) { for( int j = 1; j<= genome.Size - i - 1;j++) maximumCorrelation = Math.Max(maximumCorrelation, Math.Abs(this.getFitnessValue_getCorrelationCoefficient(i,j))); } return 1.0 / maximumCorrelation; } } } |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:15:27
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv29927/b7_Scripts Added Files: SimpleScriptsContainer.cs Log Message: Added SimpleScriptsContainer, used mainly for debugging purposes --- NEW FILE: SimpleScriptsContainer.cs --- /* QuantProject - Quantitative Finance Library SimpleScriptsContainer.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 QuantProject.Data.Selectors; using QuantProject.Data.Selectors.ByLinearIndipendence; namespace QuantProject.Scripts { /// <summary> /// Summary description for SimpleScriptsContainer. /// </summary> public class SimpleScriptsContainer { public static void Execute() { QuantProject.Data.Selectors.ByLinearIndipendence.SelectorByMaxLinearIndipendence selector = new QuantProject.Data.Selectors.ByLinearIndipendence.SelectorByMaxLinearIndipendence( "SP500",new DateTime(2004,1,1),new DateTime(2004,5,31),5,3,2000,"^GSPC"); DataTable indipendentTickers = selector.GetTableOfSelectedTickers(); SelectorByCloseToCloseCorrelationToBenchmark selector2 = new SelectorByCloseToCloseCorrelationToBenchmark("SP500",(string)indipendentTickers.Rows[0][0], false,new DateTime(2004,1,1),new DateTime(2004,5,31), 20,false); DataTable correlatedTickers = selector2.GetTableOfSelectedTickers(); } } } |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:12:27
|
Update of /cvsroot/quantproject/QuantProject/b3_Data/Selectors/ByLinearIndipendence In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv28595/ByLinearIndipendence Log Message: Directory /cvsroot/quantproject/QuantProject/b3_Data/Selectors/ByLinearIndipendence added to the repository |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:07:30
|
Update of /cvsroot/quantproject/QuantProject/b3_Data/DataTables In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv26439/b3_Data/DataTables Modified Files: Quotes.cs Log Message: Conflict resolution Index: Quotes.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b3_Data/DataTables/Quotes.cs,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** Quotes.cs 29 Jun 2006 17:53:33 -0000 1.26 --- Quotes.cs 2 Jul 2006 19:07:26 -0000 1.27 *************** *** 609,659 **** 0); } - /// <summary> - /// returns tickers of a given set of tickers ordered by close to close - /// correlation to a given benchmark - /// </summary> - public static DataTable GetTickersByCloseToCloseCorrelationToBenchmark( bool orderByASC, - DataTable setOfTickers, string benchmark, - DateTime firstQuoteDate, - DateTime lastQuoteDate, - long maxNumOfReturnedTickers, int numDaysBetweenEachClose) - { - if(!setOfTickers.Columns.Contains("CloseToCloseCorrelationToBenchmark")) - setOfTickers.Columns.Add("CloseToCloseCorrelationToBenchmark", System.Type.GetType("System.Double")); - float[] benchmarkRatios = GetArrayOfCloseToCloseRatios(benchmark, ref firstQuoteDate, lastQuoteDate, numDaysBetweenEachClose); - foreach(DataRow row in setOfTickers.Rows) - { - float[] tickerRatios = GetArrayOfCloseToCloseRatios((string)row[0], - ref firstQuoteDate, lastQuoteDate, numDaysBetweenEachClose ); - if(tickerRatios.Length == benchmarkRatios.Length) - row["CloseToCloseCorrelationToBenchmark"] = - Math.Abs(BasicFunctions.PearsonCorrelationCoefficient(benchmarkRatios, tickerRatios)); - } - DataTable tableToReturn = ExtendedDataTable.CopyAndSort(setOfTickers, - "CloseToCloseCorrelationToBenchmark>=0.0", - "CloseToCloseCorrelationToBenchmark", - orderByASC); - ExtendedDataTable.DeleteRows(tableToReturn, maxNumOfReturnedTickers); - return tableToReturn; - } ! /// <summary> ! /// returns tickers of a given set of tickers ordered by close to close ! /// correlation to a given benchmark ! /// </summary> ! public static DataTable GetTickersByCloseToCloseCorrelationToBenchmark( bool orderByASC, ! string groupID, string benchmark, ! DateTime firstQuoteDate, ! DateTime lastQuoteDate, ! long maxNumOfReturnedTickers, ! int numDaysBetweenEachClose) { ! DataTable tickersOfGroup = new Tickers_tickerGroups(groupID); ! return GetTickersByCloseToCloseCorrelationToBenchmark(orderByASC, ! tickersOfGroup, benchmark, ! firstQuoteDate, ! lastQuoteDate, ! maxNumOfReturnedTickers, ! numDaysBetweenEachClose); } --- 609,619 ---- 0); } ! public static float[] GetArrayOfAdjustedCloseQuotes(string ticker, ! DateTime firstQuoteDate, ! DateTime lastQuoteDate) { ! Quotes tickerQuotes = new Quotes(ticker, firstQuoteDate, lastQuoteDate); ! return ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuotes,"quAdjustedClose"); } *************** *** 680,683 **** --- 640,644 ---- } + private History history; *************** *** 971,974 **** --- 932,949 ---- } + /// <summary> + /// Gets the first valid close to close ratio at the given date + /// </summary> + /// <returns></returns> + public float GetFirstValidCloseToCloseRatio(DateTime date ) + { + object[] keys = new object[1]; + keys[0] = this.GetFirstValidQuoteDate(date.Date); + DataRow foundRow = this.Rows.Find(keys); + if(foundRow==null) + throw new Exception("No quote for such a date!"); + return (float)foundRow[Quotes.AdjustedCloseToCloseRatio]; + } + // public DateTime GetPrecedingDate( DateTime quoteDate , int precedingDays ) // { |
|
From: Marco M. <mi...@us...> - 2006-07-02 19:04:55
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv25195/b4_Business/a2_Strategies Modified Files: SignedTicker.cs Log Message: Conflict resolution Index: SignedTicker.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/SignedTicker.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** SignedTicker.cs 29 Jun 2006 17:51:31 -0000 1.3 --- SignedTicker.cs 2 Jul 2006 19:04:49 -0000 1.4 *************** *** 191,209 **** } ! /// <summary> ! /// Gets portfolio's return for a given period, for given tickers ! /// </summary> ! /// <param name="signedTickers">Array of signed tickers that compose the portfolio (each ticker has the same weight)</param> ! /// <param name="startDate">Start date for the period for which return has to be computed</param> ! /// <param name="endDate">End date for the period for which return has to be computed</param> ! public static double GetCloseToClosePortfolioReturn(string[] signedTickers, ! DateTime startDate, ! DateTime endDate ) ! { ! double[] tickersWeights = new double[signedTickers.Length]; ! for(int i = 0; i<signedTickers.Length; i++) ! tickersWeights[i] = 1.0/signedTickers.Length; ! ! return GetCloseToClosePortfolioReturn( signedTickers,tickersWeights, startDate, endDate); --- 191,209 ---- } ! /// <summary> ! /// Gets portfolio's return for a given period, for the given tickers ! /// </summary> ! /// <param name="signedTickers">Array of signed tickers that compose the portfolio (each ticker has the same weight)</param> ! /// <param name="startDate">Start date for the period for which return has to be computed</param> ! /// <param name="endDate">End date for the period for which return has to be computed</param> ! public static double GetCloseToClosePortfolioReturn(string[] signedTickers, ! DateTime startDate, ! DateTime endDate ) ! { ! double[] tickersWeights = new double[signedTickers.Length]; ! for(int i = 0; i<signedTickers.Length; i++) ! tickersWeights[i] = 1.0/signedTickers.Length; ! ! return GetCloseToClosePortfolioReturn( signedTickers,tickersWeights, startDate, endDate); *************** *** 301,306 **** public static void ChangeSignOfEachTicker( string[] signedTickers ) { ! for(int i = 0; i<signedTickers.Length; i++) ! signedTickers[i] = GetOppositeSignedTicker(signedTickers[i]); } } --- 301,309 ---- public static void ChangeSignOfEachTicker( string[] signedTickers ) { ! for(int i = 0; i<signedTickers.Length; i++) ! { ! if(signedTickers[i] != null) ! signedTickers[i] = GetOppositeSignedTicker(signedTickers[i]); ! } } } |
|
From: Glauco S. <gla...@us...> - 2006-06-29 17:55:30
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv22343/b1_ADT Modified Files: b1_ADT.csproj Log Message: minor vsnet automatic change Index: b1_ADT.csproj =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/b1_ADT.csproj,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** b1_ADT.csproj 1 Jun 2006 23:40:11 -0000 1.21 --- b1_ADT.csproj 29 Jun 2006 17:55:26 -0000 1.22 *************** *** 229,232 **** --- 229,233 ---- <File RelPath = "Statistics\AdvancedFunctions.cs" + SubType = "Code" BuildAction = "Compile" /> |
|
From: Glauco S. <gla...@us...> - 2006-06-29 17:53:36
|
Update of /cvsroot/quantproject/QuantProject/b3_Data/DataTables In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv21376/b3_Data/DataTables Modified Files: Quotes.cs Log Message: - the GetMarketDays static method has been added Index: Quotes.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b3_Data/DataTables/Quotes.cs,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** Quotes.cs 14 May 2006 18:28:24 -0000 1.25 --- Quotes.cs 29 Jun 2006 17:53:33 -0000 1.26 *************** *** 658,661 **** --- 658,682 ---- } + /// <summary> + /// returns dates when the ticker was exchanged, within a given + /// date interval + /// </summary> + /// <param name="ticker"></param> + /// <param name="firstDate">begin interval</param> + /// <param name="lastDate">end interval</param> + /// <returns></returns> + public static DateTime[] GetMarketDays( string ticker , + DateTime firstDate , DateTime lastDate ) + { + Quotes quotes = new Quotes( ticker , firstDate , lastDate ); + DateTime[] marketDays = new DateTime[ quotes.Rows.Count ]; + int i = 0; + foreach ( DataRow dataRow in quotes.Rows ) + { + marketDays[ i ] = (DateTime)dataRow[ Quotes.Date ]; + i++; + } + return marketDays; + } private History history; |
|
From: Glauco S. <gla...@us...> - 2006-06-29 17:51:35
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv20407/b4_Business/a2_Strategies Modified Files: SignedTicker.cs Log Message: - the GetCloseToClosePortfolioReturns static method has been added - the GetCloseToClosePortfolioReturn static method has been overloaded (to say the truth I don't remember if I ever tested this new method...) Index: SignedTicker.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/SignedTicker.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** SignedTicker.cs 14 May 2006 18:40:24 -0000 1.2 --- SignedTicker.cs 29 Jun 2006 17:51:31 -0000 1.3 *************** *** 22,25 **** --- 22,26 ---- using System; + using System.Collections; using QuantProject.Business.DataProviders; *************** *** 190,213 **** } ! /// <summary> ! /// Gets portfolio's return for a given period, for given tickers ! /// </summary> ! /// <param name="signedTickers">Array of signed tickers that compose the portfolio (each ticker has the same weight)</param> ! /// <param name="startDate">Start date for the period for which return has to be computed</param> ! /// <param name="endDate">End date for the period for which return has to be computed</param> ! public static double GetCloseToClosePortfolioReturn(string[] signedTickers, ! DateTime startDate, ! DateTime endDate ) ! { ! double[] tickersWeights = new double[signedTickers.Length]; ! for(int i = 0; i<signedTickers.Length; i++) ! tickersWeights[i] = 1.0/signedTickers.Length; ! return GetCloseToClosePortfolioReturn( ! signedTickers,tickersWeights, startDate, endDate); ! } ! /// <summary> /// Changes sign of each ticker contained in the given /// array of signed tickers --- 191,299 ---- } ! /// <summary> ! /// Gets portfolio's return for a given period, for given tickers ! /// </summary> ! /// <param name="signedTickers">Array of signed tickers that compose the portfolio (each ticker has the same weight)</param> ! /// <param name="startDate">Start date for the period for which return has to be computed</param> ! /// <param name="endDate">End date for the period for which return has to be computed</param> ! public static double GetCloseToClosePortfolioReturn(string[] signedTickers, ! DateTime startDate, ! DateTime endDate ) ! { ! double[] tickersWeights = new double[signedTickers.Length]; ! for(int i = 0; i<signedTickers.Length; i++) ! tickersWeights[i] = 1.0/signedTickers.Length; ! return GetCloseToClosePortfolioReturn( ! signedTickers,tickersWeights, startDate, endDate); ! } ! private static string[] getSignedTickersArray( ICollection signedTickers ) ! { ! string[] signedTickersArray = new string[ signedTickers.Count ]; ! int i = 0; ! foreach( string signedTicker in signedTickers ) ! { ! signedTickersArray[ i ] = signedTicker; ! i++; ! } ! return signedTickersArray; ! } ! private static string[] getSignedTickerArray ( ICollection signedTickers ) ! { ! string[] signedTickerArray = new string[ signedTickers.Count ]; ! int i = 0; ! foreach( string signedTicker in signedTickers ) ! { ! signedTickerArray[ i ] = signedTicker; ! i++; ! } ! return signedTickerArray; ! } ! #region GetCloseToClosePortfolioReturns ! private static double getCloseToCloseReturn( string ticker , ! DateTime[] datesForReturnComputation , int i ) ! { ! DateTime previousDate = datesForReturnComputation[ i ]; ! DateTime currentDate = datesForReturnComputation[ i + 1 ]; ! HistoricalAdjustedQuoteProvider historicalQuoteProvider = ! new HistoricalAdjustedQuoteProvider(); ! double previousQuote = historicalQuoteProvider.GetMarketValue( ticker , ! new EndOfDayDateTime( previousDate , EndOfDaySpecificTime.MarketClose ) ); ! double currentQuote = historicalQuoteProvider.GetMarketValue( ticker , ! new EndOfDayDateTime( currentDate , EndOfDaySpecificTime.MarketClose ) ); ! double closeToCloseReturn = currentQuote / previousQuote - 1.0; ! return closeToCloseReturn; ! } ! private static double getMultiplier( string signedTicker ) ! { ! double multiplier = 1.0; ! if ( IsShort( signedTicker ) ) ! multiplier = -multiplier; ! return multiplier; ! } ! private static double getCloseToClosePortfolioReturn( ! string[] signedTickers , DateTime[] datesForReturnComputation , int i ) ! { ! double dailyReturn = 0.0; ! foreach ( String signedTicker in signedTickers ) ! dailyReturn += getMultiplier( signedTicker ) * ! getCloseToCloseReturn( GetTicker( signedTicker ) , ! datesForReturnComputation , i ) / ! signedTickers.Length; // every position is considered with same weight ! return dailyReturn; ! } ! private static double[] getCloseToClosePortfolioReturns( ! string[] signedTickers , DateTime[] datesForReturnComputation ) ! { ! // the return for first DateTime cannot be computed so the returned ! // array will have one element less the datesForReturnComputation ! double[] closeToClosePortfolioReturns = ! new double[ datesForReturnComputation.Length - 1 ]; ! for ( int i=0 ; i < closeToClosePortfolioReturns.Length ; i++ ) ! closeToClosePortfolioReturns[ i ] = getCloseToClosePortfolioReturn( ! signedTickers , datesForReturnComputation , i ); ! return closeToClosePortfolioReturns; ! } ! /// <summary> ! /// Gets portfolio's return for a given period, for given tickers ! /// </summary> ! /// <param name="signedTickers">ICollection of signed tickers that compose the portfolio (each ticker has the same weight)</param> ! /// <param name="startDate">Start date for the period for which return has to be computed</param> ! /// <param name="endDate">End date for the period for which return has to be computed</param> ! public static double[] GetCloseToClosePortfolioReturns( ! ICollection signedTickers, DateTime firstDate, DateTime lastDate ) ! { ! string[] signedTickerArray = ! getSignedTickerArray( signedTickers ); ! DateTime[] datesForReturnComputation = Quotes.GetMarketDays( ! GetTicker( signedTickerArray[ 0 ] ), firstDate , lastDate ); ! return getCloseToClosePortfolioReturns( signedTickerArray , ! datesForReturnComputation ); ! } ! #endregion ! ! /// <summary> /// Changes sign of each ticker contained in the given /// array of signed tickers |
|
From: Glauco S. <gla...@us...> - 2006-06-29 17:46:53
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagGenomesDebugger In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv18104/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagGenomesDebugger Modified Files: WFLagChosenPositionsDebugInfo.cs Log Message: - a WFLagLog parameter has been added to the WFLagChosenPositionsDebugInfo constructor - the InSampleDays property has been added - the InSampleSharpeRatio property has been added - the PreSampleSharpeRatio30 property has been added - the PostSampleSharpeRatio30 property has been added - the InSampleDays property has been added - the InSampleDays property has been added - the InSampleDays property has been added Index: WFLagChosenPositionsDebugInfo.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagGenomesDebugger/WFLagChosenPositionsDebugInfo.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** WFLagChosenPositionsDebugInfo.cs 24 Jun 2006 14:49:54 -0000 1.1 --- WFLagChosenPositionsDebugInfo.cs 29 Jun 2006 17:46:49 -0000 1.2 *************** *** 31,34 **** --- 31,38 ---- { private WFLagChosenPositions wFLagChosenPositions; + private WFLagLog wFLagLog; + private double inSampleSharpeRatio; + private double preSampleSharpeRatio30; + private double postSampleSharpeRatio30; public string DrivingPositions *************** *** 44,48 **** get { return this.wFLagChosenPositions.LastOptimizationDate; } } ! public WFLagChosenPositionsDebugInfo( WFLagChosenPositions wFLagChosenPositions ) { // --- 48,70 ---- get { return this.wFLagChosenPositions.LastOptimizationDate; } } ! public int InSampleDays ! { ! get { return this.wFLagLog.InSampleDays; } ! } ! public double InSampleSharpeRatio ! { ! get { return this.inSampleSharpeRatio; } ! } ! public double PreSampleSharpeRatio30 ! { ! get { return this.preSampleSharpeRatio30; } ! } ! public double PostSampleSharpeRatio30 ! { ! get { return this.postSampleSharpeRatio30; } ! } ! public WFLagChosenPositionsDebugInfo( ! WFLagChosenPositions wFLagChosenPositions , ! WFLagLog wFLagLog ) { // *************** *** 50,53 **** --- 72,110 ---- // this.wFLagChosenPositions = wFLagChosenPositions; + this.wFLagLog = wFLagLog; + this.inSampleSharpeRatio = this.getInSampleSharpeRatio(); + this.preSampleSharpeRatio30 = this.getPreSampleSharpeRatio( 30 ); + this.postSampleSharpeRatio30 = this.getPostSampleSharpeRatio( 30 ); + } + private DateTime getInSampleFirstDate() + { + DateTime inSampleFirstDate = this.LastOptimization.AddDays( + -( this.wFLagLog.InSampleDays - 1 ) ); + return inSampleFirstDate; + } + private double getInSampleSharpeRatio() + { + DateTime firstDateTime = this.getInSampleFirstDate(); + return WFLagSharpeRatioComputer.GetSharpeRatio( + this.wFLagChosenPositions , firstDateTime , + this.LastOptimization ); + } + private double getPreSampleSharpeRatio( int days ) + { + DateTime lastDateTime = this.getInSampleFirstDate(); + DateTime firstDateTime = lastDateTime.AddDays( -days - 1 ); // I subtract one more day, so I have days daily returns + return WFLagSharpeRatioComputer.GetSharpeRatio( + this.wFLagChosenPositions , firstDateTime , + lastDateTime ); + } + private double getPostSampleSharpeRatio( int days ) + { + DateTime firstDateTime = + this.LastOptimization; // add one day if you want to exclude the first day after the optimization; + // consider that the real out of sample jumps out that day + DateTime lastDateTime = firstDateTime.AddDays( days + 1 ); // I add one day, so I have days daily returns + return WFLagSharpeRatioComputer.GetSharpeRatio( + this.wFLagChosenPositions , firstDateTime , + lastDateTime ); } } |
|
From: Glauco S. <gla...@us...> - 2006-06-29 17:42:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagGenomesDebugger In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv16348/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagGenomesDebugger Modified Files: WFLagRunGenomesDebugger.cs Log Message: A WFLagLog parameter has been added to the WFLagChosenPositionsDebugInfo constructor Index: WFLagRunGenomesDebugger.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagGenomesDebugger/WFLagRunGenomesDebugger.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** WFLagRunGenomesDebugger.cs 24 Jun 2006 14:38:24 -0000 1.2 --- WFLagRunGenomesDebugger.cs 29 Jun 2006 17:42:32 -0000 1.3 *************** *** 61,65 **** { WFLagChosenPositionsDebugInfo wFLagChosenPositionsDebugInfo = ! new WFLagChosenPositionsDebugInfo( wFLagChosenPositions ); this.chosenPositionsDebugInfoList.Add( wFLagChosenPositionsDebugInfo ); } --- 61,66 ---- { WFLagChosenPositionsDebugInfo wFLagChosenPositionsDebugInfo = ! new WFLagChosenPositionsDebugInfo( wFLagChosenPositions , ! this.wFLagLog ); this.chosenPositionsDebugInfoList.Add( wFLagChosenPositionsDebugInfo ); } |
|
From: Glauco S. <gla...@us...> - 2006-06-29 17:03:05
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv30398/b7_Scripts Modified Files: b7_Scripts.csproj Log Message: WalkForwardTesting\WalkForwardLag\WFLagGenomesDebugger\WFLagSharpeRatioComputer.cs has been added Index: b7_Scripts.csproj =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/b7_Scripts.csproj,v retrieving revision 1.55 retrieving revision 1.56 diff -C2 -d -r1.55 -r1.56 *** b7_Scripts.csproj 24 Jun 2006 14:48:04 -0000 1.55 --- b7_Scripts.csproj 29 Jun 2006 17:03:00 -0000 1.56 *************** *** 659,662 **** --- 659,667 ---- /> <File + RelPath = "WalkForwardTesting\WalkForwardLag\WFLagGenomesDebugger\WFLagSharpeRatioComputer.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "WalkForwardTesting\WalkForwardLag\WFLagLogDebugger\WFLagLogDebugger.cs" SubType = "Form" |
|
From: Glauco S. <gla...@us...> - 2006-06-29 17:01:01
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagGenomesDebugger In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv29419/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagGenomesDebugger Added Files: WFLagSharpeRatioComputer.cs Log Message: Computes Sharpe Ratios for the WFLag strategy, for debug purposes --- NEW FILE: WFLagSharpeRatioComputer.cs --- /* QuantProject - Quantitative Finance Library WFLagSharpeRatioComputer.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.Statistics; using QuantProject.Business.Strategies; using QuantProject.Data.DataProviders.Caching; namespace QuantProject.Scripts.WalkForwardTesting.WalkForwardLag.WFLagDebugger { /// <summary> /// Computes Sharpe Ratios for the WFLag strategy, for debug purposes /// </summary> public class WFLagSharpeRatioComputer { public WFLagSharpeRatioComputer() { // // TODO: Add constructor logic here // } // private double[] getLinearCombinationReturns( // ICollection signedTickers ) // { //// ArrayList enumeratedSignedTicker = //// this.getEnumeratedSignedTickers( signedTickers ); // int numberOfSignedTickers = signedTickers.Count; // ArrayList tickers = this.getTickers( signedTickers ); // float[] multipliers = this.getMultipliers( enumeratedSignedTicker ); // // arrays of close to close returns, one for each signed ticker // float[][] tickersReturns = // this.wFLagCandidates.GetTickersReturns( tickers ); // double[] linearCombinationReturns = // new double[ tickersReturns[ 0 ].Length ]; // for( int i = 0; i < linearCombinationReturns.Length ; i++ ) // // computes linearCombinationReturns[ i ] // { // linearCombinationReturns[ i ] = 0; // for ( int j=0 ; j < numberOfSignedTickers ; j++ ) // { // double signedTickerReturn = // tickersReturns[ j ][ i ] * multipliers[ j ]; // // the investment is assumed to be equally divided for each // // signed ticker // linearCombinationReturns[ i ] += signedTickerReturn / // numberOfSignedTickers; // } // } // return linearCombinationReturns; // } private static double[] getStrategyReturns( double[] drivingPositionsReturns , double[] portfolioPositionsReturns ) { // strategyReturns contains one element less than drivingPositionsReturns, // because there is no strategy for the very first period (at least // one day signal is needed) double[] strategyReturns = new double[ portfolioPositionsReturns.Length - 1 ]; for ( int i = 0 ; i < portfolioPositionsReturns.Length - 1 ; i++ ) if ( drivingPositionsReturns[ i ] < 0 ) // the current linear combination of tickers, at period i // has a negative return // go short tomorrow strategyReturns[ i ] = -portfolioPositionsReturns[ i + 1 ]; else // the current linear combination of tickers, at period i // has a positive return // go long tomorrow strategyReturns[ i ] = portfolioPositionsReturns[ i + 1 ]; return strategyReturns; } private static double[] getStrategyReturns( WFLagChosenPositions wFLagChosenPositions , DateTime firstDate , DateTime lastDate ) { double[] drivingPositionsReturns = SignedTicker.GetCloseToClosePortfolioReturns( wFLagChosenPositions.DrivingPositions.Keys , firstDate , lastDate ); double[] portfolioPositionsReturns = SignedTicker.GetCloseToClosePortfolioReturns( wFLagChosenPositions.PortfolioPositions.Keys , firstDate , lastDate ); double[] strategyReturns = getStrategyReturns( drivingPositionsReturns , portfolioPositionsReturns ); return strategyReturns; } public static double GetSharpeRatio( WFLagChosenPositions wFLagChosenPositions , DateTime firstDate , DateTime lastDate ) { double sharpeRatio = double.MinValue; try { double[] strategyReturns = getStrategyReturns( wFLagChosenPositions , firstDate , lastDate ); sharpeRatio = AdvancedFunctions.GetSharpeRatio( strategyReturns ); } catch( MissingQuoteException ex ) { sharpeRatio = double.MinValue; string dummy = ex.Message; } return sharpeRatio; } } } |
|
From: Glauco S. <gla...@us...> - 2006-06-24 14:49:57
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagGenomesDebugger In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv21183/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagGenomesDebugger Added Files: WFLagChosenPositionsDebugInfo.cs Log Message: Debug info related to a single genome --- NEW FILE: WFLagChosenPositionsDebugInfo.cs --- /* QuantProject - Quantitative Finance Library WFLagChosenPositionsDebugInfo.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; namespace QuantProject.Scripts.WalkForwardTesting.WalkForwardLag.WFLagDebugger { /// <summary> /// Debug info related to a single genome /// </summary> public class WFLagChosenPositionsDebugInfo { private WFLagChosenPositions wFLagChosenPositions; public string DrivingPositions { get { return this.wFLagChosenPositions.DrivingPositions.KeyConcat; } } public string PortfolioPositions { get { return this.wFLagChosenPositions.PortfolioPositions.KeyConcat; } } public DateTime LastOptimization { get { return this.wFLagChosenPositions.LastOptimizationDate; } } public WFLagChosenPositionsDebugInfo( WFLagChosenPositions wFLagChosenPositions ) { // // TODO: Add constructor logic here // this.wFLagChosenPositions = wFLagChosenPositions; } } } |