quantproject-developers Mailing List for QuantProject (Page 38)
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: Glauco S. <gla...@us...> - 2008-08-19 17:13:36
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/BestAndWorst In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/BestAndWorst Modified Files: RunBestAndWorstFollower.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunBestAndWorstFollower.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/BestAndWorst/RunBestAndWorstFollower.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunBestAndWorstFollower.cs 14 Jan 2008 23:43:47 -0000 1.2 --- RunBestAndWorstFollower.cs 19 Aug 2008 17:13:03 -0000 1.3 *************** *** 156,160 **** "_Short_" + this.numOfTickersForShortSelling + "_lenInDays_" + this.lengthInDaysForPerformance; ! string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; --- 156,161 ---- "_Short_" + this.numOfTickersForShortSelling + "_lenInDays_" + this.lengthInDaysForPerformance; ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:33
|
Update of /cvsroot/quantproject/QuantProject/b5_Presentation In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b5_Presentation Modified Files: Presentation_SD.csproj VisualObjectArchiver.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: VisualObjectArchiver.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b5_Presentation/VisualObjectArchiver.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** VisualObjectArchiver.cs 27 Feb 2008 22:29:39 -0000 1.3 --- VisualObjectArchiver.cs 19 Aug 2008 17:12:59 -0000 1.4 *************** *** 91,95 **** { this.Save( obj , suffix , title , title , ! System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] ); } private string getPath( string title , string suffix ) --- 91,95 ---- { this.Save( obj , suffix , title , title , ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] ); } private string getPath( string title , string suffix ) *************** *** 113,117 **** { return this.load( suffix , title , ! System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] ); } public object Load( string suffix , string title , string initialDirectory ) --- 113,117 ---- { return this.load( suffix , title , ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] ); } public object Load( string suffix , string title , string initialDirectory ) Index: Presentation_SD.csproj =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b5_Presentation/Presentation_SD.csproj,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** Presentation_SD.csproj 16 Mar 2008 20:14:31 -0000 1.5 --- Presentation_SD.csproj 19 Aug 2008 17:12:59 -0000 1.6 *************** *** 39,42 **** --- 39,43 ---- <ItemGroup> <Reference Include="System" /> + <Reference Include="System.Configuration" /> <Reference Include="System.Data" /> <Reference Include="System.Drawing" /> |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:32
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/WalkForwardTesting/LinearCombination Modified Files: OptimizationOutput.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: OptimizationOutput.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/OptimizationOutput.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** OptimizationOutput.cs 3 Aug 2006 21:24:36 -0000 1.3 --- OptimizationOutput.cs 19 Aug 2008 17:12:58 -0000 1.4 *************** *** 3,7 **** GenomeRepresentation.cs ! Copyright (C) 2003 Glauco Siliprandi --- 3,7 ---- GenomeRepresentation.cs ! Copyright (C) 2003 Glauco Siliprandi *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 67,71 **** // deserialize the fields from the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { FieldInfo fieldInfo = (FieldInfo) mi[i]; --- 67,71 ---- // deserialize the fields from the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { FieldInfo fieldInfo = (FieldInfo) mi[i]; *************** *** 73,81 **** // set the field to the deserialized value try{ ! fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); } catch(Exception ex) ! {ex = ex;} } --- 73,83 ---- // set the field to the deserialized value try{ ! fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); } catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } } *************** *** 89,101 **** /// <param name="context"></param> void ISerializable.GetObjectData( ! SerializationInfo info, StreamingContext context) { // get the set of serializable members for this class and base classes Type thisType = this.GetType(); ! MemberInfo[] mi = FormatterServices.GetSerializableMembers( thisType , context); // serialize the fields to the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(this)); --- 91,103 ---- /// <param name="context"></param> void ISerializable.GetObjectData( ! SerializationInfo info, StreamingContext context) { // get the set of serializable members for this class and base classes Type thisType = this.GetType(); ! MemberInfo[] mi = FormatterServices.GetSerializableMembers( thisType , context); // serialize the fields to the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(this)); |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:17
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts Modified Files: Scripts_SD.csproj Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: Scripts_SD.csproj =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/Scripts_SD.csproj,v retrieving revision 1.31 retrieving revision 1.32 diff -C2 -d -r1.31 -r1.32 *** Scripts_SD.csproj 16 Aug 2008 19:53:42 -0000 1.31 --- Scripts_SD.csproj 19 Aug 2008 17:13:13 -0000 1.32 *************** *** 40,43 **** --- 40,44 ---- <ItemGroup> <Reference Include="System" /> + <Reference Include="System.Configuration" /> <Reference Include="System.Data" /> <Reference Include="System.Drawing" /> |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:12:04
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2916/b7_Scripts/TickerSelectionTesting Modified Files: EndOfDayTimerHandlerCTO_WorstAtDay.cs EndOfDayTimerHandlerOTC_WorstAtNight.cs EndOfDayTimerHandlerOTCCTO.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: EndOfDayTimerHandlerOTCCTO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerOTCCTO.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** EndOfDayTimerHandlerOTCCTO.cs 14 Jan 2008 23:32:31 -0000 1.8 --- EndOfDayTimerHandlerOTCCTO.cs 19 Aug 2008 17:11:27 -0000 1.9 *************** *** 3,7 **** EndOfDayTimerHandlerOTCCTO.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- EndOfDayTimerHandlerOTCCTO.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 37,109 **** { ! /// <summary> ! /// Implements MarketOpenEventHandler, ! /// TwoMinutesBeforeMarketCloseEventHandler and OneHourAfterMarketCloseEventHandler ! /// These handlers contain the core strategy for the efficient close to open portfolio! ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerOTCCTO : EndOfDayTimerHandler ! { ! protected int seedForRandomGenerator; ! ! public EndOfDayTimerHandlerOTCCTO(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, double targetReturn, ! PortfolioType portfolioType, int numDaysBetweenEachOptimization): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, targetReturn, ! portfolioType) ! { ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.numDaysElapsedSinceLastOptimization = 0; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; ! } ! ! ! /// <summary> ! /// Handles a "Market Open" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! //temporarily the if condition ! //if(this.numDaysElapsedSinceLastOptimization == 0) ! AccountManager.ClosePositions(this.account); ! this.openPositions(); ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ! //temporarily ! //if(this.numDaysElapsedSinceLastOptimization == ! // this.numDaysBetweenEachOptimization) ! AccountManager.ClosePositions(this.account); ! try{ ! this.chosenWeightedPositions.Reverse(); ! this.openPositions(); ! } ! catch(Exception ex){ ! ex = ex; ! } ! this.chosenWeightedPositions.Reverse(); ! } ! ! #region OneHourAfterMarketCloseEventHandler ! ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { ! /* ! SelectorByAverageRawOpenPrice selectorByOpenPrice = new SelectorByAverageRawOpenPrice(this.tickerGroupID, false, currentDate.AddDays(-this.numDaysForLiquidity), currentDate, --- 37,110 ---- { ! /// <summary> ! /// Implements MarketOpenEventHandler, ! /// TwoMinutesBeforeMarketCloseEventHandler and OneHourAfterMarketCloseEventHandler ! /// These handlers contain the core strategy for the efficient close to open portfolio! ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerOTCCTO : EndOfDayTimerHandler ! { ! protected int seedForRandomGenerator; ! ! public EndOfDayTimerHandlerOTCCTO(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, double targetReturn, ! PortfolioType portfolioType, int numDaysBetweenEachOptimization): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, targetReturn, ! portfolioType) ! { ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.numDaysElapsedSinceLastOptimization = 0; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; ! } ! ! ! /// <summary> ! /// Handles a "Market Open" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! //temporarily the if condition ! //if(this.numDaysElapsedSinceLastOptimization == 0) ! AccountManager.ClosePositions(this.account); ! this.openPositions(); ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ! //temporarily ! //if(this.numDaysElapsedSinceLastOptimization == ! // this.numDaysBetweenEachOptimization) ! AccountManager.ClosePositions(this.account); ! try{ ! this.chosenWeightedPositions.Reverse(); ! this.openPositions(); ! } ! catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! this.chosenWeightedPositions.Reverse(); ! } ! ! #region OneHourAfterMarketCloseEventHandler ! ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { ! /* ! SelectorByAverageRawOpenPrice selectorByOpenPrice = new SelectorByAverageRawOpenPrice(this.tickerGroupID, false, currentDate.AddDays(-this.numDaysForLiquidity), currentDate, *************** *** 111,203 **** this.maxPriceForMinimumCommission, 0, 2); DataTable tickersByPrice = selectorByOpenPrice.GetTableOfSelectedTickers(); ! */ ! ! SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! SelectorByLiquidity mostLiquid = ! new SelectorByLiquidity(tickersFromGroup, ! false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromMostLiquid = ! new SelectorByQuotationAtEachMarketDay(mostLiquid.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! ! return quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(); ! ! } ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.numberOfTickersToBeChosen*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 genManEfficientOTCCTOPortfolio = ! new GenomeManagerForEfficientOTCCTOPortfolio(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, ! this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType, ! this.benchmark); ! ! GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCCTOPortfolio, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); ! ! GO.Run(false); ! this.addGenomeToBestGenomes(GO.BestGenome,currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, setOfTickersToBeOptimized.Rows.Count); ! this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers) ); ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! protected 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.seedForRandomGenerator++; ! //this.oneHourAfterMarketCloseEventHandler_updatePrices(); ! if(this.numDaysElapsedSinceLastOptimization == ! this.numDaysBetweenEachOptimization - 1) ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Open event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! else ! { ! this.numDaysElapsedSinceLastOptimization++; ! } ! ! } ! ! #endregion ! } } --- 112,204 ---- this.maxPriceForMinimumCommission, 0, 2); DataTable tickersByPrice = selectorByOpenPrice.GetTableOfSelectedTickers(); ! */ ! ! SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! SelectorByLiquidity mostLiquid = ! new SelectorByLiquidity(tickersFromGroup, ! false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromMostLiquid = ! new SelectorByQuotationAtEachMarketDay(mostLiquid.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! ! return quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(); ! ! } ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.numberOfTickersToBeChosen*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 genManEfficientOTCCTOPortfolio = ! new GenomeManagerForEfficientOTCCTOPortfolio(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, ! this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType, ! this.benchmark); ! ! GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCCTOPortfolio, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); ! ! GO.Run(false); ! this.addGenomeToBestGenomes(GO.BestGenome,currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, setOfTickersToBeOptimized.Rows.Count); ! this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers) ); ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! protected 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.seedForRandomGenerator++; ! //this.oneHourAfterMarketCloseEventHandler_updatePrices(); ! if(this.numDaysElapsedSinceLastOptimization == ! this.numDaysBetweenEachOptimization - 1) ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Open event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! else ! { ! this.numDaysElapsedSinceLastOptimization++; ! } ! ! } ! ! #endregion ! ! } } Index: EndOfDayTimerHandlerCTO_WorstAtDay.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerCTO_WorstAtDay.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** EndOfDayTimerHandlerCTO_WorstAtDay.cs 14 Jan 2008 23:32:31 -0000 1.3 --- EndOfDayTimerHandlerCTO_WorstAtDay.cs 19 Aug 2008 17:11:26 -0000 1.4 *************** *** 3,7 **** EndOfDayTimerHandlerCTO_WorstAtDay.cs ! Copyright (C) 2007 Marco Milletti --- 3,7 ---- EndOfDayTimerHandlerCTO_WorstAtDay.cs ! Copyright (C) 2007 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 38,88 **** { ! /// <summary> ! /// Implements MarketOpenEventHandler, ! /// MarketCloseEventHandler, ! /// OneHourAfterMarketCloseEventHandler ! /// These handlers contain the core strategy ! /// for the efficient close to open worst by day portfolio! ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerCTO_WorstAtDay : EndOfDayTimerHandler ! { ! protected int seedForRandomGenerator; ! protected GeneticOptimizer currentGO; protected int numOfGenomesForOTCScanning; ! ! public EndOfDayTimerHandlerCTO_WorstAtDay(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, double targetReturn, ! PortfolioType portfolioType, int numDaysBetweenEachOptimization, ! int numOfGenomesForOTCScanning): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, targetReturn, ! portfolioType) ! { ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.numDaysElapsedSinceLastOptimization = 0; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; ! this.numOfGenomesForOTCScanning = numOfGenomesForOTCScanning; ! } ! ! /// <summary> ! /// Handles a "Market Open" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! AccountManager.ClosePositions(this.account); ! } ! private void marketCloseEventHandler_chooseTheWorstOTCGenome() { int populationSize = this.currentGO.PopulationSize; --- 38,88 ---- { ! /// <summary> ! /// Implements MarketOpenEventHandler, ! /// MarketCloseEventHandler, ! /// OneHourAfterMarketCloseEventHandler ! /// These handlers contain the core strategy ! /// for the efficient close to open worst by day portfolio! ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerCTO_WorstAtDay : EndOfDayTimerHandler ! { ! protected int seedForRandomGenerator; ! protected GeneticOptimizer currentGO; protected int numOfGenomesForOTCScanning; ! ! public EndOfDayTimerHandlerCTO_WorstAtDay(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, double targetReturn, ! PortfolioType portfolioType, int numDaysBetweenEachOptimization, ! int numOfGenomesForOTCScanning): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, targetReturn, ! portfolioType) ! { ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.numDaysElapsedSinceLastOptimization = 0; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; ! this.numOfGenomesForOTCScanning = numOfGenomesForOTCScanning; ! } ! ! /// <summary> ! /// Handles a "Market Open" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! AccountManager.ClosePositions(this.account); ! } ! private void marketCloseEventHandler_chooseTheWorstOTCGenome() { int populationSize = this.currentGO.PopulationSize; *************** *** 92,243 **** double fitnessOfPreviousCombination = 0.0; IndexBasedEndOfDayTimer currentTimer = (IndexBasedEndOfDayTimer)this.account.EndOfDayTimer; ! DateTime today = currentTimer.GetCurrentTime().DateTime; ! int numOfGenomesScanned = 0; ! for(int i = 0; numOfGenomesScanned < this.numOfGenomesForOTCScanning; i++) ! { ! if( i == 0 || ! ( ((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Fitness < ! fitnessOfPreviousCombination ) ) ! //it is the best genome or the current genome is different from - and ! //so it has to be strictly less of - the previous scanned genome ! { ! fitnessOfPreviousCombination = ! ((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Fitness; ! try{ ! //retrieves loss at day for the CurrentCombination ! SignedTickers signedTickers = new SignedTickers( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Meaning).Tickers); ! WeightedPositions weightedPositions = ! new WeightedPositions( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Meaning).TickersPortfolioWeights, ! signedTickers); ! lossOfCurrentCombination = ! - weightedPositions.GetOpenToCloseReturn( today ); ! //- because fitness in GenomeOTCCTO is just the reversal of what needed ! numOfGenomesScanned++; ! if(lossOfCurrentCombination < lossOfCurrentWorstCombination) ! { ! indexOfWorstCombination = populationSize - i - 1; ! lossOfCurrentWorstCombination = lossOfCurrentCombination; ! } ! } ! catch(Exception ex){ ! //if retrieving of loss of current combination fails ! ex = ex; ! } ! } ! } this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[indexOfWorstCombination]).Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[indexOfWorstCombination]).Meaning).Tickers)); } ! ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.currentGO != null) ! //so a list of genomes is available this.marketCloseEventHandler_chooseTheWorstOTCGenome(); ! this.openPositions(); ! } #region OneHourAfterMarketCloseEventHandler ! ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); SelectorByLiquidity mostLiquid = new SelectorByLiquidity(tickersFromGroup, ! false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromMostLiquid = new SelectorByQuotationAtEachMarketDay(mostLiquid.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! ! SelectorByAverageRawOpenPrice byPrice = new SelectorByAverageRawOpenPrice(quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-30), ! currentDate, ! this.numberOfEligibleTickers, ! 30); ! return byPrice.GetTableOfSelectedTickers(); ! } ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.numberOfTickersToBeChosen * 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 GenomeManagerForEfficientOTCCTOPortfolio(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, ! this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType, ! this.benchmark); ! ! GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTOPortfolio, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); GO.MutationRate = 0.25; GO.CrossoverRate = 0.95; ! GO.Run(false); ! this.addGenomeToBestGenomes(GO.BestGenome,currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, setOfTickersToBeOptimized.Rows.Count); this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers) ); this.currentGO = GO; ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! protected 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.seedForRandomGenerator++; ! //this.oneHourAfterMarketCloseEventHandler_updatePrices(); ! if(this.numDaysElapsedSinceLastOptimization == ! this.numDaysBetweenEachOptimization - 1) ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Close event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! else ! { ! this.numDaysElapsedSinceLastOptimization++; ! } ! ! } ! #endregion ! } } --- 92,244 ---- double fitnessOfPreviousCombination = 0.0; IndexBasedEndOfDayTimer currentTimer = (IndexBasedEndOfDayTimer)this.account.EndOfDayTimer; ! DateTime today = currentTimer.GetCurrentTime().DateTime; ! int numOfGenomesScanned = 0; ! for(int i = 0; numOfGenomesScanned < this.numOfGenomesForOTCScanning; i++) ! { ! if( i == 0 || ! ( ((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Fitness < ! fitnessOfPreviousCombination ) ) ! //it is the best genome or the current genome is different from - and ! //so it has to be strictly less of - the previous scanned genome ! { ! fitnessOfPreviousCombination = ! ((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Fitness; ! try{ ! //retrieves loss at day for the CurrentCombination ! SignedTickers signedTickers = new SignedTickers( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Meaning).Tickers); ! WeightedPositions weightedPositions = ! new WeightedPositions( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Meaning).TickersPortfolioWeights, ! signedTickers); ! lossOfCurrentCombination = ! - weightedPositions.GetOpenToCloseReturn( today ); ! //- because fitness in GenomeOTCCTO is just the reversal of what needed ! numOfGenomesScanned++; ! if(lossOfCurrentCombination < lossOfCurrentWorstCombination) ! { ! indexOfWorstCombination = populationSize - i - 1; ! lossOfCurrentWorstCombination = lossOfCurrentCombination; ! } ! } ! catch(Exception ex) ! { ! //if retrieving of loss of current combination fails ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! } ! } this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[indexOfWorstCombination]).Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[indexOfWorstCombination]).Meaning).Tickers)); } ! ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.currentGO != null) ! //so a list of genomes is available this.marketCloseEventHandler_chooseTheWorstOTCGenome(); ! this.openPositions(); ! } #region OneHourAfterMarketCloseEventHandler ! ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); SelectorByLiquidity mostLiquid = new SelectorByLiquidity(tickersFromGroup, ! false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromMostLiquid = new SelectorByQuotationAtEachMarketDay(mostLiquid.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! ! SelectorByAverageRawOpenPrice byPrice = new SelectorByAverageRawOpenPrice(quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-30), ! currentDate, ! this.numberOfEligibleTickers, ! 30); ! return byPrice.GetTableOfSelectedTickers(); ! } ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.numberOfTickersToBeChosen * 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 GenomeManagerForEfficientOTCCTOPortfolio(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, ! this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType, ! this.benchmark); ! ! GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTOPortfolio, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); GO.MutationRate = 0.25; GO.CrossoverRate = 0.95; ! GO.Run(false); ! this.addGenomeToBestGenomes(GO.BestGenome,currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, setOfTickersToBeOptimized.Rows.Count); this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers) ); this.currentGO = GO; ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! protected 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.seedForRandomGenerator++; ! //this.oneHourAfterMarketCloseEventHandler_updatePrices(); ! if(this.numDaysElapsedSinceLastOptimization == ! this.numDaysBetweenEachOptimization - 1) ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Close event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! else ! { ! this.numDaysElapsedSinceLastOptimization++; ! } ! ! } ! #endregion ! } } Index: EndOfDayTimerHandlerOTC_WorstAtNight.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerOTC_WorstAtNight.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** EndOfDayTimerHandlerOTC_WorstAtNight.cs 14 Jan 2008 23:32:31 -0000 1.3 --- EndOfDayTimerHandlerOTC_WorstAtNight.cs 19 Aug 2008 17:11:26 -0000 1.4 *************** *** 3,7 **** EndOfDayTimerHandlerOTC_WorstAtNight.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- EndOfDayTimerHandlerOTC_WorstAtNight.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 40,77 **** { ! /// <summary> ! /// Implements MarketOpenEventHandler, ! /// TwoMinutesBeforeMarketCloseEventHandler and OneHourAfterMarketCloseEventHandler ! /// These handlers contain the core strategy for the efficient close to open portfolio! ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerOTC_WorstAtNight : EndOfDayTimerHandler ! { ! protected int seedForRandomGenerator; protected GeneticOptimizer currentGO; protected int numOfGenomesForCTOScanning; private HistoricalAdjustedQuoteProvider historicalAdjustedQuoteProvider; ! ! public EndOfDayTimerHandlerOTC_WorstAtNight(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, double targetReturn, ! PortfolioType portfolioType, int numDaysBetweenEachOptimization, ! int numOfGenomesForCTOScanning): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, targetReturn, ! portfolioType) ! { ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.numDaysElapsedSinceLastOptimization = 0; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; this.numOfGenomesForCTOScanning = numOfGenomesForCTOScanning; this.historicalAdjustedQuoteProvider = new HistoricalAdjustedQuoteProvider(); ! } ! private void marketOpenEventHandler_chooseTheWorstCTOGenome() { --- 40,77 ---- { ! /// <summary> ! /// Implements MarketOpenEventHandler, ! /// TwoMinutesBeforeMarketCloseEventHandler and OneHourAfterMarketCloseEventHandler ! /// These handlers contain the core strategy for the efficient close to open portfolio! ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerOTC_WorstAtNight : EndOfDayTimerHandler ! { ! protected int seedForRandomGenerator; protected GeneticOptimizer currentGO; protected int numOfGenomesForCTOScanning; private HistoricalAdjustedQuoteProvider historicalAdjustedQuoteProvider; ! ! public EndOfDayTimerHandlerOTC_WorstAtNight(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, double targetReturn, ! PortfolioType portfolioType, int numDaysBetweenEachOptimization, ! int numOfGenomesForCTOScanning): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, targetReturn, ! portfolioType) ! { ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.numDaysElapsedSinceLastOptimization = 0; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; this.numOfGenomesForCTOScanning = numOfGenomesForCTOScanning; this.historicalAdjustedQuoteProvider = new HistoricalAdjustedQuoteProvider(); ! } ! private void marketOpenEventHandler_chooseTheWorstCTOGenome() { *************** *** 82,265 **** double fitnessOfPreviousCombination = 0.0; IndexBasedEndOfDayTimer currentTimer = (IndexBasedEndOfDayTimer)this.account.EndOfDayTimer; ! DateTime today = currentTimer.GetCurrentTime().DateTime; ! DateTime lastMarketDay = currentTimer.GetPreviousDateTime(); ! ReturnsManager returnsManager = new ReturnsManager( ! new CloseToOpenIntervals(new EndOfDayDateTime(lastMarketDay, EndOfDaySpecificTime.MarketClose), ! new EndOfDayDateTime(today, EndOfDaySpecificTime.MarketOpen), ! this.benchmark), ! this.historicalAdjustedQuoteProvider ); ! int numOfGenomesScanned = 0; ! for(int i = 0; ! numOfGenomesScanned < this.numOfGenomesForCTOScanning && ! i < populationSize - 1; ! i++) ! { ! if( i == 0 || ! ( ((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Fitness < ! fitnessOfPreviousCombination ) ) ! //it is the best genome or the current genome is different from - and ! //so it has to be strictly less of - the previous scanned genome ! { ! fitnessOfPreviousCombination = ! ((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Fitness; ! try{ ! //tries to retrieve loss at night for the CurrentCombination ! SignedTickers signedTickers = new SignedTickers( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Meaning).Tickers); ! WeightedPositions weightedPositions = ! new WeightedPositions( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Meaning).TickersPortfolioWeights, ! signedTickers); ! lossOfCurrentCombination = ! weightedPositions.GetReturn( 0 , returnsManager ); ! numOfGenomesScanned++; ! if(lossOfCurrentCombination < lossOfCurrentWorstCombination) ! { ! indexOfWorstCombination = populationSize - i - 1; ! lossOfCurrentWorstCombination = lossOfCurrentCombination; ! } ! } ! catch(Exception ex){ ! //retrieve of loss of current combination fails ! ex = ex; ! } ! } ! } ! this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[indexOfWorstCombination]).Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[indexOfWorstCombination]).Meaning).Tickers)); } ! ! /// <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.currentGO != null) ! //so a list of genomes is available ! this.marketOpenEventHandler_chooseTheWorstCTOGenome(); this.openPositions(); ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! AccountManager.ClosePositions(this.account); ! } ! #region OneHourAfterMarketCloseEventHandler ! ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); SelectorByLiquidity mostLiquid = new SelectorByLiquidity(tickersFromGroup, ! false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromMostLiquid = new SelectorByQuotationAtEachMarketDay(mostLiquid.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! ! SelectorByAverageRawOpenPrice byPrice = new SelectorByAverageRawOpenPrice(quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-30), ! currentDate, ! this.numberOfEligibleTickers, ! 35); DataTable tickersByPrice = byPrice.GetTableOfSelectedTickers(); ! ! SelectorByOpenCloseCorrelationToBenchmark tickersLessCorrelatedToBenchmark = new SelectorByOpenCloseCorrelationToBenchmark(tickersByPrice, ! "^GSPC",true, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! tickersByPrice.Rows.Count/2); ! return tickersLessCorrelatedToBenchmark.GetTableOfSelectedTickers(); ! } ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.numberOfTickersToBeChosen*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 genManEfficientOTCPortfolio = ! // new GenomeManagerForEfficientOTCPortfolio(setOfTickersToBeOptimized, ! // currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! // currentDate, ! // this.numberOfTickersToBeChosen, ! // this.targetReturn, ! // this.portfolioType); ! new GenomeManagerForEfficientOTCCTOPortfolio(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, ! this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType,this.benchmark); ! GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); GO.CrossoverRate = 0.0; GO.MutationRate = 0.50; ! GO.Run(false); ! this.addGenomeToBestGenomes(GO.BestGenome,currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, setOfTickersToBeOptimized.Rows.Count); ! this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers) ); this.currentGO = GO; ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! protected 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.seedForRandomGenerator++; ! //this.oneHourAfterMarketCloseEventHandler_updatePrices(); ! if(this.numDaysElapsedSinceLastOptimization == ! this.numDaysBetweenEachOptimization - 1) ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Open event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! else ! { ! this.numDaysElapsedSinceLastOptimization++; ! } ! ! } ! ! #endregion ! } } --- 82,266 ---- double fitnessOfPreviousCombination = 0.0; IndexBasedEndOfDayTimer currentTimer = (IndexBasedEndOfDayTimer)this.account.EndOfDayTimer; ! DateTime today = currentTimer.GetCurrentTime().DateTime; ! DateTime lastMarketDay = currentTimer.GetPreviousDateTime(); ! ReturnsManager returnsManager = new ReturnsManager( ! new CloseToOpenIntervals(new EndOfDayDateTime(lastMarketDay, EndOfDaySpecificTime.MarketClose), ! new EndOfDayDateTime(today, EndOfDaySpecificTime.MarketOpen), ! this.benchmark), ! this.historicalAdjustedQuoteProvider ); ! int numOfGenomesScanned = 0; ! for(int i = 0; ! numOfGenomesScanned < this.numOfGenomesForCTOScanning && ! i < populationSize - 1; ! i++) ! { ! if( i == 0 || ! ( ((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Fitness < ! fitnessOfPreviousCombination ) ) ! //it is the best genome or the current genome is different from - and ! //so it has to be strictly less of - the previous scanned genome ! { ! fitnessOfPreviousCombination = ! ((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Fitness; ! try{ ! //tries to retrieve loss at night for the CurrentCombination ! SignedTickers signedTickers = new SignedTickers( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Meaning).Tickers); ! WeightedPositions weightedPositions = ! new WeightedPositions( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Meaning).TickersPortfolioWeights, ! signedTickers); ! lossOfCurrentCombination = ! weightedPositions.GetReturn( 0 , returnsManager ); ! numOfGenomesScanned++; ! if(lossOfCurrentCombination < lossOfCurrentWorstCombination) ! { ! indexOfWorstCombination = populationSize - i - 1; ! lossOfCurrentWorstCombination = lossOfCurrentCombination; ! } ! } ! catch(Exception ex) ! { ! //retrieve of loss of current combination fails ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! } ! } ! this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[indexOfWorstCombination]).Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[indexOfWorstCombination]).Meaning).Tickers)); } ! ! /// <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.currentGO != null) ! //so a list of genomes is available ! this.marketOpenEventHandler_chooseTheWorstCTOGenome(); this.openPositions(); ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! AccountManager.ClosePositions(this.account); ! } ! #region OneHourAfterMarketCloseEventHandler ! ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); SelectorByLiquidity mostLiquid = new SelectorByLiquidity(tickersFromGroup, ! false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromMostLiquid = new SelectorByQuotationAtEachMarketDay(mostLiquid.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! ! SelectorByAverageRawOpenPrice byPrice = new SelectorByAverageRawOpenPrice(quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-30), ! currentDate, ! this.numberOfEligibleTickers, ! 35); DataTable tickersByPrice = byPrice.GetTableOfSelectedTickers(); ! ! SelectorByOpenCloseCorrelationToBenchmark tickersLessCorrelatedToBenchmark = new SelectorByOpenCloseCorrelationToBenchmark(tickersByPrice, ! "^GSPC",true, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! tickersByPrice.Rows.Count/2); ! return tickersLessCorrelatedToBenchmark.GetTableOfSelectedTickers(); ! } ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.numberOfTickersToBeChosen*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 genManEfficientOTCPortfolio = ! // new GenomeManagerForEfficientOTCPortfolio(setOfTickersToBeOptimized, ! // currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! // currentDate, ! // this.numberOfTickersToBeChosen, ! // this.targetReturn, ! // this.portfolioType); ! new GenomeManagerForEfficientOTCCTOPortfolio(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, ! this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType,this.benchmark); ! GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); GO.CrossoverRate = 0.0; GO.MutationRate = 0.50; ! GO.Run(false); ! this.addGenomeToBestGenomes(GO.BestGenome,currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, setOfTickersToBeOptimized.Rows.Count); ! this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers) ); this.currentGO = GO; ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! protected 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.seedForRandomGenerator++; ! //this.oneHourAfterMarketCloseEventHandler_updatePrices(); ! if(this.numDaysElapsedSinceLastOptimization == ! this.numDaysBetweenEachOptimization - 1) ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Open event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! else ! { ! this.numDaysElapsedSinceLastOptimization++; ! } ! ! } ! ! #endregion ! ! } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:12:02
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2916/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower Modified Files: EndOfDayTimerHandlerITF.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: EndOfDayTimerHandlerITF.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower/EndOfDayTimerHandlerITF.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** EndOfDayTimerHandlerITF.cs 14 Jan 2008 23:32:30 -0000 1.6 --- EndOfDayTimerHandlerITF.cs 19 Aug 2008 17:11:28 -0000 1.7 *************** *** 3,7 **** EndOfDayTimerHandlerITF.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- EndOfDayTimerHandlerITF.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 40,297 **** { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the extreme ! /// counter trend strategy! ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerITF : EndOfDayTimerHandler ! { ! private int numDaysForReturnCalculation; ! private double maxAcceptableCloseToCloseDrawdown; ! private int daysCounterWithPositions; ! private DateTime lastCloseDate; ! private IGenomeManager iGenomeManager; ! private int seedForRandomGenerator; ! ! public EndOfDayTimerHandlerITF(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, ! int numDaysForReturnCalculation, ! int numDaysBetweenEachOptimization, ! PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, 0.0, ! portfolioType) ! { ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.stopLossConditionReached = false; ! this.currentAccountValue = 0.0; ! this.previousAccountValue = 0.0; ! // this.numDaysBetweenEachOptimization = 2* numDaysForReturnCalculation; ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; ! } ! ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } ! #region MarketCloseEventHandler ! ! protected void marketCloseEventHandler_updateStopLossCondition() ! { ! this.previousAccountValue = this.currentAccountValue; ! this.currentAccountValue = this.account.GetMarketValue(); ! if((this.currentAccountValue - this.previousAccountValue) ! /this.previousAccountValue < -this.maxAcceptableCloseToCloseDrawdown) ! { ! this.stopLossConditionReached = true; ! } ! else ! { ! this.stopLossConditionReached = false; ! } ! } ! private double marketCloseEventHandler_openPositions_getLastHalfPeriodGain(IndexBasedEndOfDayTimer timer) ! { ! double returnValue = 999.0; ! try ! { ! DateTime initialDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation + 1]["quDate"]; ! DateTime finalDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! returnValue = ! chosenWeightedPositions.GetCloseToCloseReturn(initialDateForHalfPeriod,finalDateForHalfPeriod); ! } ! catch(MissingQuotesException ex) ! { ! ex = ex; ! } ! return returnValue; ! } ! private void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) ! { ! double lastHalfPeriodGain = ! this.marketCloseEventHandler_openPositions_getLastHalfPeriodGain(timer); ! if(lastHalfPeriodGain != 999.0) ! //last half period gain has been properly computed ! { ! if(lastHalfPeriodGain > 0.0) ! AccountManager.OpenPositions(chosenWeightedPositions, this.account); ! else//the last HalfPeriodGain has been negative ! { ! chosenWeightedPositions.Reverse(); ! //short the portfolio ! try{ ! AccountManager.OpenPositions(chosenWeightedPositions, this.account); ! } ! catch(Exception ex) ! { ! ex = ex; ! } ! finally{ ! chosenWeightedPositions.Reverse(); ! } ! } ! } ! } ! ! private void marketCloseEventHandler_closePositions() ! { ! if(this.daysCounterWithPositions == this.numDaysForReturnCalculation || ! this.stopLossConditionReached) ! { ! //Close if halfPeriod has elapsed or stop loss condition reached ! AccountManager.ClosePositions(this.account); ! this.daysCounterWithPositions = 0; ! } ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! //this.marketCloseEventHandler_updateStopLossCondition(); ! if(this.account.Portfolio.Count > 0) ! this.daysCounterWithPositions++; ! this.marketCloseEventHandler_closePositions(); ! if(chosenWeightedPositions != null) ! //tickers to buy have been chosen ! { ! if(this.account.Portfolio.Count == 0) ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); ! } ! ! } ! #endregion ! ! #region OneHourAfterMarketCloseEventHandler ! ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! int numOfTickersInGroupAtCurrentDate = tickersFromGroup.Rows.Count; ! ! SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice(tickersFromGroup,false,currentDate, ! currentDate.AddDays(-30), ! numOfTickersInGroupAtCurrentDate, ! 30,500, 0.0001,100); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromByPrice = ! new SelectorByQuotationAtEachMarketDay(byPrice.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! numOfTickersInGroupAtCurrentDate, this.benchmark); ! ! // SelectorByCloseToCloseVolatility lessVolatile = ! // new SelectorByCloseToCloseVolatility(quotedAtEachMarketDayFromByPrice.GetTableOfSelectedTickers(), ! // true,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // this.numberOfEligibleTickers); ! ! SelectorByLiquidity mostLiquidSelector = ! new SelectorByLiquidity(quotedAtEachMarketDayFromByPrice.GetTableOfSelectedTickers(), ! true,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers); ! ! ! return mostLiquidSelector.GetTableOfSelectedTickers(); ! //OLD for etf ! // 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(); ! } ! ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.numberOfTickersToBeChosen*2) ! //the optimization process is meaningful only if the initial set of tickers is ! //larger than the number of tickers to be chosen ! ! { ! this.iGenomeManager = ! new GenomeManagerITF(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, this.numberOfTickersToBeChosen, ! this.numDaysForReturnCalculation, ! this.portfolioType, this.benchmark); ! GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); ! ! GO.Run(false); ! this.addGenomeToBestGenomes(GO.BestGenome,((GenomeManagerForEfficientPortfolio)this.iGenomeManager).FirstQuoteDate, ! ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate, setOfTickersToBeOptimized.Rows.Count, ! this.numDaysForReturnCalculation); this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers) ); ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! ! /// <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.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! this.seedForRandomGenerator++; ! this.numDaysElapsedSinceLastOptimization++; ! if((this.numDaysElapsedSinceLastOptimization - 1 == ! this.numDaysBetweenEachOptimization)) //|| this.isTheFirstClose ) ! //num days without optimization has elapsed or ! //it is the first close (OLD IMPLEMENTATION) ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Close event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! ! } #endregion ! } } --- 40,297 ---- { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the extreme ! /// counter trend strategy! ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerITF : EndOfDayTimerHandler ! { ! private int numDaysForReturnCalculation; ! private double maxAcceptableCloseToCloseDrawdown; ! private int daysCounterWithPositions; ! private DateTime lastCloseDate; ! private IGenomeManager iGenomeManager; ! private int seedForRandomGenerator; ! ! public EndOfDayTimerHandlerITF(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, ! int numDaysForReturnCalculation, ! int numDaysBetweenEachOptimization, ! PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, 0.0, ! portfolioType) ! { ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.stopLossConditionReached = false; ! this.currentAccountValue = 0.0; ! this.previousAccountValue = 0.0; ! // this.numDaysBetweenEachOptimization = 2* numDaysForReturnCalculation; ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; ! } ! ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } ! #region MarketCloseEventHandler ! ! protected void marketCloseEventHandler_updateStopLossCondition() ! { ! this.previousAccountValue = this.currentAccountValue; ! this.currentAccountValue = this.account.GetMarketValue(); ! if((this.currentAccountValue - this.previousAccountValue) ! /this.previousAccountValue < -this.maxAcceptableCloseToCloseDrawdown) ! { ! this.stopLossConditionReached = true; ! } ! else ! { ! this.stopLossConditionReached = false; ! } ! } ! private double marketCloseEventHandler_openPositions_getLastHalfPeriodGain(IndexBasedEndOfDayTimer timer) ! { ! double returnValue = 999.0; ! try ! { ! DateTime initialDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation + 1]["quDate"]; ! DateTime finalDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! returnValue = ! chosenWeightedPositions.GetCloseToCloseReturn(initialDateForHalfPeriod,finalDateForHalfPeriod); ! } ! catch(MissingQuotesException ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! return returnValue; ! } ! private void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) ! { ! double lastHalfPeriodGain = ! this.marketCloseEventHandler_openPositions_getLastHalfPeriodGain(timer); ! if(lastHalfPeriodGain != 999.0) ! //last half period gain has been properly computed ! { ! if(lastHalfPeriodGain > 0.0) ! AccountManager.OpenPositions(chosenWeightedPositions, this.account); ! else//the last HalfPeriodGain has been negative ! { ! chosenWeightedPositions.Reverse(); ! //short the portfolio ! try{ ! AccountManager.OpenPositions(chosenWeightedPositions, this.account); ! } ! catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! finally{ ! chosenWeightedPositions.Reverse(); ! } ! } ! } ! } ! ! private void marketCloseEventHandler_closePositions() ! { ! if(this.daysCounterWithPositions == this.numDaysForReturnCalculation || ! this.stopLossConditionReached) ! { ! //Close if halfPeriod has elapsed or stop loss condition reached ! AccountManager.ClosePositions(this.account); ! this.daysCounterWithPositions = 0; ! } ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! //this.marketCloseEventHandler_updateStopLossCondition(); ! if(this.account.Portfolio.Count > 0) ! this.daysCounterWithPositions++; ! this.marketCloseEventHandler_closePositions(); ! if(chosenWeightedPositions != null) ! //tickers to buy have been chosen ! { ! if(this.account.Portfolio.Count == 0) ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); ! } ! ! } ! #endregion ! ! #region OneHourAfterMarketCloseEventHandler ! ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! int numOfTickersInGroupAtCurrentDate = tickersFromGroup.Rows.Count; ! ! SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice(tickersFromGroup,false,currentDate, ! currentDate.AddDays(-30), ! numOfTickersInGroupAtCurrentDate, ! 30,500, 0.0001,100); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromByPrice = ! new SelectorByQuotationAtEachMarketDay(byPrice.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! numOfTickersInGroupAtCurrentDate, this.benchmark); ! ! // SelectorByCloseToCloseVolatility lessVolatile = ! // new SelectorByCloseToCloseVolatility(quotedAtEachMarketDayFromByPrice.GetTableOfSelectedTickers(), ! // true,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // this.numberOfEligibleTickers); ! ! SelectorByLiquidity mostLiquidSelector = ! new SelectorByLiquidity(quotedAtEachMarketDayFromByPrice.GetTableOfSelectedTickers(), ! true,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers); ! ! ! return mostLiquidSelector.GetTableOfSelectedTickers(); ! //OLD for etf ! // 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(); ! } ! ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.numberOfTickersToBeChosen*2) ! //the optimization process is meaningful only if the initial set of tickers is ! //larger than the number of tickers to be chosen ! ! { ! this.iGenomeManager = ! new GenomeManagerITF(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, this.numberOfTickersToBeChosen, ! this.numDaysForReturnCalculation, ! this.portfolioType, this.benchmark); ! GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); ! ! GO.Run(false); ! this.addGenomeToBestGenomes(GO.BestGenome,((GenomeManagerForEfficientPortfolio)this.iGenomeManager).FirstQuoteDate, ! ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate, setOfTickersToBeOptimized.Rows.Count, ! this.numDaysForReturnCalculation); this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers) ); ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! ! /// <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.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! this.seedForRandomGenerator++; ! this.numDaysElapsedSinceLastOptimization++; ! if((this.numDaysElapsedSinceLastOptimization - 1 == ! this.numDaysBetweenEachOptimization)) //|| this.isTheFirstClose ) ! //num days without optimization has elapsed or ! //it is the first close (OLD IMPLEMENTATION) ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Close event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! ! } #endregion ! } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:12:00
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/BestAndWorst In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2916/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/BestAndWorst Modified Files: EndOfDayTimerHandlerBWFollower.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: EndOfDayTimerHandlerBWFollower.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/BestAndWorst/EndOfDayTimerHandlerBWFollower.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** EndOfDayTimerHandlerBWFollower.cs 29 Aug 2007 09:32:57 -0000 1.1 --- EndOfDayTimerHandlerBWFollower.cs 19 Aug 2008 17:11:26 -0000 1.2 *************** *** 3,7 **** EndOfDayTimerHandlerBWFollower.cs ! Copyright (C) 2007 Marco Milletti --- 3,7 ---- EndOfDayTimerHandlerBWFollower.cs ! Copyright (C) 2007 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 37,147 **** { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the Best and Worst follower, ! /// based on the assumption that largest moves are confirmed ! /// the next days ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerBWFollower ! { ! private string tickerGroupID; ! private int numberOfEligibleTickers; private int lengthInDaysForPerformance; ! private string benchmark; ! private Account account; ! private int numOfWorstTickers; ! private int numOfBestTickers; ! private int numOfTickersForBuying; ! private int numOfTickersForShortSelling; ! private string[] bestTickers; ! private string[] worstTickers; ! private string[] chosenTickers; ! private string[] lastOrderedTickers; ! private ArrayList orders; private bool thereAreEnoughBestTickers; private bool thereAreEnoughWorstTickers; private int closesElapsedWithSomeOpenPosition; ! ! public EndOfDayTimerHandlerBWFollower(string tickerGroupID, int numberOfEligibleTickers, ! int lengthInDaysForPerformance, ! int numOfBestTickers, ! int numOfWorstTickers, int numOfTickersForBuying, ! int numOfTickersForShortSelling, ! Account account, string benchmark) ! { ! this.tickerGroupID = tickerGroupID; ! this.numberOfEligibleTickers = numberOfEligibleTickers; this.lengthInDaysForPerformance = lengthInDaysForPerformance; ! this.account = account; ! this.benchmark = benchmark; ! this.numOfBestTickers = numOfBestTickers; ! this.bestTickers = new string[this.numOfBestTickers]; ! this.numOfWorstTickers = numOfWorstTickers; ! this.worstTickers = new string[this.numOfWorstTickers]; ! this.numOfTickersForBuying = numOfTickersForBuying; ! this.numOfTickersForShortSelling = numOfTickersForShortSelling; ! this.chosenTickers = new string[this.numOfTickersForBuying + this.numOfTickersForShortSelling]; ! this.lastOrderedTickers = new string[this.chosenTickers.Length]; ! this.orders = new ArrayList(); ! } ! ! #region MarketOpenEventHandler ! private void addOrderForTicker(string[] tickers, ! int tickerPosition ) ! { ! SignedTickers signedTickers = new SignedTickers(tickers); ! string ticker = ! SignedTicker.GetTicker(tickers[tickerPosition]); ! double cashForSinglePosition = ! this.account.CashAmount / this.chosenTickers.Length; ! long quantity = ! Convert.ToInt64( Math.Floor( cashForSinglePosition / this.account.DataStreamer.GetCurrentBid( ticker ) ) ); ! Order order = ! new Order( ! signedTickers[tickerPosition].MarketOrderType, ! new Instrument( ticker ) , quantity ); ! this.orders.Add(order); ! } ! private void addChosenTickersToOrderList(string[] tickers) ! { ! for( int i = 0; i<tickers.Length; i++) ! { ! if(tickers[i] != null) ! { ! this.addOrderForTicker( tickers, i ); ! this.lastOrderedTickers[i] = ! SignedTicker.GetTicker(tickers[i]); ! } ! } ! } ! private void openPositions(string[] tickers) ! { ! this.addChosenTickersToOrderList(tickers); ! //execute orders actually ! foreach(object item in this.orders) ! this.account.AddOrder((Order)item); ! } ! private void setChosenTickers_addTickersForShorting() ! { ! for( int i = 0;i<this.numOfTickersForShortSelling; i++) ! this.chosenTickers[this.numOfTickersForBuying + i] = "-" + this.worstTickers[i]; ! } ! ! private void setChosenTickers_addTickersForBuying() ! { ! for( int i = 0; i<this.numOfTickersForBuying; i++ ) ! this.chosenTickers[i] = this.bestTickers[i]; ! } ! private void setChosenTickersBothForLongAndShort() ! { ! if( this.thereAreEnoughBestTickers && ! this.thereAreEnoughWorstTickers ) ! { try { --- 37,147 ---- { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the Best and Worst follower, ! /// based on the assumption that largest moves are confirmed ! /// the next days ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerBWFollower ! { ! private string tickerGroupID; ! private int numberOfEligibleTickers; private int lengthInDaysForPerformance; ! private string benchmark; ! private Account account; ! private int numOfWorstTickers; ! private int numOfBestTickers; ! private int numOfTickersForBuying; ! private int numOfTickersForShortSelling; ! private string[] bestTickers; ! private string[] worstTickers; ! private string[] chosenTickers; ! private string[] lastOrderedTickers; ! private ArrayList orders; private bool thereAreEnoughBestTickers; private bool thereAreEnoughWorstTickers; private int closesElapsedWithSomeOpenPosition; ! ! public EndOfDayTimerHandlerBWFollower(string tickerGroupID, int numberOfEligibleTickers, ! int lengthInDaysForPerformance, ! int numOfBestTickers, ! int numOfWorstTickers, int numOfTickersForBuying, ! int numOfTickersForShortSelling, ! Account account, string benchmark) ! { ! this.tickerGroupID = tickerGroupID; ! this.numberOfEligibleTickers = numberOfEligibleTickers; this.lengthInDaysForPerformance = lengthInDaysForPerformance; ! this.account = account; ! this.benchmark = benchmark; ! this.numOfBestTickers = numOfBestTickers; ! this.bestTickers = new string[this.numOfBestTickers]; ! this.numOfWorstTickers = numOfWorstTickers; ! this.worstTickers = new string[this.numOfWorstTickers]; ! this.numOfTickersForBuying = numOfTickersForBuying; ! this.numOfTickersForShortSelling = numOfTickersForShortSelling; ! this.chosenTickers = new string[this.numOfTickersForBuying + this.numOfTickersForShortSelling]; ! this.lastOrderedTickers = new string[this.chosenTickers.Length]; ! this.orders = new ArrayList(); ! } ! ! #region MarketOpenEventHandler ! private void addOrderForTicker(string[] tickers, ! int tickerPosition ) ! { ! SignedTickers signedTickers = new SignedTickers(tickers); ! string ticker = ! SignedTicker.GetTicker(tickers[tickerPosition]); ! double cashForSinglePosition = ! this.account.CashAmount / this.chosenTickers.Length; ! long quantity = ! Convert.ToInt64( Math.Floor( cashForSinglePosition / this.account.DataStreamer.GetCurrentBid( ticker ) ) ); ! Order order = ! new Order( ! signedTickers[tickerPosition].MarketOrderType, ! new Instrument( ticker ) , quantity ); ! this.orders.Add(order); ! } ! private void addChosenTickersToOrderList(string[] tickers) ! { ! for( int i = 0; i<tickers.Length; i++) ! { ! if(tickers[i] != null) ! { ! this.addOrderForTicker( tickers, i ); ! this.lastOrderedTickers[i] = ! SignedTicker.GetTicker(tickers[i]); ! } ! } ! } ! private void openPositions(string[] tickers) ! { ! this.addChosenTickersToOrderList(tickers); ! //execute orders actually ! foreach(object item in this.orders) ! this.account.AddOrder((Order)item); ! } ! private void setChosenTickers_addTickersForShorting() ! { ! for( int i = 0;i<this.numOfTickersForShortSelling; i++) ! this.chosenTickers[this.numOfTickersForBuying + i] = "-" + this.worstTickers[i]; ! } ! ! private void setChosenTickers_addTickersForBuying() ! { ! for( int i = 0; i<this.numOfTickersForBuying; i++ ) ! this.chosenTickers[i] = this.bestTickers[i]; ! } ! private void setChosenTickersBothForLongAndShort() ! { ! if( this.thereAreEnoughBestTickers && ! this.thereAreEnoughWorstTickers ) ! { try { *************** *** 150,165 **** } catch(Exception ex) ! {ex = ex;} ! } ! } ! /// <summary> ! /// Handles a "Market Open" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { if(this.orders.Count == 0 && this.account.Transactions.Count == 0) this.account.AddCash(30000); --- 150,167 ---- } catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! } ! } ! /// <summary> ! /// Handles a "Market Open" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { if(this.orders.Count == 0 && this.account.Transactions.Count == 0) this.account.AddCash(30000); *************** *** 173,200 **** if(allTickersHasBeenChosenForLongAndShort) this.openPositions(this.chosenTickers); ! } ! #endregion ! #region MarketCloseEventHandler ! private void closePosition( string ticker ) ! { ! this.account.ClosePosition( ticker ); ! } ! ! private void closePositions() ! { ! if(this.lastOrderedTickers != null) ! foreach( string ticker in this.lastOrderedTickers ) ! for( int i = 0; i<this.account.Portfolio.Keys.Count; i++ ) ! if( this.account.Portfolio[ticker]!=null ) ! closePosition( ticker ); ! } ! ! public void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.account.Portfolio.Count > 0) { this.closesElapsedWithSomeOpenPosition++; --- 175,202 ---- if(allTickersHasBeenChosenForLongAndShort) this.openPositions(this.chosenTickers); ! } ! #endregion ! #region MarketCloseEventHandler ! private void closePosition( string ticker ) ! { ! this.account.ClosePosition( ticker ); ! } ! ! private void closePositions() ! { ! if(this.lastOrderedTickers != null) ! foreach( string ticker in this.lastOrderedTickers ) ! for( int i = 0; i<this.account.Portfolio.Keys.Count; i++ ) ! if( this.account.Portfolio[ticker]!=null ) ! closePosition( ticker ); ! } ! ! public void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.account.Portfolio.Count > 0) { this.closesElapsedWithSomeOpenPosition++; *************** *** 207,211 **** } } ! else//this.account.Portfolio.Count == 0 { if( ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition >= this.lengthInDaysForPerformance ) --- 209,213 ---- } } ! else//this.account.Portfolio.Count == 0 { if( ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition >= this.lengthInDaysForPerformance ) *************** *** 215,224 **** } } ! } ! #endregion ! #region OneHourAfterMarketCloseEventHandler ! private void oneHourAfterMarketCloseEventHandler_clear() { --- 217,226 ---- } } ! } ! #endregion ! #region OneHourAfterMarketCloseEventHandler ! private void oneHourAfterMarketCloseEventHandler_clear() { *************** *** 230,244 **** this.chosenTickers[i] = null; } ! ! /// <summary> ! /// Handles a "One hour after market close" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void OneHourAfterMarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.oneHourAfterMarketCloseEventHandler_clear(); DateTime currentDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; int currentDateArrayPositionInTimer = ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition; --- 232,246 ---- this.chosenTickers[i] = null; } ! ! /// <summary> ! /// Handles a "One hour after market close" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void OneHourAfterMarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.oneHourAfterMarketCloseEventHandler_clear(); DateTime currentDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; int currentDateArrayPositionInTimer = ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition; *************** *** 246,284 **** (DateTime)((IndexBasedEndOfDayTimer)sender).IndexQuotes.Rows[currentDateArrayPositionInTimer - this.lengthInDaysForPerformance]["quDate"]; SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); //remark from here for DEBUG ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromGroup = new SelectorByQuotationAtEachMarketDay(tickersFromGroup, ! false, currentDate.AddDays(-30), currentDate, ! tickersFromGroup.Rows.Count, this.benchmark); ! SelectorByAverageRawOpenPrice byPrice = new SelectorByAverageRawOpenPrice( quotedAtEachMarketDayFromGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-10), currentDate, ! tickersFromGroup.Rows.Count, 25 ); ! SelectorByLiquidity mostLiquidSelector = new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByCloseToCloseVolatility lessVolatile = new SelectorByCloseToCloseVolatility(mostLiquidSelector.GetTableOfSelectedTickers(), ! true,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers/2); ! SelectorByAbsolutePerformance bestTickersFromLessVolatile = new SelectorByAbsolutePerformance(lessVolatile.GetTableOfSelectedTickers(), ! false,firstDateForPerformanceComputation,currentDate,this.bestTickers.Length); SelectorByAbsolutePerformance worstTickersFromLessVolatile = new SelectorByAbsolutePerformance(lessVolatile.GetTableOfSelectedTickers(), ! true,firstDateForPerformanceComputation,currentDate,this.bestTickers.Length); DataTable tableOfBestTickers = bestTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfBestTickers.Rows.Count >= this.bestTickers.Length) ! { this.thereAreEnoughBestTickers = true; for(int i = 0;i<this.bestTickers.Length;i++) --- 248,286 ---- (DateTime)((IndexBasedEndOfDayTimer)sender).IndexQuotes.Rows[currentDateArrayPositionInTimer - this.lengthInDaysForPerformance]["quDate"]; SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); //remark from here for DEBUG ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromGroup = new SelectorByQuotationAtEachMarketDay(tickersFromGroup, ! false, currentDate.AddDays(-30), currentDate, ! tickersFromGroup.Rows.Count, this.benchmark); ! SelectorByAverageRawOpenPrice byPrice = new SelectorByAverageRawOpenPrice( quotedAtEachMarketDayFromGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-10), currentDate, ! tickersFromGroup.Rows.Count, 25 ); ! SelectorByLiquidity mostLiquidSelector = new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByCloseToCloseVolatility lessVolatile = new SelectorByCloseToCloseVolatility(mostLiquidSelector.GetTableOfSelectedTickers(), ! true,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers/2); ! SelectorByAbsolutePerformance bestTickersFromLessVolatile = new SelectorByAbsolutePerformance(lessVolatile.GetTableOfSelectedTickers(), ! false,firstDateForPerformanceComputation,currentDate,this.bestTickers.Length); SelectorByAbsolutePerformance worstTickersFromLessVolatile = new SelectorByAbsolutePerformance(lessVolatile.GetTableOfSelectedTickers(), ! true,firstDateForPerformanceComputation,currentDate,this.bestTickers.Length); DataTable tableOfBestTickers = bestTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfBestTickers.Rows.Count >= this.bestTickers.Length) ! { this.thereAreEnoughBestTickers = true; for(int i = 0;i<this.bestTickers.Length;i++) *************** *** 293,297 **** DataTable tableOfWorstTickers = worstTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfWorstTickers.Rows.Count >= this.worstTickers.Length) ! { this.thereAreEnoughWorstTickers = true; for(int i = 0;i<this.worstTickers.Length;i++) --- 295,299 ---- DataTable tableOfWorstTickers = worstTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfWorstTickers.Rows.Count >= this.worstTickers.Length) ! { this.thereAreEnoughWorstTickers = true; for(int i = 0;i<this.worstTickers.Length;i++) *************** *** 303,332 **** } } ! // //for DEBUG ! // //remark from here for real running ! // SelectorByLiquidity mostLiquidSelector = ! // new SelectorByLiquidity(tickersFromGroup, ! // false,currentDate.AddDays(-30), currentDate, ! // this.numberOfEligibleTickers); // ! // SelectorByAverageCloseToClosePerformance bestTickersFromMostLiquid = ! // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), ! // false,currentDate,currentDate,this.bestTickers.Length); // ! // SelectorByAverageCloseToClosePerformance worstTickersFromMostLiquid = ! // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), ! // true,currentDate,currentDate,this.worstTickers.Length); // ! // DataTable tableOfBestTickers = bestTickersFromMostLiquid.GetTableOfSelectedTickers(); ! // for(int i = 0;i<this.bestTickers.Length;i++) ! // if(tableOfBestTickers.Rows[i][0] != null) ! // this.bestTickers[i] = (string)tableOfBestTickers.Rows[i][0]; // ! // DataTable tableOfWorstTickers = worstTickersFromMostLiquid.GetTableOfSelectedTickers(); ! // for(int i = 0;i<this.worstTickers.Length;i++) ! // if(tableOfWorstTickers.Rows[i][0] != null) ! // this.worstTickers[i] = (string)tableOfWorstTickers.Rows[i][0]; ! } ! #endregion ! } } --- 305,334 ---- } } ! // //for DEBUG ! // //remark from here for real running ! // SelectorByLiquidity mostLiquidSelector = ! // new SelectorByLiquidity(tickersFromGroup, ! // false,currentDate.AddDays(-30), currentDate, ! // this.numberOfEligibleTickers); // ! // SelectorByAverageCloseToClosePerformance bestTickersFromMostLiquid = ! // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), ! // false,currentDate,currentDate,this.bestTickers.Length); // ! // SelectorByAverageCloseToClosePerformance worstTickersFromMostLiquid = ! // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), ! // true,currentDate,currentDate,this.worstTickers.Length); // ! // DataTable tableOfBestTickers = bestTickersFromMostLiquid.GetTableOfSelectedTickers(); ! // for(int i = 0;i<this.bestTickers.Length;i++) ! // if(tableOfBestTickers.Rows[i][0] != null) ! // this.bestTickers[i] = (string)tableOfBestTickers.Rows[i][0]; // ! // DataTable tableOfWorstTickers = worstTickersFromMostLiquid.GetTableOfSelectedTickers(); ! // for(int i = 0;i<this.worstTickers.Length;i++) ! // if(tableOfWorstTickers.Rows[i][0] != null) ! // this.worstTickers[i] = (string)tableOfWorstTickers.Rows[i][0]; ! } ! #endregion ! } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:11:59
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2916/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO Modified Files: EndOfDayTimerHandlerBiasedPVO.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: EndOfDayTimerHandlerBiasedPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/EndOfDayTimerHandlerBiasedPVO.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** EndOfDayTimerHandlerBiasedPVO.cs 9 Mar 2008 22:40:51 -0000 1.5 --- EndOfDayTimerHandlerBiasedPVO.cs 19 Aug 2008 17:11:26 -0000 1.6 *************** *** 3,7 **** EndOfDayTimerHandlerBiasedPVO.cs ! Copyright (C) 2006 Marco Milletti --- 3,7 ---- EndOfDayTimerHandlerBiasedPVO.cs ! Copyright (C) 2006 Marco Milletti [...1087 lines suppressed...] ! this.numDaysElapsedSinceLastOptimization++; ! if((this.numDaysElapsedSinceLastOptimization == ! this.numDaysBetweenEachOptimization)) ! //num days without optimization has elapsed ! { ! if(this.pathOfFileContainingGenomes == null) ! //tickers have to be set by a new optimization process (in sample) ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Close event ! else//this.pathOfFileContainingGenomes != null ! this.setTickersFromFile(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime); ! //set tickers from file ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! } ! ! #endregion ! } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:11:35
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2916/b7_Scripts/WalkForwardTesting/LinearCombination Modified Files: ExtremeCounterTrendStrategy.cs FixedLevelOscillatorBiasedPVOStrategy.cs GenomeRepresentation.cs ImmediateTrendFollowerStrategy.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: FixedLevelOscillatorBiasedPVOStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/FixedLevelOscillatorBiasedPVOStrategy.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** FixedLevelOscillatorBiasedPVOStrategy.cs 12 Mar 2008 22:09:04 -0000 1.5 --- FixedLevelOscillatorBiasedPVOStrategy.cs 19 Aug 2008 17:11:29 -0000 1.6 *************** *** 3,7 **** FixedLevelOscillatorBiasedPVOStrategy.cs ! Copyright (C) 2007 Marco Milletti --- 3,7 ---- FixedLevelOscillatorBiasedPVOStrategy.cs ! Copyright (C) 2007 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 36,114 **** { /// <summary> ! /// Fixed Level Oscillators /// Biased Portfolio Value Oscillator strategy: /// from a group of optimized PVO portfolios, the strategy indicates /// to buy the portfolio that presents the highest degree ! /// of moving from a threshold /// </summary> [Serializable] public class FixedLevelOscillatorBiasedPVOStrategy : EndOfDayTimerHandlerBiasedPVO, IEndOfDayStrategy { ! public FixedLevelOscillatorBiasedPVOStrategy( Account accountPVO , ! WeightedPositions[] weightedPositionsToEvaluateOutOfSample, ! double[] oversoldThreshold, ! double[] overboughtThreshold, ! int numOfDifferentGenomesToEvaluateOutOfSample, ! int numDaysForOscillatingPeriod, ! double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain): ! base("", 0, 0, 0, ! weightedPositionsToEvaluateOutOfSample[0].Count, 0, accountPVO, null, 0, 0, ! "^GSPC", numOfDifferentGenomesToEvaluateOutOfSample, ! false,0, ! 1.0, ! 1000.0, ! false, ! false, ! numDaysForOscillatingPeriod,numDaysForOscillatingPeriod,1,1,1,1,1,false,false,0, ! PortfolioType.ShortAndLong,maxAcceptableCloseToCloseDrawdown, ! minimumAcceptableGain) ! { this.weightedPositionsToEvaluateOutOfSample = weightedPositionsToEvaluateOutOfSample; ! this.currentOversoldThreshold = oversoldThreshold; ! this.currentOverboughtThreshold = overboughtThreshold; ! this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; ! this.numOfDifferentGenomesToEvaluateOutOfSample = numOfDifferentGenomesToEvaluateOutOfSample; } ! ! public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) ! { ! } ! ! protected override double getCurrentWeightedPositionsGainOrLoss( IndexBasedEndOfDayTimer timer, ! ReturnsManager returnsManager, ! int indexForChosenWeightedPositions) ! { ! double returnValue = 999.0; ! if(timer.CurrentDateArrayPosition - this.numDaysForOscillatingPeriod >= 0) ! //if there are sufficient data for computing currentChosenTickersValue ! //that's why the method has been overriden ! { try { ! DateTime today = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! DateTime lastMarketDay = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - 1]["quDate"]; returnValue = this.weightedPositionsToEvaluateOutOfSample[indexForChosenWeightedPositions].GetReturn( ! 0, returnsManager); } catch(MissingQuotesException ex) { ! ex = ex; } ! } return returnValue; ! } ! public override void OneHourAfterMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) { ! } } --- 36,114 ---- { /// <summary> ! /// Fixed Level Oscillators /// Biased Portfolio Value Oscillator strategy: /// from a group of optimized PVO portfolios, the strategy indicates /// to buy the portfolio that presents the highest degree ! /// of moving from a threshold /// </summary> [Serializable] public class FixedLevelOscillatorBiasedPVOStrategy : EndOfDayTimerHandlerBiasedPVO, IEndOfDayStrategy { ! public FixedLevelOscillatorBiasedPVOStrategy( Account accountPVO , ! WeightedPositions[] weightedPositionsToEvaluateOutOfSample, ! double[] oversoldThreshold, ! double[] overboughtThreshold, ! int numOfDifferentGenomesToEvaluateOutOfSample, ! int numDaysForOscillatingPeriod, ! double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain): ! base("", 0, 0, 0, ! weightedPositionsToEvaluateOutOfSample[0].Count, 0, accountPVO, null, 0, 0, ! "^GSPC", numOfDifferentGenomesToEvaluateOutOfSample, ! false,0, ! 1.0, ! 1000.0, ! false, ! false, ! numDaysForOscillatingPeriod,numDaysForOscillatingPeriod,1,1,1,1,1,false,false,0, ! PortfolioType.ShortAndLong,maxAcceptableCloseToCloseDrawdown, ! minimumAcceptableGain) ! { this.weightedPositionsToEvaluateOutOfSample = weightedPositionsToEvaluateOutOfSample; ! this.currentOversoldThreshold = oversoldThreshold; ! this.currentOverboughtThreshold = overboughtThreshold; ! this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; ! this.numOfDifferentGenomesToEvaluateOutOfSample = numOfDifferentGenomesToEvaluateOutOfSample; } ! ! public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) ! { ! } ! ! protected override double getCurrentWeightedPositionsGainOrLoss( IndexBasedEndOfDayTimer timer, ! ReturnsManager returnsManager, ! int indexForChosenWeightedPositions) ! { ! double returnValue = 999.0; ! if(timer.CurrentDateArrayPosition - this.numDaysForOscillatingPeriod >= 0) ! //if there are sufficient data for computing currentChosenTickersValue ! //that's why the method has been overriden ! { try { ! DateTime today = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! DateTime lastMarketDay = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - 1]["quDate"]; returnValue = this.weightedPositionsToEvaluateOutOfSample[indexForChosenWeightedPositions].GetReturn( ! 0, returnsManager); } catch(MissingQuotesException ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } ! } return returnValue; ! } ! public override void OneHourAfterMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) { ! } } Index: ImmediateTrendFollowerStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/ImmediateTrendFollowerStrategy.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ImmediateTrendFollowerStrategy.cs 29 Aug 2007 09:43:36 -0000 1.2 --- ImmediateTrendFollowerStrategy.cs 19 Aug 2008 17:11:29 -0000 1.3 *************** *** 3,7 **** ImmediateTrendFollowerStrategy.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- ImmediateTrendFollowerStrategy.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 36,40 **** /// <summary> /// Immediate Trend Follower Strategy (it's just the ! /// reversal of the ExtremeCounterTrend strategy /// </summary> [Serializable] --- 36,40 ---- /// <summary> /// Immediate Trend Follower Strategy (it's just the ! /// reversal of the ExtremeCounterTrend strategy /// </summary> [Serializable] *************** *** 42,135 **** { private int numDaysForReturnCalculation; ! private int numOfClosesElapsed = 0; ! private int numOfDaysWithOpenPosition = 0; public ImmediateTrendFollowerStrategy( Account account , ! WeightedPositions weightedPositions, ! int numDaysForReturnCalculation) : ! base("", 0, ! weightedPositions.Count, 0, account, ! 0, ! 0, ! "^GSPC", 0.0, ! PortfolioType.ShortAndLong) { this.account = account; this.chosenWeightedPositions = weightedPositions; ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; } - - public override void MarketOpenEventHandler( - Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) - { - } ! public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) ! { ! } ! private double marketCloseEventHandler_openPositions_getLastHalfPeriodGain(IndexBasedEndOfDayTimer timer) ! { ! double returnValue = 999.0; ! try ! { ! DateTime initialDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation + 1]["quDate"]; ! DateTime finalDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! returnValue = ! this.chosenWeightedPositions.GetCloseToCloseReturn(initialDateForHalfPeriod,finalDateForHalfPeriod); ! } ! catch(MissingQuotesException ex) ! { ! ex = ex; ! } ! return returnValue; ! } ! private void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) ! { ! double lastHalfPeriodGain = ! this.marketCloseEventHandler_openPositions_getLastHalfPeriodGain(timer); ! if(lastHalfPeriodGain != 999.0) ! //last half period gain has been properly computed ! { ! if(lastHalfPeriodGain > 0.0) ! //the portfolio had a gain for the last half period ! this.openPositions(); ! else//the portfolio had a loss for the last half period ! { ! this.chosenWeightedPositions.Reverse(); ! //short the portfolio ! try{this.openPositions();} ! catch(Exception ex){ex = ex;} ! finally{this.chosenWeightedPositions.Reverse();} ! } ! } ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.account.Portfolio.Count > 0) ! this.numOfDaysWithOpenPosition++; ! ! if(this.numOfDaysWithOpenPosition == this.numDaysForReturnCalculation) ! AccountManager.ClosePositions(this.account); ! ! if(this.account.Portfolio.Count == 0 && ! (this.numOfClosesElapsed + 1) >= this.numDaysForReturnCalculation) ! //portfolio is empty and previous closes can be now checked ! if(this.account.Portfolio.Count == 0) ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); ! ! this.numOfClosesElapsed++; ! } ! public override void OneHourAfterMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) { ! } } --- 42,138 ---- { private int numDaysForReturnCalculation; ! private int numOfClosesElapsed = 0; ! private int numOfDaysWithOpenPosition = 0; public ImmediateTrendFollowerStrategy( Account account , ! WeightedPositions weightedPositions, ! int numDaysForReturnCalculation) : ! base("", 0, ! weightedPositions.Count, 0, account, ! 0, ! 0, ! "^GSPC", 0.0, ! PortfolioType.ShortAndLong) { this.account = account; this.chosenWeightedPositions = weightedPositions; ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; } ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! } ! ! public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) ! { ! } ! private double marketCloseEventHandler_openPositions_getLastHalfPeriodGain(IndexBasedEndOfDayTimer timer) ! { ! double returnValue = 999.0; ! try ! { ! DateTime initialDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation + 1]["quDate"]; ! DateTime finalDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! returnValue = ! this.chosenWeightedPositions.GetCloseToCloseReturn(initialDateForHalfPeriod,finalDateForHalfPeriod); ! } ! catch(MissingQuotesException ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! return returnValue; ! } ! private void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) ! { ! double lastHalfPeriodGain = ! this.marketCloseEventHandler_openPositions_getLastHalfPeriodGain(timer); ! if(lastHalfPeriodGain != 999.0) ! //last half period gain has been properly computed ! { ! if(lastHalfPeriodGain > 0.0) ! //the portfolio had a gain for the last half period ! this.openPositions(); ! else//the portfolio had a loss for the last half period ! { ! this.chosenWeightedPositions.Reverse(); ! //short the portfolio ! try{this.openPositions();} ! catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! finally{this.chosenWeightedPositions.Reverse();} ! } ! } ! } ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! if(this.account.Portfolio.Count > 0) ! this.numOfDaysWithOpenPosition++; ! ! if(this.numOfDaysWithOpenPosition == this.numDaysForReturnCalculation) ! AccountManager.ClosePositions(this.account); ! ! if(this.account.Portfolio.Count == 0 && ! (this.numOfClosesElapsed + 1) >= this.numDaysForReturnCalculation) ! //portfolio is empty and previous closes can be now checked ! if(this.account.Portfolio.Count == 0) ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); ! ! this.numOfClosesElapsed++; ! } ! ! public override void OneHourAfterMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) ! { ! } } Index: GenomeRepresentation.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/GenomeRepresentation.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** GenomeRepresentation.cs 17 Sep 2006 21:24:53 -0000 1.8 --- GenomeRepresentation.cs 19 Aug 2008 17:11:29 -0000 1.9 *************** *** 3,7 **** GenomeRepresentation.cs ! Copyright (C) 2003 Glauco Siliprandi --- 3,7 ---- GenomeRepresentation.cs ! Copyright (C) 2003 Glauco Siliprandi *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 41,54 **** private double fitness; private string signedTickers; ! private string weights; private int generationCounter; private DateTime firstOptimizationDate; private DateTime lastOptimizationDate; private int eligibleTickers = -1; ! private int halfPeriodDays = -1; ! private PortfolioType portfolioType = PortfolioType.ShortAndLong; private int createdGenerations = -1; ! private double oversoldThreshold = 0.0; ! private double overboughtThreshold = 0.0; public string SignedTickers --- 41,54 ---- private double fitness; private string signedTickers; ! private string weights; private int generationCounter; private DateTime firstOptimizationDate; private DateTime lastOptimizationDate; private int eligibleTickers = -1; ! private int halfPeriodDays = -1; ! private PortfolioType portfolioType = PortfolioType.ShortAndLong; private int createdGenerations = -1; ! private double oversoldThreshold = 0.0; ! private double overboughtThreshold = 0.0; public string SignedTickers *************** *** 59,63 **** } } ! public int EligibleTickers { --- 59,63 ---- } } ! public int EligibleTickers { *************** *** 68,78 **** } ! public string WeightsForSignedTickers ! { ! get ! { ! return this.weights; ! } ! } public double Fitness { --- 68,78 ---- } ! public string WeightsForSignedTickers ! { ! get ! { ! return this.weights; ! } ! } public double Fitness { *************** *** 104,138 **** } ! public int HalfPeriodDays ! { ! get ! { ! return this.halfPeriodDays; ! } ! } ! public PortfolioType PortfolioType ! { ! get ! { ! return this.portfolioType; ! } ! } ! public double OversoldThreshold ! { ! get ! { ! return this.oversoldThreshold; ! } ! } ! ! public double OverboughtThreshold ! { ! get ! { ! return this.overboughtThreshold; ! } ! } // public static string[] GetSignedTickers( string signedTickers ) --- 104,138 ---- } ! public int HalfPeriodDays ! { ! get ! { ! return this.halfPeriodDays; ! } ! } ! public PortfolioType PortfolioType ! { ! get ! { ! return this.portfolioType; ! } ! } ! public double OversoldThreshold ! { ! get ! { ! return this.oversoldThreshold; ! } ! } ! ! public double OverboughtThreshold ! { ! get ! { ! return this.overboughtThreshold; ! } ! } // public static string[] GetSignedTickers( string signedTickers ) *************** *** 142,178 **** // } ! public static double[] GetWeightsArray( string weightsWithSeparator ) ! { ! double[] returnValue; ! string[] returnValueString = weightsWithSeparator.Split( ";".ToCharArray()); ! returnValue = new double[returnValueString.Length]; ! for(int i = 0; i<returnValue.Length; i++) ! { ! returnValue[i] = Convert.ToDouble(returnValueString[i]); ! } ! return returnValue; ! } public static string[] GetSignedTickers( string signedTickersWithOrWithoutWeights ) { ! string[] returnValue = ! signedTickersWithOrWithoutWeights.Split( ConstantsProvider.SeparatorForTickers.ToCharArray()); if( signedTickersWithOrWithoutWeights.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 signedTickersWithOrWithoutWeights ) { ! string[] signedTickersWithOrWithoutWeightsArray = ! signedTickersWithOrWithoutWeights.Split( ConstantsProvider.SeparatorForTickers.ToCharArray() ); double[] returnValue = new double[signedTickersWithOrWithoutWeights.Length]; --- 142,178 ---- // } ! public static double[] GetWeightsArray( string weightsWithSeparator ) ! { ! double[] returnValue; ! string[] returnValueString = weightsWithSeparator.Split( ";".ToCharArray()); ! returnValue = new double[returnValueString.Length]; ! for(int i = 0; i<returnValue.Length; i++) ! { ! returnValue[i] = Convert.ToDouble(returnValueString[i]); ! } ! return returnValue; ! } public static string[] GetSignedTickers( string signedTickersWithOrWithoutWeights ) { ! string[] returnValue = ! signedTickersWithOrWithoutWeights.Split( ConstantsProvider.SeparatorForTickers.ToCharArray()); if( signedTickersWithOrWithoutWeights.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 signedTickersWithOrWithoutWeights ) { ! string[] signedTickersWithOrWithoutWeightsArray = ! signedTickersWithOrWithoutWeights.Split( ConstantsProvider.SeparatorForTickers.ToCharArray() ); double[] returnValue = new double[signedTickersWithOrWithoutWeights.Length]; *************** *** 181,193 **** if((signedTickersWithOrWithoutWeights.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( signedTickersWithOrWithoutWeightsArray[i].Split( ConstantsProvider.SeparatorForWeights.ToCharArray() )[1] ); } ! } return returnValue; } --- 181,193 ---- if((signedTickersWithOrWithoutWeights.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( signedTickersWithOrWithoutWeightsArray[i].Split( ConstantsProvider.SeparatorForWeights.ToCharArray() )[1] ); } ! } return returnValue; } *************** *** 218,235 **** signedTickers += signedTicker + ";"; signedTickers = signedTickers.Substring( 0 , ! signedTickers.Length - 1 ); return signedTickers; } - - private string getWeights( Genome genome ) - { - string weights = ""; - foreach ( double weight in ((GenomeMeaning)genome.Meaning).TickersPortfolioWeights ) - weights += weight.ToString() + ";"; - weights = weights.Substring( 0, weights.Length - 1 ); - return weights; - } ! // private string getSignedTickersWithWeights( Genome genome ) // { // string signedTickersWithWeights = ""; --- 218,235 ---- signedTickers += signedTicker + ";"; signedTickers = signedTickers.Substring( 0 , ! signedTickers.Length - 1 ); return signedTickers; } ! private string getWeights( Genome genome ) ! { ! string weights = ""; ! foreach ( double weight in ((GenomeMeaning)genome.Meaning).TickersPortfolioWeights ) ! weights += weight.ToString() + ";"; ! weights = weights.Substring( 0, weights.Length - 1 ); ! return weights; ! } ! ! // private string getSignedTickersWithWeights( Genome genome ) // { // string signedTickersWithWeights = ""; *************** *** 237,241 **** // { // signedTickersWithWeights += ! // ((GenomeMeaning)genome.Meaning).Tickers[i] + // ConstantsProvider.SeparatorForWeights + // ((GenomeMeaning)genome.Meaning).TickersPortfolioWeights[i] + --- 237,241 ---- // { // signedTickersWithWeights += ! // ((GenomeMeaning)genome.Meaning).Tickers[i] + // ConstantsProvider.SeparatorForWeights + // ((GenomeMeaning)genome.Meaning).TickersPortfolioWeights[i] + *************** *** 244,266 **** // signedTickersWithWeights = signedTickersWithWeights.Substring( 0 , // signedTickersWithWeights.Length - 1 ); ! // // return signedTickersWithWeights; // } ! private void genomeRepresentation_synchronizeOldWithNew() ! { ! if(this.weights == null) ! //for old genomes saved to disk not having "weights" field ! { ! foreach(double weight in GenomeRepresentation.GetWeightsForSignedTickers(this.signedTickers)) ! this.weights += weight.ToString() + ";"; ! this.weights = this.weights.Substring( 0, this.weights.Length - 1 ); ! // ! string newRepresentationForSignedTickers = null; ! foreach(string ticker in GenomeRepresentation.GetSignedTickers(this.signedTickers)) ! newRepresentationForSignedTickers += ticker + ";"; ! this.signedTickers = newRepresentationForSignedTickers.Substring(0, newRepresentationForSignedTickers.Length -1); ! } ! } /// <summary> --- 244,266 ---- // signedTickersWithWeights = signedTickersWithWeights.Substring( 0 , // signedTickersWithWeights.Length - 1 ); ! // // return signedTickersWithWeights; // } ! private void genomeRepresentation_synchronizeOldWithNew() ! { ! if(this.weights == null) ! //for old genomes saved to disk not having "weights" field ! { ! foreach(double weight in GenomeRepresentation.GetWeightsForSignedTickers(this.signedTickers)) ! this.weights += weight.ToString() + ";"; ! this.weights = this.weights.Substring( 0, this.weights.Length - 1 ); ! // ! string newRepresentationForSignedTickers = null; ! foreach(string ticker in GenomeRepresentation.GetSignedTickers(this.signedTickers)) ! newRepresentationForSignedTickers += ticker + ";"; ! this.signedTickers = newRepresentationForSignedTickers.Substring(0, newRepresentationForSignedTickers.Length -1); ! } ! } /// <summary> *************** *** 278,282 **** // deserialize the fields from the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { FieldInfo fieldInfo = (FieldInfo) mi[i]; --- 278,282 ---- // deserialize the fields from the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { FieldInfo fieldInfo = (FieldInfo) mi[i]; *************** *** 284,301 **** // set the field to the deserialized value try{ ! fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); } catch(Exception ex) ! {ex = ex;} } ! this.genomeRepresentation_synchronizeOldWithNew(); } private void genomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int generationCounter, int eligibleTickers, ! int halfPeriodDays, PortfolioType portfolioType, ! int createdGenerations) { this.fitness = genome.Fitness; --- 284,303 ---- // set the field to the deserialized value try{ ! fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); } catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } } ! this.genomeRepresentation_synchronizeOldWithNew(); } private void genomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int generationCounter, int eligibleTickers, ! int halfPeriodDays, PortfolioType portfolioType, ! int createdGenerations) { this.fitness = genome.Fitness; *************** *** 303,328 **** this.signedTickers = this.getSignedTickers( ((GenomeMeaning)genome.Meaning).Tickers ); this.weights = this.getWeights( genome ); ! this.firstOptimizationDate = firstOptimizationDate; this.lastOptimizationDate = lastOptimizationDate; this.generationCounter = generationCounter; this.eligibleTickers = eligibleTickers; ! this.halfPeriodDays = halfPeriodDays; ! this.portfolioType = portfolioType; ! this.createdGenerations = createdGenerations; } ! public GenomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate ) { this.genomeRepresentation( genome , ! firstOptimizationDate , lastOptimizationDate , -1, -1, -1, PortfolioType.ShortAndLong, -1 ); } ! public GenomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int generationCounter ) { this.genomeRepresentation( genome , firstOptimizationDate , ! lastOptimizationDate , generationCounter, -1, -1, PortfolioType.ShortAndLong, -1); } --- 305,330 ---- this.signedTickers = this.getSignedTickers( ((GenomeMeaning)genome.Meaning).Tickers ); this.weights = this.getWeights( genome ); ! this.firstOptimizationDate = firstOptimizationDate; this.lastOptimizationDate = lastOptimizationDate; this.generationCounter = generationCounter; this.eligibleTickers = eligibleTickers; ! this.halfPeriodDays = halfPeriodDays; ! this.portfolioType = portfolioType; ! this.createdGenerations = createdGenerations; } ! public GenomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate ) { this.genomeRepresentation( genome , ! firstOptimizationDate , lastOptimizationDate , -1, -1, -1, PortfolioType.ShortAndLong, -1 ); } ! public GenomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int generationCounter ) { this.genomeRepresentation( genome , firstOptimizationDate , ! lastOptimizationDate , generationCounter, -1, -1, PortfolioType.ShortAndLong, -1); } *************** *** 330,334 **** string[] signedTickersArray, DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int eligibleTickers ) { this.fitness = BFOptimizableParamaters.Fitness; --- 332,336 ---- string[] signedTickersArray, DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int eligibleTickers ) { this.fitness = BFOptimizableParamaters.Fitness; *************** *** 336,394 **** this.signedTickers = this.getSignedTickers(signedTickersArray); this.weights = null; ! this.firstOptimizationDate = firstOptimizationDate; this.lastOptimizationDate = lastOptimizationDate; this.eligibleTickers = eligibleTickers; ! } ! public GenomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int generationCounter, int eligibleTickers ) { this.genomeRepresentation( genome , firstOptimizationDate , ! lastOptimizationDate , generationCounter, eligibleTickers, -1, PortfolioType.ShortAndLong, -1); } - - public GenomeRepresentation( Genome genome , - DateTime firstOptimizationDate , DateTime lastOptimizationDate , - int generationCounter, int eligibleTickers, int halfPeriodDays ) - { - this.genomeRepresentation( genome , firstOptimizationDate , - lastOptimizationDate , generationCounter, eligibleTickers, halfPeriodDays, - PortfolioType.ShortAndLong, -1); - } - - public GenomeRepresentation( Genome genome , - DateTime firstOptimizationDate , DateTime lastOptimizationDate , - int generationCounter, int eligibleTickers, - int halfPeriodDays, PortfolioType portfolioType ) - { - this.genomeRepresentation( genome , firstOptimizationDate , - lastOptimizationDate , generationCounter, eligibleTickers, - halfPeriodDays, portfolioType, -1); - } ! public GenomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int generationCounter, int eligibleTickers, ! int halfPeriodDays, PortfolioType portfolioType, int createdGenerations ) ! { ! this.genomeRepresentation( genome , firstOptimizationDate , ! lastOptimizationDate , generationCounter, eligibleTickers, ! halfPeriodDays, portfolioType, createdGenerations); ! } ! public GenomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int generationCounter, int eligibleTickers, ! int halfPeriodDays, PortfolioType portfolioType, int createdGenerations, ! double oversoldThreshold, double overboughtThreshold) ! { ! this.genomeRepresentation( genome , firstOptimizationDate , ! lastOptimizationDate , generationCounter, eligibleTickers, ! halfPeriodDays, portfolioType, createdGenerations); ! this.oversoldThreshold = oversoldThreshold; ! this.overboughtThreshold = overboughtThreshold; ! } #region GetObjectData --- 338,396 ---- this.signedTickers = this.getSignedTickers(signedTickersArray); this.weights = null; ! this.firstOptimizationDate = firstOptimizationDate; this.lastOptimizationDate = lastOptimizationDate; this.eligibleTickers = eligibleTickers; ! } ! public GenomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int generationCounter, int eligibleTickers ) { this.genomeRepresentation( genome , firstOptimizationDate , ! lastOptimizationDate , generationCounter, eligibleTickers, -1, PortfolioType.ShortAndLong, -1); } ! public GenomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int generationCounter, int eligibleTickers, int halfPeriodDays ) ! { ! this.genomeRepresentation( genome , firstOptimizationDate , ! lastOptimizationDate , generationCounter, eligibleTickers, halfPeriodDays, ! PortfolioType.ShortAndLong, -1); ! } ! ! public GenomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int generationCounter, int eligibleTickers, ! int halfPeriodDays, PortfolioType portfolioType ) ! { ! this.genomeRepresentation( genome , firstOptimizationDate , ! lastOptimizationDate , generationCounter, eligibleTickers, ! halfPeriodDays, portfolioType, -1); ! } ! ! public GenomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int generationCounter, int eligibleTickers, ! int halfPeriodDays, PortfolioType portfolioType, int createdGenerations ) ! { ! this.genomeRepresentation( genome , firstOptimizationDate , ! lastOptimizationDate , generationCounter, eligibleTickers, ! halfPeriodDays, portfolioType, createdGenerations); ! } ! public GenomeRepresentation( Genome genome , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , ! int generationCounter, int eligibleTickers, ! int halfPeriodDays, PortfolioType portfolioType, int createdGenerations, ! double oversoldThreshold, double overboughtThreshold) ! { ! this.genomeRepresentation( genome , firstOptimizationDate , ! lastOptimizationDate , generationCounter, eligibleTickers, ! halfPeriodDays, portfolioType, createdGenerations); ! this.oversoldThreshold = oversoldThreshold; ! this.overboughtThreshold = overboughtThreshold; ! } #region GetObjectData *************** *** 399,411 **** /// <param name="context"></param> void ISerializable.GetObjectData( ! SerializationInfo info, StreamingContext context) { // get the set of serializable members for this class and base classes Type thisType = this.GetType(); ! MemberInfo[] mi = FormatterServices.GetSerializableMembers( thisType , context); // serialize the fields to the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(this)); --- 401,413 ---- /// <param name="context"></param> void ISerializable.GetObjectData( ! SerializationInfo info, StreamingContext context) { // get the set of serializable members for this class and base classes Type thisType = this.GetType(); ! MemberInfo[] mi = FormatterServices.GetSerializableMembers( thisType , context); // serialize the fields to the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(this)); Index: ExtremeCounterTrendStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/ExtremeCounterTrendStrategy.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ExtremeCounterTrendStrategy.cs 12 Mar 2008 22:09:04 -0000 1.5 --- ExtremeCounterTrendStrategy.cs 19 Aug 2008 17:11:28 -0000 1.6 *************** *** 3,7 **** ExtremeCounterTrendStrategy.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- ExtremeCounterTrendStrategy.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 44,154 **** private WeightedPositions weightedPositions; private int numDaysForReturnCalculation; ! private int numOfClosesElapsed = 0; ! private int numOfDaysWithOpenPosition = 0; ! private PortfolioType portfolioType; ! public Account Account { get { return this.account; } set { this.account = value; } } ! public ExtremeCounterTrendStrategy( Account account , ! WeightedPositions weightedPositions, ! int numDaysForReturnCalculation, ! PortfolioType portfolioType) { this.account = account; this.weightedPositions = weightedPositions; ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.portfolioType = portfolioType; } - - public void MarketOpenEventHandler( - Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) - { - } ! public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) ! { ! } ! private double marketCloseEventHandler_openPositions_getLastHalfPeriodGain(IndexBasedEndOfDayTimer timer) ! { ! double returnValue = 999.0; ! try ! { ! DateTime initialDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation + 1]["quDate"]; ! DateTime finalDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! this.weightedPositions.GetCloseToCloseReturn(initialDateForHalfPeriod,finalDateForHalfPeriod); ! } ! catch(MissingQuotesException ex) ! { ! ex = ex; ! } ! return returnValue; ! } ! private void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) ! { ! double lastHalfPeriodGain = ! this.marketCloseEventHandler_openPositions_getLastHalfPeriodGain(timer); ! if(lastHalfPeriodGain != 999.0) ! //last half period gain has been properly computed ! { ! if(lastHalfPeriodGain < 0.0) ! AccountManager.OpenPositions(this.weightedPositions,this.account); ! else if (lastHalfPeriodGain > 0.0) ! //if gain of the last half period is positive ! { ! this.weightedPositions.Reverse(); ! //short the portfolio (short --> long; long --> short) ! try{ ! AccountManager.OpenPositions(this.weightedPositions,this.account); ! } ! catch(Exception ex) ! { ! ex = ex; ! } ! finally{ ! this.weightedPositions.Reverse(); ! } ! } ! } ! } ! ! private void marketCloseEventHandler_closePositions() ! { ! AccountManager.ClosePositions(this.account); ! this.numOfDaysWithOpenPosition = 0; ! } ! ! public void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.numOfClosesElapsed++; ! if(this.account.Transactions.Count == 0) ! this.account.AddCash(15000); ! ! if(this.account.Portfolio.Count > 0) ! this.numOfDaysWithOpenPosition++; ! ! if(this.numOfDaysWithOpenPosition == this.numDaysForReturnCalculation) ! this.marketCloseEventHandler_closePositions(); ! ! if(this.account.Portfolio.Count == 0 && ! this.numOfClosesElapsed >= this.numDaysForReturnCalculation) ! //portfolio is empty and previous closes can be now checked ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); ! } ! public void OneHourAfterMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) { ! } } } --- 44,154 ---- private WeightedPositions weightedPositions; private int numDaysForReturnCalculation; ! private int numOfClosesElapsed = 0; ! private int numOfDaysWithOpenPosition = 0; ! private PortfolioType portfolioType; ! public Account Account { get { return this.account; } set { this.account = value; } } ! public ExtremeCounterTrendStrategy( Account account , ! WeightedPositions weightedPositions, ! int numDaysForReturnCalculation, ! PortfolioType portfolioType) { this.account = account; this.weightedPositions = weightedPositions; ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.portfolioType = portfolioType; } ! public void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! } ! ! public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) ! { ! } ! private double marketCloseEventHandler_openPositions_getLastHalfPeriodGain(IndexBasedEndOfDayTimer timer) ! { ! double returnValue = 999.0; ! try ! { ! DateTime initialDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation + 1]["quDate"]; ! DateTime finalDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! this.weightedPositions.GetCloseToCloseReturn(initialDateForHalfPeriod,finalDateForHalfPeriod); ! } ! catch(MissingQuotesException ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! return returnValue; ! } ! private void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) ! { ! double lastHalfPeriodGain = ! this.marketCloseEventHandler_openPositions_getLastHalfPeriodGain(timer); ! if(lastHalfPeriodGain != 999.0) ! //last half period gain has been properly computed ! { ! if(lastHalfPeriodGain < 0.0) ! AccountManager.OpenPositions(this.weightedPositions,this.account); ! else if (lastHalfPeriodGain > 0.0) ! //if gain of the last half period is positive ! { ! this.weightedPositions.Reverse(); ! //short the portfolio (short --> long; long --> short) ! try{ ! AccountManager.OpenPositions(this.weightedPositions,this.account); ! } ! catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! finally{ ! this.weightedPositions.Reverse(); ! } ! } ! } ! } ! ! private void marketCloseEventHandler_closePositions() ! { ! AccountManager.ClosePositions(this.account); ! this.numOfDaysWithOpenPosition = 0; ! } ! ! public void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.numOfClosesElapsed++; ! if(this.account.Transactions.Count == 0) ! this.account.AddCash(15000); ! ! if(this.account.Portfolio.Count > 0) ! this.numOfDaysWithOpenPosition++; ! ! if(this.numOfDaysWithOpenPosition == this.numDaysForReturnCalculation) ! this.marketCloseEventHandler_closePositions(); ! ! if(this.account.Portfolio.Count == 0 && ! this.numOfClosesElapsed >= this.numDaysForReturnCalculation) ! //portfolio is empty and previous closes can be now checked ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); ! } ! public void OneHourAfterMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) { ! } } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:11:35
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_OTC In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2916/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_OTC Modified Files: EndOfDayTimerHandlerDOR_OTC.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: EndOfDayTimerHandlerDOR_OTC.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_OTC/EndOfDayTimerHandlerDOR_OTC.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** EndOfDayTimerHandlerDOR_OTC.cs 16 Aug 2008 19:30:11 -0000 1.3 --- EndOfDayTimerHandlerDOR_OTC.cs 19 Aug 2008 17:11:27 -0000 1.4 *************** *** 3,7 **** EndOfDayTimerHandlerDOR_OTC.cs ! Copyright (C) 2007 Marco Milletti --- 3,7 ---- EndOfDayTimerHandlerDOR_OTC.cs ! Copyright (C) 2007 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 37,187 **** { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for ! /// the Double OverReaction Open To Close Test, ! /// based on the OverReaction Hypothesis ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerDOR_OTC ! { ! private string tickerGroupID; ! private int numberOfEligibleTickers; ! private string benchmark; ! private Account account; ! private int numOfWorstTickers; ! private int numOfBestTickers; ! private int numOfTickersForBuying; ! private int numOfTickersForShortSelling; ! private string[] bestTickers; ! private string[] worstTickers; ! private string[] chosenTickers; ! private string[] lastOrderedTickers; ! private ArrayList orders; private bool thereAreEnoughBestTickers; private bool thereAreEnoughWorstTickers; ! ! public EndOfDayTimerHandlerDOR_OTC(string tickerGroupID, int numberOfEligibleTickers, ! int numOfBestTickers, ! int numOfWorstTickers, int numOfTickersForBuying, ! int numOfTickersForShortSelling, ! Account account, string benchmark) ! { ! this.tickerGroupID = tickerGroupID; ! this.numberOfEligibleTickers = numberOfEligibleTickers; ! this.account = account; ! this.benchmark = benchmark; ! this.numOfBestTickers = numOfBestTickers; ! this.bestTickers = new string[this.numOfBestTickers]; ! this.numOfWorstTickers = numOfWorstTickers; ! this.worstTickers = new string[this.numOfWorstTickers]; ! this.numOfTickersForBuying = numOfTickersForBuying; ! this.numOfTickersForShortSelling = numOfTickersForShortSelling; ! this.chosenTickers = new string[this.numOfTickersForBuying + this.numOfTickersForShortSelling]; ! this.lastOrderedTickers = new string[this.chosenTickers.Length]; ! this.orders = new ArrayList(); ! } ! ! #region MarketOpenEventHandler ! private void addOrderForTicker(string[] tickers, ! int tickerPosition ) ! { ! SignedTickers signedTickers = new SignedTickers(tickers); ! string ticker = ! SignedTicker.GetTicker(tickers[tickerPosition]); ! double cashForSinglePosition = ! this.account.CashAmount / this.chosenTickers.Length; ! long quantity = ! Convert.ToInt64( Math.Floor( cashForSinglePosition / this.account.DataStreamer.GetCurrentBid( ticker ) ) ); ! Order order = new Order(signedTickers[tickerPosition].MarketOrderType, ! new Instrument( ticker ) , quantity ); ! this.orders.Add(order); ! } ! private void addChosenTickersToOrderList(string[] tickers) ! { ! for( int i = 0; i<tickers.Length; i++) ! { ! if(tickers[i] != null) ! { ! this.addOrderForTicker( tickers, i ); ! this.lastOrderedTickers[i] = ! SignedTicker.GetTicker(tickers[i]); ! } ! } ! } ! private void openPositions(string[] tickers) ! { ! this.addChosenTickersToOrderList(tickers); ! //execute orders actually ! foreach(object item in this.orders) ! this.account.AddOrder((Order)item); ! } ! ! private double setChosenTickers_getGainOrLossFromPreviousClose(string signedTicker) ! { ! IndexBasedEndOfDayTimer currentTimer = (IndexBasedEndOfDayTimer)this.account.EndOfDayTimer; ! ExtendedDateTime nowAtOpen = ! new ExtendedDateTime(currentTimer.GetCurrentTime().DateTime, ! BarComponent.Open); ! ExtendedDateTime previousClose = ! new ExtendedDateTime(currentTimer.GetPreviousDateTime(), ! BarComponent.Close); ! double currentValueAtOpen = ! HistoricalDataProvider.GetAdjustedMarketValue(SignedTicker.GetTicker(signedTicker), nowAtOpen); ! double previousValueAtClose = ! HistoricalDataProvider.GetAdjustedMarketValue(SignedTicker.GetTicker(signedTicker), previousClose); ! ! return (currentValueAtOpen - previousValueAtClose) / previousValueAtClose; ! } ! private void setChosenTickers_addTickersForShorting() ! { ! DataTable worstTickersOrderedByGainAtOpen = new DataTable(); ! worstTickersOrderedByGainAtOpen.Columns.Add("ticker", Type.GetType("System.String")); ! worstTickersOrderedByGainAtOpen.Columns.Add("gainAtOpen", Type.GetType("System.Double")); ! object[] values = new object[2]; ! for (int i = 0; i<this.worstTickers.Length; i++) ! { ! values[0] = this.worstTickers[i]; ! values[1] = this.setChosenTickers_getGainOrLossFromPreviousClose(this.worstTickers[i]); ! worstTickersOrderedByGainAtOpen.Rows.Add(values); ! } ! DataRow[] orderedRows = new DataRow[this.bestTickers.Length]; ! orderedRows = worstTickersOrderedByGainAtOpen.Select("", "gainAtOpen DESC"); ! for(int i = 0;i<this.numOfTickersForShortSelling; i++) ! if( (double)orderedRows[i]["gainAtOpen"] > 0.0 ) ! //at open, current ticker is gaining ! this.chosenTickers[this.numOfTickersForBuying + i] = "-" + ! (string)orderedRows[i]["ticker"]; ! } ! ! private void setChosenTickers_addTickersForBuying() ! { ! DataTable bestTickersOrderedByLossAtOpen = new DataTable(); ! bestTickersOrderedByLossAtOpen.Columns.Add("ticker", Type.GetType("System.String")); ! bestTickersOrderedByLossAtOpen.Columns.Add("lossAtOpen", Type.GetType("System.Double")); ! object[] values = new object[2]; ! for (int i = 0; i<this.bestTickers.Length; i++) ! { ! values[0] = this.bestTickers[i]; ! values[1] = - this.setChosenTickers_getGainOrLossFromPreviousClose(this.bestTickers[i]); ! bestTickersOrderedByLossAtOpen.Rows.Add(values); ! } ! DataRow[] orderedRows = new DataRow[this.bestTickers.Length]; ! orderedRows = bestTickersOrderedByLossAtOpen.Select("", "lossAtOpen DESC"); ! for( int i = 0; i<this.numOfTickersForBuying; i++) ! if( (double)orderedRows[i]["lossAtOpen"] > 0.0 ) ! //at open, current ticker is losing ! this.chosenTickers[i] = (string)orderedRows[i]["ticker"]; ! } ! private void setChosenTickersBothForLongAndShort() ! { ! if( this.thereAreEnoughBestTickers && ! this.thereAreEnoughWorstTickers ) ! { try { --- 37,187 ---- { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for ! /// the Double OverReaction Open To Close Test, ! /// based on the OverReaction Hypothesis ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerDOR_OTC ! { ! private string tickerGroupID; ! private int numberOfEligibleTickers; ! private string benchmark; ! private Account account; ! private int numOfWorstTickers; ! private int numOfBestTickers; ! private int numOfTickersForBuying; ! private int numOfTickersForShortSelling; ! private string[] bestTickers; ! private string[] worstTickers; ! private string[] chosenTickers; ! private string[] lastOrderedTickers; ! private ArrayList orders; private bool thereAreEnoughBestTickers; private bool thereAreEnoughWorstTickers; ! ! public EndOfDayTimerHandlerDOR_OTC(string tickerGroupID, int numberOfEligibleTickers, ! int numOfBestTickers, ! int numOfWorstTickers, int numOfTickersForBuying, ! int numOfTickersForShortSelling, ! Account account, string benchmark) ! { ! this.tickerGroupID = tickerGroupID; ! this.numberOfEligibleTickers = numberOfEligibleTickers; ! this.account = account; ! this.benchmark = benchmark; ! this.numOfBestTickers = numOfBestTickers; ! this.bestTickers = new string[this.numOfBestTickers]; ! this.numOfWorstTickers = numOfWorstTickers; ! this.worstTickers = new string[this.numOfWorstTickers]; ! this.numOfTickersForBuying = numOfTickersForBuying; ! this.numOfTickersForShortSelling = numOfTickersForShortSelling; ! this.chosenTickers = new string[this.numOfTickersForBuying + this.numOfTickersForShortSelling]; ! this.lastOrderedTickers = new string[this.chosenTickers.Length]; ! this.orders = new ArrayList(); ! } ! ! #region MarketOpenEventHandler ! private void addOrderForTicker(string[] tickers, ! int tickerPosition ) ! { ! SignedTickers signedTickers = new SignedTickers(tickers); ! string ticker = ! SignedTicker.GetTicker(tickers[tickerPosition]); ! double cashForSinglePosition = ! this.account.CashAmount / this.chosenTickers.Length; ! long quantity = ! Convert.ToInt64( Math.Floor( cashForSinglePosition / this.account.DataStreamer.GetCurrentBid( ticker ) ) ); ! Order order = new Order(signedTickers[tickerPosition].MarketOrderType, ! new Instrument( ticker ) , quantity ); ! this.orders.Add(order); ! } ! private void addChosenTickersToOrderList(string[] tickers) ! { ! for( int i = 0; i<tickers.Length; i++) ! { ! if(tickers[i] != null) ! { ! this.addOrderForTicker( tickers, i ); ! this.lastOrderedTickers[i] = ! SignedTicker.GetTicker(tickers[i]); ! } ! } ! } ! private void openPositions(string[] tickers) ! { ! this.addChosenTickersToOrderList(tickers); ! //execute orders actually ! foreach(object item in this.orders) ! this.account.AddOrder((Order)item); ! } ! ! private double setChosenTickers_getGainOrLossFromPreviousClose(string signedTicker) ! { ! IndexBasedEndOfDayTimer currentTimer = (IndexBasedEndOfDayTimer)this.account.EndOfDayTimer; ! ExtendedDateTime nowAtOpen = ! new ExtendedDateTime(currentTimer.GetCurrentTime().DateTime, ! BarComponent.Open); ! ExtendedDateTime previousClose = ! new ExtendedDateTime(currentTimer.GetPreviousDateTime(), ! BarComponent.Close); ! double currentValueAtOpen = ! HistoricalDataProvider.GetAdjustedMarketValue(SignedTicker.GetTicker(signedTicker), nowAtOpen); ! double previousValueAtClose = ! HistoricalDataProvider.GetAdjustedMarketValue(SignedTicker.GetTicker(signedTicker), previousClose); ! ! return (currentValueAtOpen - previousValueAtClose) / previousValueAtClose; ! } ! private void setChosenTickers_addTickersForShorting() ! { ! DataTable worstTickersOrderedByGainAtOpen = new DataTable(); ! worstTickersOrderedByGainAtOpen.Columns.Add("ticker", Type.GetType("System.String")); ! worstTickersOrderedByGainAtOpen.Columns.Add("gainAtOpen", Type.GetType("System.Double")); ! object[] values = new object[2]; ! for (int i = 0; i<this.worstTickers.Length; i++) ! { ! values[0] = this.worstTickers[i]; ! values[1] = this.setChosenTickers_getGainOrLossFromPreviousClose(this.worstTickers[i]); ! worstTickersOrderedByGainAtOpen.Rows.Add(values); ! } ! DataRow[] orderedRows = new DataRow[this.bestTickers.Length]; ! orderedRows = worstTickersOrderedByGainAtOpen.Select("", "gainAtOpen DESC"); ! for(int i = 0;i<this.numOfTickersForShortSelling; i++) ! if( (double)orderedRows[i]["gainAtOpen"] > 0.0 ) ! //at open, current ticker is gaining ! this.chosenTickers[this.numOfTickersForBuying + i] = "-" + ! (string)orderedRows[i]["ticker"]; ! } ! ! private void setChosenTickers_addTickersForBuying() ! { ! DataTable bestTickersOrderedByLossAtOpen = new DataTable(); ! bestTickersOrderedByLossAtOpen.Columns.Add("ticker", Type.GetType("System.String")); ! bestTickersOrderedByLossAtOpen.Columns.Add("lossAtOpen", Type.GetType("System.Double")); ! object[] values = new object[2]; ! for (int i = 0; i<this.bestTickers.Length; i++) ! { ! values[0] = this.bestTickers[i]; ! values[1] = - this.setChosenTickers_getGainOrLossFromPreviousClose(this.bestTickers[i]); ! bestTickersOrderedByLossAtOpen.Rows.Add(values); ! } ! DataRow[] orderedRows = new DataRow[this.bestTickers.Length]; ! orderedRows = bestTickersOrderedByLossAtOpen.Select("", "lossAtOpen DESC"); ! for( int i = 0; i<this.numOfTickersForBuying; i++) ! if( (double)orderedRows[i]["lossAtOpen"] > 0.0 ) ! //at open, current ticker is losing ! this.chosenTickers[i] = (string)orderedRows[i]["ticker"]; ! } ! private void setChosenTickersBothForLongAndShort() ! { ! if( this.thereAreEnoughBestTickers && ! this.thereAreEnoughWorstTickers ) ! { try { *************** *** 190,246 **** } catch(Exception ex) ! {int dummy = 1; dummy++;} ! } ! } ! /// <summary> ! /// Handles a "Market Open" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.orders.Count == 0 && this.account.Transactions.Count == 0) ! this.account.AddCash(30000); ! this.setChosenTickersBothForLongAndShort(); ! bool allTickersHasBeenChosenForLongAndShort = true; ! for( int i = 0; i<this.chosenTickers.Length; i++) ! { ! if(this.chosenTickers[i] == null) ! allTickersHasBeenChosenForLongAndShort = false; ! } ! if(allTickersHasBeenChosenForLongAndShort) ! this.openPositions(this.chosenTickers); ! } ! #endregion ! #region MarketCloseEventHandler ! private void closePosition( string ticker ) ! { ! this.account.ClosePosition( ticker ); ! } ! ! private void closePositions() ! { ! if(this.lastOrderedTickers != null) ! foreach( string ticker in this.lastOrderedTickers ) ! for( int i = 0; i<this.account.Portfolio.Keys.Count; i++ ) ! if( this.account.Portfolio[ticker]!=null ) ! closePosition( ticker ); ! } ! ! public void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.closePositions(); ! } ! #endregion ! #region OneHourAfterMarketCloseEventHandler ! private void oneHourAfterMarketCloseEventHandler_clear() { --- 190,248 ---- } catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! } ! } ! /// <summary> ! /// Handles a "Market Open" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.orders.Count == 0 && this.account.Transactions.Count == 0) ! this.account.AddCash(30000); ! this.setChosenTickersBothForLongAndShort(); ! bool allTickersHasBeenChosenForLongAndShort = true; ! for( int i = 0; i<this.chosenTickers.Length; i++) ! { ! if(this.chosenTickers[i] == null) ! allTickersHasBeenChosenForLongAndShort = false; ! } ! if(allTickersHasBeenChosenForLongAndShort) ! this.openPositions(this.chosenTickers); ! } ! #endregion ! #region MarketCloseEventHandler ! private void closePosition( string ticker ) ! { ! this.account.ClosePosition( ticker ); ! } ! ! private void closePositions() ! { ! if(this.lastOrderedTickers != null) ! foreach( string ticker in this.lastOrderedTickers ) ! for( int i = 0; i<this.account.Portfolio.Keys.Count; i++ ) ! if( this.account.Portfolio[ticker]!=null ) ! closePosition( ticker ); ! } ! ! public void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.closePositions(); ! } ! #endregion ! #region OneHourAfterMarketCloseEventHandler ! private void oneHourAfterMarketCloseEventHandler_clear() { *************** *** 252,303 **** this.chosenTickers[i] = null; } ! ! /// <summary> ! /// Handles a "One hour after market close" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void OneHourAfterMarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.oneHourAfterMarketCloseEventHandler_clear(); ! DateTime currentDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! //remark from here for DEBUG ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromGroup = new SelectorByQuotationAtEachMarketDay(tickersFromGroup, ! false, currentDate.AddDays(-30), currentDate, ! tickersFromGroup.Rows.Count, this.benchmark); ! SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice( quotedAtEachMarketDayFromGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-10), currentDate, ! tickersFromGroup.Rows.Count, 25 ); ! ! SelectorByLiquidity mostLiquidSelector = ! new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByOpenToCloseVolatility lessVolatile = ! new SelectorByOpenToCloseVolatility(mostLiquidSelector.GetTableOfSelectedTickers(), ! true,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers/2); ! ! SelectorByAverageCloseToClosePerformance bestTickersFromLessVolatile = ! new SelectorByAverageCloseToClosePerformance(lessVolatile.GetTableOfSelectedTickers(), ! false,currentDate,currentDate,this.bestTickers.Length); ! SelectorByAverageCloseToClosePerformance worstTickersFromLessVolatile = ! new SelectorByAverageCloseToClosePerformance(lessVolatile.GetTableOfSelectedTickers(), ! true,currentDate,currentDate,this.worstTickers.Length); DataTable tableOfBestTickers = bestTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfBestTickers.Rows.Count >= this.bestTickers.Length) ! { this.thereAreEnoughBestTickers = true; for(int i = 0;i<this.bestTickers.Length;i++) --- 254,305 ---- this.chosenTickers[i] = null; } ! ! /// <summary> ! /// Handles a "One hour after market close" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void OneHourAfterMarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.oneHourAfterMarketCloseEventHandler_clear(); ! DateTime currentDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! //remark from here for DEBUG ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromGroup = new SelectorByQuotationAtEachMarketDay(tickersFromGroup, ! false, currentDate.AddDays(-30), currentDate, ! tickersFromGroup.Rows.Count, this.benchmark); ! SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice( quotedAtEachMarketDayFromGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-10), currentDate, ! tickersFromGroup.Rows.Count, 25 ); ! ! SelectorByLiquidity mostLiquidSelector = ! new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByOpenToCloseVolatility lessVolatile = ! new SelectorByOpenToCloseVolatility(mostLiquidSelector.GetTableOfSelectedTickers(), ! true,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers/2); ! ! SelectorByAverageCloseToClosePerformance bestTickersFromLessVolatile = ! new SelectorByAverageCloseToClosePerformance(lessVolatile.GetTableOfSelectedTickers(), ! false,currentDate,currentDate,this.bestTickers.Length); ! SelectorByAverageCloseToClosePerformance worstTickersFromLessVolatile = ! new SelectorByAverageCloseToClosePerformance(lessVolatile.GetTableOfSelectedTickers(), ! true,currentDate,currentDate,this.worstTickers.Length); DataTable tableOfBestTickers = bestTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfBestTickers.Rows.Count >= this.bestTickers.Length) ! { this.thereAreEnoughBestTickers = true; for(int i = 0;i<this.bestTickers.Length;i++) *************** *** 312,316 **** DataTable tableOfWorstTickers = worstTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfWorstTickers.Rows.Count >= this.worstTickers.Length) ! { this.thereAreEnoughWorstTickers = true; for(int i = 0;i<this.worstTickers.Length;i++) --- 314,318 ---- DataTable tableOfWorstTickers = worstTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfWorstTickers.Rows.Count >= this.worstTickers.Length) ! { this.thereAreEnoughWorstTickers = true; for(int i = 0;i<this.worstTickers.Length;i++) *************** *** 322,351 **** } } ! // //for DEBUG ! // //remark from here for real running ! // SelectorByLiquidity mostLiquidSelector = ! // new SelectorByLiquidity(tickersFromGroup, ! // false,currentDate.AddDays(-30), currentDate, ! // this.numberOfEligibleTickers); // ! // SelectorByAverageCloseToClosePerformance bestTickersFromMostLiquid = ! // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), ! // false,currentDate,currentDate,this.bestTickers.Length); // ! // SelectorByAverageCloseToClosePerformance worstTickersFromMostLiquid = ! // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), ! // true,currentDate,currentDate,this.worstTickers.Length); // ! // DataTable tableOfBestTickers = bestTickersFromMostLiquid.GetTableOfSelectedTickers(); ! // for(int i = 0;i<this.bestTickers.Length;i++) ! // if(tableOfBestTickers.Rows[i][0] != null) ! // this.bestTickers[i] = (string)tableOfBestTickers.Rows[i][0]; // ! // DataTable tableOfWorstTickers = worstTickersFromMostLiquid.GetTableOfSelectedTickers(); ! // for(int i = 0;i<this.worstTickers.Length;i++) ! // if(tableOfWorstTickers.Rows[i][0] != null) ! // this.worstTickers[i] = (string)tableOfWorstTickers.Rows[i][0]; ! } ! #endregion ! } } --- 324,353 ---- } } ! // //for DEBUG ! // //remark from here for real running ! // SelectorByLiquidity mostLiquidSelector = ! // new SelectorByLiquidity(tickersFromGroup, ! // false,currentDate.AddDays(-30), currentDate, ! // this.numberOfEligibleTickers); // ! // SelectorByAverageCloseToClosePerformance bestTickersFromMostLiquid = ! // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), ! // false,currentDate,currentDate,this.bestTickers.Length); // ! // SelectorByAverageCloseToClosePerformance worstTickersFromMostLiquid = ! // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), ! // true,currentDate,currentDate,this.worstTickers.Length); // ! // DataTable tableOfBestTickers = bestTickersFromMostLiquid.GetTableOfSelectedTickers(); ! // for(int i = 0;i<this.bestTickers.Length;i++) ! // if(tableOfBestTickers.Rows[i][0] != null) ! // this.bestTickers[i] = (string)tableOfBestTickers.Rows[i][0]; // ! // DataTable tableOfWorstTickers = worstTickersFromMostLiquid.GetTableOfSelectedTickers(); ! // for(int i = 0;i<this.worstTickers.Length;i++) ! // if(tableOfWorstTickers.Rows[i][0] != null) ! // this.worstTickers[i] = (string)tableOfWorstTickers.Rows[i][0]; ! } ! #endregion ! } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:11:34
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/SimpleOHTest In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2916/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/SimpleOHTest Modified Files: EndOfDayTimerHandlerSimpleOHTest.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: EndOfDayTimerHandlerSimpleOHTest.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/SimpleOHTest/EndOfDayTimerHandlerSimpleOHTest.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** EndOfDayTimerHandlerSimpleOHTest.cs 29 Aug 2007 09:40:11 -0000 1.3 --- EndOfDayTimerHandlerSimpleOHTest.cs 19 Aug 2008 17:11:28 -0000 1.4 *************** *** 3,7 **** EndOfDayTimerHandlerSimpleOHTest.cs ! Copyright (C) 2007 Marco Milletti --- 3,7 ---- EndOfDayTimerHandlerSimpleOHTest.cs ! Copyright (C) 2007 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 37,137 **** { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the Simple OH Test, ! /// based on the OverReaction Hypothesis ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerSimpleOHTest ! { ! private string tickerGroupID; ! private int numberOfEligibleTickers; private int lengthInDaysForPerformance; ! private string benchmark; ! private Account account; ! private int numOfTickersForBuying; ! private int numOfTickersForShortSelling; ! private string[] bestTickers = null; ! private string[] worstTickers = null; ! private string[] chosenTickers; ! private string[] lastOrderedTickers; ! private ArrayList orders; private bool thereAreEnoughBestTickers; private bool thereAreEnoughWorstTickers; private int closesElapsedWithSomeOpenPosition; ! ! public EndOfDayTimerHandlerSimpleOHTest(string tickerGroupID, int numberOfEligibleTickers, ! int lengthInDaysForPerformance, ! int numOfTickersForBuying, ! int numOfTickersForShortSelling, ! Account account, string benchmark) ! { ! this.tickerGroupID = tickerGroupID; ! this.numberOfEligibleTickers = numberOfEligibleTickers; this.lengthInDaysForPerformance = lengthInDaysForPerformance; ! this.account = account; ! this.benchmark = benchmark; ! this.numOfTickersForBuying = numOfTickersForBuying; ! this.numOfTickersForShortSelling = numOfTickersForShortSelling; ! this.chosenTickers = new string[this.numOfTickersForBuying + this.numOfTickersForShortSelling]; ! this.lastOrderedTickers = new string[this.chosenTickers.Length]; ! this.orders = new ArrayList(); ! } ! ! #region MarketOpenEventHandler ! private void addOrderForTicker(string[] tickers, ! int tickerPosition ) ! { SignedTicker signedTicker = new SignedTicker( tickers[tickerPosition] ); ! string ticker = signedTicker.Ticker; ! double cashForSinglePosition = ! this.account.CashAmount / this.chosenTickers.Length; ! long quantity = ! Convert.ToInt64( Math.Floor( cashForSinglePosition / this.account.DataStreamer.GetCurrentBid( ticker ) ) ); ! Order order = ! new Order( signedTicker.MarketOrderType , ! new Instrument( ticker ) , quantity ); ! this.orders.Add(order); ! } ! private void addChosenTickersToOrderList(string[] tickers) ! { ! for( int i = 0; i<tickers.Length; i++) ! { ! if(tickers[i] != null) ! { ! this.addOrderForTicker( tickers, i ); ! this.lastOrderedTickers[i] = ! SignedTicker.GetTicker(tickers[i]); ! } ! } ! } ! private void openPositions(string[] tickers) ! { ! this.addChosenTickersToOrderList(tickers); ! //execute orders actually ! foreach(object item in this.orders) ! this.account.AddOrder((Order)item); ! } ! private void setChosenTickers_addTickersForShorting() ! { ! for( int i = 0;i<this.numOfTickersForShortSelling; i++) ! this.chosenTickers[this.numOfTickersForBuying + i] = "-" + this.bestTickers[i]; ! } ! ! private void setChosenTickers_addTickersForBuying() ! { ! for( int i = 0; i<this.numOfTickersForBuying; i++ ) ! this.chosenTickers[i] = this.worstTickers[i]; ! } ! private void setChosenTickersBothForLongAndShort() ! { ! if( this.thereAreEnoughBestTickers && ! this.thereAreEnoughWorstTickers ) ! { try { --- 37,137 ---- { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the Simple OH Test, ! /// based on the OverReaction Hypothesis ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerSimpleOHTest ! { ! private string tickerGroupID; ! private int numberOfEligibleTickers; private int lengthInDaysForPerformance; ! private string benchmark; ! private Account account; ! private int numOfTickersForBuying; ! private int numOfTickersForShortSelling; ! private string[] bestTickers = null; ! private string[] worstTickers = null; ! private string[] chosenTickers; ! private string[] lastOrderedTickers; ! private ArrayList orders; private bool thereAreEnoughBestTickers; private bool thereAreEnoughWorstTickers; private int closesElapsedWithSomeOpenPosition; ! ! public EndOfDayTimerHandlerSimpleOHTest(string tickerGroupID, int numberOfEligibleTickers, ! int lengthInDaysForPerformance, ! int numOfTickersForBuying, ! int numOfTickersForShortSelling, ! Account account, string benchmark) ! { ! this.tickerGroupID = tickerGroupID; ! this.numberOfEligibleTickers = numberOfEligibleTickers; this.lengthInDaysForPerformance = lengthInDaysForPerformance; ! this.account = account; ! this.benchmark = benchmark; ! this.numOfTickersForBuying = numOfTickersForBuying; ! this.numOfTickersForShortSelling = numOfTickersForShortSelling; ! this.chosenTickers = new string[this.numOfTickersForBuying + this.numOfTickersForShortSelling]; ! this.lastOrderedTickers = new string[this.chosenTickers.Length]; ! this.orders = new ArrayList(); ! } ! ! #region MarketOpenEventHandler ! private void addOrderForTicker(string[] tickers, ! int tickerPosition ) ! { SignedTicker signedTicker = new SignedTicker( tickers[tickerPosition] ); ! string ticker = signedTicker.Ticker; ! double cashForSinglePosition = ! this.account.CashAmount / this.chosenTickers.Length; ! long quantity = ! Convert.ToInt64( Math.Floor( cashForSinglePosition / this.account.DataStreamer.GetCurrentBid( ticker ) ) ); ! Order order = ! new Order( signedTicker.MarketOrderType , ! new Instrument( ticker ) , quantity ); ! this.orders.Add(order); ! } ! private void addChosenTickersToOrderList(string[] tickers) ! { ! for( int i = 0; i<tickers.Length; i++) ! { ! if(tickers[i] != null) ! { ! this.addOrderForTicker( tickers, i ); ! this.lastOrderedTickers[i] = ! SignedTicker.GetTicker(tickers[i]); ! } ! } ! } ! private void openPositions(string[] tickers) ! { ! this.addChosenTickersToOrderList(tickers); ! //execute orders actually ! foreach(object item in this.orders) ! this.account.AddOrder((Order)item); ! } ! private void setChosenTickers_addTickersForShorting() ! { ! for( int i = 0;i<this.numOfTickersForShortSelling; i++) ! this.chosenTickers[this.numOfTickersForBuying + i] = "-" + this.bestTickers[i]; ! } ! ! private void setChosenTickers_addTickersForBuying() ! { ! for( int i = 0; i<this.numOfTickersForBuying; i++ ) ! this.chosenTickers[i] = this.worstTickers[i]; ! } ! private void setChosenTickersBothForLongAndShort() ! { ! if( this.thereAreEnoughBestTickers && ! this.thereAreEnoughWorstTickers ) ! { try { *************** *** 140,155 **** } catch(Exception ex) ! {ex = ex;} ! } ! } ! /// <summary> ! /// Handles a "Market Open" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { if(this.orders.Count == 0 && this.account.Transactions.Count == 0) this.account.AddCash(30000); --- 140,157 ---- } catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! } ! } ! /// <summary> ! /// Handles a "Market Open" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { if(this.orders.Count == 0 && this.account.Transactions.Count == 0) this.account.AddCash(30000); *************** *** 163,190 **** if(allTickersHasBeenChosenForLongAndShort) this.openPositions(this.chosenTickers); ! } ! #endregion ! #region MarketCloseEventHandler ! private void closePosition( string ticker ) ! { ! this.account.ClosePosition( ticker ); ! } ! ! private void closePositions() ! { ! if(this.lastOrderedTickers != null) ! foreach( string ticker in this.lastOrderedTickers ) ! for( int i = 0; i<this.account.Portfolio.Keys.Count; i++ ) ! if( this.account.Portfolio[ticker]!=null ) ! closePosition( ticker ); ! } ! ! public void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.account.Portfolio.Count > 0) { this.closesElapsedWithSomeOpenPosition++; --- 165,192 ---- if(allTickersHasBeenChosenForLongAndShort) this.openPositions(this.chosenTickers); ! } ! #endregion ! #region MarketCloseEventHandler ! private void closePosition( string ticker ) ! { ! this.account.ClosePosition( ticker ); ! } ! ! private void closePositions() ! { ! if(this.lastOrderedTickers != null) ! foreach( string ticker in this.lastOrderedTickers ) ! for( int i = 0; i<this.account.Portfolio.Keys.Count; i++ ) ! if( this.account.Portfolio[ticker]!=null ) ! closePosition( ticker ); ! } ! ! public void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.account.Portfolio.Count > 0) { this.closesElapsedWithSomeOpenPosition++; *************** *** 197,201 **** } } ! else//this.account.Portfolio.Count == 0 { if( ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition >= this.lengthInDaysForPerformance ) --- 199,203 ---- } } ! else//this.account.Portfolio.Count == 0 { if( ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition >= this.lengthInDaysForPerformance ) *************** *** 205,214 **** } } ! } ! #endregion ! #region OneHourAfterMarketCloseEventHandler ! private void oneHourAfterMarketCloseEventHandler_clear() { --- 207,216 ---- } } ! } ! #endregion ! #region OneHourAfterMarketCloseEventHandler ! private void oneHourAfterMarketCloseEventHandler_clear() { *************** *** 220,234 **** this.chosenTickers[i] = null; } ! ! /// <summary> ! /// Handles a "One hour after market close" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void OneHourAfterMarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.oneHourAfterMarketCloseEventHandler_clear(); DateTime currentDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; int currentDateArrayPositionInTimer = ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition; --- 222,236 ---- this.chosenTickers[i] = null; } ! ! /// <summary> ! /// Handles a "One hour after market close" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void OneHourAfterMarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.oneHourAfterMarketCloseEventHandler_clear(); DateTime currentDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; int currentDateArrayPositionInTimer = ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition; *************** *** 236,274 **** (DateTime)((IndexBasedEndOfDayTimer)sender).IndexQuotes.Rows[currentDateArrayPositionInTimer - this.lengthInDaysForPerformance]["quDate"]; SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); //remark from here for DEBUG ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromGroup = new SelectorByQuotationAtEachMarketDay(tickersFromGroup, ! false, currentDate.AddDays(-30), currentDate, ! tickersFromGroup.Rows.Count, this.benchmark); ! SelectorByAverageRawOpenPrice byPrice = new SelectorByAverageRawOpenPrice( quotedAtEachMarketDayFromGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-10), currentDate, ! tickersFromGroup.Rows.Count, 25 ); ! SelectorByLiquidity mostLiquidSelector = new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByCloseToCloseVolatility lessVolatile = new SelectorByCloseToCloseVolatility(mostLiquidSelector.GetTableOfSelectedTickers(), ! true,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers/2); ! SelectorByAbsolutePerformance bestTickersFromLessVolatile = new SelectorByAbsolutePerformance(lessVolatile.GetTableOfSelectedTickers(), ! false,firstDateForPerformanceComputation,currentDate,this.bestTickers.Length); SelectorByAbsolutePerformance worstTickersFromLessVolatile = new SelectorByAbsolutePerformance(lessVolatile.GetTableOfSelectedTickers(), ! true,firstDateForPerformanceComputation,currentDate,this.bestTickers.Length); DataTable tableOfBestTickers = bestTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfBestTickers.Rows.Count >= this.bestTickers.Length) ! { this.thereAreEnoughBestTickers = true; for(int i = 0;i<this.bestTickers.Length;i++) --- 238,276 ---- (DateTime)((IndexBasedEndOfDayTimer)sender).IndexQuotes.Rows[currentDateArrayPositionInTimer - this.lengthInDaysForPerformance]["quDate"]; SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); //remark from here for DEBUG ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromGroup = new SelectorByQuotationAtEachMarketDay(tickersFromGroup, ! false, currentDate.AddDays(-30), currentDate, ! tickersFromGroup.Rows.Count, this.benchmark); ! SelectorByAverageRawOpenPrice byPrice = new SelectorByAverageRawOpenPrice( quotedAtEachMarketDayFromGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-10), currentDate, ! tickersFromGroup.Rows.Count, 25 ); ! SelectorByLiquidity mostLiquidSelector = new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByCloseToCloseVolatility lessVolatile = new SelectorByCloseToCloseVolatility(mostLiquidSelector.GetTableOfSelectedTickers(), ! true,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers/2); ! SelectorByAbsolutePerformance bestTickersFromLessVolatile = new SelectorByAbsolutePerformance(lessVolatile.GetTableOfSelectedTickers(), ! false,firstDateForPerformanceComputation,currentDate,this.bestTickers.Length); SelectorByAbsolutePerformance worstTickersFromLessVolatile = new SelectorByAbsolutePerformance(lessVolatile.GetTableOfSelectedTickers(), ! true,firstDateForPerformanceComputation,currentDate,this.bestTickers.Length); DataTable tableOfBestTickers = bestTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfBestTickers.Rows.Count >= this.bestTickers.Length) ! { this.thereAreEnoughBestTickers = true; for(int i = 0;i<this.bestTickers.Length;i++) *************** *** 283,287 **** DataTable tableOfWorstTickers = worstTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfWorstTickers.Rows.Count >= this.worstTickers.Length) ! { this.thereAreEnoughWorstTickers = true; for(int i = 0;i<this.worstTickers.Length;i++) --- 285,289 ---- DataTable tableOfWorstTickers = worstTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfWorstTickers.Rows.Count >= this.worstTickers.Length) ! { this.thereAreEnoughWorstTickers = true; for(int i = 0;i<this.worstTickers.Length;i++) *************** *** 293,322 **** } } ! // //for DEBUG ! // //remark from here for real running ! // SelectorByLiquidity mostLiquidSelector = ! // new SelectorByLiquidity(tickersFromGroup, ! // false,currentDate.AddDays(-30), currentDate, ! // this.numberOfEligibleTickers); // ! // SelectorByAverageCloseToClosePerformance bestTickersFromMostLiquid = ! // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), ! // false,currentDate,currentDate,this.bestTickers.Length); // ! // SelectorByAverageCloseToClosePerformance worstTickersFromMostLiquid = ! // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), ! // true,currentDate,currentDate,this.worstTickers.Length); // ! // DataTable tableOfBestTickers = bestTickersFromMostLiquid.GetTableOfSelectedTickers(); ! // for(int i = 0;i<this.bestTickers.Length;i++) ! // if(tableOfBestTickers.Rows[i][0] != null) ! // this.bestTickers[i] = (string)tableOfBestTickers.Rows[i][0]; // ! // DataTable tableOfWorstTickers = worstTickersFromMostLiquid.GetTableOfSelectedTickers(); ! // for(int i = 0;i<this.worstTickers.Length;i++) ! // if(tableOfWorstTickers.Rows[i][0] != null) ! // this.worstTickers[i] = (string)tableOfWorstTickers.Rows[i][0]; ! } ! #endregion ! } } --- 295,324 ---- } } ! // //for DEBUG ! // //remark from here for real running ! // SelectorByLiquidity mostLiquidSelector = ! // new SelectorByLiquidity(tickersFromGroup, ! // false,currentDate.AddDays(-30), currentDate, ! // this.numberOfEligibleTickers); // ! // SelectorByAverageCloseToClosePerformance bestTickersFromMostLiquid = ! // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), ! // false,currentDate,currentDate,this.bestTickers.Length); // ! // SelectorByAverageCloseToClosePerformance worstTickersFromMostLiquid = ! // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), ! // true,currentDate,currentDate,this.worstTickers.Length); // ! // DataTable tableOfBestTickers = bestTickersFromMostLiquid.GetTableOfSelectedTickers(); ! // for(int i = 0;i<this.bestTickers.Length;i++) ! // if(tableOfBestTickers.Rows[i][0] != null) ! // this.bestTickers[i] = (string)tableOfBestTickers.Rows[i][0]; // ! // DataTable tableOfWorstTickers = worstTickersFromMostLiquid.GetTableOfSelectedTickers(); ! // for(int i = 0;i<this.worstTickers.Length;i++) ! // if(tableOfWorstTickers.Rows[i][0] != null) ! // this.worstTickers[i] = (string)tableOfWorstTickers.Rows[i][0]; ! } ! #endregion ! } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:11:33
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2916/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend Modified Files: EndOfDayTimerHandlerECT.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: EndOfDayTimerHandlerECT.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend/EndOfDayTimerHandlerECT.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** EndOfDayTimerHandlerECT.cs 14 Jan 2008 23:32:29 -0000 1.8 --- EndOfDayTimerHandlerECT.cs 19 Aug 2008 17:11:28 -0000 1.9 *************** *** 3,7 **** EndOfDayTimerHandlerECT.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- EndOfDayTimerHandlerECT.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 43,319 **** { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the extreme ! /// counter trend strategy! ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerECT : EndOfDayTimerHandler ! { ! private int numDaysForReturnCalculation; ! private double maxAcceptableCloseToCloseDrawdown; ! private int daysCounterWithPositions; ! private DateTime lastCloseDate; ! private IGenomeManager iGenomeManager; ! private int seedForRandomGenerator; ! ! public EndOfDayTimerHandlerECT(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, ! int numDaysForReturnCalculation, ! int numDaysBetweenEachOptimization, ! PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, 0.0, ! portfolioType) ! { ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.stopLossConditionReached = false; ! this.currentAccountValue = 0.0; ! this.previousAccountValue = 0.0; ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; ! } ! ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } ! ! #region MarketCloseEventHandler ! ! protected void marketCloseEventHandler_updateStopLossCondition() ! { ! this.previousAccountValue = this.currentAccountValue; ! this.currentAccountValue = this.account.GetMarketValue(); ! if((this.currentAccountValue - this.previousAccountValue) ! /this.previousAccountValue < -this.maxAcceptableCloseToCloseDrawdown) ! { ! this.stopLossConditionReached = true; ! } ! else ! { ! this.stopLossConditionReached = false; ! } ! } ! private double marketCloseEventHandler_openPositions_getLastHalfPeriodGain(IndexBasedEndOfDayTimer timer) ! { ! double returnValue = 999.0; ! try ! { ! DateTime initialDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation]["quDate"]; ! DateTime finalDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! ReturnsManager returnsManager = new ReturnsManager(new CloseToCloseIntervals( ! new EndOfDayDateTime(initialDateForHalfPeriod, ! EndOfDaySpecificTime.MarketClose) , ! new EndOfDayDateTime(finalDateForHalfPeriod, ! EndOfDaySpecificTime.MarketClose) , ! this.benchmark , this.numDaysForReturnCalculation ) , ! new HistoricalAdjustedQuoteProvider() ); returnValue = this.chosenWeightedPositions.GetReturn(0,returnsManager); ! } ! catch(MissingQuotesException ex) ! { ! ex = ex; ! } ! return returnValue; ! } ! private void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) ! { ! double lastHalfPeriodGain = ! this.marketCloseEventHandler_openPositions_getLastHalfPeriodGain(timer); ! if(lastHalfPeriodGain != 999.0) ! //last half period gain has been properly computed ! { ! if(lastHalfPeriodGain < 0.0) ! AccountManager.OpenPositions(this.chosenWeightedPositions, ! this.account); ! else if (lastHalfPeriodGain > 0.0 && ! this.portfolioType == PortfolioType.ShortAndLong) ! { ! this.chosenWeightedPositions.Reverse(); ! //short the portfolio ! try{ ! AccountManager.OpenPositions(this.chosenWeightedPositions, ! this.account); ! } ! catch(Exception ex) ! { ! ex = ex; ! } ! finally{ ! this.chosenWeightedPositions.Reverse(); ! } ! } ! } ! } ! ! private void marketCloseEventHandler_closePositions() ! { ! if(this.daysCounterWithPositions == this.numDaysForReturnCalculation || ! this.stopLossConditionReached) ! { ! //Close if halfPeriod has elapsed or stop loss condition reached ! AccountManager.ClosePositions(this.account); ! this.daysCounterWithPositions = 0; ! } ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.account.Portfolio.Count > 0) ! this.daysCounterWithPositions++; ! //this.marketCloseEventHandler_updateStopLossCondition(); ! this.marketCloseEventHandler_closePositions(); ! if(this.chosenWeightedPositions != null) ! //tickers to buy have been chosen ! { ! if(this.account.Portfolio.Count == 0) ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); ! } ! ! } ! #endregion ! ! #region OneHourAfterMarketCloseEventHandler ! ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! int numOfTickersInGroupAtCurrentDate = tickersFromGroup.Rows.Count; ! ! SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice(tickersFromGroup,false,currentDate, ! currentDate.AddDays(-30), ! numOfTickersInGroupAtCurrentDate, ! 20,500, 0.0001,100); ! ! SelectorByLiquidity mostLiquidSelector = ! new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers() , ! false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers); ! ! // SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromByPrice = ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromGroup = ! new SelectorByQuotationAtEachMarketDay(mostLiquidSelector.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! ! // SelectorByCloseToCloseVolatility lessVolatile = ! // new SelectorByCloseToCloseVolatility(quotedAtEachMarketDayFromByPrice.GetTableOfSelectedTickers(), ! // true,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // this.numberOfEligibleTickers); ! // ! // return lessVolatile.GetTableOfSelectedTickers(); ! return quotedAtEachMarketDayFromGroup.GetTableOfSelectedTickers(); ! //OLD for etf ! // 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(); ! } ! ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.chosenWeightedPositions.Count*2) ! //the optimization process is meaningful only if the initial set of tickers is ! //larger than the number of tickers to be chosen ! { ! this.iGenomeManager = ! new GenomeManagerECT(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, this.numberOfTickersToBeChosen, ! this.numDaysForReturnCalculation, ! this.portfolioType,this.benchmark); ! GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); ! // GO.ElitismRate = 0.00; ! GO.MutationRate = 0.3; ! GO.CrossoverRate = 0.9; ! // GO.MinConvergenceRate = 0.75; ! // GO.KeepOnRunningUntilConvergenceIsReached = true; ! //GO.CrossoverRate = 0.5; ! GO.Run(false); ! this.addGenomeToBestGenomes(GO.BestGenome,((GenomeManagerForEfficientPortfolio)this.iGenomeManager).FirstQuoteDate, ! ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate, setOfTickersToBeOptimized.Rows.Count, ! this.numDaysForReturnCalculation, this.portfolioType, GO.GenerationCounter); ! // this.chosenTickers = ((GenomeMeaning)GO.BestGenome.Meaning).Tickers; ! // this.chosenTickersPortfolioWeights = ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights; SignedTickers signedTickers = new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers ); ! this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, ! signedTickers); ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! ! /// <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.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! this.seedForRandomGenerator++; ! this.numDaysElapsedSinceLastOptimization++; ! if((this.numDaysElapsedSinceLastOptimization - 1 == ! this.numDaysBetweenEachOptimization)) //|| this.isTheFirstClose ) ! //num days without optimization has elapsed or ! //it is the first close (OLD IMPLEMENTATION) ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, true); ! //sets tickers to be chosen next Market Close event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! ! } #endregion ! } } --- 43,319 ---- { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the extreme ! /// counter trend strategy! ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerECT : EndOfDayTimerHandler ! { ! private int numDaysForReturnCalculation; ! private double maxAcceptableCloseToCloseDrawdown; ! private int daysCounterWithPositions; ! private DateTime lastCloseDate; ! private IGenomeManager iGenomeManager; ! private int seedForRandomGenerator; ! ! public EndOfDayTimerHandlerECT(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, ! int numDaysForReturnCalculation, ! int numDaysBetweenEachOptimization, ! PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, 0.0, ! portfolioType) ! { ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.stopLossConditionReached = false; ! this.currentAccountValue = 0.0; ! this.previousAccountValue = 0.0; ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; ! } ! ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } ! ! #region MarketCloseEventHandler ! ! protected void marketCloseEventHandler_updateStopLossCondition() ! { ! this.previousAccountValue = this.currentAccountValue; ! this.currentAccountValue = this.account.GetMarketValue(); ! if((this.currentAccountValue - this.previousAccountValue) ! /this.previousAccountValue < -this.maxAcceptableCloseToCloseDrawdown) ! { ! this.stopLossConditionReached = true; ! } ! else ! { ! this.stopLossConditionReached = false; ! } ! } ! private double marketCloseEventHandler_openPositions_getLastHalfPeriodGain(IndexBasedEndOfDayTimer timer) ! { ! double returnValue = 999.0; ! try ! { ! DateTime initialDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation]["quDate"]; ! DateTime finalDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! ReturnsManager returnsManager = new ReturnsManager(new CloseToCloseIntervals( ! new EndOfDayDateTime(initialDateForHalfPeriod, ! EndOfDaySpecificTime.MarketClose) , ! new EndOfDayDateTime(finalDateForHalfPeriod, ! EndOfDaySpecificTime.MarketClose) , ! this.benchmark , this.numDaysForReturnCalculation ) , ! new HistoricalAdjustedQuoteProvider() ); returnValue = this.chosenWeightedPositions.GetReturn(0,returnsManager); ! } ! catch(MissingQuotesException ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! return returnValue; ! } ! private void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) ! { ! double lastHalfPeriodGain = ! this.marketCloseEventHandler_openPositions_getLastHalfPeriodGain(timer); ! if(lastHalfPeriodGain != 999.0) ! //last half period gain has been properly computed ! { ! if(lastHalfPeriodGain < 0.0) ! AccountManager.OpenPositions(this.chosenWeightedPositions, ! this.account); ! else if (lastHalfPeriodGain > 0.0 && ! this.portfolioType == PortfolioType.ShortAndLong) ! { ! this.chosenWeightedPositions.Reverse(); ! //short the portfolio ! try{ ! AccountManager.OpenPositions(this.chosenWeightedPositions, ! this.account); ! } ! catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! finally{ ! this.chosenWeightedPositions.Reverse(); ! } ! } ! } ! } ! ! private void marketCloseEventHandler_closePositions() ! { ! if(this.daysCounterWithPositions == this.numDaysForReturnCalculation || ! this.stopLossConditionReached) ! { ! //Close if halfPeriod has elapsed or stop loss condition reached ! AccountManager.ClosePositions(this.account); ! this.daysCounterWithPositions = 0; ! } ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.account.Portfolio.Count > 0) ! this.daysCounterWithPositions++; ! //this.marketCloseEventHandler_updateStopLossCondition(); ! this.marketCloseEventHandler_closePositions(); ! if(this.chosenWeightedPositions != null) ! //tickers to buy have been chosen ! { ! if(this.account.Portfolio.Count == 0) ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); ! } ! ! } ! #endregion ! ! #region OneHourAfterMarketCloseEventHandler ! ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! int numOfTickersInGroupAtCurrentDate = tickersFromGroup.Rows.Count; ! ! SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice(tickersFromGroup,false,currentDate, ! currentDate.AddDays(-30), ! numOfTickersInGroupAtCurrentDate, ! 20,500, 0.0001,100); ! ! SelectorByLiquidity mostLiquidSelector = ! new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers() , ! false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers); ! ! // SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromByPrice = ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromGroup = ! new SelectorByQuotationAtEachMarketDay(mostLiquidSelector.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! ! // SelectorByCloseToCloseVolatility lessVolatile = ! // new SelectorByCloseToCloseVolatility(quotedAtEachMarketDayFromByPrice.GetTableOfSelectedTickers(), ! // true,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // this.numberOfEligibleTickers); ! // ! // return lessVolatile.GetTableOfSelectedTickers(); ! return quotedAtEachMarketDayFromGroup.GetTableOfSelectedTickers(); ! //OLD for etf ! // 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(); ! } ! ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.chosenWeightedPositions.Count*2) ! //the optimization process is meaningful only if the initial set of tickers is ! //larger than the number of tickers to be chosen ! { ! this.iGenomeManager = ! new GenomeManagerECT(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, this.numberOfTickersToBeChosen, ! this.numDaysForReturnCalculation, ! this.portfolioType,this.benchmark); ! GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); ! // GO.ElitismRate = 0.00; ! GO.MutationRate = 0.3; ! GO.CrossoverRate = 0.9; ! // GO.MinConvergenceRate = 0.75; ! // GO.KeepOnRunningUntilConvergenceIsReached = true; ! //GO.CrossoverRate = 0.5; ! GO.Run(false); ! this.addGenomeToBestGenomes(GO.BestGenome,((GenomeManagerForEfficientPortfolio)this.iGenomeManager).FirstQuoteDate, ! ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate, setOfTickersToBeOptimized.Rows.Count, ! this.numDaysForReturnCalculation, this.portfolioType, GO.GenerationCounter); ! // this.chosenTickers = ((GenomeMeaning)GO.BestGenome.Meaning).Tickers; ! // this.chosenTickersPortfolioWeights = ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights; SignedTickers signedTickers = new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers ); ! this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, ! signedTickers); ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! ! /// <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.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! this.seedForRandomGenerator++; ! this.numDaysElapsedSinceLastOptimization++; ! if((this.numDaysElapsedSinceLastOptimization - 1 == ! this.numDaysBetweenEachOptimization)) //|| this.isTheFirstClose ) ! //num days without optimization has elapsed or ! //it is the first close (OLD IMPLEMENTATION) ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, true); ! //sets tickers to be chosen next Market Close event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! ! } #endregion ! } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:11:33
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2916/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator Modified Files: EndOfDayTimerHandlerPVO.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: EndOfDayTimerHandlerPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/EndOfDayTimerHandlerPVO.cs,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** EndOfDayTimerHandlerPVO.cs 12 Mar 2008 22:06:05 -0000 1.9 --- EndOfDayTimerHandlerPVO.cs 19 Aug 2008 17:11:28 -0000 1.10 *************** *** 3,7 **** EndOfDayTimerHandlerPVO.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- EndOfDayTimerHandlerPVO.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 46,320 **** { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the Portfolio Value ! /// Oscillator ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerPVO : EndOfDayTimerHandler ! { ! protected int minLevelForOversoldThreshold; ! protected int maxLevelForOversoldThreshold; ! protected int minLevelForOverboughtThreshold; ! protected int maxLevelForOverboughtThreshold; ! protected int divisorForThresholdComputation; ! protected int numDaysForOscillatingPeriod; ! protected double currentOversoldThreshold; ! protected double currentOverboughtThreshold; ! protected double maxAcceptableCloseToCloseDrawdown; ! protected double minimumAcceptableGain; ! protected DateTime lastCloseDate; ! protected IGenomeManager iGenomeManager; ! protected int seedForRandomGenerator; ! protected bool portfolioHasBeenOverbought; ! protected bool portfolioHasBeenOversold; ! protected bool symmetricalThresholds; ! protected bool overboughtMoreThanOversoldForFixedPortfolio; ! protected HistoricalAdjustedQuoteProvider historicalQuoteProvider; ! ! public EndOfDayTimerHandlerPVO(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, ! int numDaysForOscillatingPeriod, ! int minLevelForOversoldThreshold, ! int maxLevelForOversoldThreshold, ! int minLevelForOverboughtThreshold, ! int maxLevelForOverboughtThreshold, ! int divisorForThresholdComputation, ! bool symmetricalThresholds, ! bool overboughtMoreThanOversoldForFixedPortfolio, ! int numDaysBetweenEachOptimization, ! PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, 0.0, ! portfolioType) ! { ! this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; ! this.minLevelForOversoldThreshold = minLevelForOversoldThreshold; ! this.maxLevelForOversoldThreshold = maxLevelForOversoldThreshold; ! this.minLevelForOverboughtThreshold = minLevelForOverboughtThreshold; ! this.maxLevelForOverboughtThreshold = maxLevelForOverboughtThreshold; ! this.divisorForThresholdComputation = divisorForThresholdComputation; ! this.symmetricalThresholds = symmetricalThresholds; ! this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.minimumAcceptableGain = minimumAcceptableGain; ! this.stopLossConditionReached = false; ! this.currentAccountValue = 0.0; ! this.previousAccountValue = 0.0; ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = false; ! this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); ! } ! ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } ! #region MarketCloseEventHandler ! ! protected virtual double getCurrentChosenWeightedPositionsReturn(IndexBasedEndOfDayTimer timer) ! { ! double returnValue = 999.0; ! try ! { ! DateTime firstDayOfOscillatingPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForOscillatingPeriod]["quDate"]; ! DateTime today = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ReturnsManager returnsManager = new ReturnsManager(new CloseToCloseIntervals( new EndOfDayDateTime(firstDayOfOscillatingPeriod, ! EndOfDaySpecificTime.MarketClose) , new EndOfDayDateTime(today, ! EndOfDaySpecificTime.MarketClose) , this.benchmark , this.numDaysForOscillatingPeriod ) , ! this.historicalQuoteProvider ); returnValue = this.chosenWeightedPositions.GetReturn(0,returnsManager); ! } ! catch(MissingQuotesException ex) ! { ! ex = ex; ! } ! return returnValue; ! } ! private void marketCloseEventHandler_reverseIfNeeded(IndexBasedEndOfDayTimer timer) ! { ! double currentChosenWeightedPositionsReturn = ! this.getCurrentChosenWeightedPositionsReturn(timer); ! if(currentChosenWeightedPositionsReturn != 999.0 && ! this.portfolioType == PortfolioType.ShortAndLong) ! //currentChosenWeightedPositionsReturn has been ! //properly computedand it is possible to reverse positions ! { ! if(currentChosenWeightedPositionsReturn >= currentOverboughtThreshold && ! this.portfolioHasBeenOversold) ! //open positions derive from an overSold period but now ! //the overbought threshold has been reached ! { ! this.reversePositions(); ! this.portfolioHasBeenOversold = false; ! this.portfolioHasBeenOverbought = true; ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! if(currentChosenWeightedPositionsReturn <= - currentOversoldThreshold && ! this.portfolioHasBeenOverbought) ! //open positions derive from an overBought period but now ! //the overSold threshold has been reached ! { ! this.reversePositions(); ! this.portfolioHasBeenOversold = true; ! this.portfolioHasBeenOverbought = false; ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! } ! } ! protected void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) ! { ! if(this.account.CashAmount == 0.0 && this.account.Transactions.Count == 0) this.account.AddCash(15000); ! double currentChosenWeightedPositionsReturn = ! this.getCurrentChosenWeightedPositionsReturn(timer); ! if(currentChosenWeightedPositionsReturn != 999.0) ! //currentChosenTickersValue has been properly computed ! { ! if(currentChosenWeightedPositionsReturn >= currentOverboughtThreshold && ! this.portfolioType == PortfolioType.ShortAndLong) ! { ! this.chosenWeightedPositions.Reverse(); ! try ! { ! AccountManager.OpenPositions( this.chosenWeightedPositions, ! this.account ); ! this.portfolioHasBeenOverbought = true; ! this.portfolioHasBeenOversold = false; ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! catch(Exception ex) ! { ! ex = ex; ! } ! finally ! { ! this.chosenWeightedPositions.Reverse(); ! } ! } ! else if (currentChosenWeightedPositionsReturn <= - currentOversoldThreshold) ! { ! AccountManager.OpenPositions( this.chosenWeightedPositions, ! this.account ); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = true; ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! } ! } ! ! protected virtual void marketCloseEventHandler_closePositionsIfNeeded() ! { ! if(this.stopLossConditionReached || ! this.takeProfitConditionReached || ! this.numDaysElapsedSinceLastOptimization + 1 == this.numDaysBetweenEachOptimization ) ! { ! AccountManager.ClosePositions(this.account); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = false; ! } ! } ! ! protected virtual void marketCloseEventHandler_updateStopLossAndTakeProfitConditions() ! { ! //this.previousAccountValue has been set at opening positions ! this.currentAccountValue = this.account.GetMarketValue(); ! double portfolioGainOrLoss = (this.currentAccountValue - this.previousAccountValue) ! /this.previousAccountValue; ! ! if( portfolioGainOrLoss <= -this.maxAcceptableCloseToCloseDrawdown ) ! { ! this.stopLossConditionReached = true; ! this.takeProfitConditionReached = false; ! } ! else if (portfolioGainOrLoss >= this.minimumAcceptableGain) ! ! { ! this.stopLossConditionReached = false; ! this.takeProfitConditionReached = true; ! } ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.marketCloseEventHandler_updateStopLossAndTakeProfitConditions(); ! this.marketCloseEventHandler_closePositionsIfNeeded(); ! if(this.chosenWeightedPositions != null) ! //tickers to buy have been chosen by the optimizer ! { ! if(this.account.Portfolio.Count == 0) ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); ! //positions are opened only if thresholds are reached ! else//there are some opened positions ! this.marketCloseEventHandler_reverseIfNeeded((IndexBasedEndOfDayTimer)sender); ! } ! } ! #endregion ! ! #region OneHourAfterMarketCloseEventHandler ! ! protected virtual DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! int numOfTickersInGroupAtCurrentDate = tickersFromGroup.Rows.Count; ! ! SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice(tickersFromGroup,false,currentDate.AddDays(-15), ! currentDate, ! numOfTickersInGroupAtCurrentDate, ! 30,3000, 0.0001,100); ! ! SelectorByLiquidity mostLiquidSelector = ! new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers); ! ! // SelectorByCloseToCloseCorrelationToBenchmark byCorrelationToBenchmark = ! // new SelectorByCloseToCloseCorrelationToBenchmark(mostLiquidSelector.GetTableOfSelectedTickers(), ! // "^GSPC",false, ! // currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // this.numberOfEligibleTickers/2,false); ! // ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromLastSelection = ! new SelectorByQuotationAtEachMarketDay(mostLiquidSelector.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! // SelectorByMaxLinearDipendence dipendentTickers = // new SelectorByMaxLinearDipendence(quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(), // currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, // this.numberOfEligibleTickers/2,2,1000, this.benchmark); // return dipendentTickers.GetTableOfSelectedTickers(); ! ! // DataTable quotedAtEachMarketDay = // quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(); ! // ! // CloseToCloseCorrelationProvider correlationProvider = // new CloseToCloseCorrelationProvider( // QuantProject.ADT.ExtendedDataTable.GetArrayOfStringFromColumn( // quotedAtEachMarketDay, 0 ), ! // currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! // currentDate,1,0.005,this.benchmark); // SelectorByCloseToCloseCorrelationToBenchmark byCorrelationToBenchmark = --- 46,320 ---- { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the Portfolio Value ! /// Oscillator ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerPVO : EndOfDayTimerHandler ! { ! protected int minLevelForOversoldThreshold; ! protected int maxLevelForOversoldThreshold; ! protected int minLevelForOverboughtThreshold; ! protected int maxLevelForOverboughtThreshold; ! protected int divisorForThresholdComputation; ! protected int numDaysForOscillatingPeriod; ! protected double currentOversoldThreshold; ! protected double currentOverboughtThreshold; ! protected double maxAcceptableCloseToCloseDrawdown; ! protected double minimumAcceptableGain; ! protected DateTime lastCloseDate; ! protected IGenomeManager iGenomeManager; ! protected int seedForRandomGenerator; ! protected bool portfolioHasBeenOverbought; ! protected bool portfolioHasBeenOversold; ! protected bool symmetricalThresholds; ! protected bool overboughtMoreThanOversoldForFixedPortfolio; ! protected HistoricalAdjustedQuoteProvider historicalQuoteProvider; ! ! public EndOfDayTimerHandlerPVO(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, ! int numDaysForOscillatingPeriod, ! int minLevelForOversoldThreshold, ! int maxLevelForOversoldThreshold, ! int minLevelForOverboughtThreshold, ! int maxLevelForOverboughtThreshold, ! int divisorForThresholdComputation, ! bool symmetricalThresholds, ! bool overboughtMoreThanOversoldForFixedPortfolio, ! int numDaysBetweenEachOptimization, ! PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, 0.0, ! portfolioType) ! { ! this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; ! this.minLevelForOversoldThreshold = minLevelForOversoldThreshold; ! this.maxLevelForOversoldThreshold = maxLevelForOversoldThreshold; ! this.minLevelForOverboughtThreshold = minLevelForOverboughtThreshold; ! this.maxLevelForOverboughtThreshold = maxLevelForOverboughtThreshold; ! this.divisorForThresholdComputation = divisorForThresholdComputation; ! this.symmetricalThresholds = symmetricalThresholds; ! this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.minimumAcceptableGain = minimumAcceptableGain; ! this.stopLossConditionReached = false; ! this.currentAccountValue = 0.0; ! this.previousAccountValue = 0.0; ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = false; ! this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); ! } ! ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } ! #region MarketCloseEventHandler ! ! protected virtual double getCurrentChosenWeightedPositionsReturn(IndexBasedEndOfDayTimer timer) ! { ! double returnValue = 999.0; ! try ! { ! DateTime firstDayOfOscillatingPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForOscillatingPeriod]["quDate"]; ! DateTime today = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ReturnsManager returnsManager = new ReturnsManager(new CloseToCloseIntervals( new EndOfDayDateTime(firstDayOfOscillatingPeriod, ! EndOfDaySpecificTime.MarketClose) , new EndOfDayDateTime(today, ! EndOfDaySpecificTime.MarketClose) , this.benchmark , this.numDaysForOscillatingPeriod ) , ! this.historicalQuoteProvider ); returnValue = this.chosenWeightedPositions.GetReturn(0,returnsManager); ! } ! catch(MissingQuotesException ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! return returnValue; ! } ! private void marketCloseEventHandler_reverseIfNeeded(IndexBasedEndOfDayTimer timer) ! { ! double currentChosenWeightedPositionsReturn = ! this.getCurrentChosenWeightedPositionsReturn(timer); ! if(currentChosenWeightedPositionsReturn != 999.0 && ! this.portfolioType == PortfolioType.ShortAndLong) ! //currentChosenWeightedPositionsReturn has been ! //properly computedand it is possible to reverse positions ! { ! if(currentChosenWeightedPositionsReturn >= currentOverboughtThreshold && ! this.portfolioHasBeenOversold) ! //open positions derive from an overSold period but now ! //the overbought threshold has been reached ! { ! this.reversePositions(); ! this.portfolioHasBeenOversold = false; ! this.portfolioHasBeenOverbought = true; ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! if(currentChosenWeightedPositionsReturn <= - currentOversoldThreshold && ! this.portfolioHasBeenOverbought) ! //open positions derive from an overBought period but now ! //the overSold threshold has been reached ! { ! this.reversePositions(); ! this.portfolioHasBeenOversold = true; ! this.portfolioHasBeenOverbought = false; ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! } ! } ! protected void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) ! { ! if(this.account.CashAmount == 0.0 && this.account.Transactions.Count == 0) this.account.AddCash(15000); ! double currentChosenWeightedPositionsReturn = ! this.getCurrentChosenWeightedPositionsReturn(timer); ! if(currentChosenWeightedPositionsReturn != 999.0) ! //currentChosenTickersValue has been properly computed ! { ! if(currentChosenWeightedPositionsReturn >= currentOverboughtThreshold && ! this.portfolioType == PortfolioType.ShortAndLong) ! { ! this.chosenWeightedPositions.Reverse(); ! try ! { ! AccountManager.OpenPositions( this.chosenWeightedPositions, ! this.account ); ! this.portfolioHasBeenOverbought = true; ! this.portfolioHasBeenOversold = false; ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! finally ! { ! this.chosenWeightedPositions.Reverse(); ! } ! } ! else if (currentChosenWeightedPositionsReturn <= - currentOversoldThreshold) ! { ! AccountManager.OpenPositions( this.chosenWeightedPositions, ! this.account ); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = true; ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! } ! } ! ! protected virtual void marketCloseEventHandler_closePositionsIfNeeded() ! { ! if(this.stopLossConditionReached || ! this.takeProfitConditionReached || ! this.numDaysElapsedSinceLastOptimization + 1 == this.numDaysBetweenEachOptimization ) ! { ! AccountManager.ClosePositions(this.account); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = false; ! } ! } ! ! protected virtual void marketCloseEventHandler_updateStopLossAndTakeProfitConditions() ! { ! //this.previousAccountValue has been set at opening positions ! this.currentAccountValue = this.account.GetMarketValue(); ! double portfolioGainOrLoss = (this.currentAccountValue - this.previousAccountValue) ! /this.previousAccountValue; ! ! if( portfolioGainOrLoss <= -this.maxAcceptableCloseToCloseDrawdown ) ! { ! this.stopLossConditionReached = true; ! this.takeProfitConditionReached = false; ! } ! else if (portfolioGainOrLoss >= this.minimumAcceptableGain) ! ! { ! this.stopLossConditionReached = false; ! this.takeProfitConditionReached = true; ! } ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.marketCloseEventHandler_updateStopLossAndTakeProfitConditions(); ! this.marketCloseEventHandler_closePositionsIfNeeded(); ! if(this.chosenWeightedPositions != null) ! //tickers to buy have been chosen by the optimizer ! { ! if(this.account.Portfolio.Count == 0) ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); ! //positions are opened only if thresholds are reached ! else//there are some opened positions ! this.marketCloseEventHandler_reverseIfNeeded((IndexBasedEndOfDayTimer)sender); ! } ! } ! #endregion ! ! #region OneHourAfterMarketCloseEventHandler ! ! protected virtual DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! int numOfTickersInGroupAtCurrentDate = tickersFromGroup.Rows.Count; ! ! SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice(tickersFromGroup,false,currentDate.AddDays(-15), ! currentDate, ! numOfTickersInGroupAtCurrentDate, ! 30,3000, 0.0001,100); ! ! SelectorByLiquidity mostLiquidSelector = ! new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers); ! ! // SelectorByCloseToCloseCorrelationToBenchmark byCorrelationToBenchmark = ! // new SelectorByCloseToCloseCorrelationToBenchmark(mostLiquidSelector.GetTableOfSelectedTickers(), ! // "^GSPC",false, ! // currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // this.numberOfEligibleTickers/2,false); ! // ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromLastSelection = ! new SelectorByQuotationAtEachMarketDay(mostLiquidSelector.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! // SelectorByMaxLinearDipendence dipendentTickers = // new SelectorByMaxLinearDipendence(quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(), // currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, // this.numberOfEligibleTickers/2,2,1000, this.benchmark); // return dipendentTickers.GetTableOfSelectedTickers(); ! ! // DataTable quotedAtEachMarketDay = // quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(); ! // ! // CloseToCloseCorrelationProvider correlationProvider = // new CloseToCloseCorrelationProvider( // QuantProject.ADT.ExtendedDataTable.GetArrayOfStringFromColumn( // quotedAtEachMarketDay, 0 ), ! // currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! // currentDate,1,0.005,this.benchmark); // SelectorByCloseToCloseCorrelationToBenchmark byCorrelationToBenchmark = *************** *** 325,424 **** // this.numberOfEligibleTickers / 2, false); // return byCorrelationToBenchmark.GetTableOfSelectedTickers(); ! return quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(); ! //for debug ! // SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromLastSelection = ! // new SelectorByQuotationAtEachMarketDay(temporizedGroup.GetTableOfSelectedTickers(), ! // false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // this.numberOfEligibleTickers, this.benchmark); ! // return quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(); ! } ! protected void addPVOGenomeToBestGenomes(Genome genome, ! DateTime firstOptimizationDate, ! DateTime secondOptimizationDate, ! int eligibleTickers, int daysForOscillatingPeriod, ! PortfolioType portfolioType, ! int createdGenerations, ! double oversoldThreshold, ! double overboughtThreshold) ! { ! if(this.bestGenomes == null) ! this.bestGenomes = new ArrayList(); ! ! this.bestGenomes.Add(new GenomeRepresentation(genome, ! firstOptimizationDate, ! secondOptimizationDate, ! genome.Generation, ! eligibleTickers, ! daysForOscillatingPeriod, portfolioType, createdGenerations, ! oversoldThreshold, overboughtThreshold)); ! } ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.numberOfTickersToBeChosen*2) ! //the optimization process is meaningful only if the initial set of tickers is ! //larger than the number of tickers to be chosen ! ! { ! this.iGenomeManager = ! new GenomeManagerPVO(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, this.numberOfTickersToBeChosen, ! this.numDaysForOscillatingPeriod, ! this.minLevelForOversoldThreshold, ! this.maxLevelForOversoldThreshold, ! this.minLevelForOverboughtThreshold, ! this.maxLevelForOverboughtThreshold, ! this.divisorForThresholdComputation, ! this.symmetricalThresholds, ! this.overboughtMoreThanOversoldForFixedPortfolio, ! this.portfolioType,this.benchmark); ! GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); ! GO.MutationRate = 0.1; ! GO.Run(false); ! ! this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaningPVO)GO.BestGenome.Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaningPVO)GO.BestGenome.Meaning).Tickers) ); ! this.currentOversoldThreshold = ((GenomeMeaningPVO)GO.BestGenome.Meaning).OversoldThreshold; ! this.currentOverboughtThreshold = ((GenomeMeaningPVO)GO.BestGenome.Meaning).OverboughtThreshold; ! this.addPVOGenomeToBestGenomes(GO.BestGenome,((GenomeManagerForEfficientPortfolio)this.iGenomeManager).FirstQuoteDate, ! ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate, setOfTickersToBeOptimized.Rows.Count, ! this.numDaysForOscillatingPeriod, this.portfolioType, GO.GenerationCounter, ! this.currentOversoldThreshold, this.currentOverboughtThreshold); ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! ! /// <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.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! this.seedForRandomGenerator++; ! this.numDaysElapsedSinceLastOptimization++; ! if((this.numDaysElapsedSinceLastOptimization == ! this.numDaysBetweenEachOptimization)) ! //num days without optimization has elapsed ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Close event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! ! } #endregion ! } } --- 325,424 ---- // this.numberOfEligibleTickers / 2, false); // return byCorrelationToBenchmark.GetTableOfSelectedTickers(); ! return quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(); ! //for debug ! // SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromLastSelection = ! // new SelectorByQuotationAtEachMarketDay(temporizedGroup.GetTableOfSelectedTickers(), ! // false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // this.numberOfEligibleTickers, this.benchmark); ! // return quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(); ! } ! protected void addPVOGenomeToBestGenomes(Genome genome, ! DateTime firstOptimizationDate, ! DateTime secondOptimizationDate, ! int eligibleTickers, int daysForOscillatingPeriod, ! PortfolioType portfolioType, ! int createdGenerations, ! double oversoldThreshold, ! double overboughtThreshold) ! { ! if(this.bestGenomes == null) ! this.bestGenomes = new ArrayList(); ! ! this.bestGenomes.Add(new GenomeRepresentation(genome, ! firstOptimizationDate, ! secondOptimizationDate, ! genome.Generation, ! eligibleTickers, ! daysForOscillatingPeriod, portfolioType, createdGenerations, ! oversoldThreshold, overboughtThreshold)); ! } ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.numberOfTickersToBeChosen*2) ! //the optimization process is meaningful only if the initial set of tickers is ! //larger than the number of tickers to be chosen ! ! { ! this.iGenomeManager = ! new GenomeManagerPVO(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, this.numberOfTickersToBeChosen, ! this.numDaysForOscillatingPeriod, ! this.minLevelForOversoldThreshold, ! this.maxLevelForOversoldThreshold, ! this.minLevelForOverboughtThreshold, ! this.maxLevelForOverboughtThreshold, ! this.divisorForThresholdComputation, ! this.symmetricalThresholds, ! this.overboughtMoreThanOversoldForFixedPortfolio, ! this.portfolioType,this.benchmark); ! GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); ! GO.MutationRate = 0.1; ! GO.Run(false); ! ! this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaningPVO)GO.BestGenome.Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaningPVO)GO.BestGenome.Meaning).Tickers) ); ! this.currentOversoldThreshold = ((GenomeMeaningPVO)GO.BestGenome.Meaning).OversoldThreshold; ! this.currentOverboughtThreshold = ((GenomeMeaningPVO)GO.BestGenome.Meaning).OverboughtThreshold; ! this.addPVOGenomeToBestGenomes(GO.BestGenome,((GenomeManagerForEfficientPortfolio)this.iGenomeManager).FirstQuoteDate, ! ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate, setOfTickersToBeOptimized.Rows.Count, ! this.numDaysForOscillatingPeriod, this.portfolioType, GO.GenerationCounter, ! this.currentOversoldThreshold, this.currentOverboughtThreshold); ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! ! /// <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.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! this.seedForRandomGenerator++; ! this.numDaysElapsedSinceLastOptimization++; ! if((this.numDaysElapsedSinceLastOptimization == ! this.numDaysBetweenEachOptimization)) ! //num days without optimization has elapsed ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Close event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! ! } #endregion ! } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:11:33
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2916/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators Modified Files: EndOfDayTimerHandlerFPOscillatorCTC.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: EndOfDayTimerHandlerFPOscillatorCTC.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators/EndOfDayTimerHandlerFPOscillatorCTC.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** EndOfDayTimerHandlerFPOscillatorCTC.cs 14 Jan 2008 23:32:30 -0000 1.6 --- EndOfDayTimerHandlerFPOscillatorCTC.cs 19 Aug 2008 17:11:28 -0000 1.7 *************** *** 3,7 **** EndOfDayTimerHandlerFPOscillatorCTC.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- EndOfDayTimerHandlerFPOscillatorCTC.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 40,335 **** { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the oscillator ! /// close to close strategy! ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerFPOscillatorCTC : EndOfDayTimerHandler ! { ! private int numDaysForReturnCalculation; ! private double maxAcceptableCloseToCloseDrawdown; ! private int daysCounterWithPositions; ! private int daysCounterWithRightPositions; ! private int daysCounterWithReversalPositions; ! private bool isReversalPeriodOn = false; ! // private bool isTheFirstClose = false; ! private DateTime lastCloseDate; ! private IGenomeManager iGenomeManager; ! private int seedForRandomGenerator; ! ! public EndOfDayTimerHandlerFPOscillatorCTC(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, ! int numDaysForReturnCalculation, ! PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, 0.0, ! portfolioType) ! { ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.daysCounterWithRightPositions = 0; ! this.daysCounterWithReversalPositions = 0; ! this.isReversalPeriodOn = false; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.stopLossConditionReached = false; ! this.currentAccountValue = 0.0; ! this.previousAccountValue = 0.0; ! this.numDaysBetweenEachOptimization = 2* numDaysForReturnCalculation; ! this.numDaysBetweenEachOptimization = numDaysForReturnCalculation; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; ! } ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } ! #region MarketCloseEventHandler ! ! protected void marketCloseEventHandler_updateStopLossCondition() ! { ! this.previousAccountValue = this.currentAccountValue; ! this.currentAccountValue = this.account.GetMarketValue(); ! if((this.currentAccountValue - this.previousAccountValue) ! /this.previousAccountValue < -this.maxAcceptableCloseToCloseDrawdown) ! { ! this.stopLossConditionReached = true; ! } ! else ! { ! this.stopLossConditionReached = false; ! } ! } ! ! private void marketCloseEventHandler_updateCounters(bool isTheFirstClose) ! { ! if(this.account.Portfolio.Count > 0 && isTheFirstClose == false) ! { ! if(this.isReversalPeriodOn) ! this.daysCounterWithReversalPositions++ ; ! else ! this.daysCounterWithRightPositions++ ; ! } ! } ! private bool marketCloseEventHandler_openPositionsIfTuned_isTuned(IndexBasedEndOfDayTimer timer) ! { ! bool returnValue = false; ! try ! { ! double gainForTheLastHalfPeriod; ! DateTime initialDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation + 1]["quDate"]; ! DateTime finalDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! gainForTheLastHalfPeriod = ! chosenWeightedPositions.GetCloseToCloseReturn(initialDateForHalfPeriod,finalDateForHalfPeriod); ! if(gainForTheLastHalfPeriod < 0.0) ! //in the last periods the combination has lost, so ! //it should gain the next days ! returnValue = true; ! ! return returnValue; ! } ! catch(MissingQuotesException ex) ! { ! ex = ex; ! return returnValue; ! } ! } ! private void marketCloseEventHandler_openPositionsIfTuned(IndexBasedEndOfDayTimer timer) ! { ! if(this.marketCloseEventHandler_openPositionsIfTuned_isTuned(timer)) ! AccountManager.OpenPositions(this.chosenWeightedPositions, this.account); ! } ! ! private void marketCloseEventHandler_closePositions() ! { ! this.daysCounterWithPositions++; ! if(this.daysCounterWithPositions == this.numDaysForReturnCalculation || ! this.stopLossConditionReached) ! { ! //Close if halfPeriod has elapsed or stop loss condition reached ! AccountManager.ClosePositions(this.account); ! this.daysCounterWithPositions = 0; ! } ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.marketCloseEventHandler_updateStopLossCondition(); ! ! if(this.account.Portfolio.Count == 0 && ! this.chosenWeightedPositions != null) ! //portfolio is empty and tickers to buy have been chosen ! this.marketCloseEventHandler_openPositionsIfTuned((IndexBasedEndOfDayTimer)sender); ! else ! this.marketCloseEventHandler_closePositions(); ! ! //OLD IMPLEMENTATION: always on the market ! // //update isTheFirstClose and optimize after adding cash ! // //(this first optimization could be done also after market close) ! // if (this.account.Transactions.Count == 0) ! // { ! // this.isTheFirstClose = true; ! // this.marketCloseEventHandler_optimize(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime); ! // } ! // else ! // { ! // this.isTheFirstClose = false; ! // } ! // this.marketCloseEventHandler_updateCounters(this.isTheFirstClose); ! // this.marketCloseEventHandler_updateStopLossCondition(); ! // ! // if(this.stopLossConditionReached) ! // { ! // this.orders.Clear(); ! // this.closePositions(); ! // this.daysCounterWithReversalPositions = 0; ! // this.daysCounterWithRightPositions = 0; ! // this.marketCloseEventHandler_optimize(this.lastCloseDate); ! // this.openPositions(); ! // } ! // else ! // { ! // if(this.account.Portfolio.Count == 0) ! // { ! // this.orders.Clear(); ! // this.openPositions(); ! // } ! // ! // if((this.isTheFirstClose == false && this.isReversalPeriodOn == false && ! // this.daysCounterWithRightPositions == this.numDaysForReturnCalculation)) ! // { ! // this.orders.Clear(); ! // this.closePositions(); ! // this.daysCounterWithRightPositions = 0; ! // this.marketCloseEventHandler_reverseSignOfTickers(this.chosenTickers); ! // this.openPositions(); ! // this.isReversalPeriodOn = true; ! // } ! // ! // if((this.isReversalPeriodOn == true && ! // this.daysCounterWithReversalPositions == this.numDaysForReturnCalculation)) ! // { ! // this.orders.Clear(); ! // this.closePositions(); ! // this.daysCounterWithReversalPositions = 0; ! // this.isReversalPeriodOn = false; ! // //code for only one optimization ! //// this.marketCloseEventHandler_reverseSignOfTickers(this.chosenTickers); ! //// this.openPositions(); ! // // ! // //normal strategy ! // this.marketCloseEventHandler_optimize(this.lastCloseDate); ! // this.openPositions(); ! // } // ! // } //END OF OLD IMPLEMENTATION ! } ! #endregion ! ! #region OneHourAfterMarketCloseEventHandler ! ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { ! SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketFromTemporized = ! new SelectorByQuotationAtEachMarketDay(temporizedGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! // SelectorByCloseToCloseVolatility lessVolatile = new SelectorByCloseToCloseVolatility( ! // quotedAtEachMarketFromTemporized.GetTableOfSelectedTickers(),true, ! // currentDate.AddDays(-15), currentDate, ! // this.numberOfEligibleTickers); // ! // return lessVolatile.GetTableOfSelectedTickers(); ! ! return quotedAtEachMarketFromTemporized.GetTableOfSelectedTickers(); ! ! } ! ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.numberOfTickersToBeChosen*2) ! //the optimization process is meaningful only if the initial set of tickers is ! //larger than the number of tickers to be chosen ! ! { ! ! //double targetReturnForEachPeriodOfPortfolioLife = ! // Math.Pow(1.60,(double)(1.0/(360.0/this.numDaysOfPortfolioLife))) - 1.0; ! //the target has to be such that annual system return is minimum 50% ! //(with no commissions and bid-ask spreads) ! // IGenomeManager genManOscillatorCTC = ! // new GenomeManagerForEfficientCTCPortfolio(setOfTickersToBeOptimized, ! // currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! // currentDate, this.numberOfTickersToBeChosen, ! // this.numDaysForReturnCalculation, 0.0, ! // this.portfolioType); ! this.iGenomeManager = ! new GenomeManagerForFPOscillatorCTC(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, this.numberOfTickersToBeChosen, ! this.numDaysForReturnCalculation, ! this.portfolioType, this.benchmark); ! GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); ! ! GO.Run(false); ! this.addGenomeToBestGenomes(GO.BestGenome,((GenomeManagerForEfficientPortfolio)this.iGenomeManager).FirstQuoteDate, ! ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate, setOfTickersToBeOptimized.Rows.Count, ! this.numDaysForReturnCalculation); this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers) ); ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! /// <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.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! this.seedForRandomGenerator++; ! this.numDaysElapsedSinceLastOptimization++; ! if((this.numDaysElapsedSinceLastOptimization - 1 == ! this.numDaysBetweenEachOptimization)) //|| this.isTheFirstClose ) ! //num days without optimization has elapsed or ! //it is the first close (OLD IMPLEMENTATION) ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Close event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! ! } #endregion ! } } --- 40,335 ---- { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the oscillator ! /// close to close strategy! ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerFPOscillatorCTC : EndOfDayTimerHandler ! { ! private int numDaysForReturnCalculation; ! private double maxAcceptableCloseToCloseDrawdown; ! private int daysCounterWithPositions; ! private int daysCounterWithRightPositions; ! private int daysCounterWithReversalPositions; ! private bool isReversalPeriodOn = false; ! // private bool isTheFirstClose = false; ! private DateTime lastCloseDate; ! private IGenomeManager iGenomeManager; ! private int seedForRandomGenerator; ! public EndOfDayTimerHandlerFPOscillatorCTC(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! Account account, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, ! string benchmark, ! int numDaysForReturnCalculation, ! PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, 0.0, ! portfolioType) ! { ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.daysCounterWithRightPositions = 0; ! this.daysCounterWithReversalPositions = 0; ! this.isReversalPeriodOn = false; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.stopLossConditionReached = false; ! this.currentAccountValue = 0.0; ! this.previousAccountValue = 0.0; ! this.numDaysBetweenEachOptimization = 2* numDaysForReturnCalculation; ! this.numDaysBetweenEachOptimization = numDaysForReturnCalculation; ! this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; ! } ! ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } ! #region MarketCloseEventHandler ! ! protected void marketCloseEventHandler_updateStopLossCondition() ! { ! this.previousAccountValue = this.currentAccountValue; ! this.currentAccountValue = this.account.GetMarketValue(); ! if((this.currentAccountValue - this.previousAccountValue) ! /this.previousAccountValue < -this.maxAcceptableCloseToCloseDrawdown) ! { ! this.stopLossConditionReached = true; ! } ! else ! { ! this.stopLossConditionReached = false; ! } ! } ! ! private void marketCloseEventHandler_updateCounters(bool isTheFirstClose) ! { ! if(this.account.Portfolio.Count > 0 && isTheFirstClose == false) ! { ! if(this.isReversalPeriodOn) ! this.daysCounterWithReversalPositions++ ; ! else ! this.daysCounterWithRightPositions++ ; ! } ! } ! private bool marketCloseEventHandler_openPositionsIfTuned_isTuned(IndexBasedEndOfDayTimer timer) ! { ! bool returnValue = false; ! try ! { ! double gainForTheLastHalfPeriod; ! DateTime initialDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation + 1]["quDate"]; ! DateTime finalDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! gainForTheLastHalfPeriod = ! chosenWeightedPositions.GetCloseToCloseReturn(initialDateForHalfPeriod,finalDateForHalfPeriod); ! if(gainForTheLastHalfPeriod < 0.0) ! //in the last periods the combination has lost, so ! //it should gain the next days ! returnValue = true; ! ! return returnValue; ! } ! catch(MissingQuotesException ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! return returnValue; ! } ! } ! private void marketCloseEventHandler_openPositionsIfTuned(IndexBasedEndOfDayTimer timer) ! { ! if(this.marketCloseEventHandler_openPositionsIfTuned_isTuned(timer)) ! AccountManager.OpenPositions(this.chosenWeightedPositions, this.account); ! } ! ! private void marketCloseEventHandler_closePositions() ! { ! this.daysCounterWithPositions++; ! if(this.daysCounterWithPositions == this.numDaysForReturnCalculation || ! this.stopLossConditionReached) ! { ! //Close if halfPeriod has elapsed or stop loss condition reached ! AccountManager.ClosePositions(this.account); ! this.daysCounterWithPositions = 0; ! } ! } ! ! public override void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.marketCloseEventHandler_updateStopLossCondition(); ! ! if(this.account.Portfolio.Count == 0 && ! this.chosenWeightedPositions != null) ! //portfolio is empty and tickers to buy have been chosen ! this.marketCloseEventHandler_openPositionsIfTuned((IndexBasedEndOfDayTimer)sender); ! else ! this.marketCloseEventHandler_closePositions(); ! ! //OLD IMPLEMENTATION: always on the market ! // //update isTheFirstClose and optimize after adding cash ! // //(this first optimization could be done also after market close) ! // if (this.account.Transactions.Count == 0) ! // { ! // this.isTheFirstClose = true; ! // this.marketCloseEventHandler_optimize(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime); ! // } ! // else ! // { ! // this.isTheFirstClose = false; ! // } ! // this.marketCloseEventHandler_updateCounters(this.isTheFirstClose); ! // this.marketCloseEventHandler_updateStopLossCondition(); // ! // if(this.stopLossConditionReached) ! // { ! // this.orders.Clear(); ! // this.closePositions(); ! // this.daysCounterWithReversalPositions = 0; ! // this.daysCounterWithRightPositions = 0; ! // this.marketCloseEventHandler_optimize(this.lastCloseDate); ! // this.openPositions(); ! // } ! // else ! // { ! // if(this.account.Portfolio.Count == 0) ! // { ! // this.orders.Clear(); ! // this.openPositions(); ! // } ! // ! // if((this.isTheFirstClose == false && this.isReversalPeriodOn == false && ! // this.daysCounterWithRightPositions == this.numDaysForReturnCalculation)) ! // { ! // this.orders.Clear(); ! // this.closePositions(); ! // this.daysCounterWithRightPositions = 0; ! // this.marketCloseEventHandler_reverseSignOfTickers(this.chosenTickers); ! // this.openPositions(); ! // this.isReversalPeriodOn = true; ! // } ! // ! // if((this.isReversalPeriodOn == true && ! // this.daysCounterWithReversalPositions == this.numDaysForReturnCalculation)) ! // { ! // this.orders.Clear(); ! // this.closePositions(); ! // this.daysCounterWithReversalPositions = 0; ! // this.isReversalPeriodOn = false; ! // //code for only one optimization ! //// this.marketCloseEventHandler_reverseSignOfTickers(this.chosenTickers); ! //// this.openPositions(); ! // // ! // //normal strategy ! // this.marketCloseEventHandler_optimize(this.lastCloseDate); ! // this.openPositions(); ! // } ! // ! // } //END OF OLD IMPLEMENTATION ! } ! #endregion ! ! #region OneHourAfterMarketCloseEventHandler ! ! protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { ! SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketFromTemporized = ! new SelectorByQuotationAtEachMarketDay(temporizedGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! this.numberOfEligibleTickers, this.benchmark); ! // SelectorByCloseToCloseVolatility lessVolatile = new SelectorByCloseToCloseVolatility( ! // quotedAtEachMarketFromTemporized.GetTableOfSelectedTickers(),true, ! // currentDate.AddDays(-15), currentDate, ! // this.numberOfEligibleTickers); // ! // return lessVolatile.GetTableOfSelectedTickers(); ! ! return quotedAtEachMarketFromTemporized.GetTableOfSelectedTickers(); ! ! } ! ! ! protected virtual void setTickers(DateTime currentDate, ! bool setGenomeCounter) ! { ! DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.numberOfTickersToBeChosen*2) ! //the optimization process is meaningful only if the initial set of tickers is ! //larger than the number of tickers to be chosen ! ! { ! ! //double targetReturnForEachPeriodOfPortfolioLife = ! // Math.Pow(1.60,(double)(1.0/(360.0/this.numDaysOfPortfolioLife))) - 1.0; ! //the target has to be such that annual system return is minimum 50% ! //(with no commissions and bid-ask spreads) ! // IGenomeManager genManOscillatorCTC = ! // new GenomeManagerForEfficientCTCPortfolio(setOfTickersToBeOptimized, ! // currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! // currentDate, this.numberOfTickersToBeChosen, ! // this.numDaysForReturnCalculation, 0.0, ! // this.portfolioType); ! this.iGenomeManager = ! new GenomeManagerForFPOscillatorCTC(setOfTickersToBeOptimized, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, this.numberOfTickersToBeChosen, ! this.numDaysForReturnCalculation, ! this.portfolioType, this.benchmark); ! GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, ! this.populationSizeForGeneticOptimizer, ! this.generationNumberForGeneticOptimizer, ! this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); ! ! GO.Run(false); ! this.addGenomeToBestGenomes(GO.BestGenome,((GenomeManagerForEfficientPortfolio)this.iGenomeManager).FirstQuoteDate, ! ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate, setOfTickersToBeOptimized.Rows.Count, ! this.numDaysForReturnCalculation); this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, ! new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers) ); ! } ! //else it will be buyed again the previous optimized portfolio ! //that's it the actual chosenTickers member ! } ! /// <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.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! this.seedForRandomGenerator++; ! this.numDaysElapsedSinceLastOptimization++; ! if((this.numDaysElapsedSinceLastOptimization - 1 == ! this.numDaysBetweenEachOptimization)) //|| this.isTheFirstClose ) ! //num days without optimization has elapsed or ! //it is the first close (OLD IMPLEMENTATION) ! { ! this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); ! //sets tickers to be chosen next Market Close event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! ! } #endregion ! } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:11:32
|
Update of /cvsroot/quantproject/QuantProject/b5_Presentation/Reporting/MicrosoftExcel In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2916/b5_Presentation/Reporting/MicrosoftExcel Modified Files: ExcelManager.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: ExcelManager.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b5_Presentation/Reporting/MicrosoftExcel/ExcelManager.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** ExcelManager.cs 15 Aug 2004 00:07:47 -0000 1.2 --- ExcelManager.cs 19 Aug 2008 17:11:28 -0000 1.3 *************** *** 110,114 **** excelBook.Worksheets.get_Item( excelBook.Worksheets.Count ),1,Missing.Value); excelSheet.Name = reportTable.Name; ! excelSheet.Activate(); drawHeaders( reportTable , excelSheet ); drawRows( reportTable , excelSheet ); --- 110,114 ---- excelBook.Worksheets.get_Item( excelBook.Worksheets.Count ),1,Missing.Value); excelSheet.Name = reportTable.Name; ! ((_Worksheet)excelSheet).Activate(); drawHeaders( reportTable , excelSheet ); drawRows( reportTable , excelSheet ); |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:11:32
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_WeekEndBounce In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2916/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_WeekEndBounce Modified Files: EndOfDayTimerHandlerDOR_WeekEndBounce.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: EndOfDayTimerHandlerDOR_WeekEndBounce.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_WeekEndBounce/EndOfDayTimerHandlerDOR_WeekEndBounce.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** EndOfDayTimerHandlerDOR_WeekEndBounce.cs 29 Aug 2007 09:16:56 -0000 1.1 --- EndOfDayTimerHandlerDOR_WeekEndBounce.cs 19 Aug 2008 17:11:28 -0000 1.2 *************** *** 3,7 **** EndOfDayTimerHandlerDOR_WeekEndBounce.cs ! Copyright (C) 2007 Marco Milletti --- 3,7 ---- EndOfDayTimerHandlerDOR_WeekEndBounce.cs ! Copyright (C) 2007 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 37,207 **** { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for ! /// the Double OverReaction WeekEnd Bounce Test, ! /// based on the OverReaction Hypothesis ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerDOR_WeekEndBounce ! { ! private string tickerGroupID; ! private int numberOfEligibleTickers; ! private string benchmark; ! private Account account; ! private int numOfWorstTickers; ! private int numOfBestTickers; private int lengthInDaysForPerformance; ! private int numOfTickersForBuying; ! private int numOfTickersForShortSelling; ! private string[] bestTickers; ! private string[] worstTickers; ! private string[] chosenTickers; ! private string[] lastOrderedTickers; ! private ArrayList orders; private bool thereAreEnoughBestTickers; private bool thereAreEnoughWorstTickers; ! ! public EndOfDayTimerHandlerDOR_WeekEndBounce(string tickerGroupID, int numberOfEligibleTickers, ! int numOfBestTickers, ! int numOfWorstTickers, ! int lengthInDaysForPerformance, ! int numOfTickersForBuying, ! int numOfTickersForShortSelling, ! Account account, string benchmark) ! { ! this.tickerGroupID = tickerGroupID; ! this.numberOfEligibleTickers = numberOfEligibleTickers; ! this.account = account; ! this.benchmark = benchmark; ! this.numOfBestTickers = numOfBestTickers; ! this.bestTickers = new string[this.numOfBestTickers]; ! this.numOfWorstTickers = numOfWorstTickers; ! this.worstTickers = new string[this.numOfWorstTickers]; this.lengthInDaysForPerformance = lengthInDaysForPerformance; ! this.numOfTickersForBuying = numOfTickersForBuying; ! this.numOfTickersForShortSelling = numOfTickersForShortSelling; ! this.chosenTickers = new string[this.numOfTickersForBuying + this.numOfTickersForShortSelling]; ! this.lastOrderedTickers = new string[this.chosenTickers.Length]; ! this.orders = new ArrayList(); ! } ! ! #region MarketOpenEventHandler ! private void closePosition( string ticker ) ! { ! this.account.ClosePosition( ticker ); ! } ! ! private void closePositions() ! { ! if(this.lastOrderedTickers != null) ! foreach( string ticker in this.lastOrderedTickers ) ! for( int i = 0; i<this.account.Portfolio.Keys.Count; i++ ) ! if( this.account.Portfolio[ticker]!=null ) ! closePosition( ticker ); ! } ! ! ! private void addOrderForTicker(string[] tickers, ! int tickerPosition ) ! { ! SignedTickers signedTickers = new SignedTickers(tickers); ! string ticker = ! SignedTicker.GetTicker(tickers[tickerPosition]); ! double cashForSinglePosition = ! this.account.CashAmount / this.chosenTickers.Length; ! long quantity = ! Convert.ToInt64( Math.Floor( cashForSinglePosition / this.account.DataStreamer.GetCurrentBid( ticker ) ) ); ! Order order = ! new Order( ! signedTickers[tickerPosition].MarketOrderType, ! new Instrument( ticker ) , quantity ); ! this.orders.Add(order); ! } ! private void addChosenTickersToOrderList(string[] tickers) ! { ! for( int i = 0; i<tickers.Length; i++) ! { ! if(tickers[i] != null) ! { ! this.addOrderForTicker( tickers, i ); ! this.lastOrderedTickers[i] = ! SignedTicker.GetTicker(tickers[i]); ! } ! } ! } ! private void openPositions(string[] tickers) ! { ! this.addChosenTickersToOrderList(tickers); ! //execute orders actually ! foreach(object item in this.orders) ! this.account.AddOrder((Order)item); ! } ! ! private double setChosenTickers_getGainOrLossFromPreviousClose(string signedTicker) ! { ! IndexBasedEndOfDayTimer currentTimer = (IndexBasedEndOfDayTimer)this.account.EndOfDayTimer; ! ExtendedDateTime nowAtOpen = ! new ExtendedDateTime(currentTimer.GetCurrentTime().DateTime, ! BarComponent.Open); ! ExtendedDateTime previousClose = ! new ExtendedDateTime(currentTimer.GetPreviousDateTime(), ! BarComponent.Close); ! double currentValueAtOpen = ! HistoricalDataProvider.GetAdjustedMarketValue(SignedTicker.GetTicker(signedTicker), nowAtOpen); ! double previousValueAtClose = ! HistoricalDataProvider.GetAdjustedMarketValue(SignedTicker.GetTicker(signedTicker), previousClose); ! ! return (currentValueAtOpen - previousValueAtClose) / previousValueAtClose; ! } ! private void setChosenTickers_addTickersForShorting() ! { ! DataTable worstTickersOrderedByGainAtOpen = new DataTable(); ! worstTickersOrderedByGainAtOpen.Columns.Add("ticker", Type.GetType("System.String")); ! worstTickersOrderedByGainAtOpen.Columns.Add("gainAtOpen", Type.GetType("System.Double")); ! object[] values = new object[2]; ! for (int i = 0; i<this.worstTickers.Length; i++) ! { ! values[0] = this.worstTickers[i]; ! values[1] = this.setChosenTickers_getGainOrLossFromPreviousClose(this.worstTickers[i]); ! worstTickersOrderedByGainAtOpen.Rows.Add(values); ! } ! DataRow[] orderedRows = new DataRow[this.bestTickers.Length]; ! orderedRows = worstTickersOrderedByGainAtOpen.Select("", "gainAtOpen DESC"); ! for(int i = 0;i<this.numOfTickersForShortSelling; i++) ! if( (double)orderedRows[i]["gainAtOpen"] > 0.0 ) ! //at open, current ticker is gaining ! this.chosenTickers[this.numOfTickersForBuying + i] = "-" + ! (string)orderedRows[i]["ticker"]; ! } ! ! private void setChosenTickers_addTickersForBuying() ! { ! DataTable bestTickersOrderedByLossAtOpen = new DataTable(); ! bestTickersOrderedByLossAtOpen.Columns.Add("ticker", Type.GetType("System.String")); ! bestTickersOrderedByLossAtOpen.Columns.Add("lossAtOpen", Type.GetType("System.Double")); ! object[] values = new object[2]; ! for (int i = 0; i<this.bestTickers.Length; i++) ! { ! values[0] = this.bestTickers[i]; ! values[1] = - this.setChosenTickers_getGainOrLossFromPreviousClose(this.bestTickers[i]); ! bestTickersOrderedByLossAtOpen.Rows.Add(values); ! } ! DataRow[] orderedRows = new DataRow[this.bestTickers.Length]; ! orderedRows = bestTickersOrderedByLossAtOpen.Select("", "lossAtOpen DESC"); ! for( int i = 0; i<this.numOfTickersForBuying; i++) ! if( (double)orderedRows[i]["lossAtOpen"] > 0.0 ) ! //at open, current ticker is losing ! this.chosenTickers[i] = (string)orderedRows[i]["ticker"]; ! } ! private void setChosenTickersBothForLongAndShort() ! { ! if( this.thereAreEnoughBestTickers && ! this.thereAreEnoughWorstTickers ) ! { try { --- 37,207 ---- { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for ! /// the Double OverReaction WeekEnd Bounce Test, ! /// based on the OverReaction Hypothesis ! /// </summary> ! [Serializable] ! public class EndOfDayTimerHandlerDOR_WeekEndBounce ! { ! private string tickerGroupID; ! private int numberOfEligibleTickers; ! private string benchmark; ! private Account account; ! private int numOfWorstTickers; ! private int numOfBestTickers; private int lengthInDaysForPerformance; ! private int numOfTickersForBuying; ! private int numOfTickersForShortSelling; ! private string[] bestTickers; ! private string[] worstTickers; ! private string[] chosenTickers; ! private string[] lastOrderedTickers; ! private ArrayList orders; private bool thereAreEnoughBestTickers; private bool thereAreEnoughWorstTickers; ! ! public EndOfDayTimerHandlerDOR_WeekEndBounce(string tickerGroupID, int numberOfEligibleTickers, ! int numOfBestTickers, ! int numOfWorstTickers, ! int lengthInDaysForPerformance, ! int numOfTickersForBuying, ! int numOfTickersForShortSelling, ! Account account, string benchmark) ! { ! this.tickerGroupID = tickerGroupID; ! this.numberOfEligibleTickers = numberOfEligibleTickers; ! this.account = account; ! this.benchmark = benchmark; ! this.numOfBestTickers = numOfBestTickers; ! this.bestTickers = new string[this.numOfBestTickers]; ! this.numOfWorstTickers = numOfWorstTickers; ! this.worstTickers = new string[this.numOfWorstTickers]; this.lengthInDaysForPerformance = lengthInDaysForPerformance; ! this.numOfTickersForBuying = numOfTickersForBuying; ! this.numOfTickersForShortSelling = numOfTickersForShortSelling; ! this.chosenTickers = new string[this.numOfTickersForBuying + this.numOfTickersForShortSelling]; ! this.lastOrderedTickers = new string[this.chosenTickers.Length]; ! this.orders = new ArrayList(); ! } ! ! #region MarketOpenEventHandler ! private void closePosition( string ticker ) ! { ! this.account.ClosePosition( ticker ); ! } ! ! private void closePositions() ! { ! if(this.lastOrderedTickers != null) ! foreach( string ticker in this.lastOrderedTickers ) ! for( int i = 0; i<this.account.Portfolio.Keys.Count; i++ ) ! if( this.account.Portfolio[ticker]!=null ) ! closePosition( ticker ); ! } ! ! ! private void addOrderForTicker(string[] tickers, ! int tickerPosition ) ! { ! SignedTickers signedTickers = new SignedTickers(tickers); ! string ticker = ! SignedTicker.GetTicker(tickers[tickerPosition]); ! double cashForSinglePosition = ! this.account.CashAmount / this.chosenTickers.Length; ! long quantity = ! Convert.ToInt64( Math.Floor( cashForSinglePosition / this.account.DataStreamer.GetCurrentBid( ticker ) ) ); ! Order order = ! new Order( ! signedTickers[tickerPosition].MarketOrderType, ! new Instrument( ticker ) , quantity ); ! this.orders.Add(order); ! } ! private void addChosenTickersToOrderList(string[] tickers) ! { ! for( int i = 0; i<tickers.Length; i++) ! { ! if(tickers[i] != null) ! { ! this.addOrderForTicker( tickers, i ); ! this.lastOrderedTickers[i] = ! SignedTicker.GetTicker(tickers[i]); ! } ! } ! } ! private void openPositions(string[] tickers) ! { ! this.addChosenTickersToOrderList(tickers); ! //execute orders actually ! foreach(object item in this.orders) ! this.account.AddOrder((Order)item); ! } ! ! private double setChosenTickers_getGainOrLossFromPreviousClose(string signedTicker) ! { ! IndexBasedEndOfDayTimer currentTimer = (IndexBasedEndOfDayTimer)this.account.EndOfDayTimer; ! ExtendedDateTime nowAtOpen = ! new ExtendedDateTime(currentTimer.GetCurrentTime().DateTime, ! BarComponent.Open); ! ExtendedDateTime previousClose = ! new ExtendedDateTime(currentTimer.GetPreviousDateTime(), ! BarComponent.Close); ! double currentValueAtOpen = ! HistoricalDataProvider.GetAdjustedMarketValue(SignedTicker.GetTicker(signedTicker), nowAtOpen); ! double previousValueAtClose = ! HistoricalDataProvider.GetAdjustedMarketValue(SignedTicker.GetTicker(signedTicker), previousClose); ! ! return (currentValueAtOpen - previousValueAtClose) / previousValueAtClose; ! } ! private void setChosenTickers_addTickersForShorting() ! { ! DataTable worstTickersOrderedByGainAtOpen = new DataTable(); ! worstTickersOrderedByGainAtOpen.Columns.Add("ticker", Type.GetType("System.String")); ! worstTickersOrderedByGainAtOpen.Columns.Add("gainAtOpen", Type.GetType("System.Double")); ! object[] values = new object[2]; ! for (int i = 0; i<this.worstTickers.Length; i++) ! { ! values[0] = this.worstTickers[i]; ! values[1] = this.setChosenTickers_getGainOrLossFromPreviousClose(this.worstTickers[i]); ! worstTickersOrderedByGainAtOpen.Rows.Add(values); ! } ! DataRow[] orderedRows = new DataRow[this.bestTickers.Length]; ! orderedRows = worstTickersOrderedByGainAtOpen.Select("", "gainAtOpen DESC"); ! for(int i = 0;i<this.numOfTickersForShortSelling; i++) ! if( (double)orderedRows[i]["gainAtOpen"] > 0.0 ) ! //at open, current ticker is gaining ! this.chosenTickers[this.numOfTickersForBuying + i] = "-" + ! (string)orderedRows[i]["ticker"]; ! } ! ! private void setChosenTickers_addTickersForBuying() ! { ! DataTable bestTickersOrderedByLossAtOpen = new DataTable(); ! bestTickersOrderedByLossAtOpen.Columns.Add("ticker", Type.GetType("System.String")); ! bestTickersOrderedByLossAtOpen.Columns.Add("lossAtOpen", Type.GetType("System.Double")); ! object[] values = new object[2]; ! for (int i = 0; i<this.bestTickers.Length; i++) ! { ! values[0] = this.bestTickers[i]; ! values[1] = - this.setChosenTickers_getGainOrLossFromPreviousClose(this.bestTickers[i]); ! bestTickersOrderedByLossAtOpen.Rows.Add(values); ! } ! DataRow[] orderedRows = new DataRow[this.bestTickers.Length]; ! orderedRows = bestTickersOrderedByLossAtOpen.Select("", "lossAtOpen DESC"); ! for( int i = 0; i<this.numOfTickersForBuying; i++) ! if( (double)orderedRows[i]["lossAtOpen"] > 0.0 ) ! //at open, current ticker is losing ! this.chosenTickers[i] = (string)orderedRows[i]["ticker"]; ! } ! private void setChosenTickersBothForLongAndShort() ! { ! if( this.thereAreEnoughBestTickers && ! this.thereAreEnoughWorstTickers ) ! { try { *************** *** 210,264 **** } catch(Exception ex) ! {ex = ex;} ! } ! } ! /// <summary> ! /// Handles a "Market Open" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.orders.Count == 0 && this.account.Transactions.Count == 0) ! this.account.AddCash(30000); ! ! if ( (this.account.Portfolio.Count == 0 && ! endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == ! DayOfWeek.Monday) || ! (this.account.Portfolio.Count == 0 && ! endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == ! DayOfWeek.Tuesday) ) ! { ! this.setChosenTickersBothForLongAndShort(); ! bool allTickersHasBeenChosenForLongAndShort = true; ! for( int i = 0; i<this.chosenTickers.Length; i++) ! { ! if(this.chosenTickers[i] == null) ! allTickersHasBeenChosenForLongAndShort = false; ! } ! if(allTickersHasBeenChosenForLongAndShort) ! this.openPositions(this.chosenTickers); ! } ! else if (endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == ! DayOfWeek.Wednesday || ! endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == ! DayOfWeek.Thursday || ! endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == ! DayOfWeek.Friday) ! this.closePositions(); ! ! } #endregion ! ! public void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ! } ! #region OneHourAfterMarketCloseEventHandler ! private void oneHourAfterMarketCloseEventHandler_clear() { --- 210,266 ---- } catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! } ! } ! /// <summary> ! /// Handles a "Market Open" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! if(this.orders.Count == 0 && this.account.Transactions.Count == 0) ! this.account.AddCash(30000); ! ! if ( (this.account.Portfolio.Count == 0 && ! endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == ! DayOfWeek.Monday) || ! (this.account.Portfolio.Count == 0 && ! endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == ! DayOfWeek.Tuesday) ) ! { ! this.setChosenTickersBothForLongAndShort(); ! bool allTickersHasBeenChosenForLongAndShort = true; ! for( int i = 0; i<this.chosenTickers.Length; i++) ! { ! if(this.chosenTickers[i] == null) ! allTickersHasBeenChosenForLongAndShort = false; ! } ! if(allTickersHasBeenChosenForLongAndShort) ! this.openPositions(this.chosenTickers); ! } ! else if (endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == ! DayOfWeek.Wednesday || ! endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == ! DayOfWeek.Thursday || ! endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == ! DayOfWeek.Friday) ! this.closePositions(); ! ! } #endregion ! ! public void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ! } ! #region OneHourAfterMarketCloseEventHandler ! private void oneHourAfterMarketCloseEventHandler_clear() { *************** *** 270,329 **** this.chosenTickers[i] = null; } ! ! /// <summary> ! /// Handles a "One hour after market close" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void OneHourAfterMarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.oneHourAfterMarketCloseEventHandler_clear(); ! ! if ( endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == ! DayOfWeek.Friday && ! ( (IndexBasedEndOfDayTimer)sender ).CurrentDateArrayPosition >= this.lengthInDaysForPerformance ) ! { ! DateTime currentDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; int currentDateArrayPositionInTimer = ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition; SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromGroup = new SelectorByQuotationAtEachMarketDay(tickersFromGroup, ! false, currentDate.AddDays(-30), currentDate, ! tickersFromGroup.Rows.Count, this.benchmark); ! ! SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice( quotedAtEachMarketDayFromGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-10), currentDate, ! tickersFromGroup.Rows.Count, 20 ); ! ! SelectorByLiquidity mostLiquidSelector = ! new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByCloseToCloseVolatility lessVolatile = ! new SelectorByCloseToCloseVolatility(mostLiquidSelector.GetTableOfSelectedTickers(), ! true,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers/2); ! ! DateTime firstDateForPerformanceComputation = ! (DateTime)((IndexBasedEndOfDayTimer)sender).IndexQuotes.Rows[currentDateArrayPositionInTimer - this.lengthInDaysForPerformance]["quDate"]; ! ! SelectorByAbsolutePerformance bestTickersFromLessVolatile = new SelectorByAbsolutePerformance(lessVolatile.GetTableOfSelectedTickers(), ! false,firstDateForPerformanceComputation,currentDate,this.bestTickers.Length); ! SelectorByAbsolutePerformance worstTickersFromLessVolatile = new SelectorByAbsolutePerformance(lessVolatile.GetTableOfSelectedTickers(), ! true,firstDateForPerformanceComputation,currentDate,this.bestTickers.Length); ! DataTable tableOfBestTickers = bestTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfBestTickers.Rows.Count >= this.bestTickers.Length) ! { this.thereAreEnoughBestTickers = true; for(int i = 0;i<this.bestTickers.Length;i++) --- 272,331 ---- this.chosenTickers[i] = null; } ! ! /// <summary> ! /// Handles a "One hour after market close" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public void OneHourAfterMarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.oneHourAfterMarketCloseEventHandler_clear(); ! ! if ( endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == ! DayOfWeek.Friday && ! ( (IndexBasedEndOfDayTimer)sender ).CurrentDateArrayPosition >= this.lengthInDaysForPerformance ) ! { ! DateTime currentDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; int currentDateArrayPositionInTimer = ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition; SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromGroup = new SelectorByQuotationAtEachMarketDay(tickersFromGroup, ! false, currentDate.AddDays(-30), currentDate, ! tickersFromGroup.Rows.Count, this.benchmark); ! ! SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice( quotedAtEachMarketDayFromGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-10), currentDate, ! tickersFromGroup.Rows.Count, 20 ); ! ! SelectorByLiquidity mostLiquidSelector = ! new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), ! false,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers); ! ! SelectorByCloseToCloseVolatility lessVolatile = ! new SelectorByCloseToCloseVolatility(mostLiquidSelector.GetTableOfSelectedTickers(), ! true,currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers/2); ! ! DateTime firstDateForPerformanceComputation = ! (DateTime)((IndexBasedEndOfDayTimer)sender).IndexQuotes.Rows[currentDateArrayPositionInTimer - this.lengthInDaysForPerformance]["quDate"]; ! ! SelectorByAbsolutePerformance bestTickersFromLessVolatile = new SelectorByAbsolutePerformance(lessVolatile.GetTableOfSelectedTickers(), ! false,firstDateForPerformanceComputation,currentDate,this.bestTickers.Length); ! SelectorByAbsolutePerformance worstTickersFromLessVolatile = new SelectorByAbsolutePerformance(lessVolatile.GetTableOfSelectedTickers(), ! true,firstDateForPerformanceComputation,currentDate,this.bestTickers.Length); ! DataTable tableOfBestTickers = bestTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfBestTickers.Rows.Count >= this.bestTickers.Length) ! { this.thereAreEnoughBestTickers = true; for(int i = 0;i<this.bestTickers.Length;i++) *************** *** 338,342 **** DataTable tableOfWorstTickers = worstTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfWorstTickers.Rows.Count >= this.worstTickers.Length) ! { this.thereAreEnoughWorstTickers = true; for(int i = 0;i<this.worstTickers.Length;i++) --- 340,344 ---- DataTable tableOfWorstTickers = worstTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfWorstTickers.Rows.Count >= this.worstTickers.Length) ! { this.thereAreEnoughWorstTickers = true; for(int i = 0;i<this.worstTickers.Length;i++) *************** *** 348,356 **** } } ! } ! } ! ! #endregion ! ! } } --- 350,358 ---- } } ! } ! } ! ! #endregion ! ! } } |
Update of /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv12665/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows Modified Files: AverageLongTradePercentageReturn.cs AverageShortTradePercentageReturn.cs AverageTradePercentageReturn.cs LargestLosingTradePercentage.cs LargestWinningTradePercentage.cs NumberWinningLongTrades.cs NumberWinningShortTrades.cs NumberWinningTrades.cs TotalNumberOfLongTrades.cs TotalNumberOfShortTrades.cs TotalNumberOfTrades.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: AverageLongTradePercentageReturn.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows/AverageLongTradePercentageReturn.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** AverageLongTradePercentageReturn.cs 19 Jun 2005 14:55:09 -0000 1.4 --- AverageLongTradePercentageReturn.cs 18 Aug 2008 21:13:15 -0000 1.5 *************** *** 11,19 **** /// </summary> [Serializable] ! public class AverageLongTradePercentageReturn : PercentageSummaryRow { public AverageLongTradePercentageReturn( Summary summary ) { ! this.rowDescription = "Average long trade % Return"; double avgReturn = 0.0; try --- 11,19 ---- /// </summary> [Serializable] ! public class AverageLongTradePercentageReturn : PercentageSummaryRow { public AverageLongTradePercentageReturn( Summary summary ) { ! this.rowDescription = "Average long trade % Return"; double avgReturn = 0.0; try *************** *** 24,31 **** catch (Exception ex) { ! ex = ex; // to avoid compilation warning; } ! this.rowValue = avgReturn; ! } } } --- 24,31 ---- catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } ! this.rowValue = avgReturn; ! } } } Index: NumberWinningShortTrades.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows/NumberWinningShortTrades.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** NumberWinningShortTrades.cs 19 Jun 2005 14:47:40 -0000 1.4 --- NumberWinningShortTrades.cs 18 Aug 2008 21:13:15 -0000 1.5 *************** *** 11,19 **** /// </summary> [Serializable] ! public class NumberWinningShortTrades : IntegerSummaryRow { public NumberWinningShortTrades( Summary summary ) { ! this.rowDescription = "Number winning short trades"; this.format = ConstantsProvider.FormatWithZeroDecimals; try --- 11,19 ---- /// </summary> [Serializable] ! public class NumberWinningShortTrades : IntegerSummaryRow { public NumberWinningShortTrades( Summary summary ) { ! this.rowDescription = "Number winning short trades"; this.format = ConstantsProvider.FormatWithZeroDecimals; try *************** *** 25,31 **** catch (Exception ex) { ! ex = ex; // to avoid compilation warning; } ! } } } --- 25,31 ---- catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } ! } } } Index: AverageShortTradePercentageReturn.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows/AverageShortTradePercentageReturn.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** AverageShortTradePercentageReturn.cs 19 Jun 2005 14:55:09 -0000 1.4 --- AverageShortTradePercentageReturn.cs 18 Aug 2008 21:13:15 -0000 1.5 *************** *** 11,19 **** /// </summary> [Serializable] ! public class AverageShortTradePercentageReturn : PercentageSummaryRow { public AverageShortTradePercentageReturn( Summary summary ) { ! this.rowDescription = "Average short trade % Return"; double avgReturn = 0.0; try --- 11,19 ---- /// </summary> [Serializable] ! public class AverageShortTradePercentageReturn : PercentageSummaryRow { public AverageShortTradePercentageReturn( Summary summary ) { ! this.rowDescription = "Average short trade % Return"; double avgReturn = 0.0; try *************** *** 21,32 **** avgReturn = (double) summary.AccountReport.RoundTrades.DataTable.Compute( ! "avg([%Profit])" , "(Trade='Short')" ); } catch (Exception ex) { ! ex = ex; // to avoid compilation warning; } ! this.rowValue = avgReturn; ! } } } --- 21,32 ---- avgReturn = (double) summary.AccountReport.RoundTrades.DataTable.Compute( ! "avg([%Profit])" , "(Trade='Short')" ); } catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } ! this.rowValue = avgReturn; ! } } } Index: NumberWinningTrades.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows/NumberWinningTrades.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** NumberWinningTrades.cs 19 Jun 2005 14:47:40 -0000 1.4 --- NumberWinningTrades.cs 18 Aug 2008 21:13:15 -0000 1.5 *************** *** 11,19 **** /// </summary> [Serializable] ! public class NumberWinningTrades : IntegerSummaryRow { public NumberWinningTrades( Summary summary ) { ! this.rowDescription = "Number winning trades"; this.format = ConstantsProvider.FormatWithZeroDecimals; try --- 11,19 ---- /// </summary> [Serializable] ! public class NumberWinningTrades : IntegerSummaryRow { public NumberWinningTrades( Summary summary ) { ! this.rowDescription = "Number winning trades"; this.format = ConstantsProvider.FormatWithZeroDecimals; try *************** *** 24,30 **** catch (Exception ex) { ! ex = ex; // to avoid compilation warning; } ! } } } --- 24,30 ---- catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } ! } } } Index: TotalNumberOfShortTrades.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows/TotalNumberOfShortTrades.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** TotalNumberOfShortTrades.cs 19 Jun 2005 14:42:23 -0000 1.4 --- TotalNumberOfShortTrades.cs 18 Aug 2008 21:13:16 -0000 1.5 *************** *** 11,20 **** /// </summary> [Serializable] ! public class TotalNumberOfShortTrades : IntegerSummaryRow { public TotalNumberOfShortTrades( Summary summary ) { ! double totalROA = summary.TotalPnl / ( summary.FinalAccountValue - summary.TotalPnl ); ! this.rowDescription = "Total # of short trades"; try { --- 11,20 ---- /// </summary> [Serializable] ! public class TotalNumberOfShortTrades : IntegerSummaryRow { public TotalNumberOfShortTrades( Summary summary ) { ! double totalROA = summary.TotalPnl / ( summary.FinalAccountValue - summary.TotalPnl ); ! this.rowDescription = "Total # of short trades"; try { *************** *** 25,31 **** catch (Exception ex) { ! ex = ex; // to avoid compilation warning; } ! } } } --- 25,31 ---- catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } ! } } } Index: NumberWinningLongTrades.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows/NumberWinningLongTrades.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** NumberWinningLongTrades.cs 19 Jun 2005 14:47:40 -0000 1.4 --- NumberWinningLongTrades.cs 18 Aug 2008 21:13:15 -0000 1.5 *************** *** 11,19 **** /// </summary> [Serializable] ! public class NumberWinningLongTrades : IntegerSummaryRow { public NumberWinningLongTrades( Summary summary ) { ! this.rowDescription = "Number winning long trades"; this.format = ConstantsProvider.FormatWithZeroDecimals; try --- 11,19 ---- /// </summary> [Serializable] ! public class NumberWinningLongTrades : IntegerSummaryRow { public NumberWinningLongTrades( Summary summary ) { ! this.rowDescription = "Number winning long trades"; this.format = ConstantsProvider.FormatWithZeroDecimals; try *************** *** 24,30 **** catch (Exception ex) { ! ex = ex; // to avoid compilation warning; } ! } } } --- 24,30 ---- catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } ! } } } Index: TotalNumberOfTrades.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows/TotalNumberOfTrades.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** TotalNumberOfTrades.cs 19 Jun 2005 14:42:23 -0000 1.4 --- TotalNumberOfTrades.cs 18 Aug 2008 21:13:16 -0000 1.5 *************** *** 11,20 **** /// </summary> [Serializable] ! public class TotalNumberOfTrades : IntegerSummaryRow { public TotalNumberOfTrades( Summary summary ) { ! double totalROA = summary.TotalPnl / ( summary.FinalAccountValue - summary.TotalPnl ); ! this.rowDescription = "Total # of trades"; this.format = ConstantsProvider.FormatWithZeroDecimals; try --- 11,20 ---- /// </summary> [Serializable] ! public class TotalNumberOfTrades : IntegerSummaryRow { public TotalNumberOfTrades( Summary summary ) { ! double totalROA = summary.TotalPnl / ( summary.FinalAccountValue - summary.TotalPnl ); ! this.rowDescription = "Total # of trades"; this.format = ConstantsProvider.FormatWithZeroDecimals; try *************** *** 26,32 **** catch (Exception ex) { ! ex = ex; // to avoid compilation warning; } ! } } } --- 26,32 ---- catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } ! } } } Index: LargestWinningTradePercentage.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows/LargestWinningTradePercentage.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** LargestWinningTradePercentage.cs 19 Jun 2005 14:47:40 -0000 1.4 --- LargestWinningTradePercentage.cs 18 Aug 2008 21:13:15 -0000 1.5 *************** *** 11,19 **** /// </summary> [Serializable] ! public class LargestWinningTradePercentage : PercentageSummaryRow { public LargestWinningTradePercentage( Summary summary ) { ! this.rowDescription = "Largest winning trade"; try { --- 11,19 ---- /// </summary> [Serializable] ! public class LargestWinningTradePercentage : PercentageSummaryRow { public LargestWinningTradePercentage( Summary summary ) { ! this.rowDescription = "Largest winning trade"; try { *************** *** 23,29 **** catch (Exception ex) { ! ex = ex; // to avoid compilation warning; } ! } } } --- 23,29 ---- catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } ! } } } Index: TotalNumberOfLongTrades.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows/TotalNumberOfLongTrades.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** TotalNumberOfLongTrades.cs 19 Jun 2005 14:42:23 -0000 1.4 --- TotalNumberOfLongTrades.cs 18 Aug 2008 21:13:16 -0000 1.5 *************** *** 11,20 **** /// </summary> [Serializable] ! public class TotalNumberOfLongTrades : IntegerSummaryRow { public TotalNumberOfLongTrades( Summary summary ) : base() { ! double totalROA = summary.TotalPnl / ( summary.FinalAccountValue - summary.TotalPnl ); ! this.rowDescription = "Total # of long trades"; try { --- 11,20 ---- /// </summary> [Serializable] ! public class TotalNumberOfLongTrades : IntegerSummaryRow { public TotalNumberOfLongTrades( Summary summary ) : base() { ! double totalROA = summary.TotalPnl / ( summary.FinalAccountValue - summary.TotalPnl ); ! this.rowDescription = "Total # of long trades"; try { *************** *** 25,31 **** catch (Exception ex) { ! ex = ex; // to avoid compilation warning; } ! } } } --- 25,31 ---- catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } ! } } } Index: AverageTradePercentageReturn.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows/AverageTradePercentageReturn.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** AverageTradePercentageReturn.cs 19 Jun 2005 14:55:09 -0000 1.4 --- AverageTradePercentageReturn.cs 18 Aug 2008 21:13:15 -0000 1.5 *************** *** 11,19 **** /// </summary> [Serializable] ! public class AverageTradePercentageReturn : PercentageSummaryRow { public AverageTradePercentageReturn( Summary summary ) { ! this.rowDescription = "Average trade % Return"; try { --- 11,19 ---- /// </summary> [Serializable] ! public class AverageTradePercentageReturn : PercentageSummaryRow { public AverageTradePercentageReturn( Summary summary ) { ! this.rowDescription = "Average trade % Return"; try { *************** *** 22,28 **** catch (Exception ex) { ! ex = ex; // to avoid compilation warning; } ! } } } --- 22,28 ---- catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } ! } } } Index: LargestLosingTradePercentage.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows/LargestLosingTradePercentage.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** LargestLosingTradePercentage.cs 19 Jun 2005 14:47:40 -0000 1.4 --- LargestLosingTradePercentage.cs 18 Aug 2008 21:13:15 -0000 1.5 *************** *** 11,19 **** /// </summary> [Serializable] ! public class LargestLosingTradePercentage : PercentageSummaryRow { public LargestLosingTradePercentage( Summary summary ) { ! this.rowDescription = "Largest losing trade"; try { --- 11,19 ---- /// </summary> [Serializable] ! public class LargestLosingTradePercentage : PercentageSummaryRow { public LargestLosingTradePercentage( Summary summary ) { ! this.rowDescription = "Largest losing trade"; try { *************** *** 23,29 **** catch (Exception ex) { ! ex = ex; // to avoid compilation warning; } ! } } } --- 23,29 ---- catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } ! } } } |
|
From: Glauco S. <gla...@us...> - 2008-08-18 21:13:48
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv12665/b4_Business/a1_Financial/a2_Accounting/h5_Reporting Modified Files: AccountReport.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: AccountReport.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/AccountReport.cs,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** AccountReport.cs 6 Feb 2008 20:37:19 -0000 1.21 --- AccountReport.cs 18 Aug 2008 21:13:14 -0000 1.22 *************** *** 335,343 **** try { ! fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); } - catch(Exception ex) - {ex = ex;} } } --- 335,346 ---- try { ! fieldInfo.SetValue( ! this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); ! } ! catch (Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } } } |
|
From: Glauco S. <gla...@us...> - 2008-08-18 21:13:47
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv12665/b4_Business/a1_Financial/a2_Accounting Modified Files: Account.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: Account.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/Account.cs,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** Account.cs 26 Nov 2005 23:49:21 -0000 1.21 --- Account.cs 18 Aug 2008 21:13:14 -0000 1.22 *************** *** 182,189 **** //cashAmount = cashAmount + moneyAmount; } ! catch (Exception exception) { ! exception = exception; // to avoid warning message ! /// TO DO!!! } } --- 182,188 ---- //cashAmount = cashAmount + moneyAmount; } ! catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } } |
|
From: Glauco S. <gla...@us...> - 2008-08-18 21:13:28
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/Tables In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv12665/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/Tables Modified Files: StatisticsSummary.cs Summary.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: StatisticsSummary.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/Tables/StatisticsSummary.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** StatisticsSummary.cs 25 Apr 2008 17:13:42 -0000 1.2 --- StatisticsSummary.cs 18 Aug 2008 21:13:20 -0000 1.3 *************** *** 15,24 **** /// Summary description for StatisticsSummary. /// </summary> ! [Serializable] ! public class StatisticsSummary : ReportTable, ISerializable ! { ! private AccountReport accountReport; private IHistoricalQuoteProvider historicalQuoteProvider; ! private AverageReturnOnMondayWithOpenPositions averageReturnOnMondayWithOpenPositions; private AverageReturnOnTuesdayWithOpenPositions averageReturnOnTuesdayWithOpenPositions; --- 15,24 ---- /// Summary description for StatisticsSummary. /// </summary> ! [Serializable] ! public class StatisticsSummary : ReportTable, ISerializable ! { ! private AccountReport accountReport; private IHistoricalQuoteProvider historicalQuoteProvider; ! private AverageReturnOnMondayWithOpenPositions averageReturnOnMondayWithOpenPositions; private AverageReturnOnTuesdayWithOpenPositions averageReturnOnTuesdayWithOpenPositions; *************** *** 29,36 **** public AccountReport AccountReport ! { ! get { return accountReport; } ! } ! public AverageReturnOnMondayWithOpenPositions AverageReturnOnMondayWithOpenPositions { --- 29,36 ---- public AccountReport AccountReport ! { ! get { return accountReport; } ! } ! public AverageReturnOnMondayWithOpenPositions AverageReturnOnMondayWithOpenPositions { *************** *** 75,79 **** } public StatisticsSummary( AccountReport accountReport , ! IHistoricalQuoteProvider historicalDataProvider ) : base( accountReport.Name + " - StatisticsSummary" ) { --- 75,79 ---- } public StatisticsSummary( AccountReport accountReport , ! IHistoricalQuoteProvider historicalDataProvider ) : base( accountReport.Name + " - StatisticsSummary" ) { *************** *** 91,95 **** /// <param name="context"></param> protected StatisticsSummary( SerializationInfo info , StreamingContext context ) : ! base( "Summary" ) { // get the set of serializable members for this class and its base classes --- 91,95 ---- /// <param name="context"></param> protected StatisticsSummary( SerializationInfo info , StreamingContext context ) : ! base( "Summary" ) { // get the set of serializable members for this class and its base classes *************** *** 99,103 **** // deserialize the fields from the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { FieldInfo fieldInfo = (FieldInfo) mi[i]; --- 99,103 ---- // deserialize the fields from the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { FieldInfo fieldInfo = (FieldInfo) mi[i]; *************** *** 107,114 **** { fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); } - catch(Exception ex) - {ex = ex;} } } --- 107,116 ---- { fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); ! } ! catch (Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } } } *************** *** 120,132 **** /// <param name="context"></param> void ISerializable.GetObjectData( ! SerializationInfo info, StreamingContext context) { // get the set of serializable members for this class and base classes Type thisType = this.GetType(); ! MemberInfo[] mi = FormatterServices.GetSerializableMembers( thisType , context); // serialize the fields to the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(this)); --- 122,134 ---- /// <param name="context"></param> void ISerializable.GetObjectData( ! SerializationInfo info, StreamingContext context) { // get the set of serializable members for this class and base classes Type thisType = this.GetType(); ! MemberInfo[] mi = FormatterServices.GetSerializableMembers( thisType , context); // serialize the fields to the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(this)); *************** *** 135,145 **** #endregion ! #region "getStatisticsSummary" ! private void getStatisticsSummary() ! { if ( this.accountReport.Equity.DataTable.Rows.Count == 0 ) throw new Exception( "A StatisticsSummary computation has been requested, but the equity line is empty" ); ! this.averageReturnOnMondayWithOpenPositions = new AverageReturnOnMondayWithOpenPositions(this); this.averageReturnOnTuesdayWithOpenPositions = new AverageReturnOnTuesdayWithOpenPositions(this); --- 137,147 ---- #endregion ! #region "getStatisticsSummary" ! private void getStatisticsSummary() ! { if ( this.accountReport.Equity.DataTable.Rows.Count == 0 ) throw new Exception( "A StatisticsSummary computation has been requested, but the equity line is empty" ); ! this.averageReturnOnMondayWithOpenPositions = new AverageReturnOnMondayWithOpenPositions(this); this.averageReturnOnTuesdayWithOpenPositions = new AverageReturnOnTuesdayWithOpenPositions(this); *************** *** 147,155 **** this.averageReturnOnThursdayWithOpenPositions = new AverageReturnOnThursdayWithOpenPositions(this); this.averageReturnOnFridayWithOpenPositions = new AverageReturnOnFridayWithOpenPositions(this); ! this.averageReturnOnDayWithOpenPositions = new AverageReturnOnDayWithOpenPositions(this); ! } ! #endregion } --- 149,157 ---- this.averageReturnOnThursdayWithOpenPositions = new AverageReturnOnThursdayWithOpenPositions(this); this.averageReturnOnFridayWithOpenPositions = new AverageReturnOnFridayWithOpenPositions(this); ! this.averageReturnOnDayWithOpenPositions = new AverageReturnOnDayWithOpenPositions(this); ! } ! #endregion } Index: Summary.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/Tables/Summary.cs,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** Summary.cs 5 Sep 2007 22:10:16 -0000 1.20 --- Summary.cs 18 Aug 2008 21:13:20 -0000 1.21 *************** *** 15,28 **** /// Summary description for Summary. /// </summary> ! [Serializable] ! public class Summary : ReportTable, ISerializable ! { ! private AccountReport accountReport; private IHistoricalQuoteProvider historicalQuoteProvider; ! private double totalPnl; ! private BenchmarkPercentageReturn benchmarkPercentageReturn; private AnnualSystemPercentageReturn annualSystemPercentageReturn; private double finalAccountValue; ! private long intervalDays; private TotalNetProfit totalNetProfit; private ReturnOnAccount returnOnAccount; --- 15,28 ---- /// Summary description for Summary. /// </summary> ! [Serializable] ! public class Summary : ReportTable, ISerializable ! { ! private AccountReport accountReport; private IHistoricalQuoteProvider historicalQuoteProvider; ! private double totalPnl; ! private BenchmarkPercentageReturn benchmarkPercentageReturn; private AnnualSystemPercentageReturn annualSystemPercentageReturn; private double finalAccountValue; ! private long intervalDays; private TotalNetProfit totalNetProfit; private ReturnOnAccount returnOnAccount; *************** *** 50,60 **** public AccountReport AccountReport ! { ! get { return accountReport; } ! } ! public double TotalPnl ! { ! get { return totalPnl; } ! } public TotalNetProfit TotalNetProfit { --- 50,60 ---- public AccountReport AccountReport ! { ! get { return accountReport; } ! } ! public double TotalPnl ! { ! get { return totalPnl; } ! } public TotalNetProfit TotalNetProfit { *************** *** 66,80 **** } public BenchmarkPercentageReturn BenchmarkPercentageReturn ! { ! get { return this.benchmarkPercentageReturn; } ! } ! public double FinalAccountValue ! { ! get { return finalAccountValue; } ! } ! public double IntervalDays ! { ! get { return intervalDays; } ! } public AnnualSystemPercentageReturn AnnualSystemPercentageReturn { --- 66,80 ---- } public BenchmarkPercentageReturn BenchmarkPercentageReturn ! { ! get { return this.benchmarkPercentageReturn; } ! } ! public double FinalAccountValue ! { ! get { return finalAccountValue; } ! } ! public double IntervalDays ! { ! get { return intervalDays; } ! } public AnnualSystemPercentageReturn AnnualSystemPercentageReturn { *************** *** 185,189 **** } public Summary( AccountReport accountReport , ! IHistoricalQuoteProvider historicalDataProvider ) : base( accountReport.Name + " - Summary" ) { --- 185,189 ---- } public Summary( AccountReport accountReport , ! IHistoricalQuoteProvider historicalDataProvider ) : base( accountReport.Name + " - Summary" ) { *************** *** 199,203 **** /// <param name="context"></param> protected Summary( SerializationInfo info , StreamingContext context ) : ! base( "Summary" ) { // get the set of serializable members for this class and its base classes --- 199,203 ---- /// <param name="context"></param> protected Summary( SerializationInfo info , StreamingContext context ) : ! base( "Summary" ) { // get the set of serializable members for this class and its base classes *************** *** 207,211 **** // deserialize the fields from the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { FieldInfo fieldInfo = (FieldInfo) mi[i]; --- 207,211 ---- // deserialize the fields from the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { FieldInfo fieldInfo = (FieldInfo) mi[i]; *************** *** 215,222 **** { fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); } - catch(Exception ex) - {ex = ex;} } } --- 215,224 ---- { fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); ! } ! catch (Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } } } *************** *** 229,241 **** /// <param name="context"></param> void ISerializable.GetObjectData( ! SerializationInfo info, StreamingContext context) { // get the set of serializable members for this class and base classes Type thisType = this.GetType(); ! MemberInfo[] mi = FormatterServices.GetSerializableMembers( thisType , context); // serialize the fields to the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(this)); --- 231,243 ---- /// <param name="context"></param> void ISerializable.GetObjectData( ! SerializationInfo info, StreamingContext context) { // get the set of serializable members for this class and base classes Type thisType = this.GetType(); ! MemberInfo[] mi = FormatterServices.GetSerializableMembers( thisType , context); // serialize the fields to the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(this)); *************** *** 244,265 **** #endregion ! #region "getSummary" ! private void getSummaryTable_setColumns( DataTable equityDataTable ) ! { ! equityDataTable.Columns.Add( "Information" , Type.GetType( "System.String" ) ); ! equityDataTable.Columns.Add( "Value" , Type.GetType( "System.Double" ) ); ! } ! private void getSummary() ! { if ( this.accountReport.Equity.DataTable.Rows.Count == 0 ) throw new Exception( "A Summary computation has been requested, but the equity line is empty" ); ! this.totalPnl = ! (double)this.accountReport.Equity.DataTable.Rows[ this.accountReport.Equity.DataTable.Rows.Count - 1 ][ "PnL" ]; ! this.finalAccountValue = ! (double)this.accountReport.Equity.DataTable.Rows[ this.accountReport.Equity.DataTable.Rows.Count - 1 ][ "AccountValue" ]; ! this.intervalDays = ! ((TimeSpan)((DateTime)this.accountReport.Equity.DataTable.Rows[ this.accountReport.Equity.DataTable.Rows.Count - 1 ][ "Date" ] - ! (DateTime)this.accountReport.Equity.DataTable.Rows[ 0 ][ "Date" ])).Days; ! this.returnOnAccount = new ReturnOnAccount( this ); this.benchmarkPercentageReturn = new BenchmarkPercentageReturn( this , this.historicalQuoteProvider ); --- 246,267 ---- #endregion ! #region "getSummary" ! private void getSummaryTable_setColumns( DataTable equityDataTable ) ! { ! equityDataTable.Columns.Add( "Information" , Type.GetType( "System.String" ) ); ! equityDataTable.Columns.Add( "Value" , Type.GetType( "System.Double" ) ); ! } ! private void getSummary() ! { if ( this.accountReport.Equity.DataTable.Rows.Count == 0 ) throw new Exception( "A Summary computation has been requested, but the equity line is empty" ); ! this.totalPnl = ! (double)this.accountReport.Equity.DataTable.Rows[ this.accountReport.Equity.DataTable.Rows.Count - 1 ][ "PnL" ]; ! this.finalAccountValue = ! (double)this.accountReport.Equity.DataTable.Rows[ this.accountReport.Equity.DataTable.Rows.Count - 1 ][ "AccountValue" ]; ! this.intervalDays = ! ((TimeSpan)((DateTime)this.accountReport.Equity.DataTable.Rows[ this.accountReport.Equity.DataTable.Rows.Count - 1 ][ "Date" ] - ! (DateTime)this.accountReport.Equity.DataTable.Rows[ 0 ][ "Date" ])).Days; ! this.returnOnAccount = new ReturnOnAccount( this ); this.benchmarkPercentageReturn = new BenchmarkPercentageReturn( this , this.historicalQuoteProvider ); *************** *** 288,294 **** this.averageNumberOfTransactionsPerDay = new AverageNumberOfTransactionsPerDay(this); //this.DataTable = getSummaryDataTable(); ! } ! #endregion } --- 290,296 ---- this.averageNumberOfTransactionsPerDay = new AverageNumberOfTransactionsPerDay(this); //this.DataTable = getSummaryDataTable(); ! } ! #endregion } |
|
From: Glauco S. <gla...@us...> - 2008-08-18 21:13:27
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/TickersRelationships In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv12665/b4_Business/a2_Strategies/TickersRelationships Modified Files: CorrelationProvider.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: CorrelationProvider.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/TickersRelationships/CorrelationProvider.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** CorrelationProvider.cs 8 Apr 2008 21:47:28 -0000 1.4 --- CorrelationProvider.cs 18 Aug 2008 21:13:19 -0000 1.5 *************** *** 3,7 **** CorrelationProvider.cs ! Copyright (C) 2008 Marco Milletti --- 3,7 ---- CorrelationProvider.cs ! Copyright (C) 2008 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 34,44 **** namespace QuantProject.Business.Strategies.TickersRelationships { ! /// <summary> ! /// Abstract class that provides correlation's indexes two by two within a ! /// given set of tickers ! /// </summary> ! [Serializable] ! public abstract class CorrelationProvider ! { protected ReturnsManager returnsManager; protected string[] tickers; --- 34,44 ---- namespace QuantProject.Business.Strategies.TickersRelationships { ! /// <summary> ! /// Abstract class that provides correlation's indexes two by two within a ! /// given set of tickers ! /// </summary> ! [Serializable] ! public abstract class CorrelationProvider ! { protected ReturnsManager returnsManager; protected string[] tickers; *************** *** 53,57 **** private void correlationProvider_commonInitialization(string[] tickersToAnalyze, ! float minimumAbsoluteReturnValue, float maximumAbsoluteReturnValue) { this.tickers = tickersToAnalyze; --- 53,57 ---- private void correlationProvider_commonInitialization(string[] tickersToAnalyze, ! float minimumAbsoluteReturnValue, float maximumAbsoluteReturnValue) { this.tickers = tickersToAnalyze; *************** *** 79,101 **** /// <param name="benchmark">The benchmark used for computation /// of returns</param> ! public CorrelationProvider(string[] tickersToAnalyze, ! DateTime startDate, DateTime endDate, int returnIntervalLength, ! float minimumAbsoluteReturnValue, float maximumAbsoluteReturnValue, ! string benchmark) ! { this.correlationProvider_commonInitialization(tickersToAnalyze, ! minimumAbsoluteReturnValue, maximumAbsoluteReturnValue); this.setEndOfDayDatesTime(startDate,endDate); this.returnIntervalLength = returnIntervalLength; this.benchmark = benchmark; ! } public CorrelationProvider(string[] tickersToAnalyze, ! DateTime startDate, DateTime endDate, ! float minimumAbsoluteReturnValue, float maximumAbsoluteReturnValue, ! string benchmark) { this.correlationProvider_commonInitialization(tickersToAnalyze, ! minimumAbsoluteReturnValue, maximumAbsoluteReturnValue); this.setEndOfDayDatesTime(startDate,endDate); this.returnIntervalLength = 1; --- 79,101 ---- /// <param name="benchmark">The benchmark used for computation /// of returns</param> ! public CorrelationProvider(string[] tickersToAnalyze, ! DateTime startDate, DateTime endDate, int returnIntervalLength, ! float minimumAbsoluteReturnValue, float maximumAbsoluteReturnValue, ! string benchmark) ! { this.correlationProvider_commonInitialization(tickersToAnalyze, ! minimumAbsoluteReturnValue, maximumAbsoluteReturnValue); this.setEndOfDayDatesTime(startDate,endDate); this.returnIntervalLength = returnIntervalLength; this.benchmark = benchmark; ! } public CorrelationProvider(string[] tickersToAnalyze, ! DateTime startDate, DateTime endDate, ! float minimumAbsoluteReturnValue, float maximumAbsoluteReturnValue, ! string benchmark) { this.correlationProvider_commonInitialization(tickersToAnalyze, ! minimumAbsoluteReturnValue, maximumAbsoluteReturnValue); this.setEndOfDayDatesTime(startDate,endDate); this.returnIntervalLength = 1; *************** *** 114,126 **** /// have to be less than maximumAbsoluteReturnValue</param> public CorrelationProvider( string[] tickersToAnalyze, ! ReturnsManager returnsManager, ! float minimumAbsoluteReturnValue, float maximumAbsoluteReturnValue ) { this.correlationProvider_commonInitialization(tickersToAnalyze, ! minimumAbsoluteReturnValue, maximumAbsoluteReturnValue); this.returnsManager = returnsManager; } ! protected abstract void setEndOfDayDatesTime(DateTime startDate, DateTime endDate); --- 114,126 ---- /// have to be less than maximumAbsoluteReturnValue</param> public CorrelationProvider( string[] tickersToAnalyze, ! ReturnsManager returnsManager, ! float minimumAbsoluteReturnValue, float maximumAbsoluteReturnValue ) { this.correlationProvider_commonInitialization(tickersToAnalyze, ! minimumAbsoluteReturnValue, maximumAbsoluteReturnValue); this.returnsManager = returnsManager; } ! protected abstract void setEndOfDayDatesTime(DateTime startDate, DateTime endDate); *************** *** 135,163 **** for(int i = 0; i<firstTickerReturns.Length; i++) if( Math.Abs(firstTickerReturns[i]) >= this.minimumAbsoluteReturnValue && ! Math.Abs(firstTickerReturns[i]) <= this.maximumAbsoluteReturnValue && ! Math.Abs(secondTickerReturns[i]) >= this.minimumAbsoluteReturnValue && ! Math.Abs(secondTickerReturns[i]) <= this.maximumAbsoluteReturnValue ) ! { ! countSignificantReturns++; ! tempReturnValue[ countSignificantReturns - 1 ] = firstTickerReturns[ i ]; ! } returnValue = new float[countSignificantReturns]; ! Array.Copy(tempReturnValue, 0, returnValue, 0, countSignificantReturns); return returnValue; } protected double getOrderedTickersPearsonCorrelations_setCorrelations_getValue( ! int indexOfFirstTicker, int indexOfSecondTicker) { double returnValue; ! float[] firstTickerSignificantReturns = this.getOrderedTickersPearsonCorrelations_setCorrelations_getValue_getFilteredReturnsForFirstTicker( ! this.returnsManager.GetReturns(this.tickers[indexOfFirstTicker]), ! this.returnsManager.GetReturns(this.tickers[indexOfSecondTicker]) ); ! float[] secondTickerSignificantReturns = this.getOrderedTickersPearsonCorrelations_setCorrelations_getValue_getFilteredReturnsForFirstTicker( ! this.returnsManager.GetReturns(this.tickers[indexOfSecondTicker]), ! this.returnsManager.GetReturns(this.tickers[indexOfFirstTicker]) ); returnValue = BasicFunctions.PearsonCorrelationCoefficient( --- 135,163 ---- for(int i = 0; i<firstTickerReturns.Length; i++) if( Math.Abs(firstTickerReturns[i]) >= this.minimumAbsoluteReturnValue && ! Math.Abs(firstTickerReturns[i]) <= this.maximumAbsoluteReturnValue && ! Math.Abs(secondTickerReturns[i]) >= this.minimumAbsoluteReturnValue && ! Math.Abs(secondTickerReturns[i]) <= this.maximumAbsoluteReturnValue ) ! { ! countSignificantReturns++; ! tempReturnValue[ countSignificantReturns - 1 ] = firstTickerReturns[ i ]; ! } returnValue = new float[countSignificantReturns]; ! Array.Copy(tempReturnValue, 0, returnValue, 0, countSignificantReturns); return returnValue; } protected double getOrderedTickersPearsonCorrelations_setCorrelations_getValue( ! int indexOfFirstTicker, int indexOfSecondTicker) { double returnValue; ! float[] firstTickerSignificantReturns = this.getOrderedTickersPearsonCorrelations_setCorrelations_getValue_getFilteredReturnsForFirstTicker( ! this.returnsManager.GetReturns(this.tickers[indexOfFirstTicker]), ! this.returnsManager.GetReturns(this.tickers[indexOfSecondTicker]) ); ! float[] secondTickerSignificantReturns = this.getOrderedTickersPearsonCorrelations_setCorrelations_getValue_getFilteredReturnsForFirstTicker( ! this.returnsManager.GetReturns(this.tickers[indexOfSecondTicker]), ! this.returnsManager.GetReturns(this.tickers[indexOfFirstTicker]) ); returnValue = BasicFunctions.PearsonCorrelationCoefficient( *************** *** 167,171 **** if ( Double.IsNaN(returnValue) || Double.IsInfinity(returnValue) ) throw new MissingCorrelationException(this.tickers[indexOfFirstTicker], ! this.tickers[indexOfSecondTicker]); return returnValue; --- 167,171 ---- if ( Double.IsNaN(returnValue) || Double.IsInfinity(returnValue) ) throw new MissingCorrelationException(this.tickers[indexOfFirstTicker], ! this.tickers[indexOfSecondTicker]); return returnValue; *************** *** 176,194 **** if(this.returnsManager == null) this.setReturnsManager(); ! this.pearsonCorrelations = new TickersPearsonCorrelation[ this.numOfCombinationTwoByTwo ]; int index = 0; for (int i = 0; i < this.tickers.Length; i++) for (int j = i + 1; j < this.tickers.Length; j++) ! { ! try{ ! this.pearsonCorrelations[index] = ! new TickersPearsonCorrelation( this.tickers[i], this.tickers[j], ! this.getOrderedTickersPearsonCorrelations_setCorrelations_getValue( i , j) ); ! } ! catch(MissingCorrelationException ex) ! {ex=ex;} ! index++; ! } Array.Sort(this.pearsonCorrelations); } --- 176,196 ---- if(this.returnsManager == null) this.setReturnsManager(); ! this.pearsonCorrelations = new TickersPearsonCorrelation[ this.numOfCombinationTwoByTwo ]; int index = 0; for (int i = 0; i < this.tickers.Length; i++) for (int j = i + 1; j < this.tickers.Length; j++) ! { ! try{ ! this.pearsonCorrelations[index] = ! new TickersPearsonCorrelation( this.tickers[i], this.tickers[j], ! this.getOrderedTickersPearsonCorrelations_setCorrelations_getValue( i , j) ); ! } ! catch(MissingCorrelationException ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! index++; ! } Array.Sort(this.pearsonCorrelations); } *************** *** 202,212 **** for(int i = 0; i < this.pearsonCorrelations.Length; i++) System.Console.WriteLine(this.pearsonCorrelations[i].FirstTicker + " " + ! this.pearsonCorrelations[i].SecondTicker + " " + ! this.pearsonCorrelations[i].CorrelationValue.ToString() ); } public TickersPearsonCorrelation[] GetOrderedTickersPearsonCorrelations() { ! if( this.pearsonCorrelations == null ) this.getOrderedTickersPearsonCorrelations_setCorrelations(); this.showOutputToConsole(); --- 204,214 ---- for(int i = 0; i < this.pearsonCorrelations.Length; i++) System.Console.WriteLine(this.pearsonCorrelations[i].FirstTicker + " " + ! this.pearsonCorrelations[i].SecondTicker + " " + ! this.pearsonCorrelations[i].CorrelationValue.ToString() ); } public TickersPearsonCorrelation[] GetOrderedTickersPearsonCorrelations() { ! if( this.pearsonCorrelations == null ) this.getOrderedTickersPearsonCorrelations_setCorrelations(); this.showOutputToConsole(); *************** *** 216,235 **** public double GetPearsonCorrelation(string firstTicker, string secondTicker) { ! double returnValue = double.NaN; if( this.pearsonCorrelations == null ) this.getOrderedTickersPearsonCorrelations_setCorrelations(); ! for(int i = 0; i<this.pearsonCorrelations.Length; i++) ! { ! if( (this.pearsonCorrelations[i].FirstTicker == firstTicker && ! this.pearsonCorrelations[i].SecondTicker == secondTicker) || ! (this.pearsonCorrelations[i].FirstTicker == secondTicker && ! this.pearsonCorrelations[i].SecondTicker == firstTicker) ) ! { returnValue = this.pearsonCorrelations[i].CorrelationValue; i = this.pearsonCorrelations.Length;//exit from for } ! } ! if( double.IsNaN(returnValue) ) throw new MissingCorrelationException(firstTicker, secondTicker); --- 218,237 ---- public double GetPearsonCorrelation(string firstTicker, string secondTicker) { ! double returnValue = double.NaN; if( this.pearsonCorrelations == null ) this.getOrderedTickersPearsonCorrelations_setCorrelations(); ! for(int i = 0; i<this.pearsonCorrelations.Length; i++) ! { ! if( (this.pearsonCorrelations[i].FirstTicker == firstTicker && ! this.pearsonCorrelations[i].SecondTicker == secondTicker) || ! (this.pearsonCorrelations[i].FirstTicker == secondTicker && ! this.pearsonCorrelations[i].SecondTicker == firstTicker) ) ! { returnValue = this.pearsonCorrelations[i].CorrelationValue; i = this.pearsonCorrelations.Length;//exit from for } ! } ! if( double.IsNaN(returnValue) ) throw new MissingCorrelationException(firstTicker, secondTicker); *************** *** 237,240 **** } ! } // end of class } --- 239,242 ---- } ! } // end of class } |
|
From: Glauco S. <gla...@us...> - 2008-08-18 21:13:27
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/InSample In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv12665/b4_Business/a2_Strategies/InSample Modified Files: DummyInSampleChooser.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: DummyInSampleChooser.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/InSample/DummyInSampleChooser.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** DummyInSampleChooser.cs 30 Mar 2008 15:46:12 -0000 1.2 --- DummyInSampleChooser.cs 18 Aug 2008 21:13:19 -0000 1.3 *************** *** 40,45 **** public event NewProgressEventHandler NewProgress; - private WeightedPositions weightedPositions; - public string Description { --- 40,43 ---- *************** *** 49,53 **** public DummyInSampleChooser() { - this.weightedPositions = weightedPositions; } public object AnalyzeInSample( EligibleTickers eligibleTickers , --- 47,50 ---- |
|
From: Glauco S. <gla...@us...> - 2008-08-18 21:13:26
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/StatisticsSummaryRows In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv12665/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/StatisticsSummaryRows Modified Files: AverageReturnOnDayOfWeekWithOpenPositions.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: AverageReturnOnDayOfWeekWithOpenPositions.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/StatisticsSummaryRows/AverageReturnOnDayOfWeekWithOpenPositions.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** AverageReturnOnDayOfWeekWithOpenPositions.cs 14 Aug 2008 21:36:09 -0000 1.2 --- AverageReturnOnDayOfWeekWithOpenPositions.cs 18 Aug 2008 21:13:16 -0000 1.3 *************** *** 106,110 **** catch (Exception ex) { ! ex = ex; // to avoid compilation warning; } } --- 106,110 ---- catch (Exception ex) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } } |
|
From: Glauco S. <gla...@us...> - 2008-08-18 21:13:24
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/FixedLengthTwoPhases In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv12665/b7_Scripts/WalkForwardTesting/FixedLengthTwoPhases Modified Files: FixedLengthTwoPhasesMain.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: FixedLengthTwoPhasesMain.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/FixedLengthTwoPhases/FixedLengthTwoPhasesMain.cs,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** FixedLengthTwoPhasesMain.cs 16 Aug 2008 19:26:57 -0000 1.9 --- FixedLengthTwoPhasesMain.cs 18 Aug 2008 21:13:20 -0000 1.10 *************** *** 61,65 **** { this.benchmark = new Benchmark( "CCE" ); ! this.numberOfPortfolioPositions = 1; this.historicalQuoteProviderForInSample = new HistoricalRawQuoteProvider(); --- 61,65 ---- { this.benchmark = new Benchmark( "CCE" ); ! this.numberOfPortfolioPositions = 2; this.historicalQuoteProviderForInSample = new HistoricalRawQuoteProvider(); *************** *** 72,76 **** string tickersGroupId = "SP500"; // uncomment the following line for a faster script ! tickersGroupId = "fastTest"; int maxNumberOfEligibleTickersToBeChosen = 100; --- 72,76 ---- string tickersGroupId = "SP500"; // uncomment the following line for a faster script ! // tickersGroupId = "fastTest"; int maxNumberOfEligibleTickersToBeChosen = 100; *************** *** 111,115 **** int numberOfBestTestingPositionsToBeReturned = 20; // uncomment the following line for a faster script ! numberOfBestTestingPositionsToBeReturned = 2; IDecoderForTestingPositions decoderForWeightedPositions = --- 111,115 ---- int numberOfBestTestingPositionsToBeReturned = 20; // uncomment the following line for a faster script ! numberOfBestTestingPositionsToBeReturned = 5; IDecoderForTestingPositions decoderForWeightedPositions = *************** *** 127,131 **** double elitismRate = 0.001; int populationSizeForGeneticOptimizer = 10000; ! int generationNumberForGeneticOptimizer = 1; int seedForRandomGenerator = QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator; --- 127,131 ---- double elitismRate = 0.001; int populationSizeForGeneticOptimizer = 10000; ! int generationNumberForGeneticOptimizer = 5; int seedForRandomGenerator = QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator; *************** *** 205,212 **** double cashToStart = 30000; ! DateTime firstDateTime = new DateTime( 2006 , 1 , 2 ); ! DateTime lastDateTime = new DateTime( 2006 , 1 , 6 ); ! double maxRunningHours = 1; EndOfDayStrategyBackTester endOfDayStrategyBackTester = --- 205,212 ---- double cashToStart = 30000; ! DateTime firstDateTime = new DateTime( 2006 , 1 , 1 ); ! DateTime lastDateTime = new DateTime( 2008 , 4 , 1 ); ! double maxRunningHours = 8; EndOfDayStrategyBackTester endOfDayStrategyBackTester = |
|
From: Glauco S. <gla...@us...> - 2008-08-18 21:13:24
|
Update of /cvsroot/quantproject/QuantProject/b91_QuantProject In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv12665/b91_QuantProject Modified Files: Main.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: Main.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b91_QuantProject/Main.cs,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** Main.cs 13 Mar 2008 19:45:54 -0000 1.19 --- Main.cs 18 Aug 2008 21:13:20 -0000 1.20 *************** *** 474,479 **** // new WFLagMain().ShowDialog(); ! // new FixedLengthTwoPhasesMain().Run(); ! new PairsTradingMain().Run(); // new RunOneRank().Run(); --- 474,479 ---- // new WFLagMain().ShowDialog(); ! new FixedLengthTwoPhasesMain().Run(); ! // new PairsTradingMain().Run(); // new RunOneRank().Run(); |