[Quantproject-developers] QuantProject/b7_Scripts/TickerSelectionTesting EndOfDayTimerHandlerCTCTest
Brought to you by:
glauco_1
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting In directory sc8-pr-cvs1.sourceforge.net:/tmp/cvs-serv16116/b7_Scripts/TickerSelectionTesting Modified Files: EndOfDayTimerHandlerCTC.cs EndOfDayTimerHandlerCTO.cs EndOfDayTimerHandlerCTOTest.cs GenomeManagerForEfficientCTCPortfolio.cs GenomeManagerForEfficientCTOPortfolio.cs GenomeManagerForEfficientPortfolio.cs RunEfficientCTCPortfolio.cs RunEfficientCTOPortfolio.cs RunEfficientPortfolio.cs RunTestOptimizedCTOPortfolio.cs Added Files: EndOfDayTimerHandlerCTCTest.cs RunTestOptimizedCTCPortfolio.cs Log Message: Scripts for finding the efficient portfolio have been reorganized in a more object-oriented way. Test script handlers (for checking the optimization process through in - sample simulation) now derive directly from the main classes used for out of sample simulations. Index: RunTestOptimizedCTOPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/RunTestOptimizedCTOPortfolio.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunTestOptimizedCTOPortfolio.cs 4 May 2005 18:21:07 -0000 1.1 --- RunTestOptimizedCTOPortfolio.cs 2 Jun 2005 18:00:47 -0000 1.2 *************** *** 50,54 **** /// </summary> [Serializable] ! public class RunTestOptimizedCTOPorfolio : RunEfficientPorfolio { --- 50,54 ---- /// </summary> [Serializable] ! public class RunTestOptimizedCTOPorfolio : RunEfficientCTOPorfolio { *************** *** 58,62 **** int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, double targetReturn, ! PortfolioType portfolioType): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForLiquidity, --- 58,62 ---- int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, double targetReturn, ! PortfolioType portfolioType, double maxRunningHours): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForLiquidity, *************** *** 64,68 **** populationSizeForGeneticOptimizer, benchmark, startDate, endDate, targetReturn, ! portfolioType) { this.ScriptName = "TestOptimizedCTOPortfolio"; --- 64,68 ---- populationSizeForGeneticOptimizer, benchmark, startDate, endDate, targetReturn, ! portfolioType, maxRunningHours) { this.ScriptName = "TestOptimizedCTOPortfolio"; *************** *** 82,120 **** this.portfolioType); - - } - protected override void run_initializeHistoricalQuoteProvider() - { - this.historicalQuoteProvider = - new HistoricalRawQuoteProvider(); - } public override void Run() { ! run_initializeHistoricalQuoteProvider(); ! run_initializeEndOfDayTimer(); ! run_initializeAccount(); ! run_initializeEndOfDayTimerHandler(); ! ! this.endOfDayTimer.MarketOpen += ! new MarketOpenEventHandler( ! this.endOfDayTimerHandler.MarketOpenEventHandler); ! ! this.endOfDayTimer.MarketClose += ! new MarketCloseEventHandler( ! this.endOfDayTimerHandler.MarketCloseEventHandler); ! ! this.endOfDayTimer.MarketClose += ! new MarketCloseEventHandler( ! this.checkDateForReport); ! ! this.endOfDayTimer.OneHourAfterMarketClose += ! new OneHourAfterMarketCloseEventHandler( ! this.endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler ); ! ! this.endOfDayTimer.Start(); ((EndOfDayTimerHandlerCTOTest)this.endOfDayTimerHandler).Reset(); - } --- 82,91 ---- this.portfolioType); } public override void Run() { ! base.Run(); ((EndOfDayTimerHandlerCTOTest)this.endOfDayTimerHandler).Reset(); } Index: GenomeManagerForEfficientCTOPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/GenomeManagerForEfficientCTOPortfolio.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** GenomeManagerForEfficientCTOPortfolio.cs 26 Apr 2005 19:02:13 -0000 1.8 --- GenomeManagerForEfficientCTOPortfolio.cs 2 Jun 2005 18:00:47 -0000 1.9 *************** *** 99,103 **** } ! } --- 99,121 ---- } ! protected override double getFitnessValue_calculate() ! { ! double returnValue = 0; ! ! double a, b, c; ! a = 0.002; b = 2.0; c = 3.0; ! ! returnValue = Math.Pow((a/this.Variance),b) * ! Math.Pow((this.rateOfReturn - this.targetPerformance), ! c); ! if(this.portfolioType == PortfolioType.OnlyShort) ! returnValue = - returnValue; ! ! if(Double.IsInfinity(returnValue) || Double.IsNaN(returnValue)) ! throw new Exception("Fitness value not computed correctly!"); ! ! return returnValue; ! } ! } Index: RunEfficientCTCPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/RunEfficientCTCPortfolio.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** RunEfficientCTCPortfolio.cs 17 May 2005 23:13:25 -0000 1.6 --- RunEfficientCTCPortfolio.cs 2 Jun 2005 18:00:47 -0000 1.7 *************** *** 59,64 **** public class RunEfficientCTCPorfolio : RunEfficientPorfolio { ! private int numDayOfPortfolioLife; ! private double maxAcceptableCloseToCloseDrawdown; public RunEfficientCTCPorfolio(string tickerGroupID, int numberOfEligibleTickers, --- 59,65 ---- public class RunEfficientCTCPorfolio : RunEfficientPorfolio { ! protected int numDayOfPortfolioLife; ! protected int numDaysForReturnCalculation; ! protected double maxAcceptableCloseToCloseDrawdown; public RunEfficientCTCPorfolio(string tickerGroupID, int numberOfEligibleTickers, *************** *** 67,72 **** int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, ! int numDaysOfPortfolioLife, double targetReturn, ! PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForLiquidity, --- 68,75 ---- int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, ! int numDaysOfPortfolioLife, int numDaysForReturnCalculation, ! double targetReturn, ! PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown, ! double maxRunningHours): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForLiquidity, *************** *** 74,81 **** populationSizeForGeneticOptimizer, benchmark, startDate, endDate, targetReturn, ! portfolioType) { this.ScriptName = "CloseToCloseScripts"; this.numDayOfPortfolioLife = numDaysOfPortfolioLife; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; } --- 77,85 ---- populationSizeForGeneticOptimizer, benchmark, startDate, endDate, targetReturn, ! portfolioType, maxRunningHours) { this.ScriptName = "CloseToCloseScripts"; this.numDayOfPortfolioLife = numDaysOfPortfolioLife; + this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; } *************** *** 90,94 **** this.generationNumberForGeneticOptimizer, this.populationSizeForGeneticOptimizer, this.benchmark, ! this.numDayOfPortfolioLife, this.targetReturn, this.portfolioType, this.maxAcceptableCloseToCloseDrawdown); } --- 94,99 ---- this.generationNumberForGeneticOptimizer, this.populationSizeForGeneticOptimizer, this.benchmark, ! this.numDayOfPortfolioLife, this.numDaysForReturnCalculation, ! this.targetReturn, this.portfolioType, this.maxAcceptableCloseToCloseDrawdown); } --- NEW FILE: RunTestOptimizedCTCPortfolio.cs --- /* QuantProject - Quantitative Finance Library RunTestOptimizedCTCPortfolio.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 QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Scripting; using QuantProject.Business.Strategies; using QuantProject.Business.Testing; using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; using QuantProject.ADT.FileManaging; namespace QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios { /// <summary> /// Script to buy at close and sell at close /// after a specified number of market days /// the efficient portfolio /// The efficient portfolio's generation rules /// (contained in the EndOfDayTimerHandler) are: /// - choose the most liquid tickers; /// - choose only tickers quoted at each market day /// during a given previous interval of days; /// - choose the most efficient portfolio among these tickers /// </summary> [Serializable] public class RunTestOptimizedCTCPortfolio : RunEfficientCTCPorfolio { public RunTestOptimizedCTCPortfolio(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForLiquidity, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, int numDaysOfPortfolioLife, int numDaysForReturnCalculation, double targetReturn, PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown, double maxRunningHours): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForLiquidity, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, startDate, endDate, numDaysOfPortfolioLife, numDaysForReturnCalculation, targetReturn, portfolioType, maxAcceptableCloseToCloseDrawdown, maxRunningHours) { this.ScriptName = "TestOptimizedCTCPortfolio"; } protected override void run_initializeEndOfDayTimerHandler() { this.endOfDayTimerHandler = new EndOfDayTimerHandlerCTCTest(this.tickerGroupID, this.numberOfEligibleTickers, this.numberOfTickersToBeChosen, this.numDaysForLiquidity, this.account, this.generationNumberForGeneticOptimizer, this.populationSizeForGeneticOptimizer, this.benchmark, this.numDayOfPortfolioLife, this.numDaysForReturnCalculation, this.targetReturn, this.portfolioType, this.maxAcceptableCloseToCloseDrawdown); } public override void Run() { base.Run(); ((EndOfDayTimerHandlerCTCTest)this.endOfDayTimerHandler).Reset(); } } } Index: GenomeManagerForEfficientCTCPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/GenomeManagerForEfficientCTCPortfolio.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** GenomeManagerForEfficientCTCPortfolio.cs 26 Apr 2005 19:02:12 -0000 1.3 --- GenomeManagerForEfficientCTCPortfolio.cs 2 Jun 2005 18:00:47 -0000 1.4 *************** *** 40,43 **** --- 40,44 ---- { private int numDaysOfPortfolioLife; + private int numDaysForReturnCalculation; public GenomeManagerForEfficientCTCPortfolio(DataTable setOfInitialTickers, *************** *** 46,49 **** --- 47,51 ---- int numberOfTickersInPortfolio, int numDaysOfPortfolioLife, + int numDaysForReturnCalculation, double targetPerformance, PortfolioType portfolioType) *************** *** 59,62 **** --- 61,65 ---- { this.numDaysOfPortfolioLife = numDaysOfPortfolioLife; + this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.retrieveData(); } *************** *** 83,92 **** Quotes tickerQuotes = new Quotes(tickerCode, this.firstQuoteDate, this.lastQuoteDate); float[] allAdjValues = ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuotes, "quAdjustedClose"); ! float[] ratesOfReturns = new float[allAdjValues.Length/this.numDaysOfPortfolioLife + 1]; int i = 0; //index for ratesOfReturns array ! for(int idx = 0; idx + this.numDaysOfPortfolioLife < allAdjValues.Length; idx += this.numDaysOfPortfolioLife ) { ! ratesOfReturns[i] = (allAdjValues[idx+this.numDaysOfPortfolioLife]/ allAdjValues[idx] - 1)*coefficient; i++; --- 86,95 ---- Quotes tickerQuotes = new Quotes(tickerCode, this.firstQuoteDate, this.lastQuoteDate); float[] allAdjValues = ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuotes, "quAdjustedClose"); ! float[] ratesOfReturns = new float[allAdjValues.Length/this.numDaysForReturnCalculation + 1]; int i = 0; //index for ratesOfReturns array ! for(int idx = 0; idx + this.numDaysForReturnCalculation < allAdjValues.Length; idx += this.numDaysForReturnCalculation ) { ! ratesOfReturns[i] = (allAdjValues[idx+this.numDaysForReturnCalculation]/ allAdjValues[idx] - 1)*coefficient; i++; Index: EndOfDayTimerHandlerCTOTest.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerCTOTest.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** EndOfDayTimerHandlerCTOTest.cs 17 May 2005 23:13:25 -0000 1.2 --- EndOfDayTimerHandlerCTOTest.cs 2 Jun 2005 18:00:47 -0000 1.3 *************** *** 42,46 **** /// </summary> [Serializable] ! public class EndOfDayTimerHandlerCTOTest : EndOfDayTimerHandler { private static bool optimized; --- 42,46 ---- /// </summary> [Serializable] ! public class EndOfDayTimerHandlerCTOTest : EndOfDayTimerHandlerCTO { private static bool optimized; *************** *** 60,137 **** } - - #region MarketOpenEventHandler - - private void marketOpenEventHandler_orderChosenTickers_addToOrderList() - { - int idx = 0; - foreach ( string ticker in this.chosenTickers ) - { - if(ticker != null) - { - this.addOrderForTicker( ticker ); - this.lastChosenTickers[idx] = - GenomeManagerForEfficientPortfolio.GetCleanTickerCode(ticker); - } - idx++; - } - } - - private void marketOpenEventHandler_orderChosenTickers() - { - this.marketOpenEventHandler_orderChosenTickers_addToOrderList(); - } - - /// <summary> - /// Handles a "Market Open" event. - /// </summary> - /// <param name="sender"></param> - /// <param name="eventArgs"></param> - public override void MarketOpenEventHandler( - Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) - { - if(this.orders.Count == 0 && this.account.Transactions.Count == 0) - this.account.AddCash(17000); - - this.marketOpenEventHandler_orderChosenTickers(); - - foreach(object item in this.orders) - { - this.account.AddOrder((Order)item); - } - } - #endregion - - #region MarketCloseEventHandler ! private void marketCloseEventHandler_closePosition( ! string ticker ) ! { ! this.account.ClosePosition( ticker ); ! } ! private void marketCloseEventHandler_closePositions() ! { ! if(this.lastChosenTickers != null) ! { ! foreach( string ticker in this.lastChosenTickers) ! { ! for(int i = 0; i<this.account.Portfolio.Keys.Count; i++) ! { ! if(this.account.Portfolio[ticker]!=null) ! marketCloseEventHandler_closePosition( ticker ); ! } ! } ! } ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! ! this.marketCloseEventHandler_closePositions(); } - - - #endregion public void Reset() --- 60,72 ---- } ! protected override void setTickers(DateTime currentDate) { ! if(!EndOfDayTimerHandlerCTOTest.optimized) ! { ! base.setTickers(currentDate); ! EndOfDayTimerHandlerCTOTest.optimized = true; ! } } public void Reset() *************** *** 139,239 **** EndOfDayTimerHandlerCTOTest.optimized = false; } - - #region OneHourAfterMarketCloseEventHandler - - private DataTable getSetOfTickersToBeOptimized(DateTime currentDate) - { - /* - SelectorByAverageRawOpenPrice selectorByOpenPrice = - new SelectorByAverageRawOpenPrice(this.tickerGroupID, false, - currentDate.AddDays(-this.numDaysForLiquidity), currentDate, - this.numberOfEligibleTickers, this.minPriceForMinimumCommission, - this.maxPriceForMinimumCommission, 0, 2); - DataTable tickersByPrice = selectorByOpenPrice.GetTableOfSelectedTickers(); - */ - - SelectorByLiquidity mostLiquid = new SelectorByLiquidity(this.tickerGroupID, false, - currentDate.AddDays(-this.numDaysForLiquidity), currentDate, - this.numberOfEligibleTickers); - //SelectorByOpenToCloseVolatility lessVolatile = - // new SelectorByOpenToCloseVolatility(mostLiquid.GetTableOfSelectedTickers(), - // true, currentDate.AddDays(-this.numDaysForLiquidity/3), - // currentDate, - // this.numberOfEligibleTickers/4); - - this.eligibleTickers = mostLiquid.GetTableOfSelectedTickers(); - SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromMostLiquid = - new SelectorByQuotationAtEachMarketDay( this.eligibleTickers, - false, currentDate.AddDays(-this.numDaysForLiquidity), - currentDate, this.numberOfEligibleTickers, this.benchmark); - //SelectorByWinningOpenToClose winners = - // new SelectorByWinningOpenToClose(quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(), - // false, currentDate.AddDays(-2), - // currentDate, this.numberOfEligibleTickers/4); - //return winners.GetTableOfSelectedTickers(); - return quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(); - } - - - private void setTickers(DateTime currentDate) - { - if(!EndOfDayTimerHandlerCTOTest.optimized) - { - DataTable setOfTickersToBeOptimized = - this.getSetOfTickersToBeOptimized(currentDate.AddDays(this.numDaysForLiquidity)); - if(setOfTickersToBeOptimized.Rows.Count > this.chosenTickers.Length*2) - //the optimization process is possible only if the initial set of tickers is - //as large as the number of tickers to be chosen - - { - IGenomeManager genManEfficientCTOPortfolio = - new GenomeManagerForEfficientCTOPortfolio(setOfTickersToBeOptimized, - currentDate, - currentDate.AddDays(this.numDaysForLiquidity), - this.numberOfTickersToBeChosen, - this.targetReturn, - this.portfolioType); - GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTOPortfolio, - this.populationSizeForGeneticOptimizer, - this.generationNumberForGeneticOptimizer); - //GO.KeepOnRunningUntilConvergenceIsReached = true; - GO.GenerationNumber = this.generationNumberForGeneticOptimizer; - GO.PopulationSize = this.populationSizeForGeneticOptimizer; - GO.Run(false); - this.chosenTickers = (string[])GO.BestGenome.Meaning; - - EndOfDayTimerHandlerCTOTest.optimized = true; - //this.lastChosenTickers = this.chosenTickers; - } - //else it will be buyed again the previous optimized portfolio - //that's it the actual chosenTickers member - } - } - private void oneHourAfterMarketCloseEventHandler_updatePrices() - { - //min price for minimizing commission amount - //according to IB Broker's commission scheme - this.minPriceForMinimumCommission = this.account.CashAmount/(this.numberOfTickersToBeChosen*100); - this.maxPriceForMinimumCommission = this.maxPriceForMinimumCommission; - //just to avoid warning message - } - - /// <summary> - /// Handles a "One hour after market close" event. - /// </summary> - /// <param name="sender"></param> - /// <param name="eventArgs"></param> - public override void OneHourAfterMarketCloseEventHandler( - Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) - { - //this.oneHourAfterMarketCloseEventHandler_updatePrices(); - this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime); - //sets tickers to be chosen next Market Open event - this.orders.Clear(); - } - - #endregion - } } --- 74,78 ---- Index: EndOfDayTimerHandlerCTO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerCTO.cs,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** EndOfDayTimerHandlerCTO.cs 17 May 2005 23:13:25 -0000 1.11 --- EndOfDayTimerHandlerCTO.cs 2 Jun 2005 18:00:47 -0000 1.12 *************** *** 63,67 **** #region MarketOpenEventHandler ! private void marketOpenEventHandler_orderChosenTickers_addToOrderList() { int idx = 0; --- 63,67 ---- #region MarketOpenEventHandler ! protected void marketOpenEventHandler_orderChosenTickers_addToOrderList() { int idx = 0; *************** *** 78,82 **** } ! private void marketOpenEventHandler_orderChosenTickers() { this.marketOpenEventHandler_orderChosenTickers_addToOrderList(); --- 78,82 ---- } ! protected void marketOpenEventHandler_orderChosenTickers() { this.marketOpenEventHandler_orderChosenTickers_addToOrderList(); *************** *** 105,114 **** #region MarketCloseEventHandler ! private void marketCloseEventHandler_closePosition( string ticker ) { this.account.ClosePosition( ticker ); } ! private void marketCloseEventHandler_closePositions() { if(this.lastChosenTickers != null) --- 105,114 ---- #region MarketCloseEventHandler ! protected void marketCloseEventHandler_closePosition( string ticker ) { this.account.ClosePosition( ticker ); } ! protected void marketCloseEventHandler_closePositions() { if(this.lastChosenTickers != null) *************** *** 136,140 **** #region OneHourAfterMarketCloseEventHandler ! private DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { /* --- 136,140 ---- #region OneHourAfterMarketCloseEventHandler ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { /* *************** *** 150,161 **** currentDate.AddDays(-this.numDaysForLiquidity), currentDate, this.numberOfEligibleTickers); ! //SelectorByOpenToCloseVolatility lessVolatile = ! // new SelectorByOpenToCloseVolatility(mostLiquid.GetTableOfSelectedTickers(), ! // true, currentDate.AddDays(-this.numDaysForLiquidity/3), ! // currentDate, ! // this.numberOfEligibleTickers/4); this.eligibleTickers = mostLiquid.GetTableOfSelectedTickers(); ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromMostLiquid = new SelectorByQuotationAtEachMarketDay( this.eligibleTickers, false, currentDate.AddDays(-this.numDaysForLiquidity), --- 150,161 ---- currentDate.AddDays(-this.numDaysForLiquidity), currentDate, this.numberOfEligibleTickers); ! /*SelectorByOpenToCloseVolatility lessVolatile = ! new SelectorByOpenToCloseVolatility(mostLiquid.GetTableOfSelectedTickers(), ! true, currentDate.AddDays(-5), ! currentDate, ! this.numberOfEligibleTickers/2);*/ this.eligibleTickers = mostLiquid.GetTableOfSelectedTickers(); ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromEligible = new SelectorByQuotationAtEachMarketDay( this.eligibleTickers, false, currentDate.AddDays(-this.numDaysForLiquidity), *************** *** 166,174 **** // currentDate, this.numberOfEligibleTickers/4); //return winners.GetTableOfSelectedTickers(); ! return quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(); } ! private void setTickers(DateTime currentDate) { --- 166,174 ---- // currentDate, this.numberOfEligibleTickers/4); //return winners.GetTableOfSelectedTickers(); ! return quotedAtEachMarketDayFromEligible.GetTableOfSelectedTickers(); } ! protected virtual void setTickers(DateTime currentDate) { *************** *** 186,198 **** this.targetReturn, this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTOPortfolio, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer); ! //GO.KeepOnRunningUntilConvergenceIsReached = true; ! GO.GenerationNumber = this.generationNumberForGeneticOptimizer; ! GO.PopulationSize = this.populationSizeForGeneticOptimizer; GO.Run(false); this.chosenTickers = (string[])GO.BestGenome.Meaning; - //this.lastChosenTickers = this.chosenTickers; } //else it will be buyed again the previous optimized portfolio --- 186,197 ---- this.targetReturn, this.portfolioType); + GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTOPortfolio, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer); ! GO.Run(false); + this.chosenTickers = (string[])GO.BestGenome.Meaning; } //else it will be buyed again the previous optimized portfolio *************** *** 200,204 **** } ! private void oneHourAfterMarketCloseEventHandler_updatePrices() { //min price for minimizing commission amount --- 199,203 ---- } ! protected void oneHourAfterMarketCloseEventHandler_updatePrices() { //min price for minimizing commission amount Index: RunEfficientPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/RunEfficientPortfolio.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** RunEfficientPortfolio.cs 17 May 2005 23:13:25 -0000 1.7 --- RunEfficientPortfolio.cs 2 Jun 2005 18:00:47 -0000 1.8 *************** *** 53,59 **** public class RunEfficientPorfolio { - public static double MaxNumberOfHoursForScript = 5; - //if MaxNumberOfHoursForScript has elapsed and the script - //is still running, it will be stopped. protected string tickerGroupID; protected int numberOfEligibleTickers; --- 53,56 ---- *************** *** 87,90 **** --- 84,90 ---- protected DateTime startingTimeForScript; + protected double maxRunningHours; + //if MaxNumberOfHoursForScript has elapsed and the script + //is still running, it will be stopped. public virtual string ScriptName *************** *** 100,109 **** public RunEfficientPorfolio(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForLiquidity, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, string benchmark, ! DateTime startDate, DateTime endDate, ! double targetReturn, ! PortfolioType portfolioType) { //this.progressBarForm = new ProgressBarForm(); --- 100,110 ---- public RunEfficientPorfolio(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForLiquidity, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, string benchmark, ! DateTime startDate, DateTime endDate, ! double targetReturn, ! PortfolioType portfolioType, ! double maxRunningHours) { //this.progressBarForm = new ProgressBarForm(); *************** *** 124,127 **** --- 125,129 ---- this.portfolioType = portfolioType; this.startingTimeForScript = DateTime.Now; + this.maxRunningHours = maxRunningHours; //this.numIntervalDays = 3; } *************** *** 165,170 **** { if(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime>=this.endDateTime.DateTime || ! DateTime.Now >= this.startingTimeForScript.AddHours(RunEfficientPorfolio.MaxNumberOfHoursForScript)) ! //last date is reached by the timer or MaxNumberOfHoursForScript hours //are elapsed from the time script started this.SaveScriptResults(); --- 167,172 ---- { if(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime>=this.endDateTime.DateTime || ! DateTime.Now >= this.startingTimeForScript.AddHours(this.maxRunningHours)) ! //last date is reached by the timer or maxRunning hours //are elapsed from the time script started this.SaveScriptResults(); --- NEW FILE: EndOfDayTimerHandlerCTCTest.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerCTCTest.cs Copyright (C) 2003 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.ADT; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.ADT.Optimizing.Genetic; namespace QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios { /// <summary> /// Implements MarketOpenEventHandler and MarketCloseEventHandler /// These handlers contain the core strategy for the efficient close to close /// portfolio (with a given days of life)! /// </summary> [Serializable] public class EndOfDayTimerHandlerCTCTest : EndOfDayTimerHandlerCTC { private static bool optimized; public EndOfDayTimerHandlerCTCTest(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForLiquidity, Account account, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, int numDaysOfPortfolioLife, int numDaysForReturnCalculation, double targetReturn, PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForLiquidity, account, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, numDaysOfPortfolioLife, numDaysForReturnCalculation, targetReturn, portfolioType, maxAcceptableCloseToCloseDrawdown) { } protected override void setTickers(DateTime currentDate) { if(!EndOfDayTimerHandlerCTCTest.optimized) { base.setTickers(currentDate); EndOfDayTimerHandlerCTCTest.optimized = true; } } public void Reset() { EndOfDayTimerHandlerCTCTest.optimized = false; } } } Index: RunEfficientCTOPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/RunEfficientCTOPortfolio.cs,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** RunEfficientCTOPortfolio.cs 4 May 2005 18:30:54 -0000 1.18 --- RunEfficientCTOPortfolio.cs 2 Jun 2005 18:00:47 -0000 1.19 *************** *** 62,66 **** int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, double targetReturn, ! PortfolioType portfolioType): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForLiquidity, --- 62,66 ---- int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, double targetReturn, ! PortfolioType portfolioType, double maxRunningHours): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForLiquidity, *************** *** 68,72 **** populationSizeForGeneticOptimizer, benchmark, startDate, endDate, targetReturn, ! portfolioType) { this.ScriptName = "OpenCloseScripts"; --- 68,72 ---- populationSizeForGeneticOptimizer, benchmark, startDate, endDate, targetReturn, ! portfolioType, maxRunningHours) { this.ScriptName = "OpenCloseScripts"; Index: GenomeManagerForEfficientPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/GenomeManagerForEfficientPortfolio.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** GenomeManagerForEfficientPortfolio.cs 4 May 2005 18:29:00 -0000 1.8 --- GenomeManagerForEfficientPortfolio.cs 2 Jun 2005 18:00:47 -0000 1.9 *************** *** 163,168 **** } ! public virtual double GetFitnessValue(Genome genome) { double returnValue = 0; --- 163,188 ---- } + protected virtual double getFitnessValue_calculate() + { + double returnValue = 0; + + NormalDistribution normal = + new NormalDistribution(this.rateOfReturn, + Math.Sqrt(this.variance)); + if(this.portfolioType == PortfolioType.OnlyLong || + this.portfolioType == PortfolioType.ShortAndLong) + //the genome fitness is evaluated as if + //the portfolio was long + //returnValue = normal.GetProbability(this.targetPerformance*0.75,this.targetPerformance*1.25); + returnValue = 1.0 - normal.GetProbability(this.targetPerformance); + else//only short orders are permitted + //returnValue = normal.GetProbability(-this.targetPerformance*1.25,-this.targetPerformance*0.75); + returnValue = normal.GetProbability(-this.targetPerformance); + + return returnValue; + + } ! public double GetFitnessValue(Genome genome) { double returnValue = 0; *************** *** 179,202 **** !Double.IsInfinity(averagePortfolioRateOfReturn) && !Double.IsNaN(portfolioVariance) && ! !Double.IsNaN(averagePortfolioRateOfReturn)) //both variance and rate of return are //double values computed in the right way: ! // so it's possible to assign fitness using normal distribution class { this.variance = portfolioVariance; this.rateOfReturn = averagePortfolioRateOfReturn; ! NormalDistribution normal = ! new NormalDistribution(this.rateOfReturn, ! Math.Sqrt(this.variance)); ! if(this.portfolioType == PortfolioType.OnlyLong || ! this.portfolioType == PortfolioType.ShortAndLong) ! //the genome fitness is evaluated as if ! //the portfolio was long ! //returnValue = normal.GetProbability(this.targetPerformance*0.75,this.targetPerformance*1.25); ! returnValue = 1.0 - normal.GetProbability(this.targetPerformance); ! else//only short orders are permitted ! //returnValue = normal.GetProbability(-this.targetPerformance*1.25,-this.targetPerformance*0.75); ! returnValue = normal.GetProbability(-this.targetPerformance); } return returnValue; } --- 199,213 ---- !Double.IsInfinity(averagePortfolioRateOfReturn) && !Double.IsNaN(portfolioVariance) && ! !Double.IsNaN(averagePortfolioRateOfReturn) && ! portfolioVariance > 0.0) //both variance and rate of return are //double values computed in the right way: ! // so it's possible to assign fitness { this.variance = portfolioVariance; this.rateOfReturn = averagePortfolioRateOfReturn; ! returnValue = this.getFitnessValue_calculate(); } + return returnValue; } *************** *** 233,237 **** genome.MaxValueForGenes +1); int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); ! while(genome.HasGene(newValueForGene)) { newValueForGene = GenomeManagement.RandomGenerator.Next(genome.MinValueForGenes, --- 244,251 ---- genome.MaxValueForGenes +1); int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); ! while(genome.HasGene(newValueForGene) || ! genome.HasGene(newValueForGene + this.originalNumOfTickers)) ! //the portfolio can't have a long position and a short position ! // for the same ticker { newValueForGene = GenomeManagement.RandomGenerator.Next(genome.MinValueForGenes, Index: EndOfDayTimerHandlerCTC.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerCTC.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** EndOfDayTimerHandlerCTC.cs 17 May 2005 23:13:25 -0000 1.7 --- EndOfDayTimerHandlerCTC.cs 2 Jun 2005 18:00:47 -0000 1.8 *************** *** 44,53 **** public class EndOfDayTimerHandlerCTC : EndOfDayTimerHandler { ! private int numDaysOfPortfolioLife; ! private int daysCounter; ! private double maxAcceptableCloseToCloseDrawdown; ! private bool stopLossConditionReached; ! private double currentAccountValue; ! private double previousAccountValue; public EndOfDayTimerHandlerCTC(string tickerGroupID, int numberOfEligibleTickers, --- 44,54 ---- public class EndOfDayTimerHandlerCTC : EndOfDayTimerHandler { ! protected int numDaysOfPortfolioLife; ! protected int numDaysForReturnCalculation; ! protected int daysCounter; ! protected double maxAcceptableCloseToCloseDrawdown; ! protected bool stopLossConditionReached; ! protected double currentAccountValue; ! protected double previousAccountValue; public EndOfDayTimerHandlerCTC(string tickerGroupID, int numberOfEligibleTickers, *************** *** 58,61 **** --- 59,63 ---- string benchmark, int numDaysOfPortfolioLife, + int numDaysForReturnCalculation, double targetReturn, PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): *************** *** 68,71 **** --- 70,74 ---- { this.numDaysOfPortfolioLife = numDaysOfPortfolioLife; + this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.daysCounter = 0; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; *************** *** 76,80 **** #region MarketOpenEventHandler ! private DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { SelectorByLiquidity mostLiquid = new SelectorByLiquidity(this.tickerGroupID,false, --- 79,83 ---- #region MarketOpenEventHandler ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { SelectorByLiquidity mostLiquid = new SelectorByLiquidity(this.tickerGroupID,false, *************** *** 91,95 **** ! private void setTickers(DateTime currentDate) { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); --- 94,98 ---- ! protected virtual void setTickers(DateTime currentDate) { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); *************** *** 108,112 **** currentDate.AddDays(-this.numDaysForLiquidity), currentDate, this.numberOfTickersToBeChosen, ! this.numDaysOfPortfolioLife, this.targetReturn, this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTCPortfolio, --- 111,116 ---- currentDate.AddDays(-this.numDaysForLiquidity), currentDate, this.numberOfTickersToBeChosen, ! this.numDaysOfPortfolioLife, this.numDaysForReturnCalculation, ! this.targetReturn, this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTCPortfolio, *************** *** 143,147 **** #region MarketCloseEventHandler ! private void marketCloseEventHandler_orderChosenTickers_addToOrderList() { int idx = 0; --- 147,151 ---- #region MarketCloseEventHandler ! protected void marketCloseEventHandler_orderChosenTickers_addToOrderList() { int idx = 0; *************** *** 155,159 **** } } ! private void marketCloseEventHandler_orderChosenTickers() { this.marketCloseEventHandler_orderChosenTickers_addToOrderList(); --- 159,163 ---- } } ! protected void marketCloseEventHandler_orderChosenTickers() { this.marketCloseEventHandler_orderChosenTickers_addToOrderList(); *************** *** 161,165 **** ! private void marketCloseEventHandler_openPositions() { if(this.orders.Count == 0 && this.account.Transactions.Count == 0) --- 165,169 ---- ! protected void marketCloseEventHandler_openPositions() { if(this.orders.Count == 0 && this.account.Transactions.Count == 0) *************** *** 174,183 **** } ! private void marketCloseEventHandler_closePosition( string ticker ) { this.account.ClosePosition( ticker ); } ! private void marketCloseEventHandler_closePositions() { if(this.lastChosenTickers != null) --- 178,187 ---- } ! protected void marketCloseEventHandler_closePosition( string ticker ) { this.account.ClosePosition( ticker ); } ! protected void marketCloseEventHandler_closePositions() { if(this.lastChosenTickers != null) *************** *** 194,198 **** } ! private void updateStopLossCondition() { this.previousAccountValue = this.currentAccountValue; --- 198,202 ---- } ! protected void updateStopLossCondition() { this.previousAccountValue = this.currentAccountValue; |