quantproject-developers Mailing List for QuantProject (Page 70)
Brought to you by:
glauco_1
You can subscribe to this list here.
| 2003 |
Jan
|
Feb
|
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
(7) |
Nov
(103) |
Dec
(67) |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 2004 |
Jan
(52) |
Feb
(9) |
Mar
(69) |
Apr
(53) |
May
(80) |
Jun
(23) |
Jul
(24) |
Aug
(112) |
Sep
(9) |
Oct
|
Nov
(58) |
Dec
(93) |
| 2005 |
Jan
(90) |
Feb
(93) |
Mar
(61) |
Apr
(56) |
May
(37) |
Jun
(61) |
Jul
(55) |
Aug
(68) |
Sep
(25) |
Oct
(46) |
Nov
(41) |
Dec
(37) |
| 2006 |
Jan
(33) |
Feb
(7) |
Mar
(19) |
Apr
(27) |
May
(73) |
Jun
(49) |
Jul
(83) |
Aug
(66) |
Sep
(45) |
Oct
(16) |
Nov
(15) |
Dec
(7) |
| 2007 |
Jan
(14) |
Feb
(33) |
Mar
|
Apr
(21) |
May
|
Jun
(34) |
Jul
(18) |
Aug
(100) |
Sep
(39) |
Oct
(55) |
Nov
(12) |
Dec
(2) |
| 2008 |
Jan
(120) |
Feb
(133) |
Mar
(129) |
Apr
(104) |
May
(42) |
Jun
(2) |
Jul
(52) |
Aug
(99) |
Sep
(134) |
Oct
|
Nov
(137) |
Dec
(48) |
| 2009 |
Jan
(48) |
Feb
(55) |
Mar
(61) |
Apr
(3) |
May
(2) |
Jun
(1) |
Jul
|
Aug
(51) |
Sep
|
Oct
(7) |
Nov
|
Dec
|
| 2010 |
Jan
(7) |
Feb
(1) |
Mar
(145) |
Apr
|
May
|
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
(8) |
Dec
|
| 2011 |
Jan
(78) |
Feb
(1) |
Mar
|
Apr
|
May
|
Jun
|
Jul
|
Aug
(88) |
Sep
(6) |
Oct
(1) |
Nov
|
Dec
|
| 2012 |
Jan
|
Feb
(1) |
Mar
|
Apr
(6) |
May
(5) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(1) |
| 2013 |
Jan
|
Feb
|
Mar
|
Apr
(1) |
May
(2) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
(2) |
| 2014 |
Jan
|
Feb
|
Mar
|
Apr
|
May
(1) |
Jun
|
Jul
|
Aug
|
Sep
|
Oct
|
Nov
|
Dec
|
|
From: Marco M. <mi...@us...> - 2007-08-29 09:44:10
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv10276/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower Modified Files: EndOfDayTimerHandlerITF.cs Log Message: Code has been re-organized in a more logical and Object Oriented way: - WeightedPositions class has been used. - Some static methods have been deleted from SignedTicker class. They have been moved to WeightedPositions. - Basic orders'management has been moved to the primitive base class EndOfDayTimerHandler and to AccountManager class Index: EndOfDayTimerHandlerITF.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower/EndOfDayTimerHandlerITF.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** EndOfDayTimerHandlerITF.cs 17 Sep 2006 21:48:39 -0000 1.3 --- EndOfDayTimerHandlerITF.cs 29 Aug 2007 09:43:31 -0000 1.4 *************** *** 49,57 **** private int numDaysForReturnCalculation; private double maxAcceptableCloseToCloseDrawdown; - private bool stopLossConditionReached; - private double currentAccountValue; - private double previousAccountValue; - private int numDaysBetweenEachOptimization; - private int numDaysElapsedSinceLastOptimization; private int daysCounterWithPositions; private DateTime lastCloseDate; --- 49,52 ---- *************** *** 113,119 **** (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; returnValue = ! SignedTicker.GetCloseToClosePortfolioReturn( ! this.chosenTickers, this.chosenTickersPortfolioWeights, ! initialDateForHalfPeriod,finalDateForHalfPeriod); } catch(MissingQuotesException ex) --- 108,112 ---- (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; returnValue = ! chosenWeightedPositions.GetCloseToCloseReturn(initialDateForHalfPeriod,finalDateForHalfPeriod); } catch(MissingQuotesException ex) *************** *** 132,142 **** { if(lastHalfPeriodGain > 0.0) ! base.openPositions(this.chosenTickers); else//the last HalfPeriodGain has been negative { ! SignedTicker.ChangeSignOfEachTicker(this.chosenTickers); //short the portfolio try{ ! base.openPositions(this.chosenTickers); } catch(Exception ex) --- 125,135 ---- { 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) *************** *** 145,149 **** } finally{ ! SignedTicker.ChangeSignOfEachTicker(this.chosenTickers); } } --- 138,142 ---- } finally{ ! chosenWeightedPositions.Reverse(); } } *************** *** 157,161 **** { //Close if halfPeriod has elapsed or stop loss condition reached ! base.closePositions(); this.daysCounterWithPositions = 0; } --- 150,154 ---- { //Close if halfPeriod has elapsed or stop loss condition reached ! AccountManager.ClosePositions(this.account); this.daysCounterWithPositions = 0; } *************** *** 169,173 **** this.daysCounterWithPositions++; this.marketCloseEventHandler_closePositions(); ! if(this.chosenTickers[0] != null) //tickers to buy have been chosen { --- 162,166 ---- this.daysCounterWithPositions++; this.marketCloseEventHandler_closePositions(); ! if(chosenWeightedPositions != null) //tickers to buy have been chosen { *************** *** 244,248 **** { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.chosenTickers.Length*2) //the optimization process is meaningful only if the initial set of tickers is //larger than the number of tickers to be chosen --- 237,241 ---- { 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 *************** *** 266,271 **** ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate, setOfTickersToBeOptimized.Rows.Count, this.numDaysForReturnCalculation); ! this.chosenTickers = ((GenomeMeaning)GO.BestGenome.Meaning).Tickers; ! this.chosenTickersPortfolioWeights = ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights; } //else it will be buyed again the previous optimized portfolio --- 259,264 ---- ((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 *************** *** 284,288 **** this.seedForRandomGenerator++; this.numDaysElapsedSinceLastOptimization++; - this.orders.Clear(); if((this.numDaysElapsedSinceLastOptimization - 1 == this.numDaysBetweenEachOptimization)) //|| this.isTheFirstClose ) --- 277,280 ---- |
|
From: Marco M. <mi...@us...> - 2007-08-29 09:44:10
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_OTC In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv10276/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_OTC Modified Files: EndOfDayTimerHandlerDOR_OTC.cs Log Message: Code has been re-organized in a more logical and Object Oriented way: - WeightedPositions class has been used. - Some static methods have been deleted from SignedTicker class. They have been moved to WeightedPositions. - Basic orders'management has been moved to the primitive base class EndOfDayTimerHandler and to AccountManager class Index: EndOfDayTimerHandlerDOR_OTC.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_OTC/EndOfDayTimerHandlerDOR_OTC.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** EndOfDayTimerHandlerDOR_OTC.cs 30 Jun 2007 18:58:33 -0000 1.1 --- EndOfDayTimerHandlerDOR_OTC.cs 29 Aug 2007 09:43:30 -0000 1.2 *************** *** 87,91 **** int tickerPosition ) { ! string ticker = SignedTicker.GetTicker(tickers[tickerPosition]); double cashForSinglePosition = --- 87,92 ---- int tickerPosition ) { ! SignedTickers signedTickers = new SignedTickers(tickers); ! string ticker = SignedTicker.GetTicker(tickers[tickerPosition]); double cashForSinglePosition = *************** *** 94,99 **** Convert.ToInt64( Math.Floor( cashForSinglePosition / this.account.DataStreamer.GetCurrentBid( ticker ) ) ); Order order = ! new Order( ! SignedTicker.GetMarketOrderType(tickers[tickerPosition]), new Instrument( ticker ) , quantity ); this.orders.Add(order); --- 95,99 ---- 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); |
|
From: Marco M. <mi...@us...> - 2007-08-29 09:44:09
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv10276/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators Modified Files: EndOfDayTimerHandlerFPOscillatorCTC.cs Log Message: Code has been re-organized in a more logical and Object Oriented way: - WeightedPositions class has been used. - Some static methods have been deleted from SignedTicker class. They have been moved to WeightedPositions. - Basic orders'management has been moved to the primitive base class EndOfDayTimerHandler and to AccountManager class Index: EndOfDayTimerHandlerFPOscillatorCTC.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators/EndOfDayTimerHandlerFPOscillatorCTC.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** EndOfDayTimerHandlerFPOscillatorCTC.cs 17 Sep 2006 21:48:39 -0000 1.4 --- EndOfDayTimerHandlerFPOscillatorCTC.cs 29 Aug 2007 09:43:30 -0000 1.5 *************** *** 49,57 **** private int numDaysForReturnCalculation; private double maxAcceptableCloseToCloseDrawdown; - private bool stopLossConditionReached; - private double currentAccountValue; - private double previousAccountValue; - private int numDaysBetweenEachOptimization; - private int numDaysElapsedSinceLastOptimization; private int daysCounterWithPositions; private int daysCounterWithRightPositions; --- 49,52 ---- *************** *** 109,119 **** } - private void marketCloseEventHandler_reverseSignOfTickers(string[] signedTickers) - { - for(int i = 0; i<signedTickers.Length; i++) - if(signedTickers[i] != null) - signedTickers[i] = SignedTicker.GetOppositeSignedTicker(signedTickers[i]); - } - private void marketCloseEventHandler_updateCounters(bool isTheFirstClose) { --- 104,107 ---- *************** *** 138,144 **** (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; gainForTheLastHalfPeriod = ! SignedTicker.GetCloseToClosePortfolioReturn( ! this.chosenTickers, this.chosenTickersPortfolioWeights, ! initialDateForHalfPeriod,finalDateForHalfPeriod); if(gainForTheLastHalfPeriod < 0.0) //in the last periods the combination has lost, so --- 126,130 ---- (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 *************** *** 158,162 **** { if(this.marketCloseEventHandler_openPositionsIfTuned_isTuned(timer)) ! base.openPositions(this.chosenTickers); } --- 144,148 ---- { if(this.marketCloseEventHandler_openPositionsIfTuned_isTuned(timer)) ! AccountManager.OpenPositions(this.chosenWeightedPositions, this.account); } *************** *** 168,173 **** { //Close if halfPeriod has elapsed or stop loss condition reached ! base.closePositions(); ! this.daysCounterWithPositions = 0; } } --- 154,159 ---- { //Close if halfPeriod has elapsed or stop loss condition reached ! AccountManager.ClosePositions(this.account); ! this.daysCounterWithPositions = 0; } } *************** *** 179,183 **** if(this.account.Portfolio.Count == 0 && ! this.chosenTickers[0] != null) //portfolio is empty and tickers to buy have been chosen this.marketCloseEventHandler_openPositionsIfTuned((IndexBasedEndOfDayTimer)sender); --- 165,169 ---- if(this.account.Portfolio.Count == 0 && ! this.chosenWeightedPositions != null) //portfolio is empty and tickers to buy have been chosen this.marketCloseEventHandler_openPositionsIfTuned((IndexBasedEndOfDayTimer)sender); *************** *** 277,281 **** { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.chosenTickers.Length*2) //the optimization process is meaningful only if the initial set of tickers is //larger than the number of tickers to be chosen --- 263,267 ---- { 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 *************** *** 311,316 **** ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate, setOfTickersToBeOptimized.Rows.Count, this.numDaysForReturnCalculation); ! this.chosenTickers = ((GenomeMeaning)GO.BestGenome.Meaning).Tickers; ! this.chosenTickersPortfolioWeights = ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights; } //else it will be buyed again the previous optimized portfolio --- 297,302 ---- ((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 *************** *** 329,333 **** this.seedForRandomGenerator++; this.numDaysElapsedSinceLastOptimization++; - this.orders.Clear(); if((this.numDaysElapsedSinceLastOptimization - 1 == this.numDaysBetweenEachOptimization)) //|| this.isTheFirstClose ) --- 315,318 ---- |
|
From: Marco M. <mi...@us...> - 2007-08-29 09:44:09
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv10276/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend Modified Files: EndOfDayTimerHandlerECT.cs Log Message: Code has been re-organized in a more logical and Object Oriented way: - WeightedPositions class has been used. - Some static methods have been deleted from SignedTicker class. They have been moved to WeightedPositions. - Basic orders'management has been moved to the primitive base class EndOfDayTimerHandler and to AccountManager class Index: EndOfDayTimerHandlerECT.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend/EndOfDayTimerHandlerECT.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** EndOfDayTimerHandlerECT.cs 17 Sep 2006 21:48:39 -0000 1.5 --- EndOfDayTimerHandlerECT.cs 29 Aug 2007 09:43:30 -0000 1.6 *************** *** 49,57 **** private int numDaysForReturnCalculation; private double maxAcceptableCloseToCloseDrawdown; - private bool stopLossConditionReached; - private double currentAccountValue; - private double previousAccountValue; - private int numDaysBetweenEachOptimization; - private int numDaysElapsedSinceLastOptimization; private int daysCounterWithPositions; // private int daysCounterWithRightPositions; --- 49,52 ---- *************** *** 119,125 **** DateTime finalDateForHalfPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! returnValue = ! SignedTicker.GetCloseToClosePortfolioReturn( ! this.chosenTickers, this.chosenTickersPortfolioWeights, initialDateForHalfPeriod,finalDateForHalfPeriod); } --- 114,118 ---- DateTime finalDateForHalfPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! returnValue = this.chosenWeightedPositions.GetCloseToCloseReturn( initialDateForHalfPeriod,finalDateForHalfPeriod); } *************** *** 139,150 **** { if(lastHalfPeriodGain < 0.0) ! base.openPositions(this.chosenTickers); else if (lastHalfPeriodGain > 0.0 && this.portfolioType == PortfolioType.ShortAndLong) { ! SignedTicker.ChangeSignOfEachTicker(this.chosenTickers); //short the portfolio try{ ! base.openPositions(this.chosenTickers); } catch(Exception ex) --- 132,145 ---- { 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) *************** *** 153,157 **** } finally{ ! SignedTicker.ChangeSignOfEachTicker(this.chosenTickers); } } --- 148,152 ---- } finally{ ! this.chosenWeightedPositions.Reverse(); } } *************** *** 165,170 **** { //Close if halfPeriod has elapsed or stop loss condition reached ! base.closePositions(); ! this.daysCounterWithPositions = 0; } } --- 160,165 ---- { //Close if halfPeriod has elapsed or stop loss condition reached ! AccountManager.ClosePositions(this.account); ! this.daysCounterWithPositions = 0; } } *************** *** 177,181 **** //this.marketCloseEventHandler_updateStopLossCondition(); this.marketCloseEventHandler_closePositions(); ! if(this.chosenTickers[0] != null) //tickers to buy have been chosen { --- 172,176 ---- //this.marketCloseEventHandler_updateStopLossCondition(); this.marketCloseEventHandler_closePositions(); ! if(this.chosenWeightedPositions != null) //tickers to buy have been chosen { *************** *** 253,260 **** { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); ! if(setOfTickersToBeOptimized.Rows.Count > this.chosenTickers.Length*2) //the optimization process is meaningful only if the initial set of tickers is //larger than the number of tickers to be chosen - { this.iGenomeManager = --- 248,254 ---- { 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 = *************** *** 281,286 **** ((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; } //else it will be buyed again the previous optimized portfolio --- 275,284 ---- ((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 *************** *** 299,303 **** this.seedForRandomGenerator++; this.numDaysElapsedSinceLastOptimization++; - this.orders.Clear(); if((this.numDaysElapsedSinceLastOptimization - 1 == this.numDaysBetweenEachOptimization)) //|| this.isTheFirstClose ) --- 297,300 ---- |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv10276/b7_Scripts/WalkForwardTesting/LinearCombination Modified Files: CloseToOpenDailyStrategy.cs ExtremeCounterTrendStrategy.cs FixedLevelOscBiasedOTC_PVONoThresholdsStrategy.cs FixedLevelOscillatorBiasedPVONoThresholdsStrategy.cs FixedLevelOscillatorBiasedPVOStrategy.cs FixedLevelOscillatorPVOStrategy.cs FixedPeriodOscillatorStrategy.cs ImmediateTrendFollowerStrategy.cs LinearCombinationTest.cs OpenToCloseDailyStrategy.cs OpenToCloseWeeklyStrategy.cs OTC_CTODailyStrategy.cs Log Message: Code has been re-organized in a more logical and Object Oriented way: - WeightedPositions class has been used. - Some static methods have been deleted from SignedTicker class. They have been moved to WeightedPositions. - Basic orders'management has been moved to the primitive base class EndOfDayTimerHandler and to AccountManager class Index: FixedLevelOscillatorBiasedPVOStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/FixedLevelOscillatorBiasedPVOStrategy.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** FixedLevelOscillatorBiasedPVOStrategy.cs 9 Apr 2007 18:06:25 -0000 1.2 --- FixedLevelOscillatorBiasedPVOStrategy.cs 29 Aug 2007 09:43:36 -0000 1.3 *************** *** 46,51 **** public FixedLevelOscillatorBiasedPVOStrategy( Account accountPVO , ! string[,] tickers, ! double[,] tickersPortfolioWeights, double[] oversoldThreshold, double[] overboughtThreshold, --- 46,50 ---- public FixedLevelOscillatorBiasedPVOStrategy( Account accountPVO , ! WeightedPositions[] weightedPositionsToEvaluateOutOfSample, double[] oversoldThreshold, double[] overboughtThreshold, *************** *** 55,59 **** double minimumAcceptableGain): base("", 0, ! tickers.GetUpperBound(1)+1, 0, accountPVO, 0, 0, "", numOfDifferentGenomesToEvaluateOutOfSample, numDaysForOscillatingPeriod,1,1,1,1,1,false,false,0, --- 54,58 ---- double minimumAcceptableGain): base("", 0, ! weightedPositionsToEvaluateOutOfSample[0].Count, 0, accountPVO, 0, 0, "", numOfDifferentGenomesToEvaluateOutOfSample, numDaysForOscillatingPeriod,1,1,1,1,1,false,false,0, *************** *** 62,67 **** { ! this.bestGenomesChosenTickers = tickers; ! this.bestGenomesChosenTickersPortfolioWeights = tickersPortfolioWeights; this.currentOversoldThreshold = oversoldThreshold; this.currentOverboughtThreshold = overboughtThreshold; --- 61,65 ---- { ! this.weightedPositionsToEvaluateOutOfSample = weightedPositionsToEvaluateOutOfSample; this.currentOversoldThreshold = oversoldThreshold; this.currentOverboughtThreshold = overboughtThreshold; *************** *** 75,80 **** } ! protected override double getCurrentChosenTickersGainOrLoss(IndexBasedEndOfDayTimer timer, ! int indexForChosenTickers) { double returnValue = 999.0; --- 73,78 ---- } ! protected override double getCurrentWeightedPositionsGainOrLoss(IndexBasedEndOfDayTimer timer, ! int indexForChosenWeightedPositions) { double returnValue = 999.0; *************** *** 83,112 **** //that's why the method has been overriden { ! try ! { ! DateTime initialDate = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForOscillatingPeriod + 2]["quDate"]; ! //so to replicate exactly in sample scheme, where only numOscillatingDay - 1 returns ! //are computed ! DateTime finalDate = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! string[] tickers = new string[this.numberOfTickersToBeChosen]; ! double[] tickerWeights = new double[this.numberOfTickersToBeChosen]; ! for(int i = 0; i < this.numberOfTickersToBeChosen; i++) ! { ! tickers[i] = this.bestGenomesChosenTickers[indexForChosenTickers,i]; ! tickerWeights[i] = this.bestGenomesChosenTickersPortfolioWeights[indexForChosenTickers,i]; ! } ! returnValue = ! SignedTicker.GetCloseToClosePortfolioReturn( ! tickers, tickerWeights, ! initialDate,finalDate) + 1.0; ! } ! catch(MissingQuotesException ex) ! { ! ex = ex; ! } ! } ! return returnValue; } --- 81,100 ---- //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].GetCloseToCloseReturn( ! lastMarketDay, today); ! } ! catch(MissingQuotesException ex) ! { ! ex = ex; ! } ! } ! return returnValue; } Index: OpenToCloseWeeklyStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/OpenToCloseWeeklyStrategy.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** OpenToCloseWeeklyStrategy.cs 2 Aug 2005 23:07:59 -0000 1.1 --- OpenToCloseWeeklyStrategy.cs 29 Aug 2007 09:43:37 -0000 1.2 *************** *** 39,76 **** { private Account account; ! private string[] signedTickers; public OpenToCloseWeeklyStrategy( Account account , ! string[] signedTickers) { this.account = account; ! this.signedTickers = signedTickers; ! } ! private long marketOpenEventHandler_addOrder_getQuantity( ! string ticker ) ! { ! double accountValue = this.account.GetMarketValue(); ! double currentTickerAsk = ! this.account.DataStreamer.GetCurrentAsk( ticker ); ! double maxPositionValueForThisTicker = ! accountValue/this.signedTickers.Length; ! long quantity = Convert.ToInt64( Math.Floor( ! maxPositionValueForThisTicker / currentTickerAsk ) ); ! return quantity; ! } ! private void marketOpenEventHandler_addOrder( string signedTicker ) ! { ! OrderType orderType = GenomeRepresentation.GetOrderType( signedTicker ); ! string ticker = GenomeRepresentation.GetTicker( signedTicker ); ! long quantity = marketOpenEventHandler_addOrder_getQuantity( ticker ); ! Order order = new Order( orderType , new Instrument( ticker ) , ! quantity ); ! this.account.AddOrder( order ); ! } ! private void marketOpenEventHandler_addOrders() ! { ! foreach ( string signedTicker in this.signedTickers ) ! marketOpenEventHandler_addOrder( signedTicker ); } public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) --- 39,51 ---- { private Account account; ! private WeightedPositions weightedPositions; public OpenToCloseWeeklyStrategy( Account account , ! WeightedPositions weightedPositions) { this.account = account; ! this.weightedPositions = weightedPositions; } + public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) *************** *** 79,95 **** ( this.account.Transactions.Count == 0 ) ) // cash has not been added yet ! this.account.AddCash( 30000 ); if ( endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == DayOfWeek.Monday ) ! marketOpenEventHandler_addOrders(); ! } ! private void fiveMinutesBeforeMarketCloseEventHandler_closePositions() ! { ! ArrayList tickers = new ArrayList(); ! foreach ( Position position in this.account.Portfolio.Positions ) ! tickers.Add( position.Instrument.Key ); ! foreach ( string ticker in tickers ) ! this.account.ClosePosition( ticker ); } public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) --- 54,63 ---- ( this.account.Transactions.Count == 0 ) ) // cash has not been added yet ! this.account.AddCash( 15000 ); if ( endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == DayOfWeek.Monday ) ! AccountManager.OpenPositions(this.weightedPositions, this.account); } + public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) *************** *** 97,101 **** if ( endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == DayOfWeek.Friday ) ! this.fiveMinutesBeforeMarketCloseEventHandler_closePositions(); } --- 65,69 ---- if ( endOfDayTimingEventArgs.EndOfDayDateTime.DateTime.DayOfWeek == DayOfWeek.Friday ) ! AccountManager.ClosePositions(this.account); } Index: ExtremeCounterTrendStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/ExtremeCounterTrendStrategy.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** ExtremeCounterTrendStrategy.cs 7 Aug 2006 21:10:36 -0000 1.3 --- ExtremeCounterTrendStrategy.cs 29 Aug 2007 09:43:35 -0000 1.4 *************** *** 42,47 **** { private Account account; ! private string[] signedTickers; ! private double[] weightsForSignedTickers; private int numDaysForReturnCalculation; private int numOfClosesElapsed = 0; --- 42,46 ---- { private Account account; ! private WeightedPositions weightedPositions; private int numDaysForReturnCalculation; private int numOfClosesElapsed = 0; *************** *** 50,61 **** public ExtremeCounterTrendStrategy( Account account , ! string[] signedTickers, ! double[] weightsForSignedTickers, int numDaysForReturnCalculation, PortfolioType portfolioType) { this.account = account; ! this.signedTickers = signedTickers; ! this.weightsForSignedTickers = weightsForSignedTickers; this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.portfolioType = portfolioType; --- 49,58 ---- public ExtremeCounterTrendStrategy( Account account , ! WeightedPositions weightedPositions, int numDaysForReturnCalculation, PortfolioType portfolioType) { this.account = account; ! this.weightedPositions = weightedPositions; this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.portfolioType = portfolioType; *************** *** 72,102 **** } - private long marketCloseEventHandler_addOrder_getQuantity( - int indexForSignedTicker) - { - double accountValue = this.account.GetMarketValue(); - double currentTickerAsk = - this.account.DataStreamer.GetCurrentAsk( SignedTicker.GetTicker(this.signedTickers[indexForSignedTicker]) ); - double maxPositionValueForThisTicker = - accountValue*this.weightsForSignedTickers[indexForSignedTicker]; - long quantity = Convert.ToInt64( Math.Floor( - maxPositionValueForThisTicker / currentTickerAsk ) ); - return quantity; - } - private void marketCloseEventHandler_addOrder( int indexForSignedTicker ) - { - OrderType orderType = GenomeRepresentation.GetOrderType( this.signedTickers[indexForSignedTicker] ); - string ticker = GenomeRepresentation.GetTicker( this.signedTickers[indexForSignedTicker] ); - long quantity = marketCloseEventHandler_addOrder_getQuantity( indexForSignedTicker ); - Order order = new Order( orderType , new Instrument( ticker ) , - quantity ); - this.account.AddOrder( order ); - } - private void marketCloseEventHandler_addOrders() - { - for(int i = 0; i<this.signedTickers.Length; i++) - marketCloseEventHandler_addOrder( i ); - } - private double marketCloseEventHandler_openPositions_getLastHalfPeriodGain(IndexBasedEndOfDayTimer timer) { --- 69,72 ---- *************** *** 108,114 **** DateTime finalDateForHalfPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! returnValue = ! SignedTicker.GetCloseToClosePortfolioReturn( ! this.signedTickers,initialDateForHalfPeriod,finalDateForHalfPeriod); } catch(MissingQuotesException ex) --- 78,82 ---- DateTime finalDateForHalfPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! this.weightedPositions.GetCloseToCloseReturn(initialDateForHalfPeriod,finalDateForHalfPeriod); } catch(MissingQuotesException ex) *************** *** 127,140 **** { if(lastHalfPeriodGain < 0.0) ! this.marketCloseEventHandler_addOrders(); ! else if (lastHalfPeriodGain > 0.0 && ! this.portfolioType == PortfolioType.ShortAndLong ) ! //if gain of the last half period is positive and ! //original positions can be reversed { ! SignedTicker.ChangeSignOfEachTicker(this.signedTickers); //short the portfolio (short --> long; long --> short) try{ ! this.marketCloseEventHandler_addOrders(); } catch(Exception ex) --- 95,106 ---- { 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) *************** *** 143,147 **** } finally{ ! SignedTicker.ChangeSignOfEachTicker(this.signedTickers); } } --- 109,113 ---- } finally{ ! this.weightedPositions.Reverse(); } } *************** *** 151,159 **** private void marketCloseEventHandler_closePositions() { ! ArrayList tickers = new ArrayList(); ! foreach ( Position position in this.account.Portfolio.Positions ) ! tickers.Add( position.Instrument.Key ); ! foreach ( string ticker in tickers ) ! this.account.ClosePosition( ticker ); this.numOfDaysWithOpenPosition = 0; } --- 117,121 ---- private void marketCloseEventHandler_closePositions() { ! AccountManager.ClosePositions(this.account); this.numOfDaysWithOpenPosition = 0; } *************** *** 165,169 **** if(this.account.Transactions.Count == 0) ! this.account.AddCash(30000); if(this.account.Portfolio.Count > 0) --- 127,131 ---- if(this.account.Transactions.Count == 0) ! this.account.AddCash(15000); if(this.account.Portfolio.Count > 0) *************** *** 182,187 **** EndOfDayTimingEventArgs endOfDayTimingEventArgs) { ! ! } } } --- 144,148 ---- EndOfDayTimingEventArgs endOfDayTimingEventArgs) { ! } } } Index: FixedLevelOscBiasedOTC_PVONoThresholdsStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/FixedLevelOscBiasedOTC_PVONoThresholdsStrategy.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** FixedLevelOscBiasedOTC_PVONoThresholdsStrategy.cs 27 Feb 2007 22:54:44 -0000 1.1 --- FixedLevelOscBiasedOTC_PVONoThresholdsStrategy.cs 29 Aug 2007 09:43:35 -0000 1.2 *************** *** 48,62 **** public FixedLevelOscBiasedOTC_PVONoThresholdsStrategy( Account accountPVO , ! string[,] tickers, ! double[,] tickersPortfolioWeights, int numOfDifferentGenomesToEvaluateOutOfSample): base("", 0, ! tickers.GetUpperBound(1)+1, 0, accountPVO, 0, 0, "", numOfDifferentGenomesToEvaluateOutOfSample,0, PortfolioType.ShortAndLong) { ! this.chosenTickers = tickers; ! this.chosenTickersPortfolioWeights = tickersPortfolioWeights; } --- 48,60 ---- public FixedLevelOscBiasedOTC_PVONoThresholdsStrategy( Account accountPVO , ! WeightedPositions[] weightedPositionsToEvaluateOutOfSample, int numOfDifferentGenomesToEvaluateOutOfSample): base("", 0, ! weightedPositionsToEvaluateOutOfSample[0].Count, 0, accountPVO, 0, 0, "", numOfDifferentGenomesToEvaluateOutOfSample,0, PortfolioType.ShortAndLong) { ! this.weightedPositionsToEvaluateOutOfSample = weightedPositionsToEvaluateOutOfSample; } *************** *** 65,69 **** { if(this.account.Portfolio.Count == 0) ! this.marketOpenEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); } --- 63,67 ---- { if(this.account.Portfolio.Count == 0) ! this.openPositions((IndexBasedEndOfDayTimer)sender); } *************** *** 73,82 **** } ! protected override double getCurrentChosenTickersGainOrLoss(IndexBasedEndOfDayTimer timer, ! int indexForChosenTickers) { double returnValue = 999.0; if(timer.CurrentDateArrayPosition >= 1) ! //if there are sufficient data for computing currentChosenTickersValue //that's why the method has been overriden { --- 71,80 ---- } ! protected override double getCurrentWeightedPositionsGainOrLoss(IndexBasedEndOfDayTimer timer, ! int indexForChosenWeightedPositions) { double returnValue = 999.0; if(timer.CurrentDateArrayPosition >= 1) ! //if there are sufficient data for computing currentChosenWeightedPositionsValue //that's why the method has been overriden { *************** *** 88,102 **** (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - 1]["quDate"]; ! string[] tickers = new string[this.numberOfTickersToBeChosen]; ! double[] tickerWeights = new double[this.numberOfTickersToBeChosen]; ! for(int i = 0; i < this.numberOfTickersToBeChosen; i++) ! { ! tickers[i] = this.chosenTickers[indexForChosenTickers,i]; ! tickerWeights[i] = this.chosenTickersPortfolioWeights[indexForChosenTickers,i]; ! } ! returnValue = ! SignedTicker.GetLastNightPortfolioReturn( ! tickers, tickerWeights, ! lastMarketDay, today); } catch(MissingQuotesException ex) --- 86,91 ---- (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - 1]["quDate"]; ! returnValue = this.weightedPositionsToEvaluateOutOfSample[indexForChosenWeightedPositions].GetLastNightReturn( ! lastMarketDay, today); } catch(MissingQuotesException ex) *************** *** 111,115 **** EndOfDayTimingEventArgs endOfDayTimingEventArgs) { - } } --- 100,103 ---- Index: FixedLevelOscillatorBiasedPVONoThresholdsStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/FixedLevelOscillatorBiasedPVONoThresholdsStrategy.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** FixedLevelOscillatorBiasedPVONoThresholdsStrategy.cs 27 Feb 2007 22:54:44 -0000 1.1 --- FixedLevelOscillatorBiasedPVONoThresholdsStrategy.cs 29 Aug 2007 09:43:35 -0000 1.2 *************** *** 47,57 **** public FixedLevelOscillatorBiasedPVONoThresholdsStrategy( Account accountPVO , ! string[,] tickers, ! double[,] tickersPortfolioWeights, int numOfDifferentGenomesToEvaluateOutOfSample, double maxAcceptableCloseToCloseDrawdown, double minimumAcceptableGain): base("", 0, ! tickers.GetUpperBound(1)+1, 0, accountPVO, 0, 0, "", numOfDifferentGenomesToEvaluateOutOfSample,0, PortfolioType.ShortAndLong,maxAcceptableCloseToCloseDrawdown, --- 47,56 ---- public FixedLevelOscillatorBiasedPVONoThresholdsStrategy( Account accountPVO , ! WeightedPositions[] weightedPositionsToEvaluateOutOfSample, int numOfDifferentGenomesToEvaluateOutOfSample, double maxAcceptableCloseToCloseDrawdown, double minimumAcceptableGain): base("", 0, ! weightedPositionsToEvaluateOutOfSample[0].Count, 0, accountPVO, 0, 0, "", numOfDifferentGenomesToEvaluateOutOfSample,0, PortfolioType.ShortAndLong,maxAcceptableCloseToCloseDrawdown, *************** *** 59,64 **** { ! this.chosenTickers = tickers; ! this.chosenTickersPortfolioWeights = tickersPortfolioWeights; } --- 58,62 ---- { ! this.weightedPositionsToEvaluateOutOfSample = weightedPositionsToEvaluateOutOfSample; } *************** *** 68,73 **** } ! protected override double getCurrentChosenTickersGainOrLoss(IndexBasedEndOfDayTimer timer, ! int indexForChosenTickers) { double returnValue = 999.0; --- 66,71 ---- } ! protected override double getCurrentWeightedPositionsGainOrLoss(IndexBasedEndOfDayTimer timer, ! int indexForChosenWeightedPositions) { double returnValue = 999.0; *************** *** 76,101 **** //that's why the method has been overriden { ! try ! { ! DateTime date = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! string[] tickers = new string[this.numberOfTickersToBeChosen]; ! double[] tickerWeights = new double[this.numberOfTickersToBeChosen]; ! for(int i = 0; i < this.numberOfTickersToBeChosen; i++) ! { ! tickers[i] = this.chosenTickers[indexForChosenTickers,i]; ! tickerWeights[i] = this.chosenTickersPortfolioWeights[indexForChosenTickers,i]; ! } ! returnValue = ! SignedTicker.GetCloseToClosePortfolioReturn( ! tickers, tickerWeights, ! date,date); ! } ! catch(MissingQuotesException ex) ! { ! ex = ex; ! } ! } ! return returnValue; } --- 74,93 ---- //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].GetCloseToCloseReturn( ! lastMarketDay, today); ! } ! catch(MissingQuotesException ex) ! { ! ex = ex; ! } ! } ! return returnValue; } Index: OpenToCloseDailyStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/OpenToCloseDailyStrategy.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** OpenToCloseDailyStrategy.cs 2 Jul 2006 19:24:33 -0000 1.2 --- OpenToCloseDailyStrategy.cs 29 Aug 2007 09:43:37 -0000 1.3 *************** *** 39,78 **** { private Account account; ! private string[] signedTickers; ! private double[] weightsForSignedTickers; public OpenToCloseDailyStrategy( Account account , ! string[] signedTickers, double[] weightsForSignedTickers) { this.account = account; ! this.signedTickers = signedTickers; ! this.weightsForSignedTickers = weightsForSignedTickers; ! } ! private long marketOpenEventHandler_addOrder_getQuantity( ! int indexForSignedTicker ) ! { ! double accountValue = this.account.GetMarketValue(); ! double currentTickerAsk = ! this.account.DataStreamer.GetCurrentAsk( SignedTicker.GetTicker(this.signedTickers[indexForSignedTicker]) ); ! double maxPositionValueForThisTicker = ! accountValue*this.weightsForSignedTickers[indexForSignedTicker]; ! long quantity = Convert.ToInt64( Math.Floor( ! maxPositionValueForThisTicker / currentTickerAsk ) ); ! return quantity; ! } ! private void marketOpenEventHandler_addOrder( int indexForSignedTicker ) ! { ! OrderType orderType = GenomeRepresentation.GetOrderType( this.signedTickers[indexForSignedTicker] ); ! string ticker = GenomeRepresentation.GetTicker( this.signedTickers[indexForSignedTicker] ); ! long quantity = marketOpenEventHandler_addOrder_getQuantity( indexForSignedTicker ); ! Order order = new Order( orderType , new Instrument( ticker ) , ! quantity ); ! this.account.AddOrder( order ); ! } ! private void marketOpenEventHandler_addOrders() ! { ! for(int i = 0; i<this.signedTickers.Length; i++) ! marketOpenEventHandler_addOrder( i ); } public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) --- 39,51 ---- { private Account account; ! private WeightedPositions chosenWeightedPositions; public OpenToCloseDailyStrategy( Account account , ! WeightedPositions chosenWeightedPositions) { this.account = account; ! this.chosenWeightedPositions = chosenWeightedPositions; } + public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) *************** *** 81,99 **** ( this.account.Transactions.Count == 0 ) ) // cash has not been added yet ! this.account.AddCash( 30000 ); ! marketOpenEventHandler_addOrders(); ! } ! private void fiveMinutesBeforeMarketCloseEventHandler_closePositions() ! { ! ArrayList tickers = new ArrayList(); ! foreach ( Position position in this.account.Portfolio.Positions ) ! tickers.Add( position.Instrument.Key ); ! foreach ( string ticker in tickers ) ! this.account.ClosePosition( ticker ); } public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { ! this.fiveMinutesBeforeMarketCloseEventHandler_closePositions(); } --- 54,65 ---- ( this.account.Transactions.Count == 0 ) ) // cash has not been added yet ! this.account.AddCash( 15000 ); ! AccountManager.OpenPositions(this.chosenWeightedPositions, this.account); } + public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { ! AccountManager.ClosePositions(this.account); } *************** *** 102,105 **** --- 68,72 ---- { } + public void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) Index: CloseToOpenDailyStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/CloseToOpenDailyStrategy.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** CloseToOpenDailyStrategy.cs 8 Jan 2006 23:33:52 -0000 1.1 --- CloseToOpenDailyStrategy.cs 29 Aug 2007 09:43:35 -0000 1.2 *************** *** 39,88 **** { private Account account; ! private string[] signedTickers; public CloseToOpenDailyStrategy( Account account , ! string[] signedTickers) { this.account = account; ! this.signedTickers = signedTickers; ! } ! private long marketCloseEventHandler_addOrder_getQuantity( ! string ticker ) ! { ! double accountValue = this.account.GetMarketValue(); ! double currentTickerAsk = ! this.account.DataStreamer.GetCurrentAsk( ticker ); ! double maxPositionValueForThisTicker = ! accountValue/this.signedTickers.Length; ! long quantity = Convert.ToInt64( Math.Floor( ! maxPositionValueForThisTicker / currentTickerAsk ) ); ! return quantity; ! } ! private void marketCloseEventHandler_addOrder( string signedTicker ) ! { ! OrderType orderType = GenomeRepresentation.GetOrderType( signedTicker ); ! string ticker = GenomeRepresentation.GetTicker( signedTicker ); ! long quantity = marketCloseEventHandler_addOrder_getQuantity( ticker ); ! Order order = new Order( orderType , new Instrument( ticker ) , ! quantity ); ! this.account.AddOrder( order ); ! } ! private void marketCloseEventHandler_addOrders() ! { ! foreach ( string signedTicker in this.signedTickers ) ! marketCloseEventHandler_addOrder( signedTicker ); } public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! this.marketOpen_closePositions(); ! } ! private void marketOpen_closePositions() ! { ! ArrayList tickers = new ArrayList(); ! foreach ( Position position in this.account.Portfolio.Positions ) ! tickers.Add( position.Instrument.Key ); ! foreach ( string ticker in tickers ) ! this.account.ClosePosition( ticker ); } public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , --- 39,55 ---- { private Account account; ! private WeightedPositions weightedPositions; public CloseToOpenDailyStrategy( Account account , ! WeightedPositions weightedPositions) { this.account = account; ! this.weightedPositions = weightedPositions; } + public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! AccountManager.ClosePositions(this.account); } public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , *************** *** 90,94 **** { } - public void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) --- 57,60 ---- *************** *** 97,102 **** ( this.account.Transactions.Count == 0 ) ) // cash has not been added yet ! this.account.AddCash( 30000 ); ! marketCloseEventHandler_addOrders(); } public void OneHourAfterMarketCloseEventHandler( Object sender , --- 63,68 ---- ( this.account.Transactions.Count == 0 ) ) // cash has not been added yet ! this.account.AddCash( 15000 ); ! AccountManager.OpenPositions(this.weightedPositions, this.account); } public void OneHourAfterMarketCloseEventHandler( Object sender , Index: OTC_CTODailyStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/OTC_CTODailyStrategy.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** OTC_CTODailyStrategy.cs 2 Jul 2006 19:22:12 -0000 1.1 --- OTC_CTODailyStrategy.cs 29 Aug 2007 09:43:37 -0000 1.2 *************** *** 39,116 **** { private Account account; ! private string[] signedTickers; ! private double[] weightsForSignedTickers; public OTC_CTODailyStrategy( Account account , ! string[] signedTickers, double[] weightsForSignedTickers) { this.account = account; ! this.signedTickers = signedTickers; ! this.weightsForSignedTickers = weightsForSignedTickers; ! } ! private long addOrders_addOrder_getQuantity( ! int indexForSignedTicker ) ! { ! double accountValue = this.account.GetMarketValue(); ! double currentTickerAsk = ! this.account.DataStreamer.GetCurrentAsk( SignedTicker.GetTicker(this.signedTickers[indexForSignedTicker]) ); ! double maxPositionValueForThisTicker = ! accountValue*this.weightsForSignedTickers[indexForSignedTicker]; ! long quantity = Convert.ToInt64( Math.Floor( ! maxPositionValueForThisTicker / currentTickerAsk ) ); ! return quantity; ! } ! private void addOrders_addOrder( int indexForSignedTicker ) ! { ! OrderType orderType = GenomeRepresentation.GetOrderType( this.signedTickers[indexForSignedTicker] ); ! string ticker = GenomeRepresentation.GetTicker( this.signedTickers[indexForSignedTicker] ); ! long quantity = addOrders_addOrder_getQuantity( indexForSignedTicker ); ! Order order = new Order( orderType , new Instrument( ticker ) , ! quantity ); ! this.account.AddOrder( order ); ! } ! private void addOrders() ! { ! for(int i = 0; i<this.signedTickers.Length; i++) ! this.addOrders_addOrder( i ); } public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! this.closePositions(); if ( ( this.account.CashAmount == 0 ) && ( this.account.Transactions.Count == 0 ) ) // cash has not been added yet ! this.account.AddCash( 30000 ); ! this.addOrders(); ! } ! private void closePositions() ! { ! ArrayList tickers = new ArrayList(); ! foreach ( Position position in this.account.Portfolio.Positions ) ! tickers.Add( position.Instrument.Key ); ! foreach ( string ticker in tickers ) ! this.account.ClosePosition( ticker ); } public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { - } ! public void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { ! this.closePositions(); ! SignedTicker.ChangeSignOfEachTicker(this.signedTickers); ! this.addOrders(); ! SignedTicker.ChangeSignOfEachTicker(this.signedTickers); } ! ! public void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { } - } } --- 39,77 ---- { private Account account; ! WeightedPositions weightedPositions; public OTC_CTODailyStrategy( Account account , ! WeightedPositions weightedPositions) { this.account = account; ! this.weightedPositions = weightedPositions; } + public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! AccountManager.ClosePositions(this.account); if ( ( this.account.CashAmount == 0 ) && ( this.account.Transactions.Count == 0 ) ) // cash has not been added yet ! this.account.AddCash( 15000 ); ! AccountManager.OpenPositions(this.weightedPositions, this.account); } + public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { } ! public void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { ! AccountManager.ReversePositions(this.account); } ! ! public void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { } } } Index: FixedPeriodOscillatorStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/FixedPeriodOscillatorStrategy.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** FixedPeriodOscillatorStrategy.cs 2 Jul 2006 19:22:12 -0000 1.2 --- FixedPeriodOscillatorStrategy.cs 29 Aug 2007 09:43:36 -0000 1.3 *************** *** 37,46 **** /// </summary> [Serializable] ! public class FixedPeriodOscillatorStrategy : IEndOfDayStrategy { ! private Account account; ! private string[] signedTickers; ! private double[] weightsForSignedTickers; ! private int daysForRightPeriod; private int daysForReversalPeriod; //length for movement upwards or downwards of the given tickers --- 37,43 ---- /// </summary> [Serializable] ! public class FixedPeriodOscillatorStrategy : EndOfDayTimerHandler, IEndOfDayStrategy { ! private int daysForRightPeriod; private int daysForReversalPeriod; //length for movement upwards or downwards of the given tickers *************** *** 52,127 **** public FixedPeriodOscillatorStrategy( Account account , ! string[] signedTickers, ! double[] weightsForSignedTickers, int daysForRightPeriod, ! int daysForReversalPeriod) { this.account = account; ! this.signedTickers = signedTickers; ! this.weightsForSignedTickers = weightsForSignedTickers; this.daysForRightPeriod = daysForRightPeriod; this.daysForReversalPeriod = daysForReversalPeriod; } ! private long marketCloseEventHandler_addOrder_getQuantity( ! int indexForSignedTicker) ! { ! double accountValue = this.account.GetMarketValue(); ! double currentTickerAsk = ! this.account.DataStreamer.GetCurrentAsk( SignedTicker.GetTicker(this.signedTickers[indexForSignedTicker]) ); ! double maxPositionValueForThisTicker = ! accountValue*this.weightsForSignedTickers[indexForSignedTicker]; ! long quantity = Convert.ToInt64( Math.Floor( ! maxPositionValueForThisTicker / currentTickerAsk ) ); ! return quantity; ! } ! private void marketCloseEventHandler_addOrder( int indexForSignedTicker ) ! { ! OrderType orderType = GenomeRepresentation.GetOrderType( this.signedTickers[indexForSignedTicker] ); ! string ticker = GenomeRepresentation.GetTicker( this.signedTickers[indexForSignedTicker] ); ! long quantity = marketCloseEventHandler_addOrder_getQuantity( indexForSignedTicker ); ! Order order = new Order( orderType , new Instrument( ticker ) , ! quantity ); ! this.account.AddOrder( order ); ! } ! private void marketCloseEventHandler_addOrders() ! { ! for(int i = 0; i<this.signedTickers.Length; i++) ! marketCloseEventHandler_addOrder( i ); ! } ! ! public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { } ! ! private void marketCloseEventHandler_closePositions() ! { ! ArrayList tickers = new ArrayList(); ! foreach ( Position position in this.account.Portfolio.Positions ) ! tickers.Add( position.Instrument.Key ); ! foreach ( string ticker in tickers ) ! this.account.ClosePosition( ticker ); ! } ! ! public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) ! { ! } ! ! private void marketCloseEventHandler_reverseSignOfTickers() ! { ! for(int i = 0; i<this.signedTickers.Length; i++) ! { ! if(this.signedTickers[i] != null) ! { ! if(this.signedTickers[i].StartsWith("-")) ! this.signedTickers[i] = ! GenomeManagerForEfficientPortfolio.GetCleanTickerCode(this.signedTickers[i]); ! else ! this.signedTickers[i] = "-" + this.signedTickers[i]; ! } ! } ! } ! private void marketCloseEventHandler_updateCounters(bool isTheFirstClose) { --- 49,74 ---- public FixedPeriodOscillatorStrategy( Account account , ! WeightedPositions weightedPositions, int daysForRightPeriod, ! int daysForReversalPeriod): ! base("", 0, ! weightedPositions.Count, 0, account, ! 0, ! 0, ! "^GSPC", 0.0, ! PortfolioType.ShortAndLong) { this.account = account; ! this.chosenWeightedPositions = weightedPositions; this.daysForRightPeriod = daysForRightPeriod; this.daysForReversalPeriod = daysForReversalPeriod; } ! ! public override void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { + } ! private void marketCloseEventHandler_updateCounters(bool isTheFirstClose) { *************** *** 135,139 **** } ! public void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { --- 82,86 ---- } ! public override void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { *************** *** 147,152 **** { firstClose = true; ! this.account.AddCash( 30000 ); ! this.marketCloseEventHandler_addOrders(); } --- 94,98 ---- { firstClose = true; ! this.openPositions(); } *************** *** 157,164 **** { ! this.marketCloseEventHandler_closePositions(); ! this.daysCounterWithRightPositions = 0; ! this.marketCloseEventHandler_reverseSignOfTickers(); ! this.marketCloseEventHandler_addOrders(); this.isReversalPeriodOn = true; } --- 103,107 ---- { ! AccountManager.ReversePositions(this.account); this.isReversalPeriodOn = true; } *************** *** 168,175 **** { ! this.marketCloseEventHandler_closePositions(); ! this.daysCounterWithReversalPositions = 0; ! this.marketCloseEventHandler_reverseSignOfTickers(); ! this.marketCloseEventHandler_addOrders(); this.isReversalPeriodOn = false; } --- 111,115 ---- { ! AccountManager.ReversePositions(this.account); this.isReversalPeriodOn = false; } *************** *** 180,184 **** } ! public void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { --- 120,130 ---- } ! public override void OneHourAfterMarketCloseEventHandler( Object sender , ! EndOfDayTimingEventArgs endOfDayTimingEventArgs) ! { ! ! } ! ! public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { Index: FixedLevelOscillatorPVOStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/FixedLevelOscillatorPVOStrategy.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** FixedLevelOscillatorPVOStrategy.cs 27 Feb 2007 23:07:44 -0000 1.4 --- FixedLevelOscillatorPVOStrategy.cs 29 Aug 2007 09:43:36 -0000 1.5 *************** *** 43,52 **** public FixedLevelOscillatorPVOStrategy( Account accountPVO , ! string[] tickers, ! double[] tickersPortfolioWeights, double oversoldThreshold, double overboughtThreshold, int numDaysForOscillatingPeriod): ! base("", 0, tickers.Length, 0, accountPVO, 0,0, --- 43,51 ---- public FixedLevelOscillatorPVOStrategy( Account accountPVO , ! WeightedPositions weightedPositions, double oversoldThreshold, double overboughtThreshold, int numDaysForOscillatingPeriod): ! base("", 0, weightedPositions.Count, 0, accountPVO, 0,0, *************** *** 55,60 **** PortfolioType.ShortAndLong, 0.5) { ! this.chosenTickers = tickers; ! this.chosenTickersPortfolioWeights = tickersPortfolioWeights; this.currentOversoldThreshold = oversoldThreshold; this.currentOverboughtThreshold = overboughtThreshold; --- 54,58 ---- PortfolioType.ShortAndLong, 0.5) { ! this.chosenWeightedPositions = chosenWeightedPositions; this.currentOversoldThreshold = oversoldThreshold; this.currentOverboughtThreshold = overboughtThreshold; *************** *** 72,76 **** } ! protected override double getCurrentChosenTickersValue(IndexBasedEndOfDayTimer timer) { double returnValue = 999.0; --- 70,74 ---- } ! protected override double getCurrentChosenWeightedPositionsValue(IndexBasedEndOfDayTimer timer) { double returnValue = 999.0; *************** *** 88,94 **** (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; returnValue = ! SignedTicker.GetCloseToClosePortfolioReturn( ! this.chosenTickers, this.chosenTickersPortfolioWeights, ! initialDate,finalDate) + 1.0; } catch(Exception ex) --- 86,91 ---- (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; returnValue = ! this.chosenWeightedPositions.GetCloseToCloseReturn(initialDate,finalDate) ! + 1.0; } catch(Exception ex) Index: LinearCombinationTest.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/LinearCombinationTest.cs,v retrieving revision 1.11 retrieving revision 1.12 diff -C2 -d -r1.11 -r1.12 *** LinearCombinationTest.cs 27 Feb 2007 23:02:41 -0000 1.11 --- LinearCombinationTest.cs 29 Aug 2007 09:43:36 -0000 1.12 *************** *** 117,138 **** private void run_setStrategy_setBiasedOTC_PVONoThresholdsStrategy() { ! int numberOfTickersToBeChosen = ! GenomeRepresentation.GetSignedTickers(this.genomeRepresentations[0].SignedTickers).Length; ! string[,] signedTickers = new string[this.genomeRepresentations.Length, numberOfTickersToBeChosen]; ! double[,] tickersPortfolioWeights = new double[this.genomeRepresentations.Length, numberOfTickersToBeChosen]; ! for(int i = 0; i < this.genomeRepresentations.Length; i++) { ! for(int j = 0; j < numberOfTickersToBeChosen; j++) ! { ! signedTickers[i,j] = ! GenomeRepresentation.GetSignedTickers( ! this.genomeRepresentations[i].SignedTickers)[j]; ! tickersPortfolioWeights[i,j] = ! GenomeRepresentation.GetWeightsArray( ! this.genomeRepresentations[i].WeightsForSignedTickers)[j]; ! } } this.endOfDayStrategy = new FixedLevelOscBiasedOTC_PVONoThresholdsStrategy( ! this.account , signedTickers , tickersPortfolioWeights, this.genomeRepresentations.Length); } --- 117,131 ---- private void run_setStrategy_setBiasedOTC_PVONoThresholdsStrategy() { ! WeightedPositions[] weightedPositions = new WeightedPositions[this.genomeRepresentations.Length]; ! for(int i = 0; i<this.genomeRepresentations.Length;i++) { ! weightedPositions[i] = ! new WeightedPositions(GenomeRepresentation.GetWeightsArray(this.genomeRepresentations[i].WeightsForSignedTickers), ! new SignedTickers(this.genomeRepresentations[i].SignedTickers)); ! } + this.endOfDayStrategy = new FixedLevelOscBiasedOTC_PVONoThresholdsStrategy( ! this.account , weightedPositions, this.genomeRepresentations.Length); } *************** *** 140,161 **** private void run_setStrategy_setBiasedPVONoThresholdsStrategy() { ! int numberOfTickersToBeChosen = ! GenomeRepresentation.GetSignedTickers(this.genomeRepresentations[0].SignedTickers).Length; ! string[,] signedTickers = new string[this.genomeRepresentations.Length, numberOfTickersToBeChosen]; ! double[,] tickersPortfolioWeights = new double[this.genomeRepresentations.Length, numberOfTickersToBeChosen]; ! for(int i = 0; i < this.genomeRepresentations.Length; i++) ! { ! for(int j = 0; j < numberOfTickersToBeChosen; j++) ! { ! signedTickers[i,j] = ! GenomeRepresentation.GetSignedTickers( ! this.genomeRepresentations[i].SignedTickers)[j]; ! tickersPortfolioWeights[i,j] = ! GenomeRepresentation.GetWeightsArray( ! this.genomeRepresentations[i].WeightsForSignedTickers)[j]; ! } ! } this.endOfDayStrategy = new FixedLevelOscillatorBiasedPVONoThresholdsStrategy( ! this.account , signedTickers , tickersPortfolioWeights, this.genomeRepresentations.Length, this.stopLoss, --- 133,146 ---- private void run_setStrategy_setBiasedPVONoThresholdsStrategy() { ! WeightedPositions[] weightedPositions = new WeightedPositions[this.genomeRepresentations.Length]; ! for(int i = 0; i<this.genomeRepresentations.Length;i++) ! { ! weightedPositions[i] = ! new WeightedPositions(GenomeRepresentation.GetWeightsArray(this.genomeRepresentations[i].WeightsForSignedTickers), ! new SignedTickers(this.genomeRepresentations[i].SignedTickers)); ! ! } this.endOfDayStrategy = new FixedLevelOscillatorBiasedPVONoThresholdsStrategy( ! this.account , weightedPositions, this.genomeRepresentations.Length, this.stopLoss, *************** *** 165,190 **** private void run_setStrategy_setBiasedPVOStrategy() { ! int numberOfTickersToBeChosen = ! GenomeRepresentation.GetSignedTickers(this.genomeRepresentations[0].SignedTickers).Length; ! string[,] signedTickers = new string[this.genomeRepresentations.Length, numberOfTickersToBeChosen]; ! double[,] tickersPortfolioWeights = new double[this.genomeRepresentations.Length, numberOfTickersToBeChosen]; double[] oversoldThresholds = new double[this.genomeRepresentations.Length]; double[] overboughtThresholds = new double[this.genomeRepresentations.Length]; ! for(int i = 0; i < this.genomeRepresentations.Length; i++) { ! for(int j = 0; j < numberOfTickersToBeChosen; j++) ! { ! signedTickers[i,j] = ! GenomeRepresentation.GetSignedTickers( ! this.genomeRepresentations[i].SignedTickers)[j]; ! tickersPortfolioWeights[i,j] = ! GenomeRepresentation.GetWeightsArray( ! this.genomeRepresentations[i].WeightsForSignedTickers)[j]; ! } oversoldThresholds[i] = this.genomeRepresentations[i].OversoldThreshold; overboughtThresholds[i] = this.genomeRepresentations[i].OverboughtThreshold; } ! this.endOfDayStrategy = new FixedLevelOscillatorBiasedPVOStrategy( ! this.account , signedTickers , tickersPortfolioWeights, oversoldThresholds, overboughtThresholds, overboughtThresholds.Length, --- 150,167 ---- private void run_setStrategy_setBiasedPVOStrategy() { ! WeightedPositions[] weightedPositions = new WeightedPositions[this.genomeRepresentations.Length]; double[] oversoldThresholds = new double[this.genomeRepresentations.Length]; double[] overboughtThresholds = new double[this.genomeRepresentations.Length]; ! for(int i = 0; i<this.genomeRepresentations.Length;i++) { ! weightedPositions[i] = ! new WeightedPositions(GenomeRepresentation.GetWeightsArray(this.genomeRepresentations[i].WeightsForSignedTickers), ! new SignedTickers(this.genomeRepresentations[i].SignedTickers)); oversoldThresholds[i] = this.genomeRepresentations[i].OversoldThreshold; overboughtThresholds[i] = this.genomeRepresentations[i].OverboughtThreshold; } ! ! this.endOfDayStrategy = new FixedLevelOscillatorBiasedPVOStrategy( ! this.account , weightedPositions, oversoldThresholds, overboughtThresholds, overboughtThresholds.Length, *************** *** 195,225 **** private void run_setStrategy() { ! string[] signedTickers = genomeRepresentations[0].SignedTickers.Split(";".ToCharArray()); ! double[] weightsForSignedTickers = ! GenomeRepresentation.GetWeightsArray(this.genomeRepresentations[0].WeightsForSignedTickers); ! switch (this.strategyType) { case StrategyType.OpenToCloseDaily: this.endOfDayStrategy = new OpenToCloseDailyStrategy( ! this.account , signedTickers, ! weightsForSignedTickers ); break; case StrategyType.OpenToCloseWeekly: this.endOfDayStrategy = new OpenToCloseWeeklyStrategy( ! this.account , signedTickers ); break; case StrategyType.CloseToOpenDaily: this.endOfDayStrategy = new CloseToOpenDailyStrategy( ! this.account , signedTickers ); break; case StrategyType.OpenToCloseCloseToOpenDaily: this.endOfDayStrategy = new OTC_CTODailyStrategy( ! this.account , signedTickers , weightsForSignedTickers); break; case StrategyType.FixedPeriodOscillator: this.endOfDayStrategy = new FixedPeriodOscillatorStrategy( ! this.account , signedTickers , weightsForSignedTickers, this.numDaysForOscillatorStrategy , this.numDaysForOscillatorStrategy ); --- 172,200 ---- private void run_setStrategy() { ! WeightedPositions weightedPositions = ! this.run_getWeightedPositions(this.genomeRepresentations[0]); ! switch (this.strategyType) { case StrategyType.OpenToCloseDaily: this.endOfDayStrategy = new OpenToCloseDailyStrategy( ! this.account , weightedPositions ); break; case StrategyType.OpenToCloseWeekly: this.endOfDayStrategy = new OpenToCloseWeeklyStrategy( ! this.account , weightedPositions ); break; case StrategyType.CloseToOpenDaily: this.endOfDayStrategy = new CloseToOpenDailyStrategy( ! this.account , weightedPositions ); break; case StrategyType.OpenToCloseCloseToOpenDaily: this.endOfDayStrategy = new OTC_CTODailyStrategy( ! this.account , weightedPositions); break; case StrategyType.FixedPeriodOscillator: this.endOfDayStrategy = new FixedPeriodOscillatorStrategy( ! this.account , weightedPositions, this.numDaysForOscillatorStrategy , this.numDaysForOscillatorStrategy ); *************** *** 228,232 **** case StrategyType.ExtremeCounterTrend: this.endOfDayStrategy = new ExtremeCounterTrendStrategy( ! this.account , signedTickers , weightsForSignedTickers, this.numDaysForOscillatorStrategy, this.portfolioType); break; --- 203,207 ---- case StrategyType.ExtremeCounterTrend: this.endOfDayStrategy = new ExtremeCounterTrendStrategy( ! this.account , weightedPositions, this.numDaysForOscillatorStrategy, this.portfolioType); break; *************** *** 234,243 **** case StrategyType.ImmediateTrendFollower: this.endOfDayStrategy = new ImmediateTrendFollowerStrategy( ! this.account , signedTickers , weightsForSignedTickers, this.numDaysForOscillatorStrategy ); break; case StrategyType.PortfolioValueOscillator: this.endOfDayStrategy = new FixedLevelOscillatorPVOStrategy( ! this.account , signedTickers , weightsForSignedTickers, this.genomeRepresentations[0].OversoldThreshold, this.genomeRepresentations[0].OverboughtThreshold, this.numDaysForOscillatorStrategy ); --- 209,218 ---- case StrategyType.ImmediateTrendFollower: this.endOfDayStrategy = new ImmediateTrendFollowerStrategy( ! this.account , weightedPositions, this.numDaysForOscillatorStrategy ); break; case StrategyType.PortfolioValueOscillator: this.endOfDayStrategy = new FixedLevelOscillatorPVOStrategy( ! this.account , weightedPositions, this.genomeRepresentations[0].OversoldThreshold, this.genomeRepresentations[0].OverboughtThreshold, this.numDaysForOscillatorStrategy ); *************** *** 282,286 **** EquityLine equityLineForWeightedPositions = weightedPositions.GetVirtualEquityLine( ! 30000 , report.AccountReport.EquityLine ); report.AddEquityLine( equityLineForWeightedPositions , color ); --- 257,261 ---- EquityLine equityLineForWeightedPositions = weightedPositions.GetVirtualEquityLine( ! 15000 , report.AccountReport.EquityLine ); report.AddEquityLine( equityLineForWeightedPositions , color ); Index: ImmediateTrendFollowerStrategy.cs =================================================================== RCS file: /cvsroot/q... [truncated message content] |
|
From: Marco M. <mi...@us...> - 2007-08-29 09:40:21
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/SimpleOHTest In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv8862/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/SimpleOHTest Modified Files: EndOfDayTimerHandlerSimpleOHTest.cs RunSimpleOHTest.cs Log Message: Minor changes to the strategy based on the simple over reaction hypothesis Index: RunSimpleOHTest.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/SimpleOHTest/RunSimpleOHTest.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunSimpleOHTest.cs 9 Apr 2007 18:23:49 -0000 1.1 --- RunSimpleOHTest.cs 29 Aug 2007 09:40:11 -0000 1.2 *************** *** 37,47 **** /// Script that implements the SimpleOHTest strategy: /// at each open, l long positions and s short positions will be open, ! /// buying and shorting, accordingly, the l tickers among the ! /// b best that more moves down (at open) and the s tickers among the w worst ! /// that more moves up (at open). /// The fundamental of the strategy should be the fact (to be verified ...) ! /// that overreactions may be followed by opposite overreactions. ! /// For chosing the b best and w worst tickers it is considered just the ! /// previous close. /// At each close, open positions are closed. /// </summary> --- 37,47 ---- /// Script that implements the SimpleOHTest strategy: /// at each open, l long positions and s short positions will be open, ! /// buying and shorting, accordingly, the l worst tickers ! /// and the s best tickers. ! /// For chosing the best and worst tickers just the ! /// previous close to close ratio is considered. /// The fundamental of the strategy should be the fact (to be verified ...) ! /// that great moves are probably overreactions that may be followed by opposite moves (corrections). ! /// At each close, open positions are closed. /// </summary> *************** *** 53,58 **** private string benchmark; private int numberOfEligibleTickers; ! private int numOfBestTickers; ! private int numOfWorstTickers; private int numOfTickersForBuying; private int numOfTickersForShortSelling; --- 53,57 ---- private string benchmark; private int numberOfEligibleTickers; ! private int lengthInDaysForPerformance; private int numOfTickersForBuying; private int numOfTickersForShortSelling; *************** *** 66,71 **** public RunSimpleOHTest(string tickerGroupID, string benchmark, ! int numberOfEligibleTickers, int numOfBestTickers, ! int numOfWorstTickers, int numOfTickersForBuying, int numOfTickersForShortSelling, DateTime startDate, DateTime endDate, --- 65,70 ---- public RunSimpleOHTest(string tickerGroupID, string benchmark, ! int numberOfEligibleTickers, int lengthInDaysForPerformance, ! int numOfTickersForBuying, int numOfTickersForShortSelling, DateTime startDate, DateTime endDate, *************** *** 75,80 **** this.benchmark = benchmark; this.numberOfEligibleTickers = numberOfEligibleTickers; ! this.numOfBestTickers = numOfBestTickers; ! this.numOfWorstTickers = numOfWorstTickers; this.numOfTickersForBuying = numOfTickersForBuying; this.numOfTickersForShortSelling = numOfTickersForShortSelling; --- 74,78 ---- this.benchmark = benchmark; this.numberOfEligibleTickers = numberOfEligibleTickers; ! this.lengthInDaysForPerformance = lengthInDaysForPerformance; this.numOfTickersForBuying = numOfTickersForBuying; this.numOfTickersForShortSelling = numOfTickersForShortSelling; *************** *** 83,87 **** this.maxRunningHours = maxRunningHours; this.scriptName = "SimpleOHTest"; ! this.historicalQuoteProvider = new HistoricalRawQuoteProvider(); this.endOfDayTimer = new IndexBasedEndOfDayTimer( new EndOfDayDateTime( this.startDate , --- 81,86 ---- this.maxRunningHours = maxRunningHours; this.scriptName = "SimpleOHTest"; ! // this.historicalQuoteProvider = new HistoricalRawQuoteProvider(); ! this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); this.endOfDayTimer = new IndexBasedEndOfDayTimer( new EndOfDayDateTime( this.startDate , *************** *** 93,109 **** { this.startingTimeForScript = DateTime.Now; ! this.account = new Account( "SimpleOH" , this.endOfDayTimer , new HistoricalEndOfDayDataStreamer( this.endOfDayTimer , this.historicalQuoteProvider ) , new HistoricalEndOfDayOrderExecutor( this.endOfDayTimer , this.historicalQuoteProvider ) ); ! EndOfDayTimerHandlerSimpleOHTest endOfDayTimerHandler = new EndOfDayTimerHandlerSimpleOHTest(this.tickerGroupID, this.numberOfEligibleTickers, ! this.numOfBestTickers, this.numOfWorstTickers, ! this.numOfTickersForBuying, this.numOfTickersForShortSelling, this.account, this.benchmark); ! this.endOfDayTimer.MarketOpen += new MarketOpenEventHandler( ! endOfDayTimerHandler.MarketOpenEventHandler ); ! this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( endOfDayTimerHandler.MarketCloseEventHandler ); --- 92,107 ---- { this.startingTimeForScript = DateTime.Now; ! ! this.account = new Account( "SimpleOH" , this.endOfDayTimer , new HistoricalEndOfDayDataStreamer( this.endOfDayTimer , this.historicalQuoteProvider ) , new HistoricalEndOfDayOrderExecutor( this.endOfDayTimer , this.historicalQuoteProvider ) ); ! ! EndOfDayTimerHandlerSimpleOHTest endOfDayTimerHandler = new EndOfDayTimerHandlerSimpleOHTest(this.tickerGroupID, this.numberOfEligibleTickers, ! this.lengthInDaysForPerformance, this.numOfTickersForBuying, this.numOfTickersForShortSelling, this.account, this.benchmark); ! this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( endOfDayTimerHandler.MarketCloseEventHandler ); *************** *** 111,117 **** this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); - - this.endOfDayTimer.OneHourAfterMarketClose += new OneHourAfterMarketCloseEventHandler( - endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler ); this.endOfDayTimer.Start(); --- 109,112 ---- *************** *** 135,146 **** public void SaveScriptResults() { ! string fileName = DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + this.scriptName + "_From_" + this.tickerGroupID + "_elig_" + this.numberOfEligibleTickers + ! "_best_" + this.numOfBestTickers + ! "_worst_" + this.numOfWorstTickers + ! "_forLong_" + this.numOfTickersForBuying + ! "_forShort_" + this.numOfTickersForShortSelling; string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; --- 130,146 ---- public void SaveScriptResults() { ! TimeSpan span; ! span = DateTime.Now.Subtract(this.startingTimeForScript); ! int secondsElapsed = span.Hours * 3600 + span.Minutes * 60 + span.Seconds; ! string fileName = ! "SecondsElapsed_" + ! secondsElapsed.ToString() + "_" + ! DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + this.scriptName + "_From_" + this.tickerGroupID + "_elig_" + this.numberOfEligibleTickers + ! "_Long_" + this.numOfTickersForBuying + ! "_Short_" + this.numOfTickersForShortSelling + ! "_lenInDays_" + this.lengthInDaysForPerformance; string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; *************** *** 150,155 **** this.endOfDayTimer.GetCurrentTime(), this.benchmark, ! new HistoricalRawQuoteProvider() ); ! // new HistoricalAdjustedQuoteProvider()); this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ObjectArchiver.Archive(accountReport, --- 150,155 ---- this.endOfDayTimer.GetCurrentTime(), this.benchmark, ! // new HistoricalRawQuoteProvider() ); ! new HistoricalAdjustedQuoteProvider()); this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ObjectArchiver.Archive(accountReport, Index: EndOfDayTimerHandlerSimpleOHTest.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/SimpleOHTest/EndOfDayTimerHandlerSimpleOHTest.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** EndOfDayTimerHandlerSimpleOHTest.cs 7 Aug 2007 16:44:43 -0000 1.2 --- EndOfDayTimerHandlerSimpleOHTest.cs 29 Aug 2007 09:40:11 -0000 1.3 *************** *** 46,64 **** 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; ! public EndOfDayTimerHandlerSimpleOHTest(string tickerGroupID, int numberOfEligibleTickers, ! int numOfBestTickers, ! int numOfWorstTickers, int numOfTickersForBuying, int numOfTickersForShortSelling, Account account, string benchmark) --- 46,67 ---- 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) *************** *** 66,75 **** 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; --- 69,75 ---- this.tickerGroupID = tickerGroupID; this.numberOfEligibleTickers = numberOfEligibleTickers; + this.lengthInDaysForPerformance = lengthInDaysForPerformance; this.account = account; this.benchmark = benchmark; this.numOfTickersForBuying = numOfTickersForBuying; this.numOfTickersForShortSelling = numOfTickersForShortSelling; *************** *** 116,187 **** 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.numOfTickersForBuying; i++) ! if( (double)orderedRows[i]["gainAtOpen"] > 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.numOfTickersForShortSelling; i++) ! if( (double)orderedRows[i]["lossAtOpen"] > 0 ) ! //at open, current ticker is losing ! this.chosenTickers[i] = (string)orderedRows[i]["ticker"]; } ! private void setChosenTickers() { ! for(int i = 0; i<this.chosenTickers.Length;i++) ! this.chosenTickers[i] = null; ! if( this.bestTickers[0] != null && ! this.worstTickers[0] != null ) { ! this.setChosenTickers_addTickersForBuying(); ! this.setChosenTickers_addTickersForShorting(); } } --- 116,144 ---- 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 ! { ! this.setChosenTickers_addTickersForBuying(); ! this.setChosenTickers_addTickersForShorting(); ! } ! catch(Exception ex) ! {ex = ex;} } } *************** *** 195,209 **** Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! if(this.orders.Count == 0 && this.account.Transactions.Count == 0) ! this.account.AddCash(30000); ! this.setChosenTickers(); ! bool allTickerHasBeenChosen = true; ! for( int i = 0; i<this.chosenTickers.Length; i++) ! { ! if(this.chosenTickers[i] == null) ! allTickerHasBeenChosen = false; ! } ! if(allTickerHasBeenChosen) ! this.openPositions(this.chosenTickers); } --- 152,166 ---- 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); } *************** *** 229,233 **** Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! this.closePositions(); } --- 186,208 ---- Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! if(this.account.Portfolio.Count > 0) ! { ! this.closesElapsedWithSomeOpenPosition++; ! if(this.closesElapsedWithSomeOpenPosition == this.lengthInDaysForPerformance) ! { ! this.closePositions(); ! this.OneHourAfterMarketCloseEventHandler(sender,endOfDayTimingEventArgs); ! this.MarketOpenEventHandler(sender, endOfDayTimingEventArgs); ! this.closesElapsedWithSomeOpenPosition = 0; ! } ! } ! else//this.account.Portfolio.Count == 0 ! { ! if( ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition >= this.lengthInDaysForPerformance ) ! { ! this.OneHourAfterMarketCloseEventHandler(sender,endOfDayTimingEventArgs); ! this.MarketOpenEventHandler(sender, endOfDayTimingEventArgs); ! } ! } } *************** *** 235,239 **** #region OneHourAfterMarketCloseEventHandler ! /// <summary> /// Handles a "One hour after market close" event. --- 210,225 ---- #region OneHourAfterMarketCloseEventHandler ! ! private void oneHourAfterMarketCloseEventHandler_clear() ! { ! this.orders.Clear(); ! this.thereAreEnoughBestTickers = false; ! this.thereAreEnoughWorstTickers = false; ! ! for(int i = 0; i<this.chosenTickers.Length;i++) ! this.chosenTickers[i] = null; ! } ! ! /// <summary> /// Handles a "One hour after market close" event. *************** *** 244,291 **** Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! this.orders.Clear(); ! DateTime currentDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); ! DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); ! //remark from here for DEBUG ! SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice( tickersFromGroup,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); ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromMostLiquid = ! new SelectorByQuotationAtEachMarketDay(lessVolatile.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-30), currentDate, ! this.numberOfEligibleTickers/2, this.benchmark); ! ! SelectorByAverageCloseToClosePerformance bestTickersFromQuoted = ! new SelectorByAverageCloseToClosePerformance(quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(), ! false,currentDate,currentDate,this.bestTickers.Length); ! ! SelectorByAverageCloseToClosePerformance worstTickersFromQuoted = ! new SelectorByAverageCloseToClosePerformance(quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(), ! true,currentDate,currentDate,this.worstTickers.Length); ! DataTable tableOfBestTickers = bestTickersFromQuoted.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 = worstTickersFromQuoted.GetTableOfSelectedTickers(); ! for(int i = 0;i<this.worstTickers.Length;i++) ! if(tableOfWorstTickers.Rows[i][0] != null) ! this.worstTickers[i] = (string)tableOfWorstTickers.Rows[i][0]; // //for DEBUG // //remark from here for real running --- 230,296 ---- Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! this.oneHourAfterMarketCloseEventHandler_clear(); ! DateTime currentDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! int currentDateArrayPositionInTimer = ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition; ! DateTime firstDateForPerformanceComputation = ! (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++) ! { ! if( (double)tableOfBestTickers.Rows[i]["SimpleReturn"] > 0.0 ) ! this.bestTickers[i] = (string)tableOfBestTickers.Rows[i][0]; ! else//not all best tickers have gained ! this.thereAreEnoughBestTickers = false; ! } ! } ! ! DataTable tableOfWorstTickers = worstTickersFromLessVolatile.GetTableOfSelectedTickers(); ! if(tableOfWorstTickers.Rows.Count >= this.worstTickers.Length) ! { ! this.thereAreEnoughWorstTickers = true; ! for(int i = 0;i<this.worstTickers.Length;i++) ! { ! if( (double)tableOfWorstTickers.Rows[i]["SimpleReturn"] < 0.0 ) ! this.worstTickers[i] = (string)tableOfWorstTickers.Rows[i][0]; ! else//not all best tickers have lost ! this.thereAreEnoughWorstTickers = false; ! } ! } // //for DEBUG // //remark from here for real running |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/OTC_CTOTrendFollower In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv7029/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/OTC_CTOTrendFollower Added Files: EndOfDayTimerHandlerOTC_CTOTrendFollower.cs RunEfficientOTC_CTOTrendFollower.cs Log Message: Added strategy based on the hypothesis that portofolios optimized with respect to the Open to Close and Close to Open strategy follow an upward trend for some days ahead (out of sample) --- NEW FILE: EndOfDayTimerHandlerOTC_CTOTrendFollower.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerOTC_CTOTrendFollower.cs Copyright (C) 2007 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.ADT; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Strategies; using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.TechnicalAnalysisTesting.TrendFollowing.OTC_CTOTrendFollower { /// <summary> /// Implements MarketOpenEventHandler, /// TwoMinutesBeforeMarketCloseEventHandler and OneHourAfterMarketCloseEventHandler /// These handlers contain the core strategy for the efficient close to open portfolio! /// </summary> [Serializable] public class EndOfDayTimerHandlerOTC_CTOTrendFollower : EndOfDayTimerHandler { protected int seedForRandomGenerator; private double stopLossLevel; private double accountValueAtOpeningPositions; public EndOfDayTimerHandlerOTC_CTOTrendFollower(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, double targetReturn, double stopLossLevel, 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; this.stopLossLevel = stopLossLevel; } /// <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.account.Transactions.Count == 0) this.account.AddCash(15000); if(this.account.Portfolio.Count == 0) { AccountManager.OpenPositions(this.chosenWeightedPositions, this.account); this.accountValueAtOpeningPositions = this.account.GetMarketValue(); } } private void marketCloseEventHandler_updateTakeProfitCondition() { if( (this.currentAccountValue - this.accountValueAtOpeningPositions)/ this.accountValueAtOpeningPositions > this.targetReturn ) this.takeProfitConditionReached = true; else this.takeProfitConditionReached = false; } private void marketCloseEventHandler_updateStopLossCondition() { if( (this.currentAccountValue - this.accountValueAtOpeningPositions)/ this.accountValueAtOpeningPositions < -this.stopLossLevel ) this.stopLossConditionReached = true; else this.stopLossConditionReached = false; } public override void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { this.currentAccountValue = this.account.GetMarketValue(); this.marketCloseEventHandler_updateStopLossCondition(); this.marketCloseEventHandler_updateTakeProfitCondition(); if( (this.numDaysElapsedSinceLastOptimization == this.numDaysBetweenEachOptimization - 1) || this.stopLossConditionReached || this.takeProfitConditionReached ) 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, 20); 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 GenomeManagerForEfficientOTCCTOPortfolio(setOfTickersToBeOptimized, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, this.targetReturn, this.portfolioType); 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.70; 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.account.Portfolio.Count == 0 ) //it is time to optimize again or //portfolio is empty { this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); //sets tickers to be chosen next Market Open event this.numDaysElapsedSinceLastOptimization = 0; } else { this.numDaysElapsedSinceLastOptimization++; } } #endregion } } --- NEW FILE: RunEfficientOTC_CTOTrendFollower.cs --- /* QuantProject - Quantitative Finance Library RunEfficientOTC_CTOTrendFollower.cs Copyright (C) 2007 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using System.Data; using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.ADT.FileManaging; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Scripting; using QuantProject.Business.Strategies; using QuantProject.Business.Testing; using QuantProject.Business.Timing; using QuantProject.Business.Financial.Accounting.Commissions; using QuantProject.Business.Financial.Accounting.Slippage; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; namespace QuantProject.Scripts.TechnicalAnalysisTesting.TrendFollowing.OTC_CTOTrendFollower { /// <summary> /// Script that aims to anticipate the growing trend /// of a portfolio using the OTC_CTO indicator /// In other words: if a portfolio, in sample, has a /// a good performance with the OTC_CTO strategy, then it should /// gain also (we hope ...) out of sample /// </summary> [Serializable] public class RunEfficientOTC_CTOTrendFollower : RunEfficientPortfolio { protected int numDaysBetweenEachOptimization; private double stopLossLevel; public RunEfficientOTC_CTOTrendFollower(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, double targetReturn, double stopLossLevel, PortfolioType portfolioType, double maxRunningHours, int numDaysBetweenEachOptimization): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, startDate, endDate, targetReturn, portfolioType, maxRunningHours) { //this.ScriptName = "OTC_CTOTrendFollowerSharpeRatioNoCoeff"; this.ScriptName = "OTC_CTOTrendFollowerSharpeRatioWithCoeffOnlyMutation"; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.stopLossLevel = stopLossLevel; } // delete remark delimitations for having ib commission // and a fixed percentage calculation of slippage protected override void run_initializeAccount() { this.account = new Account(this.ScriptName, this.endOfDayTimer , new HistoricalEndOfDayDataStreamer(this.endOfDayTimer , this.historicalQuoteProvider ) , new HistoricalEndOfDayOrderExecutor(this.endOfDayTimer , this.historicalQuoteProvider)//, // new FixedPercentageSlippageManager(this.historicalQuoteProvider, // this.endOfDayTimer,0.08)), ); //new IBCommissionManager()); } protected override void run_initializeEndOfDayTimerHandler() { this.endOfDayTimerHandler = new EndOfDayTimerHandlerOTC_CTOTrendFollower(this.tickerGroupID, this.numberOfEligibleTickers, this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, this.account, this.generationNumberForGeneticOptimizer, this.populationSizeForGeneticOptimizer, this.benchmark, this.targetReturn, this.stopLossLevel, this.portfolioType, this.numDaysBetweenEachOptimization); } protected override void run_initializeHistoricalQuoteProvider() { //this.historicalQuoteProvider = new HistoricalRawQuoteProvider(); this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); } protected override void run_addEventHandlers() { this.endOfDayTimer.MarketOpen += new MarketOpenEventHandler( this.endOfDayTimerHandler.MarketOpenEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.endOfDayTimerHandler.MarketCloseEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); this.endOfDayTimer.OneHourAfterMarketClose += new OneHourAfterMarketCloseEventHandler( this.endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler ); } //necessary far calling RunEfficientPortfolio.Run() //in classes that inherit from this class public override void Run() { base.Run(); } } } |
|
From: Marco M. <mi...@us...> - 2007-08-29 09:33:04
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/BestAndWorst In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3686/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/BestAndWorst Added Files: EndOfDayTimerHandlerBWFollower.cs RunBestAndWorstFollower.cs Log Message: Added Best and Worst Follower strategy, based on the trend following assumption --- NEW FILE: EndOfDayTimerHandlerBWFollower.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerBWFollower.cs Copyright (C) 2007 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.ADT; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.Strategies; using QuantProject.Data; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; namespace QuantProject.Scripts.TechnicalAnalysisTesting.TrendFollowing.BestAndWorst { /// <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 { this.setChosenTickers_addTickersForBuying(); this.setChosenTickers_addTickersForShorting(); } 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); 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 ) { if(this.account.Portfolio.Count > 0) { this.closesElapsedWithSomeOpenPosition++; if(this.closesElapsedWithSomeOpenPosition == this.lengthInDaysForPerformance) { this.closePositions(); this.OneHourAfterMarketCloseEventHandler(sender,endOfDayTimingEventArgs); this.MarketOpenEventHandler(sender, endOfDayTimingEventArgs); this.closesElapsedWithSomeOpenPosition = 0; } } else//this.account.Portfolio.Count == 0 { if( ((IndexBasedEndOfDayTimer)sender).CurrentDateArrayPosition >= this.lengthInDaysForPerformance ) { this.OneHourAfterMarketCloseEventHandler(sender,endOfDayTimingEventArgs); this.MarketOpenEventHandler(sender, endOfDayTimingEventArgs); } } } #endregion #region OneHourAfterMarketCloseEventHandler private void oneHourAfterMarketCloseEventHandler_clear() { this.orders.Clear(); this.thereAreEnoughBestTickers = false; this.thereAreEnoughWorstTickers = false; for(int i = 0; i<this.chosenTickers.Length;i++) 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; DateTime firstDateForPerformanceComputation = (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++) { if( (double)tableOfBestTickers.Rows[i]["SimpleReturn"] > 0.0 ) this.bestTickers[i] = (string)tableOfBestTickers.Rows[i][0]; else//not all best tickers have gained this.thereAreEnoughBestTickers = false; } } DataTable tableOfWorstTickers = worstTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfWorstTickers.Rows.Count >= this.worstTickers.Length) { this.thereAreEnoughWorstTickers = true; for(int i = 0;i<this.worstTickers.Length;i++) { if( (double)tableOfWorstTickers.Rows[i]["SimpleReturn"] < 0.0 ) this.worstTickers[i] = (string)tableOfWorstTickers.Rows[i][0]; else//not all best tickers have lost this.thereAreEnoughWorstTickers = false; } } // //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 } } --- NEW FILE: RunBestAndWorstFollower.cs --- /* QuantProject - Quantitative Finance Library RunBestAndWorstFollower.cs Copyright (C) 2007 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.IO; using QuantProject.ADT.FileManaging; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Presentation.Reporting.WindowsForm; namespace QuantProject.Scripts.TechnicalAnalysisTesting.TrendFollowing.BestAndWorst { /// <summary> /// Script that implements the Best and Worst Follower strategy: /// every n closes, l long positions and s short positions will be open, /// buying and shorting, accordingly, the l worst tickers /// and the s best tickers. /// For chosing the best and worst tickers just the /// previous close to close ratio is considered. /// The fundamental of the strategy should be the fact (to be verified ...) /// that great moves are confirmed the next days /// (just the reversal of simpleOHTest) /// At each close, open positions are closed. /// </summary> [Serializable] public class RunBestAndWorstFollower { private string scriptName; private string tickerGroupID; private string benchmark; private int numberOfEligibleTickers; private int lengthInDaysForPerformance; private int numOfBestTickers; private int numOfWorstTickers; private int numOfTickersForBuying; private int numOfTickersForShortSelling; private DateTime startDate; private DateTime endDate; private double maxRunningHours; private DateTime startingTimeForScript; private Account account; private IHistoricalQuoteProvider historicalQuoteProvider; private IEndOfDayTimer endOfDayTimer; public RunBestAndWorstFollower(string tickerGroupID, string benchmark, int numberOfEligibleTickers, int lengthInDaysForPerformance, int numOfBestTickers, int numOfWorstTickers, int numOfTickersForBuying, int numOfTickersForShortSelling, DateTime startDate, DateTime endDate, double maxRunningHours) { this.tickerGroupID = tickerGroupID; this.benchmark = benchmark; this.numberOfEligibleTickers = numberOfEligibleTickers; this.lengthInDaysForPerformance = lengthInDaysForPerformance; this.numOfBestTickers = numOfBestTickers; this.numOfWorstTickers = numOfWorstTickers; this.numOfTickersForBuying = numOfTickersForBuying; this.numOfTickersForShortSelling = numOfTickersForShortSelling; this.startDate = startDate; this.endDate = endDate; this.maxRunningHours = maxRunningHours; this.scriptName = "BWFollower"; // this.historicalQuoteProvider = new HistoricalRawQuoteProvider(); this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); this.endOfDayTimer = new IndexBasedEndOfDayTimer( new EndOfDayDateTime( this.startDate , EndOfDaySpecificTime.MarketOpen ) , this.benchmark ); } public void Run() { this.startingTimeForScript = DateTime.Now; this.account = new Account( "BestAndWorstFollower" , this.endOfDayTimer , new HistoricalEndOfDayDataStreamer( this.endOfDayTimer , this.historicalQuoteProvider ) , new HistoricalEndOfDayOrderExecutor( this.endOfDayTimer , this.historicalQuoteProvider ) ); EndOfDayTimerHandlerBWFollower endOfDayTimerHandler = new EndOfDayTimerHandlerBWFollower(this.tickerGroupID, this.numberOfEligibleTickers, this.lengthInDaysForPerformance, this.numOfBestTickers, this.numOfWorstTickers, this.numOfTickersForBuying, this.numOfTickersForShortSelling, this.account, this.benchmark); // this.endOfDayTimer.MarketOpen += new MarketOpenEventHandler( // endOfDayTimerHandler.MarketOpenEventHandler ); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( endOfDayTimerHandler.MarketCloseEventHandler ); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); // this.endOfDayTimer.OneHourAfterMarketClose += new OneHourAfterMarketCloseEventHandler( // endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler ); this.endOfDayTimer.Start(); } private void checkDateForReport(Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { if(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime>=this.endDate || DateTime.Now >= this.startingTimeForScript.AddHours(this.maxRunningHours)) //last date is reached by the timer or maxRunning hours //are elapsed from the time script started this.SaveScriptResults(); } private void checkDateForReport_createDirIfNotPresent(string dirPath) { if(!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); } public void SaveScriptResults() { TimeSpan span; span = DateTime.Now.Subtract(this.startingTimeForScript); int secondsElapsed = span.Hours * 3600 + span.Minutes * 60 + span.Seconds; string fileName = "SecondsElapsed_" + secondsElapsed.ToString() + "_" + DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + this.scriptName + "_From_" + this.tickerGroupID + "_elig_" + this.numberOfEligibleTickers + "_best_" + this.numOfBestTickers + "_worst_" + this.numOfWorstTickers + "_Long_" + this.numOfTickersForBuying + "_Short_" + this.numOfTickersForShortSelling + "_lenInDays_" + this.lengthInDaysForPerformance; string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; //default report with numIntervalDays = 1 AccountReport accountReport = this.account.CreateReport(fileName,1, this.endOfDayTimer.GetCurrentTime(), this.benchmark, // new HistoricalRawQuoteProvider() ); new HistoricalAdjustedQuoteProvider()); this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ObjectArchiver.Archive(accountReport, dirNameWhereToSaveReports + fileName + ".qPr"); this.endOfDayTimer.Stop(); } } } |
|
From: Marco M. <mi...@us...> - 2007-08-29 09:20:20
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv28752/b4_Business/a1_Financial/a2_Accounting/h5_Reporting/SummaryRows Added Files: AverageNumberOfTransactionsPerDay.cs Log Message: Added new class for a new line in summary report. Summary has not been modified yet (and so the report), because deserialization doesn't manage old reports at the moment. --- NEW FILE: AverageNumberOfTransactionsPerDay.cs --- /* QuantProject - Quantitative Finance Library AverageNumberOfTransactionsPerDay.cs Copyright (C) 2007 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using QuantProject.ADT.Histories; using QuantProject.ADT.Statistics; using QuantProject.Business.Financial.Accounting.Reporting.Tables; namespace QuantProject.Business.Financial.Accounting.Reporting.SummaryRows { /// <summary> /// Summary row containing the average number of transactions for each market day /// in the backtest's period for /// the account report equity line /// </summary> [Serializable] public class AverageNumberOfTransactionsPerDay : DoubleSummaryRow { public AverageNumberOfTransactionsPerDay( Summary summary ) : base( 1 ) { this.rowDescription = "Average n. of transactions per day"; int totalNumberOfTransactions = summary.AccountReport.Account.Transactions.Count; TimeSpan timeSpanForScript = summary.AccountReport.EndDateTime.DateTime.Subtract(summary.AccountReport.StartDateTime); this.rowValue = (double)totalNumberOfTransactions / (double)timeSpanForScript.Days; } } } |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_WeekEndBounce In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv26481/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_WeekEndBounce Added Files: EndOfDayTimerHandlerDOR_WeekEndBounce.cs RunDOR_WeekEndBounce.cs Log Message: Added files for an implementation of the WeekEnd Bounce Hypothesis --- NEW FILE: RunDOR_WeekEndBounce.cs --- /* QuantProject - Quantitative Finance Library RunDOR_WeekEndBounce.cs Copyright (C) 2007 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.IO; using QuantProject.ADT.FileManaging; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Presentation.Reporting.WindowsForm; namespace QuantProject.Scripts.ArbitrageTesting.OverReactionHypothesis.DoubleOverReaction_WeekEndBounce { /// <summary> /// Script that implements the Double OverReaction Week End Bounce strategy: /// at each Monday open, l long positions and s short positions will be open, /// buying and shorting, accordingly, the l tickers among the /// b best that more moves down (at open) and the s tickers among the w worst /// that more moves up (at open). /// For chosing the b best and w worst tickers the /// given previous lengthInDays Performance is considered. /// The fundamental of the strategy should be the fact (to be verified ...) /// that overreactions may be followed by opposite overreactions. /// At each wednesday open, positions are closed. /// </summary> [Serializable] public class RunDOR_WeekEndBounce { private string scriptName; private string tickerGroupID; private string benchmark; private int numberOfEligibleTickers; private int numOfBestTickers; private int numOfWorstTickers; private int lengthInDaysForPerformance; private int numOfTickersForBuying; private int numOfTickersForShortSelling; private DateTime startDate; private DateTime endDate; private double maxRunningHours; private DateTime startingTimeForScript; private Account account; private IHistoricalQuoteProvider historicalQuoteProvider; private IEndOfDayTimer endOfDayTimer; public RunDOR_WeekEndBounce(string tickerGroupID, string benchmark, int numberOfEligibleTickers, int numOfBestTickers, int numOfWorstTickers, int numOfTickersForBuying, int numOfTickersForShortSelling, DateTime startDate, DateTime endDate, int lengthInDaysForPerformance, double maxRunningHours) { this.tickerGroupID = tickerGroupID; this.benchmark = benchmark; this.numberOfEligibleTickers = numberOfEligibleTickers; this.numOfBestTickers = numOfBestTickers; this.numOfWorstTickers = numOfWorstTickers; this.numOfTickersForBuying = numOfTickersForBuying; this.numOfTickersForShortSelling = numOfTickersForShortSelling; this.startDate = startDate; this.endDate = endDate; this.maxRunningHours = maxRunningHours; this.scriptName = "DoubleOverReaction_WeekEndBounce"; this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); this.endOfDayTimer = new IndexBasedEndOfDayTimer( new EndOfDayDateTime( this.startDate , EndOfDaySpecificTime.MarketOpen ) , this.benchmark ); this.lengthInDaysForPerformance = lengthInDaysForPerformance; } public void Run() { this.startingTimeForScript = DateTime.Now; this.account = new Account( "WeekEndBounce" , this.endOfDayTimer , new HistoricalEndOfDayDataStreamer( this.endOfDayTimer , this.historicalQuoteProvider ) , new HistoricalEndOfDayOrderExecutor( this.endOfDayTimer , this.historicalQuoteProvider ) ); EndOfDayTimerHandlerDOR_WeekEndBounce endOfDayTimerHandler = new EndOfDayTimerHandlerDOR_WeekEndBounce(this.tickerGroupID, this.numberOfEligibleTickers, this.numOfBestTickers, this.numOfWorstTickers, this.lengthInDaysForPerformance, this.numOfTickersForBuying, this.numOfTickersForShortSelling, this.account, this.benchmark); this.endOfDayTimer.MarketOpen += new MarketOpenEventHandler( endOfDayTimerHandler.MarketOpenEventHandler ); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( endOfDayTimerHandler.MarketCloseEventHandler ); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); this.endOfDayTimer.OneHourAfterMarketClose += new OneHourAfterMarketCloseEventHandler( endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler ); this.endOfDayTimer.Start(); } private void checkDateForReport(Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { if(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime>=this.endDate || DateTime.Now >= this.startingTimeForScript.AddHours(this.maxRunningHours)) //last date is reached by the timer or maxRunning hours //are elapsed from the time script started this.SaveScriptResults(); } private void checkDateForReport_createDirIfNotPresent(string dirPath) { if(!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); } public void SaveScriptResults() { TimeSpan span; span = DateTime.Now.Subtract(this.startingTimeForScript); int secondsElapsed = span.Hours * 3600 + span.Minutes * 60 + span.Seconds; string fileName = "SecondsElapsed_" + secondsElapsed.ToString() + "_" + DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + this.scriptName + "_From_" + this.tickerGroupID + "_elig_" + this.numberOfEligibleTickers + "_best_" + this.numOfBestTickers + "_worst_" + this.numOfWorstTickers + "_forLong_" + this.numOfTickersForBuying + "_forShort_" + this.numOfTickersForShortSelling; string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; //default report with numIntervalDays = 1 AccountReport accountReport = this.account.CreateReport( fileName,1, this.endOfDayTimer.GetCurrentTime(), this.benchmark, new HistoricalAdjustedQuoteProvider() ); this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ObjectArchiver.Archive(accountReport, dirNameWhereToSaveReports + fileName + ".qPr"); this.endOfDayTimer.Stop(); } } } --- NEW FILE: EndOfDayTimerHandlerDOR_WeekEndBounce.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerDOR_WeekEndBounce.cs Copyright (C) 2007 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.ADT; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.Strategies; using QuantProject.Data; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; namespace QuantProject.Scripts.ArbitrageTesting.OverReactionHypothesis.DoubleOverReaction_WeekEndBounce { /// <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 { this.setChosenTickers_addTickersForBuying(); this.setChosenTickers_addTickersForShorting(); } 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() { this.orders.Clear(); this.thereAreEnoughBestTickers = false; this.thereAreEnoughWorstTickers = false; for(int i = 0; i<this.chosenTickers.Length;i++) 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++) { if( (double)tableOfBestTickers.Rows[i]["SimpleReturn"] > 0.0 ) this.bestTickers[i] = (string)tableOfBestTickers.Rows[i][0]; else this.thereAreEnoughBestTickers = false; } } DataTable tableOfWorstTickers = worstTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfWorstTickers.Rows.Count >= this.worstTickers.Length) { this.thereAreEnoughWorstTickers = true; for(int i = 0;i<this.worstTickers.Length;i++) { if( (double)tableOfWorstTickers.Rows[i]["SimpleReturn"] < 0.0 ) this.worstTickers[i] = (string)tableOfWorstTickers.Rows[i][0]; else this.thereAreEnoughWorstTickers = false; } } } } #endregion } } |
|
From: Marco M. <mi...@us...> - 2007-08-29 09:11:51
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv17922/b4_Business/a2_Strategies Added Files: AccountManager.cs Log Message: The new AccountManager class provides basic methods for orders'management --- NEW FILE: AccountManager.cs --- /* QuantProject - Quantitative Finance Library AccountManager.cs Copyright (C) 2007 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.Strategies; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Data.DataTables; namespace QuantProject.Business.Strategies { /// <summary> /// Class providing static methods for common operations on /// a given account /// </summary> [Serializable] public class AccountManager { private static ArrayList orders; static AccountManager() { orders = new ArrayList(); } static private string[] getTickersInOpenedPositions(Account account) { Position[] positions = new Position[account.Portfolio.Count]; account.Portfolio.Positions.CopyTo( positions, 0); string[] returnValue = new string[positions.Length]; for( int i = 0; i < positions.Length; i++ ) returnValue[i] = positions[i].Instrument.Key; return returnValue; } static public void ClosePositions(Account account) { string[] tickers = getTickersInOpenedPositions( account ); foreach( string ticker in tickers) account.ClosePosition( ticker ); } #region OpenPositions static private void addWeightedPositionToOrderList(WeightedPosition weightedPosition, Account account) { string ticker = weightedPosition.Ticker; double cashForSinglePosition = account.CashAmount * Math.Abs( weightedPosition.Weight ); long quantity = Convert.ToInt64( Math.Floor( cashForSinglePosition / account.DataStreamer.GetCurrentBid( ticker ) ) ); Order order = new Order( weightedPosition.GetOrderType(), new Instrument( ticker ) , quantity ); orders.Add(order); } /// <summary> /// Modifies the state for the given account, /// opening positions provided by the given weightedPositions /// </summary> static public void OpenPositions(WeightedPositions weightedPositions, Account account) { if(weightedPositions == null || account == null) throw new Exception("Both parameters have to be set to valid objects!"); orders.Clear(); foreach(WeightedPosition weightedPosition in weightedPositions.Values) addWeightedPositionToOrderList( weightedPosition, account ); foreach(object item in orders) account.AddOrder( (Order)item ); } #endregion #region ReversePositions static private double reversePositions_getReversedWeightedPositionsFromAccount_getPositionsAbsoluteValue(Account account) { double totalValue = 0; foreach (Position position in account.Portfolio.Values) totalValue += Math.Abs( account.DataStreamer.GetCurrentBid( position.Instrument.Key ) * position.Quantity ); return totalValue; } static private WeightedPositions reversePositions_getReversedWeightedPositionsFromAccount(Account account) { double positionsAbsoluteValue = reversePositions_getReversedWeightedPositionsFromAccount_getPositionsAbsoluteValue(account); string[] tickers = getTickersInOpenedPositions( account ); double[] weights = new double[tickers.Length]; for(int i = 0; i < tickers.Length; i++) weights[i] = ( account.GetMarketValue( tickers[i] )* account.Portfolio.GetPosition( tickers[i] ).Quantity ) / positionsAbsoluteValue; WeightedPositions returnValue = new WeightedPositions( weights, tickers ); returnValue.Reverse(); return returnValue; } static public void ReversePositions(Account account) { orders.Clear(); WeightedPositions reversedWeightedPositions = reversePositions_getReversedWeightedPositionsFromAccount( account ); ClosePositions(account); OpenPositions( reversedWeightedPositions , account ); } #endregion } // end of class } |
|
From: Marco M. <mi...@us...> - 2007-08-29 09:09:07
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/OTC_CTOTrendFollower In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv14079/OTC_CTOTrendFollower Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/OTC_CTOTrendFollower added to the repository |
|
From: Marco M. <mi...@us...> - 2007-08-29 09:08:37
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/BestAndWorst In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv13561/BestAndWorst Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/BestAndWorst added to the repository |
|
From: Marco M. <mi...@us...> - 2007-08-29 09:07:36
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_WeekEndBounce In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv11907/DoubleOverReaction_WeekEndBounce Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_WeekEndBounce added to the repository |
|
From: Marco M. <mi...@us...> - 2007-08-28 09:36:04
|
Update of /cvsroot/quantproject/QuantProject/b3_Data/DataTables In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv13390/b3_Data/DataTables Modified Files: TickerDataTable.cs Log Message: Fixed minor bugs in GetTickersByPerformanceMethod Index: TickerDataTable.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b3_Data/DataTables/TickerDataTable.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** TickerDataTable.cs 8 Apr 2006 14:20:56 -0000 1.7 --- TickerDataTable.cs 28 Aug 2007 09:35:52 -0000 1.8 *************** *** 160,165 **** QuantProject.Data.DataTables.Quotes quotesOfCurrentTicker = new QuantProject.Data.DataTables.Quotes((string)row[0]); ! firstAvailableQuoteDate = quotesOfCurrentTicker.GetFirstValidQuoteDate(firstQuoteDate); ! lastAvailableQuoteDate = quotesOfCurrentTicker.GetFirstValidQuoteDate(lastQuoteDate); firstQuote = quotesOfCurrentTicker.GetAdjustedClose(firstAvailableQuoteDate); lastQuote = quotesOfCurrentTicker.GetAdjustedClose(lastAvailableQuoteDate); --- 160,165 ---- QuantProject.Data.DataTables.Quotes quotesOfCurrentTicker = new QuantProject.Data.DataTables.Quotes((string)row[0]); ! firstAvailableQuoteDate = quotesOfCurrentTicker.GetQuoteDateOrPreceding(firstQuoteDate); ! lastAvailableQuoteDate = quotesOfCurrentTicker.GetQuoteDateOrPreceding(lastQuoteDate); firstQuote = quotesOfCurrentTicker.GetAdjustedClose(firstAvailableQuoteDate); lastQuote = quotesOfCurrentTicker.GetAdjustedClose(lastAvailableQuoteDate); |
|
From: Marco M. <mi...@us...> - 2007-08-28 09:26:01
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv1175/b4_Business/a2_Strategies Modified Files: WeightedPositions.cs Log Message: Fixed bugs in foreach statements Index: WeightedPositions.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/WeightedPositions.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** WeightedPositions.cs 26 Aug 2007 18:36:30 -0000 1.5 --- WeightedPositions.cs 28 Aug 2007 09:25:32 -0000 1.6 *************** *** 59,63 **** { this.numberOfLongPositions = 0; ! foreach(WeightedPosition weightedPosition in this) if(weightedPosition.IsLong) this.numberOfLongPositions++; --- 59,63 ---- { this.numberOfLongPositions = 0; ! foreach(WeightedPosition weightedPosition in this.Values) if(weightedPosition.IsLong) this.numberOfLongPositions++; *************** *** 73,77 **** { this.numberOfShortPositions = 0; ! foreach(WeightedPosition weightedPosition in this) if(weightedPosition.IsShort) this.numberOfShortPositions++; --- 73,77 ---- { this.numberOfShortPositions = 0; ! foreach(WeightedPosition weightedPosition in this.Values) if(weightedPosition.IsShort) this.numberOfShortPositions++; *************** *** 682,686 **** public void Reverse() { ! foreach(WeightedPosition weightedPosition in this) weightedPosition.Weight = - weightedPosition.Weight; } --- 682,686 ---- public void Reverse() { ! foreach(WeightedPosition weightedPosition in this.Values) weightedPosition.Weight = - weightedPosition.Weight; } |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers/WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3094/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers/WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio Modified Files: WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio.cs Log Message: Bug fixed: now driving positions are actually balanced for equal volatility Index: WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers/WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio/WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio.cs 7 Aug 2007 16:55:22 -0000 1.4 --- WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio.cs 27 Aug 2007 22:24:21 -0000 1.5 *************** *** 28,31 **** --- 28,32 ---- using QuantProject.ADT.Optimizing.Genetic; using QuantProject.ADT.Statistics; + using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.ReturnsManagement; *************** *** 60,64 **** // private DateTime lastOptimizationDate; ! private double minimumPositionWeight; // protected WFLagCandidates wFLagCandidates; --- 61,65 ---- // private DateTime lastOptimizationDate; ! // private double minimumPositionWeight; // protected WFLagCandidates wFLagCandidates; *************** *** 114,118 **** this.timeLineForOptimization = timeLineForOptimization; ! this.minimumPositionWeight = 0.2; // TO DO this value should become a constructor parameter this.equityEvaluator = equityEvaluator; --- 115,119 ---- this.timeLineForOptimization = timeLineForOptimization; ! // this.minimumPositionWeight = 0.2; // TO DO this value should become a constructor parameter this.equityEvaluator = equityEvaluator; *************** *** 289,296 **** { int genePosition = firstGenePosition + i; ! genes[ i ] = this.getTickerIndex( genome , genePosition ); } return genes; } private int[] getTickerRelatedGeneValuesForDrivingPositions( Genome genome ) --- 290,298 ---- { int genePosition = firstGenePosition + i; ! genes[ i ] = genome.Genes()[ genePosition ]; } return genes; } + #region getSignedTickersForDrivingPositions private int[] getTickerRelatedGeneValuesForDrivingPositions( Genome genome ) *************** *** 298,308 **** return this.getGenes( genome , 0 , this.numberOfDrivingPositions ); } ! // private int[] getTickerRelatedGeneValuesForPortfolioPositions( ! // Genome genome ) ! // { ! // return this.getGenes( genome , this.numberOfDrivingPositions , ! // this.numberOfPortfolioPositions ); ! // } ! private void decodeTicker_checkParameters( int geneValue , DataTable eligibleTickers ) { if ( geneValue >= eligibleTickers.Rows.Count ) --- 300,305 ---- return this.getGenes( genome , 0 , this.numberOfDrivingPositions ); } ! private void decodeSignedTicker_checkParameters( ! int geneValue , DataTable eligibleTickers ) { if ( geneValue >= eligibleTickers.Rows.Count ) *************** *** 311,344 **** throw new Exception( "geneValue is too (negative) large for eligibleTickers !!" ); } ! private string decodeTicker( int geneValue , DataTable eligibleTickers ) { string ticker; ! decodeTicker_checkParameters( geneValue , eligibleTickers ); if ( geneValue >= 0 ) // long ticker ticker = ( string )eligibleTickers.Rows[ geneValue ][ 0 ]; else // short ticker ticker = ( string )eligibleTickers.Rows[ -(geneValue+1) ][ 0 ]; ! return ticker; } ! private string[] decodeTickers( int[] tickerRelatedGeneValues , DataTable eligibleTickers ) { ! string[] tickers = new string[ tickerRelatedGeneValues.Length ]; for( int i = 0 ; i < tickerRelatedGeneValues.Length ; i++ ) { ! int currentGeneValue = tickerRelatedGeneValues[ i ]; ! tickers[ i ] = decodeTicker( currentGeneValue , eligibleTickers ); ! ! tickers[ i ] = ! ( string )eligibleTickers.Rows[ currentGeneValue ][ 0 ]; } ! return tickers; } ! private string[] getTickersForDrivingPositions( Genome genome ) { int[] geneValues = this.getTickerRelatedGeneValuesForDrivingPositions( genome ); ! return this.decodeTickers( geneValues , this.eligibleTickersForDrivingWeightedPositions ); } #region getTickersForPortfolioPositions --- 308,359 ---- throw new Exception( "geneValue is too (negative) large for eligibleTickers !!" ); } ! private SignedTicker decodeSignedTicker( int geneValue , ! DataTable eligibleTickers ) { + SignedTicker signedTicker; string ticker; ! decodeSignedTicker_checkParameters( geneValue , eligibleTickers ); if ( geneValue >= 0 ) + { // long ticker ticker = ( string )eligibleTickers.Rows[ geneValue ][ 0 ]; + signedTicker = new SignedTicker( ticker , PositionType.Long ); + } else + { // short ticker ticker = ( string )eligibleTickers.Rows[ -(geneValue+1) ][ 0 ]; ! signedTicker = new SignedTicker( ticker , PositionType.Short ); ! } ! return signedTicker; } ! private SignedTicker decodeSignedTickers( int i , ! int[] tickerRelatedGeneValues , DataTable eligibleTickers ) ! { ! int currentGeneValue = tickerRelatedGeneValues[ i ]; ! return this.decodeSignedTicker( currentGeneValue , eligibleTickers ); ! } ! private SignedTickers decodeSignedTickers( int[] tickerRelatedGeneValues , DataTable eligibleTickers ) { ! SignedTickers signedTickers = new SignedTickers(); for( int i = 0 ; i < tickerRelatedGeneValues.Length ; i++ ) { ! SignedTicker signedTicker = this.decodeSignedTickers( ! i , tickerRelatedGeneValues , eligibleTickers ); ! signedTickers.Add( signedTicker ); } ! return signedTickers; } ! private SignedTickers getSignedTickersForDrivingPositions( Genome genome ) { int[] geneValues = this.getTickerRelatedGeneValuesForDrivingPositions( genome ); ! return this.decodeSignedTickers( geneValues , ! this.eligibleTickersForDrivingWeightedPositions ); ! } ! #endregion getSignedTickersForDrivingPositions ! private string[] getTickersForDrivingPositions( Genome genome ) ! { ! return this.getSignedTickersForDrivingPositions( genome ).Tickers; } #region getTickersForPortfolioPositions *************** *** 378,411 **** // return weightRelatedGeneValuesForDrivingPositions; // } ! private int getTickerIndex( Genome genome , int genePosition ) ! { ! int tickerIndex = genome.GetGeneValue( genePosition ); ! if ( tickerIndex < 0 ) ! // the position is short ! tickerIndex += -this.GetMinValueForGenes( genePosition ); ! return tickerIndex; ! } ! private double getWeight( Genome genome , int genePosition ) ! { ! double weight = 1; ! if ( genome.GetGeneValue( genePosition ) < 0 ) ! // the position is short ! weight = -1; ! return weight; ! } ! private double[] getWeights( Genome genome , int firstGenePosition , int numberOfGenes ) ! { ! double[] weights = new double[ numberOfGenes ]; ! for ( int i = 0 ; i < numberOfGenes ; i++ ) ! { ! int genePosition = firstGenePosition + i; ! weights[ i ] = this.getWeight( genome , genePosition ); ! } ! return weights; ! } ! private double[] getWeightsForDrivingPositions( Genome genome ) ! { ! return this.getWeights( genome , 0 , this.numberOfDrivingPositions ); ! } // private double[] getWeightsForPortfolioPositions( Genome genome ) // { --- 393,426 ---- // return weightRelatedGeneValuesForDrivingPositions; // } ! // private int getTickerIndex( Genome genome , int genePosition ) ! // { ! // int tickerIndex = genome.GetGeneValue( genePosition ); ! // if ( tickerIndex < 0 ) ! // // the position is short ! // tickerIndex += -this.GetMinValueForGenes( genePosition ); ! // return tickerIndex; ! // } ! // private double getWeight( Genome genome , int genePosition ) ! // { ! // double weight = 1; ! // if ( genome.GetGeneValue( genePosition ) < 0 ) ! // // the position is short ! // weight = -1; ! // return weight; ! // } ! // private double[] getWeights( Genome genome , int firstGenePosition , int numberOfGenes ) ! // { ! // double[] weights = new double[ numberOfGenes ]; ! // for ( int i = 0 ; i < numberOfGenes ; i++ ) ! // { ! // int genePosition = firstGenePosition + i; ! // weights[ i ] = this.getWeight( genome , genePosition ); ! // } ! // return weights; ! // } ! // private double[] getWeightsForDrivingPositions( Genome genome ) ! // { ! // return this.getWeights( genome , 0 , this.numberOfDrivingPositions ); ! // } // private double[] getWeightsForPortfolioPositions( Genome genome ) // { *************** *** 414,480 **** // } #region decodeWeightedPositions ! #region getNormalizedWeightValues ! private double getAdditionalWeight( int weightRelatedGeneValue ) ! { ! double midrangeValue = ( ! this.GetMinValueForGenes( 0 ) + this.GetMaxValueForGenes( 0 ) ) / 2; ! double singleWeightFreeRange = 1 - this.minimumPositionWeight; ! double scaleRange = Convert.ToDouble( ! this.GetMinValueForGenes( 0 ) - this.GetMaxValueForGenes( 0 ) ); ! double nonScaledAdditionalWeight = Convert.ToDouble( weightRelatedGeneValue ) - ! midrangeValue; ! double scaledAdditionalWeight = ! nonScaledAdditionalWeight * singleWeightFreeRange / scaleRange; ! return scaledAdditionalWeight; ! } ! private double getNonNormalizedWeightValue( int weightRelatedGeneValue ) ! { ! double additionalWeight = this.getAdditionalWeight( weightRelatedGeneValue ); ! double nonNormalizedWeightValue = 0; ! if ( additionalWeight >= 0 ) ! // the gene value represents a long position ! nonNormalizedWeightValue = this.minimumPositionWeight + additionalWeight; ! else ! // additionalWeight < 0 , i.e. the gene value represents a short position ! nonNormalizedWeightValue = -this.minimumPositionWeight + additionalWeight; ! return nonNormalizedWeightValue; ! } ! private double[] getNonNormalizedWeightValues( int[] weightRelatedGeneValues ) ! { ! double[] nonNormalizedWeightValues = new double[ weightRelatedGeneValues.Length ]; ! for ( int i = 0 ; i < weightRelatedGeneValues.Length ; i++ ) ! nonNormalizedWeightValues[ i ] = ! this.getNonNormalizedWeightValue( weightRelatedGeneValues[ i ] ); ! return nonNormalizedWeightValues; ! } ! private double getNormalizingFactor( double[] nonNormalizedWeightValues ) ! { ! // the absolute value for each nonNormalizedWeightValue is between ! // this.minimumPositionWeight and 1 ! double totalForNonNormalizedWeightValues = BasicFunctions.SumOfAbs( nonNormalizedWeightValues ); ! double normalizingFactor = 1 / totalForNonNormalizedWeightValues; ! return normalizingFactor; ! } ! private double[] getNormalizedWeightValues( double[] nonNormalizedWeightValues , ! double normalizingFactor ) ! { ! return BasicFunctions.MultiplyBy( nonNormalizedWeightValues , normalizingFactor ); ! } ! private double[] getNormalizedWeights( double[] nonNormalizedWeights ) ! { ! double normalizingFactor = this.getNormalizingFactor( nonNormalizedWeights ); ! return getNormalizedWeightValues( nonNormalizedWeights , normalizingFactor ); ! } ! // private double[] getNormalizedWeightValues( int[] weightRelatedGeneValues ) // { ! // double[] nonNormalizedWeightValues = ! // this.getNonNormalizedWeightValues( weightRelatedGeneValues ); ! // return this.getNormalizedWeightValues( nonNormalizedWeightValues ); // } ! #endregion private WeightedPositions decodeWeightedPositions( double[] weights , string[] tickers , DataTable eligibleTickers ) { ! double[] normalizedWeights = this.getNormalizedWeights( weights ); WeightedPositions weightedPositions = new WeightedPositions( normalizedWeights , tickers ); --- 429,496 ---- // } #region decodeWeightedPositions ! // #region getNormalizedWeightValues ! // private double getAdditionalWeight( int weightRelatedGeneValue ) // { ! // double midrangeValue = ( ! // this.GetMinValueForGenes( 0 ) + this.GetMaxValueForGenes( 0 ) ) / 2; ! // double singleWeightFreeRange = 1 - this.minimumPositionWeight; ! // double scaleRange = Convert.ToDouble( ! // this.GetMinValueForGenes( 0 ) - this.GetMaxValueForGenes( 0 ) ); ! // double nonScaledAdditionalWeight = Convert.ToDouble( weightRelatedGeneValue ) - ! // midrangeValue; ! // double scaledAdditionalWeight = ! // nonScaledAdditionalWeight * singleWeightFreeRange / scaleRange; ! // return scaledAdditionalWeight; // } ! // private double getNonNormalizedWeightValue( int weightRelatedGeneValue ) ! // { ! // double additionalWeight = this.getAdditionalWeight( weightRelatedGeneValue ); ! // double nonNormalizedWeightValue = 0; ! // if ( additionalWeight >= 0 ) ! // // the gene value represents a long position ! // nonNormalizedWeightValue = this.minimumPositionWeight + additionalWeight; ! // else ! // // additionalWeight < 0 , i.e. the gene value represents a short position ! // nonNormalizedWeightValue = -this.minimumPositionWeight + additionalWeight; ! // return nonNormalizedWeightValue; ! // } ! // private double[] getNonNormalizedWeightValues( int[] weightRelatedGeneValues ) ! // { ! // double[] nonNormalizedWeightValues = new double[ weightRelatedGeneValues.Length ]; ! // for ( int i = 0 ; i < weightRelatedGeneValues.Length ; i++ ) ! // nonNormalizedWeightValues[ i ] = ! // this.getNonNormalizedWeightValue( weightRelatedGeneValues[ i ] ); ! // return nonNormalizedWeightValues; ! // } ! // private double getNormalizingFactor( double[] nonNormalizedWeightValues ) ! // { ! // // the absolute value for each nonNormalizedWeightValue is between ! // // this.minimumPositionWeight and 1 ! // double totalForNonNormalizedWeightValues = BasicFunctions.SumOfAbs( nonNormalizedWeightValues ); ! // double normalizingFactor = 1 / totalForNonNormalizedWeightValues; ! // return normalizingFactor; ! // } ! // private double[] getNormalizedWeightValues( double[] nonNormalizedWeightValues , ! // double normalizingFactor ) ! // { ! // return BasicFunctions.MultiplyBy( nonNormalizedWeightValues , normalizingFactor ); ! // } ! // private double[] getNormalizedWeights( double[] nonNormalizedWeights ) ! // { ! // double normalizingFactor = this.getNormalizingFactor( nonNormalizedWeights ); ! // return getNormalizedWeightValues( nonNormalizedWeights , normalizingFactor ); ! // } ! //// private double[] getNormalizedWeightValues( int[] weightRelatedGeneValues ) ! //// { ! //// double[] nonNormalizedWeightValues = ! //// this.getNonNormalizedWeightValues( weightRelatedGeneValues ); ! //// return this.getNormalizedWeightValues( nonNormalizedWeightValues ); ! //// } ! // #endregion private WeightedPositions decodeWeightedPositions( double[] weights , string[] tickers , DataTable eligibleTickers ) { ! double[] normalizedWeights = ! WeightedPositions.GetNormalizedWeights( weights ); WeightedPositions weightedPositions = new WeightedPositions( normalizedWeights , tickers ); *************** *** 482,496 **** } #endregion private WeightedPositions decodeDrivingWeightedPositions( Genome genome ) { ! string[] tickersForDrivingPositions = this.getTickersForDrivingPositions( genome ); ! double[] weightsForDrivingPositions = this.getWeightsForDrivingPositions( genome ); ! return decodeWeightedPositions( ! weightsForDrivingPositions , ! tickersForDrivingPositions , ! this.eligibleTickersForDrivingWeightedPositions ); } ! private double[] getNormalizedWeightsForPortfolioPositions() { return WeightedPositions.GetBalancedWeights( this.portfolioSignedTickers , --- 498,530 ---- } #endregion + private double[] getNormalizedWeightsForDrivingPositions( + string[] tickersForDrivingPositions ) + { + return WeightedPositions.GetBalancedWeights( this.portfolioSignedTickers , + this.closeToCloseReturnsManager ); + } private WeightedPositions decodeDrivingWeightedPositions( Genome genome ) { ! SignedTickers signedTickers = ! this.getSignedTickersForDrivingPositions( genome ); ! double[] balancedWeightsForDrivingPositions = ! WeightedPositions.GetBalancedWeights( signedTickers , ! this.closeToCloseReturnsManager ); ! WeightedPositions weightedPositions = new WeightedPositions( ! balancedWeightsForDrivingPositions , signedTickers.Tickers ); ! // string[] tickersForDrivingPositions = ! // this.getTickersForDrivingPositions( genome ); ! // double[] weightsForDrivingPositions = ! // this.getWeightsForDrivingPositions( genome ); ! // double[] balancedWeightsForDrivingPositions = ! // WeightedPositions.GetBalancedWeights( qui!!!! , weightsForDrivingPositions ); ! // return this.decodeWeightedPositions( ! // weightsForDrivingPositions , ! // tickersForDrivingPositions , ! // this.eligibleTickersForDrivingWeightedPositions ); ! return weightedPositions; } ! private double[] getBalancedWeightsForPortfolioPositions() { return WeightedPositions.GetBalancedWeights( this.portfolioSignedTickers , *************** *** 502,512 **** string[] tickersForPortfolioPositions = this.getTickersForPortfolioPositions(); double[] portfolioPositionsWeights = ! this.getNormalizedWeightsForPortfolioPositions(); ! return decodeWeightedPositions( portfolioPositionsWeights , tickersForPortfolioPositions , this.eligibleTickersForPortfolioWeightedPositions ); } ! private WFLagWeightedPositions dedcodeDecodableGenome( Genome genome ) { WeightedPositions drivingWeightedPositions = --- 536,546 ---- string[] tickersForPortfolioPositions = this.getTickersForPortfolioPositions(); double[] portfolioPositionsWeights = ! this.getBalancedWeightsForPortfolioPositions(); ! return this.decodeWeightedPositions( portfolioPositionsWeights , tickersForPortfolioPositions , this.eligibleTickersForPortfolioWeightedPositions ); } ! private WFLagWeightedPositions decodeDecodableGenome( Genome genome ) { WeightedPositions drivingWeightedPositions = *************** *** 532,536 **** if ( this.isDecodable( genome ) ) // genome can be decoded to a WFLagWeightedPositions object ! meaning = this.dedcodeDecodableGenome( genome ); else // genome cannot be decoded to a WFLagWeightedPositions object --- 566,570 ---- if ( this.isDecodable( genome ) ) // genome can be decoded to a WFLagWeightedPositions object ! meaning = this.decodeDecodableGenome( genome ); else // genome cannot be decoded to a WFLagWeightedPositions object |
|
From: Glauco S. <gla...@us...> - 2007-08-27 22:22:10
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv1085/b4_Business/a2_Strategies Modified Files: SignedTickers.cs Log Message: The Tickers property has been added Index: SignedTickers.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/SignedTickers.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** SignedTickers.cs 21 Aug 2007 22:07:15 -0000 1.2 --- SignedTickers.cs 27 Aug 2007 22:22:03 -0000 1.3 *************** *** 55,58 **** --- 55,73 ---- } } + /// <summary> + /// Array of the tickers (without sign) + /// </summary> + public string[] Tickers + { + get + { + string[] arrayForTickers = new string[ List.Count ]; + for ( int i = 0 ; i < List.Count ; i++ ) + { + arrayForTickers[ i ] = ((SignedTicker)(List[ i ])).Ticker; + } + return arrayForTickers; + } + } public SignedTickers() { |
|
From: Glauco S. <gla...@us...> - 2007-08-27 22:21:35
|
Update of /cvsroot/quantproject/QuantProject/b3_Data In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv874/b3_Data Modified Files: b3_Data.csproj Log Message: VSNet automatic change Index: b3_Data.csproj =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b3_Data/b3_Data.csproj,v retrieving revision 1.49 retrieving revision 1.50 diff -C2 -d -r1.49 -r1.50 *** b3_Data.csproj 1 Aug 2007 22:50:17 -0000 1.49 --- b3_Data.csproj 27 Aug 2007 22:21:27 -0000 1.50 *************** *** 144,148 **** <File RelPath = "ExtendedDataTable.cs" ! SubType = "Code" BuildAction = "Compile" /> --- 144,148 ---- <File RelPath = "ExtendedDataTable.cs" ! SubType = "Component" BuildAction = "Compile" /> |
|
From: Marco M. <mi...@us...> - 2007-08-27 17:38:48
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv22797/b4_Business/a2_Strategies Modified Files: WeightedPositions.cs Log Message: Property Tickers has been renamed to "SignedTickers", which is self - describing Index: WeightedPositions.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/WeightedPositions.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** WeightedPositions.cs 21 Aug 2007 22:05:34 -0000 1.4 --- WeightedPositions.cs 26 Aug 2007 18:36:30 -0000 1.5 *************** *** 81,85 **** } ! public SignedTickers Tickers { get { string[] arrayOfTickersWithSign = new string[this.Count]; --- 81,85 ---- } ! public SignedTickers SignedTickers { get { string[] arrayOfTickersWithSign = new string[this.Count]; |
|
From: Marco M. <mi...@us...> - 2007-08-21 22:07:19
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv19148/b4_Business/a2_Strategies Modified Files: SignedTickers.cs Log Message: Added property ArrayForSignedTickers Index: SignedTickers.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/SignedTickers.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** SignedTickers.cs 7 Aug 2007 16:38:21 -0000 1.1 --- SignedTickers.cs 21 Aug 2007 22:07:15 -0000 1.2 *************** *** 40,43 **** --- 40,58 ---- } } + public string[] ArrayForSignedTickers + { + get + { + string[] arrayForSignedTickers = new string[ List.Count ]; + for ( int i = 0 ; i < List.Count ; i++ ) + { + if( ((SignedTicker)(List[ i ])).IsLong ) + arrayForSignedTickers[ i ] = ((SignedTicker)(List[ i ])).Ticker; + else //ticker is short + arrayForSignedTickers[ i ] = "-"+((SignedTicker)(List[ i ])).Ticker; + } + return arrayForSignedTickers; + } + } public SignedTickers() { |
|
From: Marco M. <mi...@us...> - 2007-08-21 22:06:40
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv18216/b4_Business/a2_Strategies Modified Files: SignedTicker.cs Log Message: The two public static methods GetLastNightReturn and GetCloseToCloseReturn have been moved to the WeightedPositions class (where now they are instance methods) Index: SignedTicker.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/SignedTicker.cs,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** SignedTicker.cs 7 Aug 2007 16:48:12 -0000 1.9 --- SignedTicker.cs 21 Aug 2007 22:06:35 -0000 1.10 *************** *** 244,339 **** // } // #endregion //GetCloseToCloseReturnsForUnsignedTicker - #region getCloseToClosePortfolioReturn_setReturns - - private static double getCloseToClosePortfolioReturn_setReturns_getReturn( - int returnDay, string[] signedTickers , - double[] tickersWeights, Quotes[] tickersQuotes ) - { - double returnValue = 0.0; - float signOfTicker = 1.0f; - for(int indexForTicker = 0; indexForTicker<signedTickers.Length; indexForTicker++) - { - SignedTicker signedTicker = - new SignedTicker( signedTickers[indexForTicker] ); - if( signedTicker.IsLong ) - signOfTicker = 1.0f; - else - signOfTicker = -1.0f; - - returnValue += - signOfTicker * - ((float)tickersQuotes[indexForTicker].Rows[returnDay][Quotes.AdjustedCloseToCloseRatio] - 1.0f)* - (float)tickersWeights[indexForTicker]; - } - return returnValue; - } - - private static void getCloseToClosePortfolioReturn_setReturns(double[] returnsToSet, - string[] signedTickers, - double[] tickersWeights, - Quotes[] tickersQuotes ) - { - for(int i = 0; i < returnsToSet.Length; i++) - { - returnsToSet[i] = - getCloseToClosePortfolioReturn_setReturns_getReturn( - i,signedTickers,tickersWeights,tickersQuotes); - } - } - #endregion - - /// <summary> - /// Gets portfolio's return for a given period, for given tickers - /// </summary> - /// <param name="signedTickers">Array of signed tickers that compose the portfolio</param> - /// <param name="tickersWeights">Array of weights for tickers - the same order has to be provided!</param> - /// <param name="startDate">Start date for the period for which return has to be computed</param> - /// <param name="endDate">End date for the period for which return has to be computed</param> - public static double GetCloseToClosePortfolioReturn(string[] signedTickers, - double[] tickersWeights, - DateTime startDate, - DateTime endDate ) - { - const double initialEquity = 1.0; - double equityValue = initialEquity; - Quotes[] tickersQuotes = new Quotes[signedTickers.Length]; - for(int i = 0; i<signedTickers.Length; i++) - { - tickersQuotes[i] = new Quotes(SignedTicker.GetTicker(signedTickers[i]), - startDate, endDate); - if(tickersQuotes[i].Rows.Count == 0) - //no quotes are available at the given period - throw new MissingQuotesException(SignedTicker.GetTicker(signedTickers[i]), - startDate, endDate); - } - double[] returns = new double[tickersQuotes[0].Rows.Count]; - getCloseToClosePortfolioReturn_setReturns(returns,signedTickers, - tickersWeights, tickersQuotes); - for(int i = 0; i < returns.Length; i++) - equityValue = - equityValue + equityValue * returns[i]; - - return (equityValue - initialEquity)/initialEquity; - } - - /// <summary> - /// Gets portfolio's return for a given period, for the given tickers - /// </summary> - /// <param name="signedTickers">Array of signed tickers that compose the portfolio (each ticker has the same weight)</param> - /// <param name="startDate">Start date for the period for which return has to be computed</param> - /// <param name="endDate">End date for the period for which return has to be computed</param> - public static double GetCloseToClosePortfolioReturn(string[] signedTickers, - DateTime startDate, - DateTime endDate ) - { - double[] tickersWeights = new double[signedTickers.Length]; - for(int i = 0; i<signedTickers.Length; i++) - tickersWeights[i] = 1.0/signedTickers.Length; - - return GetCloseToClosePortfolioReturn( - signedTickers,tickersWeights, startDate, endDate); - - } /// <summary> --- 244,248 ---- *************** *** 386,431 **** // } // - private static double getLastNightPortfolioReturn(float[] tickersLastNightReturns, - double[] tickersWeights) - { - double returnValue = 0.0; - for(int i = 0; i<tickersLastNightReturns.Length; i++) - returnValue += tickersLastNightReturns[i]*(float)tickersWeights[i]; - - return returnValue; - } - - private static float getLastNightPortfolioReturn_getLastNightReturnForTicker(string ticker, - DateTime lastMarketDay, DateTime today) - { - Quotes tickerQuotes = new Quotes(ticker, lastMarketDay, today); - return ( (float)tickerQuotes.Rows[1]["quOpen"] * - (float)tickerQuotes.Rows[1]["quAdjustedClose"]/ - (float)tickerQuotes.Rows[1]["quClose"] ) / - (float)tickerQuotes.Rows[0]["quAdjustedClose"] - 1; - } - - - /// <summary> - /// Gets portfolio's last night return for the given tickers - /// </summary> - /// <param name="signedTickers">Array of signed tickers that compose the portfolio</param> - /// <param name="tickersWeights">Array of weights for tickers - the same order has to be provided!</param> - /// <param name="lastMarketDay">The last market date before today</param> - /// <param name="today">today</param> - public static double GetLastNightPortfolioReturn(string[] signedTickers, - double[] tickersWeights, - DateTime lastMarketDay, - DateTime today) - { - float[] tickersLastNightReturns = new float[signedTickers.Length]; - for(int i = 0; i<signedTickers.Length; i++) - { - tickersLastNightReturns[i] = - getLastNightPortfolioReturn_getLastNightReturnForTicker( - SignedTicker.GetTicker(signedTickers[i]), lastMarketDay, today ); - } - return getLastNightPortfolioReturn(tickersLastNightReturns, tickersWeights); - } private static string[] getSignedTickersArray( ICollection signedTickers ) --- 295,298 ---- |
|
From: Marco M. <mi...@us...> - 2007-08-21 22:06:07
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv17652/b4_Business/a2_Strategies Modified Files: WeightedPositions.cs Log Message: Added to the class: - new property "Tickers" (SignedTickers type); - new constructor with only one parameter (SignedTicker signedTicker); - instance methods GetLastNightReturn adn GetCloseToCloseReturn (they were static methods in SignedTicker class). Index: WeightedPositions.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/WeightedPositions.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** WeightedPositions.cs 15 Aug 2007 19:24:26 -0000 1.3 --- WeightedPositions.cs 21 Aug 2007 22:05:34 -0000 1.4 *************** *** 30,33 **** --- 30,34 ---- using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Timing; + using QuantProject.Data; using QuantProject.Data.DataTables; *************** *** 79,83 **** } } ! private void weightedPositions_default( double[] normalizedWeightValues , --- 80,97 ---- } } ! ! public SignedTickers Tickers { ! get { ! string[] arrayOfTickersWithSign = new string[this.Count]; ! for(int i = 0; i < this.Count; i++) ! { ! if(this[i].IsShort) ! arrayOfTickersWithSign[i] = "-" + this[i].Ticker; ! else ! arrayOfTickersWithSign[i] = this[i].Ticker; ! } ! return new SignedTickers(arrayOfTickersWithSign); ! } ! } private void weightedPositions_default( double[] normalizedWeightValues , *************** *** 117,120 **** --- 131,153 ---- } + /// <summary> + /// It creates a new instance with all equal weights for + /// the given SignedTickers object + /// </summary> + public WeightedPositions( SignedTickers signedTickers ) + { + string[] unsignedTickers = new string [ signedTickers.Count ]; + double[] allEqualSignedWeights = + new double[ signedTickers.Count ]; + for(int i = 0; i < signedTickers.Count; i++) + { + unsignedTickers[i] = signedTickers[i].Ticker; + allEqualSignedWeights[i] = + signedTickers[i].Multiplier / (double)signedTickers.Count; + } + this.weightedPositions_default( allEqualSignedWeights, + unsignedTickers ); + } + #region checkParameters private void checkParameters_checkDoubleTickers( string[] tickers ) *************** *** 561,564 **** --- 594,679 ---- return openToCloseReturn; } + + #region getLastNightReturn + private double getLastNightReturn( float[] weightedPositionsLastNightReturns ) + { + double returnValue = 0.0; + for(int i = 0; i<weightedPositionsLastNightReturns.Length; i++) + returnValue += weightedPositionsLastNightReturns[i]*((WeightedPosition)this[i]).Weight; + return returnValue; + } + private float getLastNightReturn_getLastNightReturnForTicker(string ticker, + DateTime lastMarketDay, DateTime today) + { + Quotes tickerQuotes = new Quotes(ticker, lastMarketDay, today); + return ( ( (float)tickerQuotes.Rows[1]["quOpen"] * + (float)tickerQuotes.Rows[1]["quAdjustedClose"] / + (float)tickerQuotes.Rows[1]["quClose"] ) / + (float)tickerQuotes.Rows[0]["quAdjustedClose"] - 1 ); + } + #endregion + + /// <summary> + /// Gets the last night return for the current instance + /// </summary> + /// <param name="lastMarketDay">The last market date before today</param> + /// <param name="today">today</param> + public double GetLastNightReturn( DateTime lastMarketDay , DateTime today ) + { + float[] weightedPositionsLastNightReturns = new float[this.Count]; + for(int i = 0; i<this.Count; i++) + weightedPositionsLastNightReturns[i] = + this.getLastNightReturn_getLastNightReturnForTicker( + ((WeightedPosition)this[i]).Ticker, lastMarketDay, today ); + return getLastNightReturn( weightedPositionsLastNightReturns ); + } + + private double getCloseToCloseReturn_setReturns_getReturn( + int returnDayIndex, Quotes[] tickersQuotes ) + { + double returnValue = 0.0; + for(int indexForTicker = 0; indexForTicker<this.Count; indexForTicker++) + returnValue += + ((float)tickersQuotes[indexForTicker].Rows[returnDayIndex][Quotes.AdjustedCloseToCloseRatio] - 1.0f)* + (float)this[indexForTicker].Weight; + return returnValue; + } + private void getCloseToCloseReturn_setReturns( double[] returnsToSet, + Quotes[] tickersQuotes ) + { + for(int i = 0; i < returnsToSet.Length; i++) + { + returnsToSet[i] = + getCloseToCloseReturn_setReturns_getReturn(i,tickersQuotes); + } + } + /// <summary> + /// Gets portfolio's return for a given period, for the current instance + /// of weighted positions + /// </summary> + /// <param name="startDate">Start date for the period for which return has to be computed</param> + /// <param name="endDate">End date for the period for which return has to be computed</param> + public double GetCloseToCloseReturn(DateTime startDate,DateTime endDate ) + { + const double initialEquity = 1.0; + double equityValue = initialEquity; + Quotes[] tickersQuotes = new Quotes[this.Count]; + for(int i = 0; i < this.Count; i++) + { + tickersQuotes[i] = new Quotes( this[i].Ticker,startDate, endDate ); + if(tickersQuotes[i].Rows.Count == 0) + //no quotes are available at the given period + throw new MissingQuotesException(this[i].Ticker, + startDate, endDate); + } + double[] returns = new double[tickersQuotes[0].Rows.Count]; + getCloseToCloseReturn_setReturns(returns,tickersQuotes); + for(int i = 0; i < returns.Length; i++) + equityValue = + equityValue + equityValue * returns[i]; + + return (equityValue - initialEquity)/initialEquity; + } + /// <summary> /// Reverse the sign of each weight for each position in the current instance: |
|
From: Marco M. <mi...@us...> - 2007-08-21 21:52:32
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv8463/b1_ADT/Optimizing/Genetic Modified Files: GeneticOptimizer.cs Genome.cs Log Message: The Property HasBeenChanged has been renamed to HasBeenMutated. This property is now set by the genetic optimizer directly after the call of the IGenomeManager's Mutate method (this is now more logical and direct than before). Index: Genome.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic/Genome.cs,v retrieving revision 1.18 retrieving revision 1.19 diff -C2 -d -r1.18 -r1.19 *** Genome.cs 29 Jun 2007 15:18:21 -0000 1.18 --- Genome.cs 21 Aug 2007 21:52:24 -0000 1.19 *************** *** 39,43 **** private object meaning; private bool hasBeenCloned; ! private bool hasBeenChanged; private IGenomeManager genomeManager; --- 39,43 ---- private object meaning; private bool hasBeenCloned; ! private bool hasBeenMutated; private IGenomeManager genomeManager; *************** *** 53,62 **** /// <summary> ! /// Returns true if a gene has been set ! /// by calling SetGeneValue /// </summary> ! public bool HasBeenChanged { ! get{return this.hasBeenChanged;} } --- 53,63 ---- /// <summary> ! /// Returns true if a gene has been mutated ! /// through a IGenomeManager Mutate method /// </summary> ! public bool HasBeenMutated { ! get{return this.hasBeenMutated;} ! set{this.hasBeenMutated = value;} } *************** *** 204,208 **** //the current generation number is stored this.generation = this.geneticOptimizer.GenerationCounter; - this.hasBeenChanged = true; } --- 205,208 ---- Index: GeneticOptimizer.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic/GeneticOptimizer.cs,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** GeneticOptimizer.cs 4 Aug 2007 19:57:47 -0000 1.25 --- GeneticOptimizer.cs 21 Aug 2007 21:52:23 -0000 1.26 *************** *** 336,340 **** System.Console.WriteLine("\r\n" + this.GenerationCounter + " " + genomeNumber + " " + genes + " " + ((Genome)this.currentGeneration[i]).Fitness + " " + ! ((Genome)this.currentGeneration[i]).HasBeenChanged.ToString() + " " + ((Genome)this.currentGeneration[i]).HasBeenCloned.ToString() + " " + ((Genome)this.currentGeneration[i]).Generation + " " + --- 336,340 ---- System.Console.WriteLine("\r\n" + this.GenerationCounter + " " + genomeNumber + " " + genes + " " + ((Genome)this.currentGeneration[i]).Fitness + " " + ! ((Genome)this.currentGeneration[i]).HasBeenMutated.ToString() + " " + ((Genome)this.currentGeneration[i]).HasBeenCloned.ToString() + " " + ((Genome)this.currentGeneration[i]).Generation + " " + *************** *** 342,346 **** // w.Write("\r\n" + this.GenerationCounter + " " + genomeNumber + " " + genes + " " + // ((Genome)this.currentGeneration[i]).Fitness + " " + ! // ((Genome)this.currentGeneration[i]).HasBeenChanged.ToString() + " " + // ((Genome)this.currentGeneration[i]).HasBeenCloned.ToString() + " " + // ((Genome)this.currentGeneration[i]).Generation + " " + --- 342,346 ---- // w.Write("\r\n" + this.GenerationCounter + " " + genomeNumber + " " + genes + " " + // ((Genome)this.currentGeneration[i]).Fitness + " " + ! // ((Genome)this.currentGeneration[i]).HasBeenMutated.ToString() + " " + // ((Genome)this.currentGeneration[i]).HasBeenCloned.ToString() + " " + // ((Genome)this.currentGeneration[i]).Generation + " " + *************** *** 491,495 **** { if( GenomeManagement.RandomGenerator.Next(0,101) < (int)(this.mutationRate*100) ) ! this.genomeManager.Mutate(g); } } --- 491,498 ---- { if( GenomeManagement.RandomGenerator.Next(0,101) < (int)(this.mutationRate*100) ) ! { ! this.genomeManager.Mutate(g); ! g.HasBeenMutated = true; ! } } } |
|
From: Glauco S. <gla...@us...> - 2007-08-15 19:26:49
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagBruteForceOptimizableItemManager In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3978/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagBruteForceOptimizableItemManager Modified Files: WFLagFixedPortfolioBruteForceOptParamManagerWithPortfolioNormalizedVolatility.cs Log Message: The WeigthedPositions class has been moved from the QuantProject.Scripts.WalkForwardTesting.WalkForwardLag namespace to the QuantProject.Business.Strategies namespace. The WalkForwardTesting\WalkForwardLag\WeightedPositions.cs file has been moved from the b7_scripts project, to a2_Strategies\WeightedPositions.cs, in the b4_business project. Index: WFLagFixedPortfolioBruteForceOptParamManagerWithPortfolioNormalizedVolatility.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagBruteForceOptimizableItemManager/WFLagFixedPortfolioBruteForceOptParamManagerWithPortfolioNormalizedVolatility.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** WFLagFixedPortfolioBruteForceOptParamManagerWithPortfolioNormalizedVolatility.cs 3 Nov 2006 16:35:46 -0000 1.3 --- WFLagFixedPortfolioBruteForceOptParamManagerWithPortfolioNormalizedVolatility.cs 15 Aug 2007 19:26:46 -0000 1.4 *************** *** 24,27 **** --- 24,28 ---- using QuantProject.ADT.Statistics; + using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.EquityEvaluation; |