quantproject-developers Mailing List for QuantProject (Page 63)
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...> - 2008-01-14 23:38:40
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv21302/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower Modified Files: GenomeManagerITF.cs Log Message: GenomeManagers have been updated (WeightedPositions have been used instead of CandidateProperties) Index: GenomeManagerITF.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower/GenomeManagerITF.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** GenomeManagerITF.cs 17 Sep 2006 21:48:39 -0000 1.2 --- GenomeManagerITF.cs 14 Jan 2008 23:38:36 -0000 1.3 *************** *** 28,31 **** --- 28,36 ---- using QuantProject.Data; using QuantProject.Data.DataTables; + using QuantProject.Business.DataProviders; + using QuantProject.Business.Timing; + using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; + using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; *************** *** 41,44 **** --- 46,50 ---- { private int numDaysForReturnCalculation; + private ReturnsManager returnsManager; public GenomeManagerITF(DataTable setOfInitialTickers, *************** *** 47,51 **** int numberOfTickersInPortfolio, int numDaysForReturnCalculation, ! PortfolioType portfolioType) : base(setOfInitialTickers, --- 53,58 ---- int numberOfTickersInPortfolio, int numDaysForReturnCalculation, ! PortfolioType portfolioType, ! string benchmark) : base(setOfInitialTickers, *************** *** 54,126 **** numberOfTickersInPortfolio, 0.0, ! portfolioType) { this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.retrieveData(); } ! protected override float[] getArrayOfRatesOfReturn(string ticker) ! { ! float[] returnValue = null; ! Quotes tickerQuotes = new Quotes(ticker, this.firstQuoteDate, this.lastQuoteDate); ! returnValue = ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuotes, ! Quotes.AdjustedCloseToCloseRatio); ! for(int i = 0; i<returnValue.Length; i++) ! returnValue[i] = returnValue[i] - 1.0f; ! ! this.numberOfExaminedReturns = returnValue.Length; ! ! return returnValue; ! } ! ! ! //fitness is a sharpe-ratio based indicator for the equity line resulting ! //from applying the strategy ! public override double GetFitnessValue(Genome genome) { ! this.portfolioRatesOfReturn = this.getPortfolioRatesOfReturn(genome.Genes()); ! ! double[] equityLine = this.getFitnessValue_getEquityLineRates(); ! //return AdvancedFunctions.GetExpectancyScore(equityLine); ! return AdvancedFunctions.GetSharpeRatio(equityLine); } ! private double[] getFitnessValue_getEquityLineRates() ! { ! double[] returnValue = new double[this.PortfolioRatesOfReturn.Length]; ! double K;//initial capital invested at the beginning of the period ! for(int i = this.numDaysForReturnCalculation - 1; ! i<this.PortfolioRatesOfReturn.Length - this.numDaysForReturnCalculation; ! i += this.numDaysForReturnCalculation) { ! K = 1.0; ! for(int j=this.numDaysForReturnCalculation - 1; ! j > -1; j--) ! { ! K = K + K * this.PortfolioRatesOfReturn[i-j]; ! } ! ! for(int t=1;t<this.numDaysForReturnCalculation + 1;t++) ! { ! if(K < 1.0 && this.PortfolioType == PortfolioType.ShortAndLong) ! // if gain of first half period is negative and ! //positions can be reversed ! returnValue[i+t] = - this.PortfolioRatesOfReturn[i+t]; ! else if(K > 1.0) ! //if gain of first half period is positive ! returnValue[i+t] = this.PortfolioRatesOfReturn[i+t]; ! else if(K < 1.0 && this.PortfolioType != PortfolioType.ShortAndLong) ! //if gain of first half period is negative and ! //original positions can't be reversed ! returnValue[i+t] = 0.0;//out of the market ! } ! } return returnValue; ! } ! } - } --- 61,118 ---- numberOfTickersInPortfolio, 0.0, ! portfolioType, ! benchmark) { this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.setReturnsManager(); } ! private void setReturnsManager() { ! EndOfDayDateTime firstEndOfDayDateTime = ! new EndOfDayDateTime(firstQuoteDate, EndOfDaySpecificTime.MarketClose); ! EndOfDayDateTime lastEndOfDayDateTime = ! new EndOfDayDateTime(lastQuoteDate, EndOfDaySpecificTime.MarketClose); ! this.returnsManager = ! new ReturnsManager( new CloseToCloseIntervals( ! firstEndOfDayDateTime, ! lastEndOfDayDateTime, ! this.benchmark, ! this.numDaysForReturnCalculation) , ! new HistoricalAdjustedQuoteProvider() ); } ! private float[] getStrategyReturns_getReturnsActually( ! float[] plainReturns) ! { ! float[] returnValue = new float[plainReturns.Length]; ! returnValue[0] = 0; //a the very first day the ! //first strategy return is equal to 0 because no position ! //has been entered ! float coefficient = 0; ! for(int i = 0; i < returnValue.Length - 1; i++) { ! if( plainReturns[i] > 0 ) ! coefficient = 1;//the strategy follows ... ! else if( plainReturns[i] <= 0 ) ! coefficient = - 1; ! ! returnValue[i + 1] = coefficient * plainReturns[i + 1]; } return returnValue; ! } ! ! protected override float[] getStrategyReturns() ! { ! EndOfDayDateTime firstEndOfDayDateTime = ! new EndOfDayDateTime(firstQuoteDate, EndOfDaySpecificTime.MarketClose); ! EndOfDayDateTime lastEndOfDayDateTime = ! new EndOfDayDateTime(lastQuoteDate, EndOfDaySpecificTime.MarketClose); ! float[] plainReturns = this.weightedPositionsFromGenome.GetReturns( ! this.returnsManager); ! return this.getStrategyReturns_getReturnsActually(plainReturns); ! } } } |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:38:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv21302/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend Modified Files: GenomeManagerECT.cs Log Message: GenomeManagers have been updated (WeightedPositions have been used instead of CandidateProperties) Index: GenomeManagerECT.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend/GenomeManagerECT.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** GenomeManagerECT.cs 17 Sep 2006 21:48:39 -0000 1.4 --- GenomeManagerECT.cs 14 Jan 2008 23:38:36 -0000 1.5 *************** *** 24,31 **** --- 24,37 ---- using System.Data; using System.Collections; + using QuantProject.ADT.Statistics; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Data; using QuantProject.Data.DataTables; + using QuantProject.Business.DataProviders; + using QuantProject.Business.Timing; + using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; + using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; *************** *** 41,158 **** { private int numDaysForReturnCalculation; public GenomeManagerECT(DataTable setOfInitialTickers, ! DateTime firstQuoteDate, ! DateTime lastQuoteDate, ! int numberOfTickersInPortfolio, ! int numDaysForReturnCalculation, ! PortfolioType portfolioType) ! : ! base(setOfInitialTickers, ! firstQuoteDate, ! lastQuoteDate, ! numberOfTickersInPortfolio, ! 0.0, ! portfolioType) { this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.retrieveData(); } ! protected override float[] getArrayOfRatesOfReturn(string ticker) ! { ! float[] returnValue = null; ! Quotes tickerQuotes = new Quotes(ticker, this.firstQuoteDate, this.lastQuoteDate); ! returnValue = ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuotes, ! Quotes.AdjustedCloseToCloseRatio); ! ! ! for(int i = 0; i<returnValue.Length; i++) ! returnValue[i] = returnValue[i] - 1.0f; ! ! this.numberOfExaminedReturns = returnValue.Length; ! ! return returnValue; ! } ! ! //delete remarks if this object inherits from ! //simple genomeManagerForEfficientPortfolio (no coefficients) ! ! // public override object Decode(Genome genome) ! // { ! // ! // string[] arrayOfTickers = new string[genome.Genes().Length]; ! // int indexOfTicker; ! // for(int index = 0; index < genome.Genes().Length; index++) ! // { ! // indexOfTicker = (int)genome.Genes().GetValue(index); ! // arrayOfTickers[index] = this.decode_getTickerCodeForLongOrShortTrade(indexOfTicker); ! // } ! // GenomeMeaning meaning = new GenomeMeaning(arrayOfTickers); ! // return meaning; ! // } ! ! ! //fitness is a sharpe-ratio based indicator for the equity line resulting ! //from applying the strategy ! public override double GetFitnessValue(Genome genome) { ! this.portfolioRatesOfReturn = this.getPortfolioRatesOfReturn(genome.Genes()); ! ! double[] equityLine = this.getFitnessValue_getEquityLineRates(); ! // double sharpeRatioAll = BasicFunctions.SimpleAverage(equityLine)/ ! // BasicFunctions.StdDev(equityLine); ! // double modifiedSharpeRatioAll = BasicFunctions.SimpleAverage(equityLine)/ ! // Math.Pow(BasicFunctions.StdDev(equityLine),0.9); ! ! // double[] equityLineSecondHalf = new double[equityLine.Length/2]; ! // for(int i = 0; i<equityLine.Length/2; i++) ! // equityLineSecondHalf[i] = equityLine[i+equityLine.Length/2]; ! // double sharpeRatioSecondHalf = BasicFunctions.SimpleAverage(equityLineSecondHalf)/ ! // Math.Pow(BasicFunctions.StdDev(equityLineSecondHalf),1.2); ! // return sharpeRatioAll;//*sharpeRatioSecondHalf; ! // return modifiedSharpeRatioAll; ! //return AdvancedFunctions.GetExpectancyScore(equityLine); ! return AdvancedFunctions.GetSharpeRatio(equityLine); ! } ! private double[] getFitnessValue_getEquityLineRates() ! { ! double[] returnValue = new double[this.PortfolioRatesOfReturn.Length]; ! double K;//initial capital invested at the beginning of the period ! for(int i = this.numDaysForReturnCalculation - 1; ! i<this.PortfolioRatesOfReturn.Length - this.numDaysForReturnCalculation; ! i += this.numDaysForReturnCalculation) { ! K = 1.0; ! for(int j=this.numDaysForReturnCalculation - 1; ! j > -1; j--) ! { ! K = K + K * this.PortfolioRatesOfReturn[i-j]; ! } ! ! for(int t=1;t<this.numDaysForReturnCalculation + 1;t++) ! { ! if(K < 1.0) ! // if gain of first half period is negative ! returnValue[i+t] = this.PortfolioRatesOfReturn[i+t]; ! else if(K > 1.0 && this.PortfolioType == PortfolioType.ShortAndLong) ! //if gain of first half period is positive and ! //original positions can be reversed ! returnValue[i+t] = - this.PortfolioRatesOfReturn[i+t]; ! else if(K > 1.0 && this.PortfolioType != PortfolioType.ShortAndLong) ! //if gain of first half period is positive and ! //original positions can't be reversed ! returnValue[i+t] = 0.0;//out of the market ! } ! } return returnValue; ! } ! } - } --- 47,121 ---- { private int numDaysForReturnCalculation; + private ReturnsManager returnsManager; public GenomeManagerECT(DataTable setOfInitialTickers, ! DateTime firstQuoteDate, ! DateTime lastQuoteDate, ! int numberOfTickersInPortfolio, ! int numDaysForReturnCalculation, ! PortfolioType portfolioType, ! string benchmark) ! : ! base(setOfInitialTickers, ! firstQuoteDate, ! lastQuoteDate, ! numberOfTickersInPortfolio, ! 0.0, ! portfolioType, ! benchmark) { this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.setReturnsManager(); } ! private void setReturnsManager() { ! EndOfDayDateTime firstEndOfDayDateTime = ! new EndOfDayDateTime(firstQuoteDate, EndOfDaySpecificTime.MarketClose); ! EndOfDayDateTime lastEndOfDayDateTime = ! new EndOfDayDateTime(lastQuoteDate, EndOfDaySpecificTime.MarketClose); ! this.returnsManager = ! new ReturnsManager( new CloseToCloseIntervals( ! firstEndOfDayDateTime, ! lastEndOfDayDateTime, ! this.benchmark, ! this.numDaysForReturnCalculation) , ! new HistoricalAdjustedQuoteProvider() ); } ! private float[] getStrategyReturns_getReturnsActually( ! float[] plainReturns) ! { ! float[] returnValue = new float[plainReturns.Length]; ! returnValue[0] = 0; //a the very first day the ! //first strategy return is equal to 0 because no position ! //has been entered ! float coefficient = 0; ! for(int i = 0; i < returnValue.Length - 1; i++) { ! if( plainReturns[i] > 0 ) ! //portfolio is overbought ! coefficient = -1; ! else if( plainReturns[i] <= 0 ) ! //portfolio is oversold ! coefficient = 1; ! ! returnValue[i + 1] = coefficient * plainReturns[i + 1]; } return returnValue; ! } ! ! protected override float[] getStrategyReturns() ! { ! EndOfDayDateTime firstEndOfDayDateTime = ! new EndOfDayDateTime(firstQuoteDate, EndOfDaySpecificTime.MarketClose); ! EndOfDayDateTime lastEndOfDayDateTime = ! new EndOfDayDateTime(lastQuoteDate, EndOfDaySpecificTime.MarketClose); ! float[] plainReturns = this.weightedPositionsFromGenome.GetReturns( ! this.returnsManager); ! return this.getStrategyReturns_getReturnsActually(plainReturns); ! } } } |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:38:39
|
Update of /cvsroot/quantproject/QuantProject/b3_Data/Selectors/ByLinearIndipendence In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv21302/b3_Data/Selectors/ByLinearIndipendence Modified Files: GenomeManagerForMaxLinearIndipendenceSelector.cs Log Message: GenomeManagers have been updated (WeightedPositions have been used instead of CandidateProperties) Index: GenomeManagerForMaxLinearIndipendenceSelector.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b3_Data/Selectors/ByLinearIndipendence/GenomeManagerForMaxLinearIndipendenceSelector.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** GenomeManagerForMaxLinearIndipendenceSelector.cs 3 Jan 2007 23:20:15 -0000 1.3 --- GenomeManagerForMaxLinearIndipendenceSelector.cs 14 Jan 2008 23:38:36 -0000 1.4 *************** *** 39,50 **** public class GenomeManagerForMaxLinearIndipendenceSelector : IGenomeManager { ! private DataTable setOfInitialTickers; ! private Candidate[] candidates; ! private DateTime firstQuoteDate; ! private DateTime lastQuoteDate; ! private int genomeSize; ! private int minValueForGenes; ! private int maxValueForGenes; ! private double[,] correlationMatrix; //IGenomeManager implementation for properties --- 39,50 ---- public class GenomeManagerForMaxLinearIndipendenceSelector : IGenomeManager { ! protected DataTable setOfInitialTickers; ! protected Candidate[] candidates; ! protected DateTime firstQuoteDate; ! protected DateTime lastQuoteDate; ! protected int genomeSize; ! protected int minValueForGenes; ! protected int maxValueForGenes; ! protected double[,] correlationMatrix; //IGenomeManager implementation for properties *************** *** 166,170 **** } ! private double getFitnessValue_getCorrelationCoefficient(int i, int j) { int row = i; --- 166,170 ---- } ! protected double getFitnessValue_getCorrelationCoefficient(int i, int j) { int row = i; |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:34:26
|
Update of /cvsroot/quantproject/QuantProject/b3_Data/DataTables In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv19590/b3_Data/DataTables Modified Files: Quotes.cs Log Message: Some code has been cleaned Index: Quotes.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b3_Data/DataTables/Quotes.cs,v retrieving revision 1.34 retrieving revision 1.35 diff -C2 -d -r1.34 -r1.35 *** Quotes.cs 13 Jul 2007 10:07:59 -0000 1.34 --- Quotes.cs 14 Jan 2008 23:34:22 -0000 1.35 *************** *** 307,396 **** return tableToReturn; } - - private static void getTickersByAdjCloseToClosePearsonCorrelationCoefficient_setTickersAdjCloses(out float[][] - tickersReturns, DataTable setOfTickers, DateTime firstQuoteDate, DateTime lastQuoteDate) - - { - tickersReturns = new float[setOfTickers.Rows.Count][]; - for(int i = 0; i<setOfTickers.Rows.Count; i++) - { - DataTable tickerQuoteTable = - QuantProject.DataAccess.Tables.Quotes.GetTickerQuotes((string)setOfTickers.Rows[i][0], - firstQuoteDate, - lastQuoteDate); - tickersReturns[i] = - ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuoteTable,"quAdjustedClose"); - - } - } - - /// <summary> - /// Returns a table containing the Pearson correlation coefficient for the adjusted close values - /// for any possible couple of tickers contained in the given table, for the specified interval - /// </summary> - public static DataTable GetTickersByAdjCloseToClosePearsonCorrelationCoefficient( bool orderByASC, - DataTable setOfTickers, - DateTime firstQuoteDate, - DateTime lastQuoteDate) - - { - if(!setOfTickers.Columns.Contains("CorrelatedTicker")) - setOfTickers.Columns.Add("CorrelatedTicker", System.Type.GetType("System.String")); - if(!setOfTickers.Columns.Contains("PearsonCorrelationCoefficient")) - setOfTickers.Columns.Add("PearsonCorrelationCoefficient", System.Type.GetType("System.Double")); - int initialNumberOfRows = setOfTickers.Rows.Count; - float[][] tickersAdjCloses; - getTickersByAdjCloseToClosePearsonCorrelationCoefficient_setTickersAdjCloses(out tickersAdjCloses, setOfTickers, firstQuoteDate, lastQuoteDate); - for(int j=0; j!= initialNumberOfRows; j++) - { - string firstTicker = (string)setOfTickers.Rows[j][0]; - for(int i = j+1; i!= initialNumberOfRows; i++) - { - string secondTicker = (string)setOfTickers.Rows[i][0]; - DataRow rowToAdd = setOfTickers.NewRow(); - rowToAdd[0] = firstTicker; - rowToAdd["PearsonCorrelationCoefficient"] = -2.0; - //unassigned value for this column - rowToAdd["CorrelatedTicker"] = secondTicker; - try - { - rowToAdd["PearsonCorrelationCoefficient"] = - QuantProject.ADT.Statistics.BasicFunctions.PearsonCorrelationCoefficient( - tickersAdjCloses[j],tickersAdjCloses[i]); - } - catch(Exception ex) - { - ex = ex; - } - finally - { - setOfTickers.Rows.Add(rowToAdd); - } - } - } - ExtendedDataTable.DeleteRows(setOfTickers, 0, initialNumberOfRows - 1); - //delete initial rows that don't contain correlated ticker and Pearson coeff. - return ExtendedDataTable.CopyAndSort(setOfTickers,"PearsonCorrelationCoefficient>-2.0", - "PearsonCorrelationCoefficient", orderByASC); - } - - /// <summary> - /// Returns a table containing the Pearson correlation coefficient for the adjusted close values - /// for any possible couple of tickers contained in the given group of tickers, - /// for the specified interval - /// </summary> - public static DataTable GetTickersByAdjCloseToClosePearsonCorrelationCoefficient( bool orderByASC, - string groupID, - DateTime firstQuoteDate, - DateTime lastQuoteDate) - - { - - DataTable tickersOfGroup = new Tickers_tickerGroups(groupID); - return GetTickersByAdjCloseToClosePearsonCorrelationCoefficient(orderByASC, - tickersOfGroup, - firstQuoteDate, - lastQuoteDate); - } /// <summary> --- 307,310 ---- |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:33:06
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv18649/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower Modified Files: EndOfDayTimerHandlerITF.cs Log Message: Handlers have been updated (minor changes) Index: EndOfDayTimerHandlerITF.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower/EndOfDayTimerHandlerITF.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** EndOfDayTimerHandlerITF.cs 23 Sep 2007 22:08:31 -0000 1.5 --- EndOfDayTimerHandlerITF.cs 14 Jan 2008 23:32:30 -0000 1.6 *************** *** 252,256 **** currentDate, this.numberOfTickersToBeChosen, this.numDaysForReturnCalculation, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, --- 252,256 ---- currentDate, this.numberOfTickersToBeChosen, this.numDaysForReturnCalculation, ! this.portfolioType, this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:33:05
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv18649/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend Modified Files: EndOfDayTimerHandlerECT.cs Log Message: Handlers have been updated (minor changes) Index: EndOfDayTimerHandlerECT.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend/EndOfDayTimerHandlerECT.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** EndOfDayTimerHandlerECT.cs 23 Sep 2007 22:07:56 -0000 1.7 --- EndOfDayTimerHandlerECT.cs 14 Jan 2008 23:32:29 -0000 1.8 *************** *** 25,28 **** --- 25,29 ---- using QuantProject.ADT; + using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; *************** *** 30,33 **** --- 31,36 ---- using QuantProject.Business.Timing; using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; + using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Data; using QuantProject.Data.DataProviders; *************** *** 50,57 **** private double maxAcceptableCloseToCloseDrawdown; private int daysCounterWithPositions; - // private int daysCounterWithRightPositions; - // private int daysCounterWithReversalPositions; - // private bool isReversalPeriodOn = false; - // private bool isTheFirstClose = false; private DateTime lastCloseDate; private IGenomeManager iGenomeManager; --- 53,56 ---- *************** *** 75,86 **** { this.numDaysForReturnCalculation = numDaysForReturnCalculation; - // this.daysCounterWithRightPositions = 0; - // this.daysCounterWithReversalPositions = 0; - // this.isReversalPeriodOn = false; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; this.stopLossConditionReached = false; this.currentAccountValue = 0.0; this.previousAccountValue = 0.0; - // this.numDaysBetweenEachOptimization = 2* numDaysForReturnCalculation; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; --- 74,81 ---- *************** *** 117,125 **** { DateTime initialDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation + 1]["quDate"]; DateTime finalDateForHalfPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! returnValue = this.chosenWeightedPositions.GetCloseToCloseReturn( ! initialDateForHalfPeriod,finalDateForHalfPeriod); } catch(MissingQuotesException ex) --- 112,126 ---- { DateTime initialDateForHalfPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation]["quDate"]; DateTime finalDateForHalfPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! ReturnsManager returnsManager = new ReturnsManager(new CloseToCloseIntervals( ! new EndOfDayDateTime(initialDateForHalfPeriod, ! EndOfDaySpecificTime.MarketClose) , ! new EndOfDayDateTime(finalDateForHalfPeriod, ! EndOfDaySpecificTime.MarketClose) , ! this.benchmark , this.numDaysForReturnCalculation ) , ! new HistoricalAdjustedQuoteProvider() ); ! returnValue = this.chosenWeightedPositions.GetReturn(0,returnsManager); } catch(MissingQuotesException ex) *************** *** 263,267 **** currentDate, this.numberOfTickersToBeChosen, this.numDaysForReturnCalculation, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, --- 264,268 ---- currentDate, this.numberOfTickersToBeChosen, this.numDaysForReturnCalculation, ! this.portfolioType,this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:33:04
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/OTC_CTOTrendFollower In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv18649/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/OTC_CTOTrendFollower Modified Files: EndOfDayTimerHandlerOTC_CTOTrendFollower.cs Log Message: Handlers have been updated (minor changes) Index: EndOfDayTimerHandlerOTC_CTOTrendFollower.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/OTC_CTOTrendFollower/EndOfDayTimerHandlerOTC_CTOTrendFollower.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** EndOfDayTimerHandlerOTC_CTOTrendFollower.cs 29 Aug 2007 09:36:28 -0000 1.1 --- EndOfDayTimerHandlerOTC_CTOTrendFollower.cs 14 Jan 2008 23:32:30 -0000 1.2 *************** *** 164,168 **** this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, --- 164,168 ---- this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType, this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv18649/b7_Scripts/TickerSelectionTesting Modified Files: EndOfDayTimerHandler.cs EndOfDayTimerHandlerCTC.cs EndOfDayTimerHandlerCTCWeekly.cs EndOfDayTimerHandlerCTO.cs EndOfDayTimerHandlerCTO_WorstAtDay.cs EndOfDayTimerHandlerLastChosenPortfolio.cs EndOfDayTimerHandlerOTC.cs EndOfDayTimerHandlerOTC_WorstAtNight.cs EndOfDayTimerHandlerOTCCTO.cs EndOfDayTimerHandlerOTCMultiAccount.cs EndOfDayTimerHandlerOTCMultiday.cs Log Message: Handlers have been updated (minor changes) Index: EndOfDayTimerHandler.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandler.cs,v retrieving revision 1.25 retrieving revision 1.26 diff -C2 -d -r1.25 -r1.26 *** EndOfDayTimerHandler.cs 29 Aug 2007 09:47:09 -0000 1.25 --- EndOfDayTimerHandler.cs 14 Jan 2008 23:32:30 -0000 1.26 *************** *** 37,41 **** /// </summary> [Serializable] ! public class EndOfDayTimerHandler { protected DataTable eligibleTickers; --- 37,41 ---- /// </summary> [Serializable] ! public abstract class EndOfDayTimerHandler { protected DataTable eligibleTickers; *************** *** 233,238 **** //add cash first if(this.account.Transactions.Count == 0) ! this.account.AddCash(15000); ! AccountManager.OpenPositions(this.chosenWeightedPositions, this.account); } --- 233,239 ---- //add cash first if(this.account.Transactions.Count == 0) ! this.account.AddCash(15000); ! if(this.chosenWeightedPositions != null) ! AccountManager.OpenPositions(this.chosenWeightedPositions, this.account); } *************** *** 247,265 **** } ! public virtual void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } ! public virtual void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } ! public virtual void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) - { ; - } } } --- 248,260 ---- } ! public abstract void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! ; ! public abstract void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! ; ! public abstract void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ; } } Index: EndOfDayTimerHandlerLastChosenPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerLastChosenPortfolio.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** EndOfDayTimerHandlerLastChosenPortfolio.cs 29 Aug 2007 09:43:32 -0000 1.4 --- EndOfDayTimerHandlerLastChosenPortfolio.cs 14 Jan 2008 23:32:31 -0000 1.5 *************** *** 86,89 **** --- 86,94 ---- } + public override void OneHourAfterMarketCloseEventHandler( + Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) + { + ; + } } Index: EndOfDayTimerHandlerOTCCTO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerOTCCTO.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** EndOfDayTimerHandlerOTCCTO.cs 29 Aug 2007 09:43:33 -0000 1.7 --- EndOfDayTimerHandlerOTCCTO.cs 14 Jan 2008 23:32:31 -0000 1.8 *************** *** 145,149 **** this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCCTOPortfolio, --- 145,150 ---- this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType, ! this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCCTOPortfolio, Index: EndOfDayTimerHandlerCTO_WorstAtDay.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerCTO_WorstAtDay.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** EndOfDayTimerHandlerCTO_WorstAtDay.cs 29 Aug 2007 09:43:32 -0000 1.2 --- EndOfDayTimerHandlerCTO_WorstAtDay.cs 14 Jan 2008 23:32:31 -0000 1.3 *************** *** 185,189 **** this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTOPortfolio, --- 185,190 ---- this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType, ! this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTOPortfolio, Index: EndOfDayTimerHandlerOTCMultiday.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerOTCMultiday.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** EndOfDayTimerHandlerOTCMultiday.cs 29 Aug 2007 09:43:33 -0000 1.8 --- EndOfDayTimerHandlerOTCMultiday.cs 14 Jan 2008 23:32:32 -0000 1.9 *************** *** 128,132 **** this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, --- 128,133 ---- this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType, ! this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, Index: EndOfDayTimerHandlerOTC.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerOTC.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** EndOfDayTimerHandlerOTC.cs 29 Aug 2007 09:43:32 -0000 1.6 --- EndOfDayTimerHandlerOTC.cs 14 Jan 2008 23:32:31 -0000 1.7 *************** *** 135,145 **** // this.numberOfTickersToBeChosen, // this.targetReturn, ! // this.portfolioType); new GenomeManagerForEfficientOTCCTOPortfolio(setOfTickersToBeOptimized, currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, --- 135,146 ---- // this.numberOfTickersToBeChosen, // this.targetReturn, ! // this.portfolioType, ! // this.benchmark); new GenomeManagerForEfficientOTCCTOPortfolio(setOfTickersToBeOptimized, currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType, this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, *************** *** 149,157 **** 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) ); --- 150,164 ---- if(setGenomeCounter) this.genomeCounter = new GenomeCounter(GO); ! GO.CrossoverRate = 0.85; ! GO.MutationRate = 0.10; GO.Run(false); ! this.addGenomeToBestGenomes( ! GO.BestGenome, ! currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! currentDate, ! setOfTickersToBeOptimized.Rows.Count, ! -1, ! this.portfolioType, ! GO.GenerationCounter); this.chosenWeightedPositions = new WeightedPositions( ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights, new SignedTickers( ((GenomeMeaning)GO.BestGenome.Meaning).Tickers) ); Index: EndOfDayTimerHandlerOTCMultiAccount.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerOTCMultiAccount.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** EndOfDayTimerHandlerOTCMultiAccount.cs 29 Aug 2007 09:43:33 -0000 1.3 --- EndOfDayTimerHandlerOTCMultiAccount.cs 14 Jan 2008 23:32:32 -0000 1.4 *************** *** 166,170 **** this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, --- 166,171 ---- this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType, ! this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, Index: EndOfDayTimerHandlerCTO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerCTO.cs,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** EndOfDayTimerHandlerCTO.cs 29 Aug 2007 09:43:32 -0000 1.26 --- EndOfDayTimerHandlerCTO.cs 14 Jan 2008 23:32:31 -0000 1.27 *************** *** 122,126 **** this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTOPortfolio, --- 122,127 ---- this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType, ! this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTOPortfolio, Index: EndOfDayTimerHandlerCTCWeekly.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerCTCWeekly.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** EndOfDayTimerHandlerCTCWeekly.cs 23 Sep 2007 22:09:34 -0000 1.8 --- EndOfDayTimerHandlerCTCWeekly.cs 14 Jan 2008 23:32:31 -0000 1.9 *************** *** 146,150 **** this.numDaysForReturnCalculation, this.targetReturn, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTCPortfolio, this.populationSizeForGeneticOptimizer, --- 146,150 ---- this.numDaysForReturnCalculation, this.targetReturn, ! this.portfolioType, this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTCPortfolio, this.populationSizeForGeneticOptimizer, Index: EndOfDayTimerHandlerCTC.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerCTC.cs,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** EndOfDayTimerHandlerCTC.cs 23 Sep 2007 22:09:24 -0000 1.24 --- EndOfDayTimerHandlerCTC.cs 14 Jan 2008 23:32:30 -0000 1.25 *************** *** 205,209 **** this.numDaysForReturnCalculation, this.targetReturn, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTCPortfolio, this.populationSizeForGeneticOptimizer, --- 205,209 ---- this.numDaysForReturnCalculation, this.targetReturn, ! this.portfolioType, this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTCPortfolio, this.populationSizeForGeneticOptimizer, Index: EndOfDayTimerHandlerOTC_WorstAtNight.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/EndOfDayTimerHandlerOTC_WorstAtNight.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** EndOfDayTimerHandlerOTC_WorstAtNight.cs 29 Aug 2007 09:43:32 -0000 1.2 --- EndOfDayTimerHandlerOTC_WorstAtNight.cs 14 Jan 2008 23:32:31 -0000 1.3 *************** *** 28,33 **** --- 28,36 ---- using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; + using QuantProject.Business.DataProviders; using QuantProject.Business.Strategies; using QuantProject.Business.Timing; + using QuantProject.Business.Strategies.ReturnsManagement; + using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; *************** *** 48,51 **** --- 51,55 ---- protected GeneticOptimizer currentGO; protected int numOfGenomesForCTOScanning; + private HistoricalAdjustedQuoteProvider historicalAdjustedQuoteProvider; public EndOfDayTimerHandlerOTC_WorstAtNight(string tickerGroupID, int numberOfEligibleTickers, *************** *** 67,70 **** --- 71,75 ---- this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; this.numOfGenomesForCTOScanning = numOfGenomesForCTOScanning; + this.historicalAdjustedQuoteProvider = new HistoricalAdjustedQuoteProvider(); } *************** *** 79,82 **** --- 84,92 ---- DateTime today = currentTimer.GetCurrentTime().DateTime; DateTime lastMarketDay = currentTimer.GetPreviousDateTime(); + ReturnsManager returnsManager = new ReturnsManager( + new CloseToOpenIntervals(new EndOfDayDateTime(lastMarketDay, EndOfDaySpecificTime.MarketClose), + new EndOfDayDateTime(today, EndOfDaySpecificTime.MarketOpen), + this.benchmark), + this.historicalAdjustedQuoteProvider ); int numOfGenomesScanned = 0; for(int i = 0; *************** *** 101,105 **** signedTickers); lossOfCurrentCombination = ! weightedPositions.GetLastNightReturn(lastMarketDay,today); numOfGenomesScanned++; if(lossOfCurrentCombination < lossOfCurrentWorstCombination) --- 111,115 ---- signedTickers); lossOfCurrentCombination = ! weightedPositions.GetReturn( 0 , returnsManager ); numOfGenomesScanned++; if(lossOfCurrentCombination < lossOfCurrentWorstCombination) *************** *** 196,200 **** this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, --- 206,210 ---- this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType,this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, *************** *** 205,209 **** this.genomeCounter = new GenomeCounter(GO); GO.CrossoverRate = 0.0; ! GO.MutationRate = 0.70; GO.Run(false); this.addGenomeToBestGenomes(GO.BestGenome,currentDate.AddDays(-this.numDaysForOptimizationPeriod), --- 215,219 ---- this.genomeCounter = new GenomeCounter(GO); GO.CrossoverRate = 0.0; ! GO.MutationRate = 0.50; GO.Run(false); this.addGenomeToBestGenomes(GO.BestGenome,currentDate.AddDays(-this.numDaysForOptimizationPeriod), |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:32:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv18649/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators Modified Files: EndOfDayTimerHandlerFPOscillatorCTC.cs Log Message: Handlers have been updated (minor changes) Index: EndOfDayTimerHandlerFPOscillatorCTC.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators/EndOfDayTimerHandlerFPOscillatorCTC.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** EndOfDayTimerHandlerFPOscillatorCTC.cs 29 Aug 2007 09:43:30 -0000 1.5 --- EndOfDayTimerHandlerFPOscillatorCTC.cs 14 Jan 2008 23:32:30 -0000 1.6 *************** *** 85,89 **** this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; } ! #region MarketCloseEventHandler --- 85,94 ---- this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; } ! ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } #region MarketCloseEventHandler *************** *** 285,289 **** currentDate, this.numberOfTickersToBeChosen, this.numDaysForReturnCalculation, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, --- 290,294 ---- currentDate, this.numberOfTickersToBeChosen, this.numDaysForReturnCalculation, ! this.portfolioType, this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:32:35
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/TestingOTCTypes In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv18649/b7_Scripts/TickerSelectionTesting/TestingOTCTypes Modified Files: EndOfDayTimerHandlerOTCTypes.cs Log Message: Handlers have been updated (minor changes) Index: EndOfDayTimerHandlerOTCTypes.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/TestingOTCTypes/EndOfDayTimerHandlerOTCTypes.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** EndOfDayTimerHandlerOTCTypes.cs 29 Aug 2007 09:43:34 -0000 1.8 --- EndOfDayTimerHandlerOTCTypes.cs 14 Jan 2008 23:32:32 -0000 1.9 *************** *** 174,178 **** this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCTypes, --- 174,179 ---- this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType, ! this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCTypes, |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:29:02
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv16889/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio Modified Files: RunTestingOptimizationCloseToOpen.cs RunTestingOptimizationOpenToClose.cs RunTestingOptimizationOpenToCloseFitnessCombined.cs Log Message: Minor changes Index: RunTestingOptimizationOpenToClose.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio/RunTestingOptimizationOpenToClose.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** RunTestingOptimizationOpenToClose.cs 14 May 2006 18:10:31 -0000 1.8 --- RunTestingOptimizationOpenToClose.cs 14 Jan 2008 23:28:58 -0000 1.9 *************** *** 282,286 **** this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType); this.setFitnesses_setFitnessesActually(genManEfficientOTC); --- 282,287 ---- this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType, ! this.benchmark); this.setFitnesses_setFitnessesActually(genManEfficientOTC); Index: RunTestingOptimizationCloseToOpen.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio/RunTestingOptimizationCloseToOpen.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunTestingOptimizationCloseToOpen.cs 14 May 2006 18:10:31 -0000 1.2 --- RunTestingOptimizationCloseToOpen.cs 14 Jan 2008 23:28:58 -0000 1.3 *************** *** 253,257 **** this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType); this.setFitnesses_setFitnessesActually(genManEfficientCTOPortfolio); --- 253,258 ---- this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType, ! this.benchmark); this.setFitnesses_setFitnessesActually(genManEfficientCTOPortfolio); Index: RunTestingOptimizationOpenToCloseFitnessCombined.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio/RunTestingOptimizationOpenToCloseFitnessCombined.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunTestingOptimizationOpenToCloseFitnessCombined.cs 2 Jul 2006 19:36:12 -0000 1.2 --- RunTestingOptimizationOpenToCloseFitnessCombined.cs 14 Jan 2008 23:28:58 -0000 1.3 *************** *** 260,264 **** this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType); this.setFitnesses_setFitnessesActually(genManEfficientOTC_CTO); --- 260,265 ---- this.numberOfTickersToBeChosen, this.targetReturn, ! this.portfolioType, ! this.benchmark); this.setFitnesses_setFitnessesActually(genManEfficientOTC_CTO); |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:29:02
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/TechnicalAnalysis In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv16889/b7_Scripts/EvaluatingOptimizationTechnique/TechnicalAnalysis Modified Files: RunTestingOptimizationExtremeCounterTrend.cs Log Message: Minor changes Index: RunTestingOptimizationExtremeCounterTrend.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/TechnicalAnalysis/RunTestingOptimizationExtremeCounterTrend.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunTestingOptimizationExtremeCounterTrend.cs 2 Jul 2006 19:36:12 -0000 1.2 --- RunTestingOptimizationExtremeCounterTrend.cs 14 Jan 2008 23:28:58 -0000 1.3 *************** *** 269,273 **** this.numberOfTickersToBeChosen, this.numDaysForReturnCalculation, ! this.portfolioType); this.setFitnesses_setFitnessesActually(genManExtremeCounterTrend); --- 269,274 ---- this.numberOfTickersToBeChosen, this.numDaysForReturnCalculation, ! this.portfolioType, ! this.benchmark); this.setFitnesses_setFitnessesActually(genManExtremeCounterTrend); |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:27:29
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv16409/b4_Business/a2_Strategies Modified Files: WeightedPositions.cs Log Message: Added methods: - HasTheSameSignedTickersAs; - HasTheOppositeSignedTickersAs Index: WeightedPositions.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/WeightedPositions.cs,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** WeightedPositions.cs 4 Nov 2007 18:59:19 -0000 1.12 --- WeightedPositions.cs 14 Jan 2008 23:27:26 -0000 1.13 *************** *** 605,626 **** } ! #region getLastNightReturn ! private double getLastNightReturn( float[] weightedPositionsLastNightReturns ) ! { ! double returnValue = 0.0; ! for(int i = 0; i<weightedPositionsLastNightReturns.Length; i++) ! returnValue += weightedPositionsLastNightReturns[i] * 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> --- 605,625 ---- } ! // private double getLastNightReturn( float[] weightedPositionsLastNightReturns ) ! // { ! // double returnValue = 0.0; ! // for(int i = 0; i<weightedPositionsLastNightReturns.Length; i++) ! // returnValue += weightedPositionsLastNightReturns[i] * 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 ); ! // } ! /// <summary> *************** *** 629,641 **** /// <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( ! this[i].Ticker, lastMarketDay, today ); ! return getLastNightReturn( weightedPositionsLastNightReturns ); ! } private double getCloseToCloseReturn_setReturns_getReturn( --- 628,640 ---- /// <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( ! // this[i].Ticker, lastMarketDay, today ); ! // return getLastNightReturn( weightedPositionsLastNightReturns ); ! // } private double getCloseToCloseReturn_setReturns_getReturn( *************** *** 707,710 **** --- 706,749 ---- return toString; } + + public bool HasTheSameSignedTickersAs(WeightedPositions weightedPositions) + { + //Check for null and compare run-time types and compare length of the weightedPositions + if (weightedPositions.Count != this.Count) + return false; + int numOfEquals = 0; + //WeightedPositions can't contain the same ticker twice: + //so, if at the end of the nested cycle + //numOfEquals is equal to the number of + //positions, the two instances represent + //portfolios that contain the same signed tickers + for (int i = 0; i<this.Count; i++) + for (int j = 0; j<this.Count; j++) + if ( this[i].HasTheSameSignedTickerAs(weightedPositions[j]) ) + numOfEquals++; + + return numOfEquals == this.Count; + } + + public bool HasTheOppositeSignedTickersAs(WeightedPositions weightedPositions) + { + //Check for null and compare run-time types and compare length of the weightedPositions + if (weightedPositions.Count != this.Count) + return false; + int numOfEqualsWithOppositeSign = 0; + //WeightedPositions can't contain the same ticker twice: + //so, if at the end of the nested cycle + //numOfEqualsWithOppositeSign is equal to the number of + //positions, the two instances represent + //portfolios that contain the same signed tickers with + //opposite signs + for (int i = 0; i<this.Count; i++) + for (int j = 0; j<this.Count; j++) + if ( this[i].HasTheOppositeSignedTickerAs(weightedPositions[j]) ) + numOfEqualsWithOppositeSign++; + + return numOfEqualsWithOppositeSign == this.Count; + } + } } |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:24:51
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv15095/b4_Business/a2_Strategies Modified Files: WeightedPosition.cs Log Message: Added methods: - HasTheSameSignedTickerAs; - HasTheOppositeSignedTickerAs Index: WeightedPosition.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/WeightedPosition.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** WeightedPosition.cs 4 Nov 2007 18:55:39 -0000 1.2 --- WeightedPosition.cs 14 Jan 2008 23:24:48 -0000 1.3 *************** *** 120,126 **** public override string ToString() { ! string toString = this.Ticker + ";" + this.Weight; return toString; } } } --- 120,146 ---- public override string ToString() { ! string toString = this.Ticker + ";" + this.Weight.ToString(); return toString; } + + public bool HasTheSameSignedTickerAs(WeightedPosition weightedPosition) + { + if ( weightedPosition.Ticker == this.Ticker && + ( (weightedPosition.IsLong && this.IsLong) || + (weightedPosition.IsShort && this.IsShort) ) ) + return true; + else + return false; + } + + public bool HasTheOppositeSignedTickerAs(WeightedPosition weightedPosition) + { + if ( weightedPosition.Ticker == this.Ticker && + ( (weightedPosition.IsShort && this.IsLong) || + (weightedPosition.IsLong && this.IsShort) ) ) + return true; + else + return false; + } } } |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:23:09
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv14515/b4_Business/a2_Strategies Modified Files: AccountManager.cs Log Message: Code has been reorganised in a more logical way Index: AccountManager.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/AccountManager.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** AccountManager.cs 23 Sep 2007 21:53:20 -0000 1.3 --- AccountManager.cs 14 Jan 2008 23:23:05 -0000 1.4 *************** *** 102,108 **** #endregion ! #region ReversePositions ! ! static private double reversePositions_getReversedWeightedPositionsFromAccount_getPositionsAbsoluteValue(Account account) { double totalValue = 0; --- 102,106 ---- #endregion ! static private double getWeightedPositions_getPositionsAbsoluteValue(Account account) { double totalValue = 0; *************** *** 111,119 **** 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]; --- 109,120 ---- position.Instrument.Key ) * position.Quantity ); return totalValue; ! } ! /// <summary> ! /// Gets the current open WeightedPositions for the given account ! /// </summary> ! static public WeightedPositions GetWeightedPositions(Account account) { ! double positionsAbsoluteValue = getWeightedPositions_getPositionsAbsoluteValue(account); string[] tickers = getTickersInOpenedPositions( account ); double[] weights = new double[tickers.Length]; *************** *** 121,141 **** 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 } --- 122,139 ---- weights[i] = ( account.GetMarketValue( tickers[i] )* ! account.Portfolio.GetPosition( tickers[i] ).Quantity ) / positionsAbsoluteValue; ! ! return new WeightedPositions( weights, tickers ); ! } ! static public void ReversePositions(Account account) { orders.Clear(); ! WeightedPositions currentWeightedPositions = GetWeightedPositions( account ); ! currentWeightedPositions.Reverse(); ClosePositions(account); ! OpenPositions( currentWeightedPositions, account ); } } // end of class } |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:21:08
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a05_Timing In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv13374/b4_Business/a05_Timing Modified Files: IndexBasedEndOfDayTimer.cs Log Message: Added method GetPreviousDateTime Index: IndexBasedEndOfDayTimer.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a05_Timing/IndexBasedEndOfDayTimer.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** IndexBasedEndOfDayTimer.cs 14 May 2006 18:23:38 -0000 1.8 --- IndexBasedEndOfDayTimer.cs 14 Jan 2008 23:21:03 -0000 1.9 *************** *** 120,123 **** --- 120,132 ---- return this.indexQuotes.GetPrecedingDate(this.currentTime.DateTime,1); } + /// <summary> + /// Gets the date time that is 'precedingDays' days before + /// the current date time of the current timer + /// </summary> + public DateTime GetPreviousDateTime(int precedingDays) + { + return this.indexQuotes.GetPrecedingDate( + this.currentTime.DateTime,precedingDays); + } } |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:18:50
|
Update of /cvsroot/quantproject/QuantProject/b3_Data/Selectors In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv12311/b3_Data/Selectors Modified Files: SelectorByCloseToCloseLinearCorrelation.cs Log Message: Minor changes to a class the will be deleted soon (correlations should be treated in business project) Index: SelectorByCloseToCloseLinearCorrelation.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b3_Data/Selectors/SelectorByCloseToCloseLinearCorrelation.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** SelectorByCloseToCloseLinearCorrelation.cs 28 Dec 2005 23:27:56 -0000 1.2 --- SelectorByCloseToCloseLinearCorrelation.cs 14 Jan 2008 23:18:47 -0000 1.3 *************** *** 25,28 **** --- 25,30 ---- using System.Data; using System.Windows.Forms; + + using QuantProject.ADT.Statistics; using QuantProject.DataAccess.Tables; using QuantProject.Data.DataTables; *************** *** 35,39 **** public class SelectorByCloseToCloseLinearCorrelation : TickerSelector , ITickerSelector { - public SelectorByCloseToCloseLinearCorrelation(DataTable setOfTickersToBeSelected, --- 37,40 ---- *************** *** 48,58 **** maxNumOfReturnedTickers) { ! } ! public SelectorByCloseToCloseLinearCorrelation(string groupID, bool orderInASCmode, DateTime firstQuoteDate, DateTime lastQuoteDate, ! long maxNumOfReturnedTickers): base(groupID, orderInASCmode, --- 49,59 ---- maxNumOfReturnedTickers) { ! } ! public SelectorByCloseToCloseLinearCorrelation(string groupID, bool orderInASCmode, DateTime firstQuoteDate, DateTime lastQuoteDate, ! long maxNumOfReturnedTickers): base(groupID, orderInASCmode, *************** *** 60,66 **** lastQuoteDate, maxNumOfReturnedTickers) ! { ! ! } --- 61,67 ---- lastQuoteDate, maxNumOfReturnedTickers) ! { ! ! } *************** *** 68,77 **** { if(this.setOfTickersToBeSelected == null) ! return QuantProject.Data.DataTables.Quotes.GetTickersByAdjCloseToClosePearsonCorrelationCoefficient(this.isOrderedInASCMode, this.groupID, this.firstQuoteDate, this.lastQuoteDate); else ! return QuantProject.Data.DataTables.Quotes.GetTickersByAdjCloseToClosePearsonCorrelationCoefficient(this.isOrderedInASCMode, this.setOfTickersToBeSelected, this.firstQuoteDate, --- 69,78 ---- { if(this.setOfTickersToBeSelected == null) ! return this.getTickersByAdjCloseToClosePearsonCorrelationCoefficient(this.isOrderedInASCMode, this.groupID, this.firstQuoteDate, this.lastQuoteDate); else ! return this.getTickersByAdjCloseToClosePearsonCorrelationCoefficient(this.isOrderedInASCMode, this.setOfTickersToBeSelected, this.firstQuoteDate, *************** *** 79,82 **** --- 80,170 ---- } + private void getTickersByAdjCloseToClosePearsonCorrelationCoefficient_setTickersAdjCloses(out float[][] + tickersReturns, DataTable setOfTickers, DateTime firstQuoteDate, DateTime lastQuoteDate) + + { + tickersReturns = new float[setOfTickers.Rows.Count][]; + for(int i = 0; i<setOfTickers.Rows.Count; i++) + { + DataTable tickerQuoteTable = + QuantProject.DataAccess.Tables.Quotes.GetTickerQuotes((string)setOfTickers.Rows[i][0], + firstQuoteDate, + lastQuoteDate); + tickersReturns[i] = + ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuoteTable,"quAdjustedClose"); + + } + } + + /// <summary> + /// Returns a table containing the Pearson correlation coefficient for the adjusted close values + /// for any possible couple of tickers contained in the given table, for the specified interval + /// </summary> + private DataTable getTickersByAdjCloseToClosePearsonCorrelationCoefficient( bool orderByASC, + DataTable setOfTickers, + DateTime firstQuoteDate, + DateTime lastQuoteDate) + + { + if(!setOfTickers.Columns.Contains("CorrelatedTicker")) + setOfTickers.Columns.Add("CorrelatedTicker", System.Type.GetType("System.String")); + if(!setOfTickers.Columns.Contains("PearsonCorrelationCoefficient")) + setOfTickers.Columns.Add("PearsonCorrelationCoefficient", System.Type.GetType("System.Double")); + int initialNumberOfRows = setOfTickers.Rows.Count; + float[][] tickersAdjCloses; + getTickersByAdjCloseToClosePearsonCorrelationCoefficient_setTickersAdjCloses(out tickersAdjCloses, setOfTickers, firstQuoteDate, lastQuoteDate); + for(int j=0; j!= initialNumberOfRows; j++) + { + string firstTicker = (string)setOfTickers.Rows[j][0]; + for(int i = j+1; i!= initialNumberOfRows; i++) + { + string secondTicker = (string)setOfTickers.Rows[i][0]; + DataRow rowToAdd = setOfTickers.NewRow(); + rowToAdd[0] = firstTicker; + rowToAdd["PearsonCorrelationCoefficient"] = -2.0; + //unassigned value for this column + rowToAdd["CorrelatedTicker"] = secondTicker; + try + { + rowToAdd["PearsonCorrelationCoefficient"] = + QuantProject.ADT.Statistics.BasicFunctions.PearsonCorrelationCoefficient( + tickersAdjCloses[j],tickersAdjCloses[i]); + } + catch(Exception ex) + { + ex = ex; + } + finally + { + setOfTickers.Rows.Add(rowToAdd); + } + } + } + ExtendedDataTable.DeleteRows(setOfTickers, 0, initialNumberOfRows - 1); + //delete initial rows that don't contain correlated ticker and Pearson coeff. + return ExtendedDataTable.CopyAndSort(setOfTickers,"PearsonCorrelationCoefficient>-2.0", + "PearsonCorrelationCoefficient", orderByASC); + } + + /// <summary> + /// Returns a table containing the Pearson correlation coefficient for the adjusted close values + /// for any possible couple of tickers contained in the given group of tickers, + /// for the specified interval + /// </summary> + private DataTable getTickersByAdjCloseToClosePearsonCorrelationCoefficient( bool orderByASC, + string groupID, + DateTime firstQuoteDate, + DateTime lastQuoteDate) + + { + + DataTable tickersOfGroup = + new QuantProject.Data.DataTables.Tickers_tickerGroups(groupID); + return this.getTickersByAdjCloseToClosePearsonCorrelationCoefficient(orderByASC, + tickersOfGroup, + firstQuoteDate, + lastQuoteDate); + } + public void SelectAllTickers() |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:14:44
|
Update of /cvsroot/quantproject/QuantProject/b3_Data/Selectors In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv10304/b3_Data/Selectors Modified Files: SelectorByCloseToCloseCorrelationToBenchmark.cs Log Message: The selector has been simplified Index: SelectorByCloseToCloseCorrelationToBenchmark.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b3_Data/Selectors/SelectorByCloseToCloseCorrelationToBenchmark.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** SelectorByCloseToCloseCorrelationToBenchmark.cs 3 Aug 2006 21:17:16 -0000 1.4 --- SelectorByCloseToCloseCorrelationToBenchmark.cs 14 Jan 2008 23:14:41 -0000 1.5 *************** *** 31,38 **** /// Class for selection on tickers by close to close absolute correlation to /// a given benchmark - /// NOTE that - /// close values are grouped in pairs and the first close value in each group is - /// not the last close in the previous group. There is, in other words, a discontinuity - /// between each group, with length equal to the group's length /// </summary> public class SelectorByCloseToCloseCorrelationToBenchmark : TickerSelector, ITickerSelector --- 31,34 ---- *************** *** 131,143 **** float[] tickerQuotes = QuantProject.Data.DataTables.Quotes.GetArrayOfAdjustedCloseQuotes((string)row[0], firstQuoteDate, lastQuoteDate); ! if(tickerQuotes.Length == benchmarkQuotes.Length) ! { ! if((string)row[0] == benchmark) ! row["CloseToCloseCorrelationToBenchmark"] = 1; ! else ! row["CloseToCloseCorrelationToBenchmark"] = BasicFunctions.PearsonCorrelationCoefficient(benchmarkQuotes, tickerQuotes); - } - } DataTable tableToReturn = ExtendedDataTable.CopyAndSort(setOfTickers, --- 127,132 ---- float[] tickerQuotes = QuantProject.Data.DataTables.Quotes.GetArrayOfAdjustedCloseQuotes((string)row[0], firstQuoteDate, lastQuoteDate); ! row["CloseToCloseCorrelationToBenchmark"] = BasicFunctions.PearsonCorrelationCoefficient(benchmarkQuotes, tickerQuotes); } DataTable tableToReturn = ExtendedDataTable.CopyAndSort(setOfTickers, |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:11:22
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv8993/b1_ADT Modified Files: ExtendedMath.cs Log Message: Added static method ArrayOfAbs Index: ExtendedMath.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/ExtendedMath.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** ExtendedMath.cs 8 Sep 2006 15:18:22 -0000 1.1 --- ExtendedMath.cs 14 Jan 2008 23:11:19 -0000 1.2 *************** *** 25,28 **** --- 25,51 ---- return factorial; } + #region ArrayOfAbs + public static double[] ArrayOfAbs( double[] sourceArray ) + { + double[] arrayOfAbs = new double[sourceArray.Length]; + for(int i = 0; i < sourceArray.Length; i++) + arrayOfAbs[i] = Math.Abs( sourceArray[i] ); + return arrayOfAbs; + } + public static float[] ArrayOfAbs( float[] sourceArray ) + { + float[] arrayOfAbs = new float[sourceArray.Length]; + for(int i = 0; i < sourceArray.Length; i++) + arrayOfAbs[i] = Math.Abs( sourceArray[i] ); + return arrayOfAbs; + } + public static int[] ArrayOfAbs( int[] sourceArray ) + { + int[] arrayOfAbs = new int[sourceArray.Length]; + for(int i = 0; i < sourceArray.Length; i++) + arrayOfAbs[i] = Math.Abs( sourceArray[i] ); + return arrayOfAbs; + } + #endregion } } |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:10:05
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv8107/b1_ADT Modified Files: ExtendedDataTable.cs Log Message: Added static method GetArrayOfStringFromColumn Index: ExtendedDataTable.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/ExtendedDataTable.cs,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** ExtendedDataTable.cs 25 Jun 2005 10:01:54 -0000 1.10 --- ExtendedDataTable.cs 14 Jan 2008 23:10:00 -0000 1.11 *************** *** 109,112 **** --- 109,136 ---- } /// <summary> + /// Get an array of string corresponding to a column compatible with the string type in a given data table + /// </summary> + public static string[] GetArrayOfStringFromColumn(DataTable table, + int columnIndex) + { + int numRows = table.Rows.Count; + string[] arrayOfString = new string[numRows]; + int index = 0; + try + { + for(; index!= numRows; index++) + { + arrayOfString[index] = (string) table.Rows[index][columnIndex]; + } + } + catch(Exception ex) + { + MessageBox.Show(ex.ToString()); + index = numRows; + } + return arrayOfString; + } + + /// <summary> /// Get an array of float corresponding to a column compatible with the float type in a given data table, /// filtered by the given filterExpression |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:07:38
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/BiasedPVONoThresholds In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv7110/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/BiasedPVONoThresholds Modified Files: EndOfDayTimerHandlerBiasedPVONoThresholds.cs GenomeManagerBiasedPVONoThresholds.cs Log Message: Several changes applied to the classes implementing the Portfolio Value Oscillator strategy (the most important one relates to the use of ReturnsManager) Index: GenomeManagerBiasedPVONoThresholds.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/BiasedPVONoThresholds/GenomeManagerBiasedPVONoThresholds.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** GenomeManagerBiasedPVONoThresholds.cs 27 Feb 2007 22:52:40 -0000 1.1 --- GenomeManagerBiasedPVONoThresholds.cs 14 Jan 2008 23:07:04 -0000 1.2 *************** *** 24,27 **** --- 24,28 ---- using System.Data; using System.Collections; + using QuantProject.ADT; using QuantProject.ADT.Statistics; *************** *** 29,32 **** --- 30,38 ---- using QuantProject.Data; using QuantProject.Data.DataTables; + using QuantProject.Business.DataProviders; + using QuantProject.Business.Timing; + using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; + using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; *************** *** 41,50 **** public class GenomeManagerBiasedPVONoThresholds : GenomeManagerForEfficientPortfolio { ! public GenomeManagerBiasedPVONoThresholds(DataTable setOfInitialTickers, DateTime firstQuoteDate, DateTime lastQuoteDate, int numberOfTickersInPortfolio, ! PortfolioType inSamplePortfolioType) : base(setOfInitialTickers, --- 47,58 ---- public class GenomeManagerBiasedPVONoThresholds : GenomeManagerForEfficientPortfolio { ! private ReturnsManager returnsManager; ! public GenomeManagerBiasedPVONoThresholds(DataTable setOfInitialTickers, DateTime firstQuoteDate, DateTime lastQuoteDate, int numberOfTickersInPortfolio, ! PortfolioType inSamplePortfolioType, ! string benchmark) : base(setOfInitialTickers, *************** *** 53,142 **** numberOfTickersInPortfolio, 0.0, ! inSamplePortfolioType) { ! this.retrieveData(); } ! #region Get Min and Max Value ! ! public override int GetMinValueForGenes(int genePosition) ! { ! int returnValue; ! switch (this.portfolioType) ! { ! case PortfolioType.OnlyLong : ! returnValue = 0; ! break; ! default://For ShortAndLong or OnlyShort portfolios ! returnValue = - this.originalNumOfTickers; ! break; ! } ! return returnValue; ! } ! ! public override int GetMaxValueForGenes(int genePosition) ! { ! int returnValue; ! switch (this.portfolioType) { ! case PortfolioType.OnlyShort : ! returnValue = - 1; ! break; ! default ://For ShortAndLong or OnlyLong portfolios ! returnValue = this.originalNumOfTickers - 1; ! break; } - return returnValue; - } - - #endregion - - protected override float[] getArrayOfRatesOfReturn(string ticker) - { - float[] returnValue = null; - Quotes tickerQuotes = new Quotes(ticker, this.firstQuoteDate, this.lastQuoteDate); - tickerQuotes.RecalculateCloseToCloseRatios(); - returnValue = QuantProject.ADT.ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuotes, - Quotes.AdjustedCloseToCloseRatio); - for(int i = 0; i<returnValue.Length; i++) - returnValue[i] = returnValue[i] - 1.0f; - - this.numberOfExaminedReturns = returnValue.Length; - - return returnValue; - } - - //fitness is a number that indicates how much the portfolio - //tends to preserve equity (no gain and no loss), with a low std dev - public override double GetFitnessValue(Genome genome) - { - double returnValue = -1.0; - this.portfolioRatesOfReturn = this.getPortfolioRatesOfReturn( genome.Genes() ); - //double[] asbolutePortfolioRatesOfReturns = new double[this.portfolioRatesOfReturn.Length]; - // for( int i = 0; i<asbolutePortfolioRatesOfReturns.Length; i++ ) - // asbolutePortfolioRatesOfReturns[i] = Math.Abs(this.portfolioRatesOfReturn[i]); - returnValue = 1.0/ - //( BasicFunctions.SimpleAverage(asbolutePortfolioRatesOfReturns) * - ( - Math.Abs( BasicFunctions.SimpleAverage(this.portfolioRatesOfReturn) ) * - BasicFunctions.StdDev(this.portfolioRatesOfReturn) ); //); return returnValue; ! } ! public override object Decode(Genome genome) ! { ! string[] arrayOfTickers = new string[genome.Genes().Length]; ! int indexOfTicker; ! for(int index = 0; index < genome.Genes().Length; index++) ! { ! indexOfTicker = (int)genome.Genes().GetValue(index); ! arrayOfTickers[index] = this.decode_getTickerCodeForLongOrShortTrade(indexOfTicker); ! } ! GenomeMeaningPVO meaning = new GenomeMeaningPVO(arrayOfTickers, ! 0.0, 0.0, 2); ! return meaning; ! } } } --- 61,134 ---- numberOfTickersInPortfolio, 0.0, ! inSamplePortfolioType, ! benchmark) { ! this.setReturnsManager(); } ! private void setReturnsManager() ! { ! EndOfDayDateTime firstEndOfDayDateTime = ! new EndOfDayDateTime(firstQuoteDate, EndOfDaySpecificTime.MarketClose); ! EndOfDayDateTime lastEndOfDayDateTime = ! new EndOfDayDateTime(lastQuoteDate, EndOfDaySpecificTime.MarketClose); ! this.returnsManager = ! new ReturnsManager( new CloseToCloseIntervals( ! firstEndOfDayDateTime, ! lastEndOfDayDateTime, ! this.benchmark), ! new HistoricalAdjustedQuoteProvider() ); ! } ! ! private float[] getStrategyReturns_getReturnsActually( ! float[] plainReturns) ! { ! float[] returnValue = new float[plainReturns.Length]; ! returnValue[0] = 0; //at the very first day the ! //first strategy return is equal to 0 because no position ! //has been entered ! float coefficient = 0; ! for(int i = 0; i < returnValue.Length - 1; i++) { ! if( plainReturns[i] >= 0 ) ! //portfolio is overbought ! coefficient = -1; ! else if( plainReturns[i] <= 0 ) ! //portfolio is oversold ! coefficient = 1; ! //else ! // coefficient = coefficient; the previous coeff is kept ! returnValue[i + 1] = coefficient * plainReturns[i + 1]; } return returnValue; ! } ! protected override float[] getStrategyReturns() ! { ! EndOfDayDateTime firstEndOfDayDateTime = ! new EndOfDayDateTime(firstQuoteDate, EndOfDaySpecificTime.MarketClose); ! EndOfDayDateTime lastEndOfDayDateTime = ! new EndOfDayDateTime(lastQuoteDate, EndOfDaySpecificTime.MarketClose); ! float[] plainReturns = this.weightedPositionsFromGenome.GetReturns( ! this.returnsManager); ! return this.getStrategyReturns_getReturnsActually(plainReturns); ! } } + + // public override object Decode(Genome genome) + // { + // string[] arrayOfTickers = new string[genome.Genes().Length]; + // int indexOfTicker; + // for(int index = 0; index < genome.Genes().Length; index++) + // { + // indexOfTicker = (int)genome.Genes().GetValue(index); + // arrayOfTickers[index] = this.decode_getTickerCodeForLongOrShortTrade(indexOfTicker); + // } + // GenomeMeaningPVO meaning = new GenomeMeaningPVO(arrayOfTickers, + // 0.0, 0.0, 2); + // return meaning; + // } + } Index: EndOfDayTimerHandlerBiasedPVONoThresholds.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/BiasedPVONoThresholds/EndOfDayTimerHandlerBiasedPVONoThresholds.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** EndOfDayTimerHandlerBiasedPVONoThresholds.cs 29 Aug 2007 09:48:18 -0000 1.2 --- EndOfDayTimerHandlerBiasedPVONoThresholds.cs 14 Jan 2008 23:07:04 -0000 1.3 *************** *** 30,33 **** --- 30,36 ---- using QuantProject.Business.Timing; using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; + using QuantProject.Business.Strategies.ReturnsManagement.Time; + using QuantProject.Business.DataProviders; using QuantProject.Data; using QuantProject.Data.DataProviders; *************** *** 78,94 **** #region MarketCloseEventHandler ! protected override double getCurrentWeightedPositionsGainOrLoss(IndexBasedEndOfDayTimer timer, ! int indexForChosenWeightedPositions) { double returnValue = 999.0; 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) --- 81,104 ---- #region MarketCloseEventHandler ! protected override double getCurrentWeightedPositionsGainOrLoss( ! IndexBasedEndOfDayTimer timer, ! ReturnsManager returnsManager, ! int indexForChosenWeightedPositions) { double returnValue = 999.0; try { + DateTime firstDayOfOscillatingPeriod = + (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForOscillatingPeriod]["quDate"]; DateTime today = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! ReturnsManager returnsManager = new ReturnsManager(new CloseToCloseIntervals( ! new EndOfDayDateTime(firstDayOfOscillatingPeriod, ! EndOfDaySpecificTime.MarketClose) , ! new EndOfDayDateTime(finalDateForHalfPeriod, ! EndOfDaySpecificTime.MarketClose) , ! this.benchmark , this.numDaysForReturnCalculation ) , ! new HistoricalAdjustedQuoteProvider() ); ! returnValue = this.chosenWeightedPositions.GetReturn(0,returnsManager); } catch(MissingQuotesException ex) *************** *** 106,110 **** /this.previousAccountValue; ! if( portfolioGainOrLoss < -this.maxAcceptableCloseToCloseDrawdown ) { this.stopLossConditionReached = true; --- 116,120 ---- /this.previousAccountValue; ! if( portfolioGainOrLoss <= -this.maxAcceptableCloseToCloseDrawdown ) { this.stopLossConditionReached = true; *************** *** 130,135 **** this.takeProfitConditionReached || this.numDaysElapsedSinceLastOptimization + 1 == this.numDaysBetweenEachOptimization ) ! //reversal conditions have not been reached but ! //stop loss or take profit conditions yes //or after the close it is necessary to run //another optimization --- 140,144 ---- this.takeProfitConditionReached || this.numDaysElapsedSinceLastOptimization + 1 == this.numDaysBetweenEachOptimization ) ! //stop loss or take profit conditions have been reached //or after the close it is necessary to run //another optimization *************** *** 146,150 **** this.marketCloseEventHandler_closeIfItIsTimeToClose(); else if ( this.account.Portfolio.Count == 0 && ! this.weightedPositionsToEvaluateOutOfSample != null ) //portfolio is empty and optimization has been already launched this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); --- 155,159 ---- this.marketCloseEventHandler_closeIfItIsTimeToClose(); else if ( this.account.Portfolio.Count == 0 && ! this.weightedPositionsToEvaluateOutOfSample[0] != null ) //portfolio is empty and optimization has been already launched this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); *************** *** 165,169 **** currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, --- 174,178 ---- currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, ! this.portfolioType,this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:07:37
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/BiasedOTC_PVONoThresholds In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv7110/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/BiasedOTC_PVONoThresholds Modified Files: EndOfDayTimerHandlerBiasedOTC_PVONoThresholds.cs GenomeManagerBiasedOTC_PVONoThresholds.cs Log Message: Several changes applied to the classes implementing the Portfolio Value Oscillator strategy (the most important one relates to the use of ReturnsManager) Index: EndOfDayTimerHandlerBiasedOTC_PVONoThresholds.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/BiasedOTC_PVONoThresholds/EndOfDayTimerHandlerBiasedOTC_PVONoThresholds.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** EndOfDayTimerHandlerBiasedOTC_PVONoThresholds.cs 29 Aug 2007 09:50:20 -0000 1.2 --- EndOfDayTimerHandlerBiasedOTC_PVONoThresholds.cs 14 Jan 2008 23:07:04 -0000 1.3 *************** *** 25,28 **** --- 25,29 ---- using QuantProject.ADT; + using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; *************** *** 30,33 **** --- 31,36 ---- using QuantProject.Business.Timing; using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; + using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Data; using QuantProject.Data.DataProviders; *************** *** 87,103 **** } ! protected virtual double getCurrentWeightedPositionsGainOrLoss(IndexBasedEndOfDayTimer timer, ! int indexForChosenWeightedPositions) { double returnValue = 999.0; try { ! DateTime today = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! DateTime lastMarketDay = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - 1]["quDate"]; ! returnValue = ! this.weightedPositionsToEvaluateOutOfSample[indexForChosenWeightedPositions].GetLastNightReturn( ! lastMarketDay, today); } catch(MissingQuotesException ex) --- 90,104 ---- } ! protected virtual double getCurrentWeightedPositionsGainOrLoss( ! IndexBasedEndOfDayTimer timer, ! ReturnsManager returnsManager, ! int indexForChosenWeightedPositions ) { double returnValue = 999.0; try { ! returnValue = ! this.weightedPositionsToEvaluateOutOfSample[indexForChosenWeightedPositions].GetReturn( ! 0 , returnsManager); } catch(MissingQuotesException ex) *************** *** 118,124 **** double currentMaxAbsoluteMove = 0.0; double currentAbsoluteMove = 0.0; for(int i = 0; i < this.numOfDifferentGenomesToEvaluateOutOfSample; i++) { ! currentWeightedPositionsGainOrLoss = this.getCurrentWeightedPositionsGainOrLoss(timer, i); currentAbsoluteMove = Math.Abs( currentWeightedPositionsGainOrLoss ); --- 119,133 ---- double currentMaxAbsoluteMove = 0.0; double currentAbsoluteMove = 0.0; + DateTime today = timer.GetCurrentTime().DateTime; + DateTime lastMarketDay = timer.GetPreviousDateTime(); + ReturnsManager returnsManager = new ReturnsManager( + new CloseToOpenIntervals(new EndOfDayDateTime(lastMarketDay, EndOfDaySpecificTime.MarketClose), + new EndOfDayDateTime(today, EndOfDaySpecificTime.MarketOpen), + this.benchmark), + new HistoricalAdjustedQuoteProvider() ); for(int i = 0; i < this.numOfDifferentGenomesToEvaluateOutOfSample; i++) { ! currentWeightedPositionsGainOrLoss = this.getCurrentWeightedPositionsGainOrLoss( ! timer, returnsManager, i); currentAbsoluteMove = Math.Abs( currentWeightedPositionsGainOrLoss ); *************** *** 219,223 **** currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, --- 228,232 ---- currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, ! this.portfolioType, this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, Index: GenomeManagerBiasedOTC_PVONoThresholds.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/BiasedOTC_PVONoThresholds/GenomeManagerBiasedOTC_PVONoThresholds.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** GenomeManagerBiasedOTC_PVONoThresholds.cs 9 Apr 2007 18:04:00 -0000 1.2 --- GenomeManagerBiasedOTC_PVONoThresholds.cs 14 Jan 2008 23:07:04 -0000 1.3 *************** *** 24,27 **** --- 24,28 ---- using System.Data; using System.Collections; + using QuantProject.ADT; using QuantProject.ADT.Statistics; *************** *** 29,32 **** --- 30,39 ---- using QuantProject.Data; using QuantProject.Data.DataTables; + using QuantProject.Business.DataProviders; + using QuantProject.Business.Timing; + using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; + using QuantProject.Business.Strategies.ReturnsManagement.Time; + using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; *************** *** 41,50 **** public class GenomeManagerBiasedOTC_PVONoThresholds : GenomeManagerForEfficientPortfolio { ! public GenomeManagerBiasedOTC_PVONoThresholds(DataTable setOfInitialTickers, DateTime firstQuoteDate, DateTime lastQuoteDate, int numberOfTickersInPortfolio, ! PortfolioType inSamplePortfolioType) : base(setOfInitialTickers, --- 48,59 ---- public class GenomeManagerBiasedOTC_PVONoThresholds : GenomeManagerForEfficientPortfolio { ! private ReturnsManager returnsManager; ! public GenomeManagerBiasedOTC_PVONoThresholds(DataTable setOfInitialTickers, DateTime firstQuoteDate, DateTime lastQuoteDate, int numberOfTickersInPortfolio, ! PortfolioType inSamplePortfolioType, ! string benchmark) : base(setOfInitialTickers, *************** *** 53,149 **** numberOfTickersInPortfolio, 0.0, ! inSamplePortfolioType) { ! this.retrieveData(); } ! #region Get Min and Max Value ! ! public override int GetMinValueForGenes(int genePosition) ! { ! int returnValue; ! switch (this.portfolioType) ! { ! case PortfolioType.OnlyLong : ! returnValue = 0; ! break; ! default://For ShortAndLong or OnlyShort portfolios ! returnValue = - this.originalNumOfTickers; ! break; ! } ! return returnValue; ! } ! ! public override int GetMaxValueForGenes(int genePosition) ! { ! int returnValue; ! switch (this.portfolioType) ! { ! case PortfolioType.OnlyShort : ! returnValue = - 1; ! break; ! default ://For ShortAndLong or OnlyLong portfolios ! returnValue = this.originalNumOfTickers - 1; ! break; ! } ! return returnValue; ! } ! ! #endregion ! ! protected override float[] getArrayOfRatesOfReturn(string ticker) ! { ! Quotes tickerQuotes = new Quotes(ticker, this.firstQuoteDate, this.lastQuoteDate); ! float[] returnValue = new float[2*tickerQuotes.Rows.Count - 1]; ! int j = 0; ! for(int i = 0;i<tickerQuotes.Rows.Count; i++) { ! //open to close ! returnValue[j] = (float)tickerQuotes.Rows[i]["quClose"]/ ! (float)tickerQuotes.Rows[i]["quOpen"] - 1; ! //close to open ! if(i<tickerQuotes.Rows.Count-1) ! { ! returnValue[j+1] = ! ( (float)tickerQuotes.Rows[i+1]["quOpen"]* ! (float)tickerQuotes.Rows[i+1]["quAdjustedClose"]/ ! (float)tickerQuotes.Rows[i+1]["quClose"] ) ! /(float)tickerQuotes.Rows[i]["quAdjustedClose"] - 1; ! } ! j += 2 ; } - this.numberOfExaminedReturns = returnValue.Length; return returnValue; ! } ! ! //fitness is a number that indicates how much the portfolio ! //tends to preserve equity (no gain and no loss), with a low std dev ! public override double GetFitnessValue(Genome genome) ! { ! double returnValue = -1.0; ! this.portfolioRatesOfReturn = this.getPortfolioRatesOfReturn( genome.Genes() ); ! //double[] asbolutePortfolioRatesOfReturns = new double[this.portfolioRatesOfReturn.Length]; ! // for( int i = 0; i<asbolutePortfolioRatesOfReturns.Length; i++ ) ! // asbolutePortfolioRatesOfReturns[i] = Math.Abs(this.portfolioRatesOfReturn[i]); ! returnValue = BasicFunctions.SimpleAverage(this.portfolioRatesOfReturn); ! //BasicFunctions.StdDev(this.portfolioRatesOfReturn) ); //); ! return returnValue; ! } ! public override object Decode(Genome genome) ! { ! string[] arrayOfTickers = new string[genome.Genes().Length]; ! int indexOfTicker; ! for(int index = 0; index < genome.Genes().Length; index++) ! { ! indexOfTicker = (int)genome.Genes().GetValue(index); ! arrayOfTickers[index] = this.decode_getTickerCodeForLongOrShortTrade(indexOfTicker); ! } ! GenomeMeaningPVO meaning = new GenomeMeaningPVO(arrayOfTickers, ! 0.0, 0.0, 2); ! return meaning; ! } } } --- 62,120 ---- numberOfTickersInPortfolio, 0.0, ! inSamplePortfolioType, ! benchmark) { ! this.setReturnsManager(); } ! private void setReturnsManager() ! { ! EndOfDayDateTime firstEndOfDayDateTime = ! new EndOfDayDateTime(firstQuoteDate, EndOfDaySpecificTime.MarketClose); ! EndOfDayDateTime lastEndOfDayDateTime = ! new EndOfDayDateTime(lastQuoteDate, EndOfDaySpecificTime.MarketClose); ! this.returnsManager = ! new ReturnsManager( new OpenToCloseCloseToOpenIntervals( ! firstEndOfDayDateTime, ! lastEndOfDayDateTime, ! this.benchmark) , ! new HistoricalAdjustedQuoteProvider() ); ! } ! ! private float[] getStrategyReturns_getReturnsActually( ! float[] plainReturns) ! { ! float[] returnValue = new float[plainReturns.Length]; ! returnValue[0] = 0; //at the very first day the ! //first strategy return is equal to 0 because no position ! //has been entered ! float coefficient = 0; ! for(int i = 0; i < returnValue.Length - 1; i++) { ! if( plainReturns[i] >= 0 ) ! //portfolio is overbought ! coefficient = -1; ! else if( plainReturns[i] <= 0 ) ! //portfolio is oversold ! coefficient = 1; ! //else ! // coefficient = coefficient; the previous coeff is kept ! returnValue[i + 1] = coefficient * plainReturns[i + 1]; } return returnValue; ! } ! protected override float[] getStrategyReturns() ! { ! EndOfDayDateTime firstEndOfDayDateTime = ! new EndOfDayDateTime(firstQuoteDate, EndOfDaySpecificTime.MarketClose); ! EndOfDayDateTime lastEndOfDayDateTime = ! new EndOfDayDateTime(lastQuoteDate, EndOfDaySpecificTime.MarketClose); ! float[] plainReturns = this.weightedPositionsFromGenome.GetReturns( ! this.returnsManager); ! return this.getStrategyReturns_getReturnsActually(plainReturns); ! } } } |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv7110/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator Modified Files: EndOfDayTimerHandlerPVO.cs GenomeManagerPVO.cs RunPVO.cs Log Message: Several changes applied to the classes implementing the Portfolio Value Oscillator strategy (the most important one relates to the use of ReturnsManager) Index: GenomeManagerPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/GenomeManagerPVO.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** GenomeManagerPVO.cs 3 Jan 2007 23:20:14 -0000 1.3 --- GenomeManagerPVO.cs 14 Jan 2008 23:07:02 -0000 1.4 *************** *** 24,27 **** --- 24,28 ---- using System.Data; using System.Collections; + using QuantProject.ADT; using QuantProject.ADT.Statistics; *************** *** 29,32 **** --- 30,39 ---- using QuantProject.Data; using QuantProject.Data.DataTables; + using QuantProject.Business.DataProviders; + using QuantProject.Business.Timing; + using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; + using QuantProject.Business.Strategies.ReturnsManagement.Time; + using QuantProject.Business.Strategies.TickersRelationships; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; *************** *** 41,60 **** public class GenomeManagerPVO : GenomeManagerForEfficientPortfolio { ! private int minLevelForOversoldThreshold; ! private int maxLevelForOversoldThreshold; ! private int minLevelForOverboughtThreshold; ! private int maxLevelForOverboughtThreshold; ! private int divisorForThresholdComputation; ! private bool symmetricalThresholds = false; ! private bool overboughtMoreThanOversoldForFixedPortfolio = false; ! private int numOfGenesDedicatedToThresholds; ! private double currentOversoldThreshold = 0.0; ! private double currentOverboughtThreshold = 0.0; ! private int numDaysForOscillatingPeriod; ! ! private double[] portfolioValues;//the values for each unit, invested ! //at the beginning of the optimization period, ! //throughout the period itself ! private void genomeManagerPVO_checkParametersForThresholdsComputation() { --- 48,66 ---- public class GenomeManagerPVO : GenomeManagerForEfficientPortfolio { ! protected int minLevelForOversoldThreshold; ! protected int maxLevelForOversoldThreshold; ! protected int minLevelForOverboughtThreshold; ! protected int maxLevelForOverboughtThreshold; ! protected int divisorForThresholdComputation; ! protected bool symmetricalThresholds = false; ! protected bool overboughtMoreThanOversoldForFixedPortfolio = false; ! protected int numOfGenesDedicatedToThresholds; ! protected double currentOversoldThreshold = 0.0; ! protected double currentOverboughtThreshold = 0.0; ! protected int numDaysForOscillatingPeriod; ! protected ReturnsManager returnsManager; ! protected CorrelationProvider correlationProvider;//used for experimental ! //tests using 2 tickers and PearsonCorrelationCoefficient as fitness ! private void genomeManagerPVO_checkParametersForThresholdsComputation() { *************** *** 86,90 **** bool symmetricalThresholds, bool overboughtMoreThanOversoldForFixedPortfolio, ! PortfolioType inSamplePortfolioType) : base(setOfInitialTickers, --- 92,97 ---- bool symmetricalThresholds, bool overboughtMoreThanOversoldForFixedPortfolio, ! PortfolioType inSamplePortfolioType, ! string benchmark) : base(setOfInitialTickers, *************** *** 93,97 **** numberOfTickersInPortfolio, 0.0, ! inSamplePortfolioType) --- 100,105 ---- numberOfTickersInPortfolio, 0.0, ! inSamplePortfolioType, ! benchmark) *************** *** 110,114 **** numOfGenesDedicatedToThresholds = 2; this.genomeManagerPVO_checkParametersForThresholdsComputation(); ! this.retrieveData(); } --- 118,140 ---- numOfGenesDedicatedToThresholds = 2; this.genomeManagerPVO_checkParametersForThresholdsComputation(); ! this.setReturnsManager(firstQuoteDate , lastQuoteDate); ! } ! ! protected virtual void setReturnsManager(DateTime firstQuoteDate, ! DateTime lastQuoteDate) ! { ! EndOfDayDateTime firstEndOfDayDateTime = ! new EndOfDayDateTime(firstQuoteDate, ! EndOfDaySpecificTime.MarketClose); ! EndOfDayDateTime lastEndOfDayDateTime = ! new EndOfDayDateTime(lastQuoteDate, ! EndOfDaySpecificTime.MarketClose); ! this.returnsManager = ! new ReturnsManager( new CloseToCloseIntervals( ! firstEndOfDayDateTime, ! lastEndOfDayDateTime, ! this.benchmark, ! this.numDaysForOscillatingPeriod), ! new HistoricalAdjustedQuoteProvider() ); } *************** *** 193,231 **** #endregion ! ! protected override float[] getArrayOfRatesOfReturn(string ticker) ! { ! float[] returnValue = null; ! Quotes tickerQuotes = new Quotes(ticker, this.firstQuoteDate, this.lastQuoteDate); ! tickerQuotes.RecalculateCloseToCloseRatios(); ! returnValue = QuantProject.ADT.ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuotes, ! Quotes.AdjustedCloseToCloseRatio); ! for(int i = 0; i<returnValue.Length; i++) ! returnValue[i] = returnValue[i] - 1.0f; ! ! this.numberOfExaminedReturns = returnValue.Length; ! ! return returnValue; ! } ! //starting from this.numDaysForOscillatingPeriod day, ! //it computes for each day ahead the value of the ! //portfolio opened numDaysForOscillatingPeriod days ago ! private double[] getPortfolioMovingValues() ! { ! double[] returnValue = new double[this.portfolioRatesOfReturn.Length]; ! double[] valuesInOscillatingPeriod = new double[this.numDaysForOscillatingPeriod]; ! valuesInOscillatingPeriod[0] = 1.0; ! for(int i = this.numDaysForOscillatingPeriod; i<returnValue.Length; i++) { ! for(int j = 1; ! j < this.numDaysForOscillatingPeriod; j++) ! valuesInOscillatingPeriod[j] = ! valuesInOscillatingPeriod[j - 1] + ! valuesInOscillatingPeriod[j - 1] * ! this.portfolioRatesOfReturn[i-this.numDaysForOscillatingPeriod+j]; ! returnValue[i-1] = valuesInOscillatingPeriod[this.numDaysForOscillatingPeriod -1]; } return returnValue; ! } private void getFitnessValue_setCurrentThresholds(Genome genome) --- 219,261 ---- #endregion ! ! ! #region getStrategyReturns ! ! private float[] getStrategyReturns_getReturnsActually( ! float[] plainReturns) ! { ! ! float[] returnValue = new float[plainReturns.Length]; ! returnValue[0] = 0; //a the very first day the ! //strategy return is equal to 0 because no position ! //has been entered ! float coefficient = 0; ! for(int i = 0; i < returnValue.Length - 1; i++) { ! if( plainReturns[i] >= (float)this.currentOverboughtThreshold ) ! //portfolio has been overbought ! coefficient = -1; ! else if( plainReturns[i] <= - (float)this.currentOversoldThreshold ) ! //portfolio has been oversold ! coefficient = 1; ! //else the previous coeff is kept or, if no threshold has been ! //reached, then no positions will be opened (coefficient = 0) ! returnValue[i + 1] = coefficient * plainReturns[i + 1]; } return returnValue; ! ! //return plainReturns; ! } ! ! protected override float[] getStrategyReturns() ! { ! float[] plainReturns = this.weightedPositionsFromGenome.GetReturns( ! this.returnsManager); ! return this.getStrategyReturns_getReturnsActually(plainReturns); ! } ! ! #endregion ! private void getFitnessValue_setCurrentThresholds(Genome genome) *************** *** 241,249 **** } ! private int getFitnessValue_getDaysOnTheMarket(double[] equityLine) { int returnValue = 0; ! foreach(double equityReturn in equityLine) ! if(equityReturn != 0.0) //the applied strategy gets positions on the market returnValue++; --- 271,279 ---- } ! protected int getFitnessValue_getDaysOnTheMarket() { int returnValue = 0; ! foreach(float strategyReturn in this.strategyReturns) ! if(strategyReturn != 0) //the applied strategy gets positions on the market returnValue++; *************** *** 251,315 **** return returnValue; } ! ! //fitness is a sharpe-ratio based indicator for the equity line resulting ! //from applying the strategy ! public override double GetFitnessValue(Genome genome) { ! double returnValue = -1.0; ! this.portfolioRatesOfReturn = this.getPortfolioRatesOfReturn(genome.Genes()); ! this.portfolioValues = this.getPortfolioMovingValues(); ! this.getFitnessValue_setCurrentThresholds(genome); ! double[] equityLine = this.getFitnessValue_getEquityLineRates(); ! double fitness = Double.NaN; ! if(this.getFitnessValue_getDaysOnTheMarket(equityLine) > ! equityLine.Length / 2) ! //if the genome represents a portfolio that stays on the market ! //at least half of the theoretical days ! fitness = AdvancedFunctions.GetSharpeRatio(equityLine); ! if(!double.IsNaN(fitness) && !double.IsInfinity(fitness)) ! returnValue = fitness; ! ! return returnValue; } ! private double[] getFitnessValue_getEquityLineRates() { ! double[] returnValue = new double[this.PortfolioRatesOfReturn.Length]; ! double coefficient = 0.0; ! for(int i = 0; i<this.PortfolioRatesOfReturn.Length - 1;i++) ! { ! if(this.portfolioValues[i] >= ! 1.0 + this.currentOverboughtThreshold) ! //portfolio is overbought ! coefficient = -1.0; ! else if(this.portfolioValues[i] <= ! 1.0 - this.currentOversoldThreshold && ! this.portfolioValues[i] > 0.0) ! //portfolio is oversold ! coefficient = 1.0; ! ! returnValue[i + 1] = ! coefficient * this.PortfolioRatesOfReturn[i + 1]; ! } ! return returnValue; } ! ! protected override double getTickerWeight(int[] genes, int tickerPositionInGenes) { ! return 1.0/(genes.Length - this.numOfGenesDedicatedToThresholds); } ! ! protected override double[] getPortfolioRatesOfReturn(int[] genes) { ! double[] returnValue = new double[this.numberOfExaminedReturns]; ! for(int i = 0; i<returnValue.Length; i++) ! { ! for(int j=this.numOfGenesDedicatedToThresholds; j<genes.Length; j++)//the first numOfGenesDedicatedToThresholds are for thresholds ! returnValue[i] += ! this.getPortfolioRatesOfReturn_getRateOfTickerToBeAddedToTheArray(genes,j,i); ! } ! return returnValue; } public override object Decode(Genome genome) { --- 281,348 ---- return returnValue; } ! ! private double getFitnessValue_calculate_calculateActually() { ! return this.AverageOfStrategyReturns/Math.Sqrt(this.VarianceOfStrategyReturns); ! //return Math.Sqrt(this.VarianceOfStrategyReturns); } ! ! protected override double getFitnessValue_calculate() { ! double returnValue = -1.0; ! if(this.getFitnessValue_getDaysOnTheMarket() > ! this.strategyReturns.Length / 2) ! //if the genome represents a portfolio that stays on the market ! //at least half of the theoretical days ! returnValue = ! this.getFitnessValue_calculate_calculateActually(); ! return returnValue; } ! ! protected string getFitnessValue_getFirstTickerFromGenome(Genome genome) { ! GenomeMeaningPVO genomeMeaning = (GenomeMeaningPVO)genome.Meaning; ! return genomeMeaning.Tickers[0]; } ! protected string getFitnessValue_getSecondTickerFromGenome(Genome genome) { ! GenomeMeaningPVO genomeMeaning = (GenomeMeaningPVO)genome.Meaning; ! return genomeMeaning.Tickers[1]; } + + //fitness is a sharpe-ratio based indicator for the equity line resulting + //from applying the strategy + public override double GetFitnessValue(Genome genome) + { + //OLD CLASSICAL IMPLEMENTATION (sharpeRatio applied to strategyReturns) + // this.getFitnessValue_setCurrentThresholds(genome); + // return base.GetFitnessValue(genome); + //NEW implementation: fitness is just the pearson correlation + //applied to two tickers. This kind of fitness is only valid + //for experimental tests with 2-tickers portfolios + double returnValue = -2.0; + if(this.correlationProvider == null) + this.correlationProvider = new CloseToCloseCorrelationProvider( + QuantProject.ADT.ExtendedDataTable.GetArrayOfStringFromColumn(this.setOfTickers, 0), + this.returnsManager, 0.0001f, 0.5f); + string firstTicker = this.getFitnessValue_getFirstTickerFromGenome(genome); + string secondTicker = this.getFitnessValue_getSecondTickerFromGenome(genome); + if( ( firstTicker.StartsWith("-") && !secondTicker.StartsWith("-") ) || + ( secondTicker.StartsWith("-") && !firstTicker.StartsWith("-") ) ) + //tickers have to be opposite in sign + { + double correlationIndex = correlationProvider.GetPearsonCorrelation( + SignedTicker.GetTicker(firstTicker), + SignedTicker.GetTicker(secondTicker) ); + if(correlationIndex < 0.96) + // if correlation index is not too high to be + // probably originated by the same instrument + returnValue = correlationIndex; + } + return returnValue; + } + public override object Decode(Genome genome) { *************** *** 326,338 **** this.decode_getTickerCodeForLongOrShortTrade(geneForTicker); } if(this.symmetricalThresholds) ! meaning = new GenomeMeaningPVO( ! arrayOfTickers, Convert.ToDouble(genome.Genes()[0])/Convert.ToDouble(this.divisorForThresholdComputation), Convert.ToDouble(genome.Genes()[0])/Convert.ToDouble(this.divisorForThresholdComputation), this.numDaysForOscillatingPeriod); else ! meaning = new GenomeMeaningPVO( ! arrayOfTickers, Convert.ToDouble(genome.Genes()[0])/Convert.ToDouble(this.divisorForThresholdComputation), Convert.ToDouble(genome.Genes()[1])/Convert.ToDouble(this.divisorForThresholdComputation), --- 359,376 ---- this.decode_getTickerCodeForLongOrShortTrade(geneForTicker); } + + double[] arrayOfWeights = ExtendedMath.ArrayOfAbs( + WeightedPositions.GetBalancedWeights(new SignedTickers(arrayOfTickers), + this.returnsManager) ); + if(this.symmetricalThresholds) ! meaning = new GenomeMeaningPVO(arrayOfTickers, ! arrayOfWeights, Convert.ToDouble(genome.Genes()[0])/Convert.ToDouble(this.divisorForThresholdComputation), Convert.ToDouble(genome.Genes()[0])/Convert.ToDouble(this.divisorForThresholdComputation), this.numDaysForOscillatingPeriod); else ! meaning = new GenomeMeaningPVO(arrayOfTickers, ! arrayOfWeights, Convert.ToDouble(genome.Genes()[0])/Convert.ToDouble(this.divisorForThresholdComputation), Convert.ToDouble(genome.Genes()[1])/Convert.ToDouble(this.divisorForThresholdComputation), Index: RunPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/RunPVO.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RunPVO.cs 27 Feb 2007 22:19:51 -0000 1.4 --- RunPVO.cs 14 Jan 2008 23:07:02 -0000 1.5 *************** *** 61,64 **** --- 61,65 ---- protected int numDaysBetweenEachOptimization; protected double maxAcceptableCloseToCloseDrawdown; + protected double minimumAcceptableGain; protected int numDaysForOscillatingPeriod; protected bool symmetricalThresholds = false; *************** *** 80,83 **** --- 81,85 ---- int numDaysBetweenEachOptimization, PortfolioType inSamplePortfolioType, double maxAcceptableCloseToCloseDrawdown, + double minimumAcceptableGain, double maxRunningHours): base(tickerGroupID, maxNumOfEligibleTickersForOptimization, *************** *** 97,100 **** --- 99,103 ---- this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; + this.minimumAcceptableGain = minimumAcceptableGain; this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; *************** *** 119,123 **** this.overboughtMoreThanOversoldForFixedPortfolio, this.numDaysBetweenEachOptimization, ! this.portfolioType, this.maxAcceptableCloseToCloseDrawdown); } --- 122,127 ---- this.overboughtMoreThanOversoldForFixedPortfolio, this.numDaysBetweenEachOptimization, ! this.portfolioType, this.maxAcceptableCloseToCloseDrawdown, ! this.minimumAcceptableGain); } Index: EndOfDayTimerHandlerPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/EndOfDayTimerHandlerPVO.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** EndOfDayTimerHandlerPVO.cs 23 Sep 2007 22:07:57 -0000 1.7 --- EndOfDayTimerHandlerPVO.cs 14 Jan 2008 23:07:02 -0000 1.8 *************** *** 30,36 **** --- 30,41 ---- using QuantProject.Business.Timing; using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; + using QuantProject.Business.Strategies.ReturnsManagement.Time; + using QuantProject.Business.DataProviders; + using QuantProject.Business.Strategies.TickersRelationships; using QuantProject.Data; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; + //using QuantProject.Data.Selectors.ByLinearDipendence; using QuantProject.Data.DataTables; using QuantProject.ADT.Optimizing.Genetic; *************** *** 57,60 **** --- 62,66 ---- protected double currentOverboughtThreshold; protected double maxAcceptableCloseToCloseDrawdown; + protected double minimumAcceptableGain; protected DateTime lastCloseDate; protected IGenomeManager iGenomeManager; *************** *** 64,67 **** --- 70,74 ---- protected bool symmetricalThresholds; protected bool overboughtMoreThanOversoldForFixedPortfolio; + protected HistoricalAdjustedQuoteProvider historicalQuoteProvider; public EndOfDayTimerHandlerPVO(string tickerGroupID, int numberOfEligibleTickers, *************** *** 80,84 **** bool overboughtMoreThanOversoldForFixedPortfolio, int numDaysBetweenEachOptimization, ! PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, --- 87,92 ---- bool overboughtMoreThanOversoldForFixedPortfolio, int numDaysBetweenEachOptimization, ! PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, *************** *** 97,100 **** --- 105,109 ---- this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; + this.minimumAcceptableGain = minimumAcceptableGain; this.stopLossConditionReached = false; this.currentAccountValue = 0.0; *************** *** 104,107 **** --- 113,117 ---- this.portfolioHasBeenOverbought = false; this.portfolioHasBeenOversold = false; + this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); } *************** *** 114,142 **** #region MarketCloseEventHandler ! protected void marketCloseEventHandler_updateStopLossCondition() ! { ! this.previousAccountValue = this.currentAccountValue; ! this.currentAccountValue = this.account.GetMarketValue(); ! if( (this.currentAccountValue - this.previousAccountValue)/ ! this.previousAccountValue < -this.maxAcceptableCloseToCloseDrawdown ) ! this.stopLossConditionReached = true; ! else ! this.stopLossConditionReached = false; ! } ! ! protected virtual double getCurrentChosenWeightedPositionsValue(IndexBasedEndOfDayTimer timer) { double returnValue = 999.0; try { ! DateTime initialDate = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForOscillatingPeriod + 2]["quDate"]; ! //so to replicate exactly in sample scheme, where only numOscillatingDay - 1 returns ! //are computed ! DateTime finalDate = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! returnValue = ! this.chosenWeightedPositions.GetCloseToCloseReturn( initialDate, ! finalDate) + 1.0; } catch(MissingQuotesException ex) --- 124,144 ---- #region MarketCloseEventHandler ! protected virtual double getCurrentChosenWeightedPositionsReturn(IndexBasedEndOfDayTimer timer) { double returnValue = 999.0; try { ! DateTime firstDayOfOscillatingPeriod = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForOscillatingPeriod]["quDate"]; ! DateTime today = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! ReturnsManager returnsManager = new ReturnsManager(new CloseToCloseIntervals( ! new EndOfDayDateTime(firstDayOfOscillatingPeriod, ! EndOfDaySpecificTime.MarketClose) , ! new EndOfDayDateTime(today, ! EndOfDaySpecificTime.MarketClose) , ! this.benchmark , this.numDaysForOscillatingPeriod ) , ! this.historicalQuoteProvider ); ! returnValue = this.chosenWeightedPositions.GetReturn(0,returnsManager); } catch(MissingQuotesException ex) *************** *** 149,179 **** private void marketCloseEventHandler_reverseIfNeeded(IndexBasedEndOfDayTimer timer) { ! double currentChosenWeightedPositionsTickersValue = ! this.getCurrentChosenWeightedPositionsValue(timer); ! if(currentChosenWeightedPositionsTickersValue != 999.0) ! //currentChosenTickersValue has been properly computed { ! if(this.portfolioType == PortfolioType.ShortAndLong) ! //it is possible to reverse positions ! { ! if(currentChosenWeightedPositionsTickersValue >= 1.0 + currentOverboughtThreshold && ! this.portfolioHasBeenOversold) ! //open positions derive from an overSold period but now ! //an the overbought threshold has been reached ! { ! this.reversePositions(); ! this.portfolioHasBeenOversold = false; ! this.portfolioHasBeenOverbought = true; ! } ! if(currentChosenWeightedPositionsTickersValue <= 1.0 - currentOversoldThreshold && ! this.portfolioHasBeenOverbought) ! //open positions derive from an overSold period but now ! //an the overbought threshold has been reached ! { ! this.reversePositions(); ! this.portfolioHasBeenOversold = true; ! this.portfolioHasBeenOverbought = false; ! } ! } } } --- 151,181 ---- private void marketCloseEventHandler_reverseIfNeeded(IndexBasedEndOfDayTimer timer) { ! double currentChosenWeightedPositionsReturn = ! this.getCurrentChosenWeightedPositionsReturn(timer); ! if(currentChosenWeightedPositionsReturn != 999.0 && ! this.portfolioType == PortfolioType.ShortAndLong) ! //currentChosenWeightedPositionsReturn has been ! //properly computedand it is possible to reverse positions { ! if(currentChosenWeightedPositionsReturn >= currentOverboughtThreshold && ! this.portfolioHasBeenOversold) ! //open positions derive from an overSold period but now ! //the overbought threshold has been reached ! { ! this.reversePositions(); ! this.portfolioHasBeenOversold = false; ! this.portfolioHasBeenOverbought = true; ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! if(currentChosenWeightedPositionsReturn <= - currentOversoldThreshold && ! this.portfolioHasBeenOverbought) ! //open positions derive from an overBought period but now ! //the overSold threshold has been reached ! { ! this.reversePositions(); ! this.portfolioHasBeenOversold = true; ! this.portfolioHasBeenOverbought = false; ! this.previousAccountValue = this.account.GetMarketValue(); ! } } } *************** *** 183,192 **** if(this.account.CashAmount == 0.0 && this.account.Transactions.Count == 0) this.account.AddCash(15000); ! double currentChosenWeightedPositionsValue = ! this.getCurrentChosenWeightedPositionsValue(timer); ! if(currentChosenWeightedPositionsValue != 999.0) //currentChosenTickersValue has been properly computed { ! if(currentChosenWeightedPositionsValue >= 1.0 + currentOverboughtThreshold && this.portfolioType == PortfolioType.ShortAndLong) { --- 185,194 ---- if(this.account.CashAmount == 0.0 && this.account.Transactions.Count == 0) this.account.AddCash(15000); ! double currentChosenWeightedPositionsReturn = ! this.getCurrentChosenWeightedPositionsReturn(timer); ! if(currentChosenWeightedPositionsReturn != 999.0) //currentChosenTickersValue has been properly computed { ! if(currentChosenWeightedPositionsReturn >= currentOverboughtThreshold && this.portfolioType == PortfolioType.ShortAndLong) { *************** *** 198,201 **** --- 200,204 ---- this.portfolioHasBeenOverbought = true; this.portfolioHasBeenOversold = false; + this.previousAccountValue = this.account.GetMarketValue(); } catch(Exception ex) *************** *** 208,219 **** } } ! else if (currentChosenWeightedPositionsValue <= 1.0 - currentOversoldThreshold) { AccountManager.OpenPositions( this.chosenWeightedPositions, ! this.account ); this.portfolioHasBeenOverbought = false; this.portfolioHasBeenOversold = true; } ! } } --- 211,223 ---- } } ! else if (currentChosenWeightedPositionsReturn <= - currentOversoldThreshold) { AccountManager.OpenPositions( this.chosenWeightedPositions, ! this.account ); this.portfolioHasBeenOverbought = false; this.portfolioHasBeenOversold = true; + this.previousAccountValue = this.account.GetMarketValue(); } ! } } *************** *** 221,231 **** { if(this.stopLossConditionReached || ! this.numDaysElapsedSinceLastOptimization + 1 == this.numDaysBetweenEachOptimization ) { AccountManager.ClosePositions(this.account); - //a new optimization is needed, now - this.chosenWeightedPositions = null; - //when positions are closed, these parameters - //have to be reset to false this.portfolioHasBeenOverbought = false; this.portfolioHasBeenOversold = false; --- 225,232 ---- { if(this.stopLossConditionReached || ! this.takeProfitConditionReached || ! this.numDaysElapsedSinceLastOptimization + 1 == this.numDaysBetweenEachOptimization ) { AccountManager.ClosePositions(this.account); this.portfolioHasBeenOverbought = false; this.portfolioHasBeenOversold = false; *************** *** 233,240 **** } public override void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! //this.marketCloseEventHandler_updateStopLossCondition(); this.marketCloseEventHandler_closePositionsIfNeeded(); if(this.chosenWeightedPositions != null) --- 234,261 ---- } + protected virtual void marketCloseEventHandler_updateStopLossAndTakeProfitConditions() + { + //this.previousAccountValue has been set at opening positions + this.currentAccountValue = this.account.GetMarketValue(); + double portfolioGainOrLoss = (this.currentAccountValue - this.previousAccountValue) + /this.previousAccountValue; + + if( portfolioGainOrLoss <= -this.maxAcceptableCloseToCloseDrawdown ) + { + this.stopLossConditionReached = true; + this.takeProfitConditionReached = false; + } + else if (portfolioGainOrLoss >= this.minimumAcceptableGain) + + { + this.stopLossConditionReached = false; + this.takeProfitConditionReached = true; + } + } + public override void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { ! this.marketCloseEventHandler_updateStopLossAndTakeProfitConditions(); this.marketCloseEventHandler_closePositionsIfNeeded(); if(this.chosenWeightedPositions != null) *************** *** 247,251 **** this.marketCloseEventHandler_reverseIfNeeded((IndexBasedEndOfDayTimer)sender); } - } --- 268,271 ---- *************** *** 253,258 **** #region OneHourAfterMarketCloseEventHandler ! ! protected virtual DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { --- 273,277 ---- #region OneHourAfterMarketCloseEventHandler ! protected virtual DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { *************** *** 262,269 **** SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice(tickersFromGroup,false,currentDate.AddDays(-30), currentDate, numOfTickersInGroupAtCurrentDate, ! 20,500, 0.0001,100); SelectorByLiquidity mostLiquidSelector = --- 281,288 ---- SelectorByAverageRawOpenPrice byPrice = ! new SelectorByAverageRawOpenPrice(tickersFromGroup,false,currentDate.AddDays(-15), currentDate, numOfTickersInGroupAtCurrentDate, ! 30,3000, 0.0001,100); SelectorByLiquidity mostLiquidSelector = *************** *** 283,288 **** false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfEligibleTickers, this.benchmark); ! ! return quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(); //for debug // SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromLastSelection = --- 302,330 ---- false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfEligibleTickers, this.benchmark); ! // SelectorByMaxLinearDipendence dipendentTickers = ! // new SelectorByMaxLinearDipendence(quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(), ! // currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // this.numberOfEligibleTickers/2,2,1000, this.benchmark); ! // return dipendentTickers.GetTableOfSelectedTickers(); ! ! // DataTable quotedAtEachMarketDay = ! // quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(); ! // ! // CloseToCloseCorrelationProvider correlationProvider = ! // new CloseToCloseCorrelationProvider( ! // QuantProject.ADT.ExtendedDataTable.GetArrayOfStringFromColumn( ! // quotedAtEachMarketDay, 0 ), ! // currentDate.AddDays(-this.numDaysForOptimizationPeriod), ! // currentDate,1,0.005,this.benchmark); ! ! // SelectorByCloseToCloseCorrelationToBenchmark byCorrelationToBenchmark = ! // new SelectorByCloseToCloseCorrelationToBenchmark( ! // quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(), ! // this.benchmark, false, ! // currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // this.numberOfEligibleTickers / 2, false); ! // return byCorrelationToBenchmark.GetTableOfSelectedTickers(); ! ! return quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(); //for debug // SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromLastSelection = *************** *** 334,338 **** this.symmetricalThresholds, this.overboughtMoreThanOversoldForFixedPortfolio, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, --- 376,380 ---- this.symmetricalThresholds, this.overboughtMoreThanOversoldForFixedPortfolio, ! this.portfolioType,this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, *************** *** 341,345 **** if(setGenomeCounter) this.genomeCounter = new GenomeCounter(GO); ! GO.MutationRate = 0.2; GO.Run(false); --- 383,387 ---- if(setGenomeCounter) this.genomeCounter = new GenomeCounter(GO); ! GO.MutationRate = 0.1; GO.Run(false); |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv7110/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO Modified Files: EndOfDayTimerHandlerBiasedPVO.cs RunBiasedPVO.cs Log Message: Several changes applied to the classes implementing the Portfolio Value Oscillator strategy (the most important one relates to the use of ReturnsManager) Index: RunBiasedPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/RunBiasedPVO.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunBiasedPVO.cs 8 Apr 2007 18:56:00 -0000 1.2 --- RunBiasedPVO.cs 14 Jan 2008 23:07:03 -0000 1.3 *************** *** 24,27 **** --- 24,29 ---- using System.Collections; using System.Data; + using System.IO; + using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; *************** *** 58,65 **** public class RunBiasedPVO : RunPVO { ! private int numOfDifferentGenomesToEvaluateOutOfSample; ! private double minimumAcceptableGain; ! ! public RunBiasedPVO(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, --- 60,84 ---- public class RunBiasedPVO : RunPVO { ! protected double minPriceForTickersToBeChosen; ! protected double maxPriceForTickersToBeChosen; ! protected int numOfDifferentGenomesToEvaluateOutOfSample; ! protected int numDaysOfStayingOnTheMarket; ! protected double maxCoefficientForDegreeComputationOfCrossingThreshold; ! protected double numOfStdDevForThresholdsComputation; ! protected bool resetThresholdsBeforeCheckingOutOfSample; ! protected bool buyOnlyPositionsThatAreMovingTogether; ! protected bool doNotOpenReversedPositionsThatHaveJustBeenClosed; ! protected int numDaysForThresholdsReComputation; ! ! protected string pathOfFileContainingGenomes; ! public string PathOfFileContainingGenomes ! { ! get { return pathOfFileContainingGenomes; } ! set { pathOfFileContainingGenomes = value; } ! } ! ! public RunBiasedPVO(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, ! double minPriceForTickersToBeChosen, ! double maxPriceForTickersToBeChosen, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, *************** *** 67,71 **** --- 86,97 ---- DateTime startDate, DateTime endDate, int numOfDifferentGenomesToEvaluateOutOfSample, + bool resetThresholdsBeforeCheckingOutOfSample, + int numDaysForThresholdsReComputation, + double numOfStdDevForThresholdsComputation, + double maxCoefficientForDegreeComputationOfCrossingThreshold, + bool buyOnlyPositionsThatAreMovingTogether, + bool doNotOpenReversedPositionsThatHaveJustBeenClosed, int numDaysForOscillatingPeriod, + int numDaysOfStayingOnTheMarket, int minLevelForOversoldThreshold, int maxLevelForOversoldThreshold, *************** *** 93,101 **** numDaysBetweenEachOptimization, inSamplePortfolioType, maxAcceptableCloseToCloseDrawdown, maxRunningHours) { ! this.numOfDifferentGenomesToEvaluateOutOfSample = numOfDifferentGenomesToEvaluateOutOfSample; this.minimumAcceptableGain = minimumAcceptableGain; ! this.ScriptName = "PVO_Biased_WithWeightsPriceSel"; } --- 119,144 ---- numDaysBetweenEachOptimization, inSamplePortfolioType, maxAcceptableCloseToCloseDrawdown, + minimumAcceptableGain, maxRunningHours) { ! this.minPriceForTickersToBeChosen = minPriceForTickersToBeChosen; ! this.maxPriceForTickersToBeChosen = maxPriceForTickersToBeChosen; ! this.numOfDifferentGenomesToEvaluateOutOfSample = numOfDifferentGenomesToEvaluateOutOfSample; this.minimumAcceptableGain = minimumAcceptableGain; ! //this.ScriptName = "PVO_Biased_WithWeightsPriceSel"; ! this.ScriptName = "PVO_Biased_NoWeightsPriceSel"; ! this.numDaysOfStayingOnTheMarket = numDaysOfStayingOnTheMarket; ! this.maxCoefficientForDegreeComputationOfCrossingThreshold = maxCoefficientForDegreeComputationOfCrossingThreshold; ! this.resetThresholdsBeforeCheckingOutOfSample = resetThresholdsBeforeCheckingOutOfSample; ! this.numDaysForThresholdsReComputation = numDaysForThresholdsReComputation; ! this.numOfStdDevForThresholdsComputation = numOfStdDevForThresholdsComputation; ! this.buyOnlyPositionsThatAreMovingTogether = buyOnlyPositionsThatAreMovingTogether; ! this.doNotOpenReversedPositionsThatHaveJustBeenClosed = doNotOpenReversedPositionsThatHaveJustBeenClosed; ! this.pathOfFileContainingGenomes = null; ! //if this field is set to null, selections of tickers (with ! //optimization), takes place; otherwise, tickers for ! //out of sample testing are chosen from a given ! //set of genomes saved to disk (representing a set of ! //a certain number of optimizations run over a given period) } *************** *** 105,127 **** { this.endOfDayTimerHandler = new EndOfDayTimerHandlerBiasedPVO(this.tickerGroupID, this.numberOfEligibleTickers, ! this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, ! this.account, ! this.generationNumberForGeneticOptimizer, ! this.populationSizeForGeneticOptimizer, this.benchmark, ! this.numOfDifferentGenomesToEvaluateOutOfSample, ! this.numDaysForOscillatingPeriod, ! this.minLevelForOversoldThreshold, ! this.maxLevelForOversoldThreshold, ! this.minLevelForOverboughtThreshold, ! this.maxLevelForOverboughtThreshold, ! this.divisorForThresholdComputation, ! this.symmetricalThresholds, ! this.overboughtMoreThanOversoldForFixedPortfolio, ! this.numDaysBetweenEachOptimization, ! this.portfolioType, this.maxAcceptableCloseToCloseDrawdown, ! this.minimumAcceptableGain); } ! public override void SaveScriptResults() --- 148,228 ---- { this.endOfDayTimerHandler = new EndOfDayTimerHandlerBiasedPVO(this.tickerGroupID, this.numberOfEligibleTickers, ! this.minPriceForTickersToBeChosen, ! this.maxPriceForTickersToBeChosen, ! this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, ! this.account, ! this.PathOfFileContainingGenomes, ! this.generationNumberForGeneticOptimizer, ! this.populationSizeForGeneticOptimizer, this.benchmark, ! this.numOfDifferentGenomesToEvaluateOutOfSample, ! this.resetThresholdsBeforeCheckingOutOfSample, ! this.numDaysForThresholdsReComputation, ! this.numOfStdDevForThresholdsComputation, ! this.maxCoefficientForDegreeComputationOfCrossingThreshold, ! this.buyOnlyPositionsThatAreMovingTogether, ! this.doNotOpenReversedPositionsThatHaveJustBeenClosed, ! this.numDaysForOscillatingPeriod, ! this.numDaysOfStayingOnTheMarket, ! this.minLevelForOversoldThreshold, ! this.maxLevelForOversoldThreshold, ! this.minLevelForOverboughtThreshold, ! this.maxLevelForOverboughtThreshold, ! this.divisorForThresholdComputation, ! this.symmetricalThresholds, ! this.overboughtMoreThanOversoldForFixedPortfolio, ! this.numDaysBetweenEachOptimization, ! this.portfolioType, this.maxAcceptableCloseToCloseDrawdown, ! this.minimumAcceptableGain); } ! ! private void saveScriptResults_saveScriptFeaturesToLogFile(string nameForScriptFiles) ! { ! string pathFile = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + ! "\\" + this.ScriptName + "\\" + nameForScriptFiles + ".txt"; ! StreamWriter w = File.AppendText(pathFile); ! w.WriteLine ("\n----------------------------------------------\r\n"); ! w.Write("\r\nScript file: {0}\r", nameForScriptFiles); ! w.Write("\r\nSelection of tickers from group: {0}\r", this.tickerGroupID); ! w.Write("\r\nSelect eligible from tickers with minimum price (in the last 30 days): {0}\r", this.minPriceForTickersToBeChosen.ToString()); ! w.Write("\r\nSelect eligible from tickers with maximum price (in the last 30 days): {0}\r", this.maxPriceForTickersToBeChosen.ToString()); ! w.Write("\r\nMax num of eligible tickers for optimization (most liquid): {0}\r", this.numberOfEligibleTickers.ToString()); ! w.Write("\r\nNum of tickers in portfolio: {0}\r", this.numberOfTickersToBeChosen.ToString()); ! w.Write("\r\nPath name file of already optimized genomes: {0}\r", this.PathOfFileContainingGenomes); ! w.Write("\r\nLength in days for optimization period: {0}\r", this.numDaysForOptimizationPeriod.ToString()); ! w.Write("\r\nGeneration number for genetic optimizer: {0}\r", this.generationNumberForGeneticOptimizer.ToString()); ! w.Write("\r\nPopulation size for genetic optimizer: {0}\r", this.populationSizeForGeneticOptimizer.ToString()); ! w.Write("\r\nOptimization each (num of days): {0}\r", this.numDaysBetweenEachOptimization.ToString()); ! w.Write("\r\nBenchmark: {0}\r", this.benchmark); ! w.Write("\r\nStart date: {0}\r", this.startDateTime.DateTime.ToLongDateString()); ! w.Write("\r\nEnd date: {0}\r", this.endDateTime.DateTime.ToLongDateString()); ! w.Write("\r\nNum of genomes to check out of sample: {0}\r", this.numOfDifferentGenomesToEvaluateOutOfSample.ToString()); ! w.Write("\r\nReset thresholds out of sample: {0}\r", this.resetThresholdsBeforeCheckingOutOfSample.ToString()); ! w.Write("\r\nNum of Days for thresholds recomputation out of sample: {0}\r", this.numDaysForThresholdsReComputation.ToString()); ! w.Write("\r\nNum of standard deviation from average for setting thresholds out of sample: {0}\r", this.numOfStdDevForThresholdsComputation.ToString()); ! w.Write("\r\nDiscard genome if degree of crossing threshold is {0} * threshold away\r", this.maxCoefficientForDegreeComputationOfCrossingThreshold.ToString()); ! w.Write("\r\nBuy only positions that are moving together: {0}\r", this.buyOnlyPositionsThatAreMovingTogether.ToString()); ! w.Write("\r\nDo not reverse positions that have just been closed: {0}\r", this.doNotOpenReversedPositionsThatHaveJustBeenClosed.ToString()); ! w.Write("\r\nLength return (oscillating period): {0}\r", this.numDaysForOscillatingPeriod.ToString()); ! w.Write("\r\nNumDays of staying on the market: {0}\r", this.numDaysOfStayingOnTheMarket.ToString()); ! w.Write("\r\nMin level for oversold threshold: {0}\r", this.minLevelForOversoldThreshold.ToString()); ! w.Write("\r\nMax level for oversold threshold: {0}\r", this.maxLevelForOversoldThreshold.ToString()); ! w.Write("\r\nMin level for overbought threshold: {0}\r", this.minLevelForOverboughtThreshold.ToString()); ! w.Write("\r\nMax level for overbought threshold: {0}\r", this.maxLevelForOverboughtThreshold.ToString()); ! w.Write("\r\nDivisor for threshold computation: {0}\r", this.divisorForThresholdComputation.ToString()); ! w.Write("\r\nSymmetrical thresholds: {0}\r", this.symmetricalThresholds.ToString()); ! w.Write("\r\nOverbought more than oversold: {0}\r", this.overboughtMoreThanOversoldForFixedPortfolio.ToString()); ! w.Write("\r\nSymmetrical thresholds: {0}\r", this.symmetricalThresholds.ToString()); ! w.Write("\r\nNum days between each optimization: {0}\r", this.numDaysBetweenEachOptimization.ToString()); ! w.Write("\r\nIn sample portfolio type: {0}\r", this.portfolioType.ToString()); ! w.Write("\r\nMax acceptable draw down: {0}\r", this.maxAcceptableCloseToCloseDrawdown.ToString()); ! w.Write("\r\nMinimum acceptable gain: {0}\r", this.minimumAcceptableGain.ToString()); ! w.Write("\r\nMax running hours: {0}\r", this.maxRunningHours.ToString()); ! w.WriteLine ("\n----------------------------------------------"); ! //w.Write("\r\nFitnesses compared (sharpe r. OTC): {0}\r", this.fitnessesInSample.Length.ToString()); ! // Update the underlying file. ! w.Flush(); ! w.Close(); ! } public override void SaveScriptResults() *************** *** 129,132 **** --- 230,234 ---- string fileName = DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + + DateTime.Now.Second.ToString().PadLeft(2,'0') + "_" + this.scriptName + "GenOS_" + this.numOfDifferentGenomesToEvaluateOutOfSample + "_OsDays_" + numDaysForOscillatingPeriod + *************** *** 145,170 **** this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); ! OptimizationOutput optimizationOutput = new OptimizationOutput(); ! foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) optimizationOutput.Add(genomeRepresentation); ! ObjectArchiver.Archive(optimizationOutput, dirNameWhereToSaveBestGenomes + fileName + ".bgn"); ! ! //default report with numIntervalDays = 1 AccountReport accountReport = this.account.CreateReport(fileName,1, this.endOfDayTimer.GetCurrentTime(), this.benchmark, ! new HistoricalAdjustedQuoteProvider()); ! this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ObjectArchiver.Archive(accountReport, dirNameWhereToSaveReports + fileName + ".qPr"); ! this.endOfDayTimer.Stop(); - } ! #endregion } --- 247,272 ---- this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); ! if( this.PathOfFileContainingGenomes == null ) ! { ! OptimizationOutput optimizationOutput = new OptimizationOutput(); ! foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) optimizationOutput.Add(genomeRepresentation); ! ObjectArchiver.Archive(optimizationOutput, dirNameWhereToSaveBestGenomes + fileName + ".bgn"); ! } ! this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); AccountReport accountReport = this.account.CreateReport(fileName,1, this.endOfDayTimer.GetCurrentTime(), this.benchmark, ! new HistoricalAdjustedQuoteProvider()); ObjectArchiver.Archive(accountReport, dirNameWhereToSaveReports + fileName + ".qPr"); ! this.saveScriptResults_saveScriptFeaturesToLogFile(fileName); this.endOfDayTimer.Stop(); } ! #endregion } Index: EndOfDayTimerHandlerBiasedPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/EndOfDayTimerHandlerBiasedPVO.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** EndOfDayTimerHandlerBiasedPVO.cs 29 Aug 2007 09:47:54 -0000 1.3 --- EndOfDayTimerHandlerBiasedPVO.cs 14 Jan 2008 23:07:03 -0000 1.4 *************** *** 25,28 **** --- 25,31 ---- using QuantProject.ADT; + using QuantProject.ADT.Statistics; + using QuantProject.ADT.FileManaging; + using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; *************** *** 30,33 **** --- 33,39 ---- using QuantProject.Business.Timing; using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; + using QuantProject.Business.Strategies.ReturnsManagement.Time; + using QuantProject.Business.Strategies.TickersRelationships; using QuantProject.Data; using QuantProject.Data.DataProviders; *************** *** 39,43 **** using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.WeightedPVO.WeightedBalancedPVO; - using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.BiasedPVO.BiasedPVONoThresholds; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.BiasedPVO --- 45,48 ---- *************** *** 49,65 **** /// </summary> [Serializable] ! public class EndOfDayTimerHandlerBiasedPVO : EndOfDayTimerHandlerBiasedPVONoThresholds { ! new protected double[] currentOverboughtThreshold; new protected double[] currentOversoldThreshold; ! public EndOfDayTimerHandlerBiasedPVO(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! Account account, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, int numOfDifferentGenomesToEvaluateOutOfSample, int numDaysForOscillatingPeriod, int minLevelForOversoldThreshold, int maxLevelForOversoldThreshold, --- 54,98 ---- /// </summary> [Serializable] ! public class EndOfDayTimerHandlerBiasedPVO : EndOfDayTimerHandlerPVO { ! protected int numOfDifferentGenomesToEvaluateOutOfSample; ! protected int currentGenomeIndex = 0; ! protected double currentWeightedPositionsGainOrLoss = 0.0; ! protected Hashtable genomesCollector; ! protected WeightedPositions[] weightedPositionsToEvaluateOutOfSample; ! new protected double[] currentOverboughtThreshold; new protected double[] currentOversoldThreshold; + protected double maxCoefficientForDegreeComputationOfCrossingThreshold; + protected int numDaysWithOpenPositions; + protected double numOfStdDevForThresholdsComputation; + protected int numDaysOfStayingOnTheMarket; + protected bool resetThresholdsBeforeCheckingOutOfSample; + protected int numDaysForThresholdsReComputation; + protected bool buyOnlyPositionsThatAreMovingTogether; + protected bool doNotOpenReversedPositionsThatHaveJustBeenClosed; + protected double minPriceForTickersToBeChosen; + protected double maxPriceForTickersToBeChosen; + protected WeightedPositions lastWeightedPositionsClosed; + protected string pathOfFileContainingGenomes; + protected OptimizationOutput optimizationOutput; ! public EndOfDayTimerHandlerBiasedPVO(string tickerGroupID, int numberOfEligibleTickers, ! double minPriceForTickersToBeChosen, ! double maxPriceForTickersToBeChosen, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! Account account, ! string pathOfFileContainingGenomes, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, int numOfDifferentGenomesToEvaluateOutOfSample, + bool resetThresholdsBeforeCheckingOutOfSample, + int numDaysForThresholdsReComputation, + double numOfStdDevForThresholdsComputation, + double maxCoefficientForDegreeComputationOfCrossingThreshold, + bool buyOnlyPositionsThatAreMovingTogether, + bool doNotOpenReversedPositionsThatHaveJustBeenClosed, int numDaysForOscillatingPeriod, + int numDaysOfStayingOnTheMarket, int minLevelForOversoldThreshold, int maxLevelForOversoldThreshold, *************** *** 72,103 **** PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown, double minimumAcceptableGain): ! base(tickerGroupID, numberOfEligibleTickers, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, ! account, generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, benchmark, ! numOfDifferentGenomesToEvaluateOutOfSample, ! numDaysBetweenEachOptimization, ! portfolioType, maxAcceptableCloseToCloseDrawdown, ! minimumAcceptableGain) { this.currentOverboughtThreshold = new double[numOfDifferentGenomesToEvaluateOutOfSample]; ! this.currentOversoldThreshold = new double[numOfDifferentGenomesToEvaluateOutOfSample]; ! this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; ! this.minLevelForOversoldThreshold = minLevelForOversoldThreshold; ! this.maxLevelForOversoldThreshold = maxLevelForOversoldThreshold; ! this.minLevelForOverboughtThreshold = minLevelForOverboughtThreshold; ! this.maxLevelForOverboughtThreshold = maxLevelForOverboughtThreshold; ! this.divisorForThresholdComputation = divisorForThresholdComputation; ! this.symmetricalThresholds =symmetricalThresholds; ! this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; } - #region MarketCloseEventHandler //sets currentGenomeIndex with the genome's index that crosses an overbought/oversold threshold with the ! //highest degree and sets currentTickersGainOrLoss accordingly ! protected override void openPositions_chooseBestGenome(IndexBasedEndOfDayTimer timer) { //default index is the first --- 105,272 ---- PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown, double minimumAcceptableGain): ! base(tickerGroupID,numberOfEligibleTickers, ! numberOfTickersToBeChosen,numDaysForOptimizationPeriod, ! account, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, ! benchmark, ! numDaysForOscillatingPeriod, ! minLevelForOversoldThreshold, ! maxLevelForOversoldThreshold, ! minLevelForOverboughtThreshold, ! maxLevelForOverboughtThreshold, ! divisorForThresholdComputation, ! symmetricalThresholds, ! overboughtMoreThanOversoldForFixedPortfolio, ! numDaysBetweenEachOptimization, ! portfolioType, maxAcceptableCloseToCloseDrawdown, ! minimumAcceptableGain) ! { + this.minPriceForTickersToBeChosen = minPriceForTickersToBeChosen; + this.maxPriceForTickersToBeChosen = maxPriceForTickersToBeChosen; + this.numOfDifferentGenomesToEvaluateOutOfSample = numOfDifferentGenomesToEvaluateOutOfSample; + this.weightedPositionsToEvaluateOutOfSample = new WeightedPositions[numOfDifferentGenomesToEvaluateOutOfSample]; + this.currentOversoldThreshold = new double[numOfDifferentGenomesToEvaluateOutOfSample]; this.currentOverboughtThreshold = new double[numOfDifferentGenomesToEvaluateOutOfSample]; ! this.resetThresholdsBeforeCheckingOutOfSample = resetThresholdsBeforeCheckingOutOfSample; ! this.numDaysForThresholdsReComputation = numDaysForThresholdsReComputation; ! this.maxCoefficientForDegreeComputationOfCrossingThreshold = maxCoefficientForDegreeComputationOfCrossingThreshold; ! this.numOfStdDevForThresholdsComputation = numOfStdDevForThresholdsComputation; ! this.numDaysOfStayingOnTheMarket = numDaysOfStayingOnTheMarket; ! this.buyOnlyPositionsThatAreMovingTogether = buyOnlyPositionsThatAreMovingTogether; ! this.doNotOpenReversedPositionsThatHaveJustBeenClosed = doNotOpenReversedPositionsThatHaveJustBeenClosed; ! this.genomesCollector = new Hashtable(); ! this.pathOfFileContainingGenomes = pathOfFileContainingGenomes; ! } ! ! //to avoid handlers in inherited classes ! public override void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; } #region MarketCloseEventHandler + protected virtual double getCurrentWeightedPositionsGainOrLoss( + IndexBasedEndOfDayTimer timer, + ReturnsManager returnsManager, + int indexForChosenWeightedPositions ) + { + double returnValue = double.MinValue; + try + { + returnValue = + this.weightedPositionsToEvaluateOutOfSample[indexForChosenWeightedPositions].GetReturn( + 0 , returnsManager); + } + catch(MissingQuotesException ex) + { + ex = ex; + } + return returnValue; + } + protected bool areAllTickersMovingTogetherUpOrDown( + IndexBasedEndOfDayTimer timer, + ReturnsManager returnsManager, + int indexForChosenWeightedPositions ) + { + bool returnValue = true; + SignedTickers signedTickers = + this.weightedPositionsToEvaluateOutOfSample[indexForChosenWeightedPositions].SignedTickers; + float returnOfCurrentTicker, returnOfNextTicker; + for( int i = 0; + signedTickers.Count > 1 && i < signedTickers.Count - 1 && returnValue == true; + i++ ) + { + returnOfCurrentTicker = returnsManager.GetReturn(signedTickers[ i ].Ticker, 0); + returnOfNextTicker = returnsManager.GetReturn(signedTickers[ i+1 ].Ticker, 0); + if( (returnOfCurrentTicker > 0 && returnOfNextTicker < 0) || + (returnOfCurrentTicker < 0 && returnOfNextTicker > 0) ) + returnValue = false; + } + return returnValue; + } + + protected virtual void openPositions_chooseGenome_resetThresholds(DateTime today) + { + for(int i = 0; i < this.weightedPositionsToEvaluateOutOfSample.Length; i++) + { + this.currentOversoldThreshold[i] = (double)this.maxLevelForOversoldThreshold/ + (double)this.divisorForThresholdComputation; + this.currentOverboughtThreshold[i] = (double)this.maxLevelForOverboughtThreshold/ + (double)this.divisorForThresholdComputation; + } + // + // ReturnsManager returnsManager = new ReturnsManager( + // new CloseToCloseIntervals(new EndOfDayDateTime(today.AddDays(-this.numDaysForThresholdsReComputation), EndOfDaySpecificTime.MarketClose), + // new EndOfDayDateTime(today, EndOfDaySpecificTime.MarketClose), + // this.benchmark, + // this.numDaysForOscillatingPeriod), + // new HistoricalAdjustedQuoteProvider() ); + // //double returnsAverage; + // double returnsStdDev; + // for(int i = 0; i < this.weightedPositionsToEvaluateOutOfSample.Length; i++) + // { + //// returnsAverage = BasicFunctions.GetSimpleAverage( + //// this.weightedPositionsToEvaluateOutOfSample[i].GetReturns(returnsManager) ); + // returnsStdDev = BasicFunctions.GetStdDev( + // this.weightedPositionsToEvaluateOutOfSample[i].GetReturns(returnsManager) ); + // this.currentOversoldThreshold[i] = -this.numOfStdDevForThresholdsComputation * returnsStdDev; + // this.currentOverboughtThreshold[i] = this.numOfStdDevForThresholdsComputation * returnsStdDev; + // } + } + //NEW IMPLEMENTATION of chooseBestGenome, now named chooseGenome + //sets currentGenomeIndex with the first genome's index that crosses an overbought/oversold threshold with the + //"acceptable" degree and sets currentWeightedPositionsGainOrLoss accordingly + protected virtual void openPositions_chooseGenome(IndexBasedEndOfDayTimer timer) + { + DateTime today = timer.GetCurrentTime().DateTime; + DateTime firstMarketDayForOscillatingPeriod = + timer.GetPreviousDateTime(this.numDaysForOscillatingPeriod); + ReturnsManager returnsManager = new ReturnsManager( + new CloseToCloseIntervals(new EndOfDayDateTime(firstMarketDayForOscillatingPeriod, EndOfDaySpecificTime.MarketClose), + new EndOfDayDateTime(today, EndOfDaySpecificTime.MarketClose), + this.benchmark, + this.numDaysForOscillatingPeriod), + new HistoricalAdjustedQuoteProvider() ); + if(this.resetThresholdsBeforeCheckingOutOfSample) + this.openPositions_chooseGenome_resetThresholds(today); + this.currentWeightedPositionsGainOrLoss = double.MinValue; + double currentWeightedPositionsGainOrLoss_temp = double.MinValue; + for(int i = 0; i < this.numOfDifferentGenomesToEvaluateOutOfSample; i++) + { + currentWeightedPositionsGainOrLoss_temp = + this.getCurrentWeightedPositionsGainOrLoss( + timer, returnsManager, i); + if( currentWeightedPositionsGainOrLoss_temp != double.MinValue && + ( this.buyOnlyPositionsThatAreMovingTogether == false || + ( this.buyOnlyPositionsThatAreMovingTogether == true && + this.areAllTickersMovingTogetherUpOrDown(timer, returnsManager, i) == true ) ) ) + //currentWeightedPositionsGainOrLoss_temp has been properly computed and + //only positions that are moving together can be bought + { + if( (currentWeightedPositionsGainOrLoss_temp >= this.currentOverboughtThreshold[i] && + currentWeightedPositionsGainOrLoss_temp <= this.maxCoefficientForDegreeComputationOfCrossingThreshold * + this.currentOverboughtThreshold[i] ) || + (currentWeightedPositionsGainOrLoss_temp <= - this.currentOversoldThreshold[i] && + Math.Abs(currentWeightedPositionsGainOrLoss_temp) <= this.maxCoefficientForDegreeComputationOfCrossingThreshold * + this.currentOversoldThreshold[i] ) ) + // if the current genome matches the requested criteria + { + this.currentGenomeIndex = i; + this.currentWeightedPositionsGainOrLoss = currentWeightedPositionsGainOrLoss_temp; + i = this.numOfDifferentGenomesToEvaluateOutOfSample; //exit from for + } + } + } + } + + /* OLD IMPLEMENTATION OF chooseBestGenome //sets currentGenomeIndex with the genome's index that crosses an overbought/oversold threshold with the ! //highest "acceptable" degree and sets currentWeightedPositionsGainOrLoss accordingly ! protected void openPositions_chooseBestGenome(IndexBasedEndOfDayTimer timer) { //default index is the first *************** *** 106,132 **** double currentMaxDegreeOfCrossingThreshold = 0.0; double currentDegreeOfCrossingThreshold = 0.0; for(int i = 0; i < this.numOfDifferentGenomesToEvaluateOutOfSample; i++) { double currentChosenWeightedPositionsGainOrLoss = ! this.getCurrentWeightedPositionsGainOrLoss(timer, i); ! if(currentChosenWeightedPositionsGainOrLoss != 999.0) ! //currentChosenTickersValue has been properly computed { ! //computing degree of crossing threshold ! if(currentChosenWeightedPositionsGainOrLoss >= 1.0 + this.currentOverboughtThreshold[i]) { currentDegreeOfCrossingThreshold = ! (currentChosenWeightedPositionsGainOrLoss - 1.0 - this.currentOverboughtThreshold[i])/ ! (1 + this.currentOverboughtThreshold[i]); } ! else if (currentChosenWeightedPositionsGainOrLoss <= 1.0 - this.currentOversoldThreshold[i]) { currentDegreeOfCrossingThreshold = ! (1.0 - this.currentOversoldThreshold[i] - currentChosenWeightedPositionsGainOrLoss)/ ! (1.0 - this.currentOversoldThreshold[i]); } ! if(currentDegreeOfCrossingThreshold > currentMaxDegreeOfCrossingThreshold) ! { currentMaxDegreeOfCrossingThreshold = currentDegreeOfCrossingThreshold; this.currentGenomeIndex = i; --- 275,337 ---- double currentMaxDegreeOfCrossingThreshold = 0.0; double currentDegreeOfCrossingThreshold = 0.0; + DateTime today = timer.GetCurrentTime().DateTime; + DateTime firstMarketDayForOscillatingPeriod = + timer.GetPreviousDateTime(this.numDaysForOscillatingPeriod); + ReturnsManager returnsManager = new ReturnsManager( + new CloseToCloseIntervals(new EndOfDayDateTime(firstMarketDayForOscillatingPeriod, EndOfDaySpecificTime.MarketClose), + new EndOfDayDateTime(today, EndOfDaySpecificTime.MarketClose), + this.benchmark, + this.numDaysForOscillatingPeriod), + new HistoricalAdjustedQuoteProvider() ); + if(this.resetThresholdsBeforeCheckingOutOfSample) + this.openPositions_chooseBestGenome_resetThresholds(today); + this.currentWeightedPositionsGainOrLoss = 999.0; for(int i = 0; i < this.numOfDifferentGenomesToEvaluateOutOfSample; i++) { double currentChosenWeightedPositionsGainOrLoss = ! this.getCurrentWeightedPositionsGainOrLoss( ! timer, returnsManager, i); ! if(currentChosenWeightedPositionsGainOrLoss != 999.0) ! //currentChosenWeightedPositionsGainOrLoss has been properly computed { ! if( ( this.buyOnlyPositionsThatAreMovingTogether == false || ! ( this.buyOnlyPositionsThatAreMovingTogether == true && ! this.areAllTickersMovingTogetherUpOrDown(timer, returnsManager, i) == true ) ) && ! currentChosenWeightedPositionsGainOrLoss >= this.currentOverboughtThreshold[i] && ! currentChosenWeightedPositionsGainOrLoss <= this.maxCoefficientForDegreeComputationOfCrossingThreshold * ! this.currentOverboughtThreshold[i] ) ! // if it is requested that current tickers have to move together in the same direction ! // if current gain crosses overbought threshold but not ! // as maxCoefficientForDegreeComputationOfCrossingThreshold times ! // as overbought threshold (that is, it could be a reasonable ! // market inefficiency) { currentDegreeOfCrossingThreshold = ! (currentChosenWeightedPositionsGainOrLoss - this.currentOverboughtThreshold[i])/ ! this.currentOverboughtThreshold[i]; } ! else if ( ( this.buyOnlyPositionsThatAreMovingTogether == false || ! ( this.buyOnlyPositionsThatAreMovingTogether == true && ! this.areAllTickersMovingTogetherUpOrDown(timer, returnsManager, i) == true ) ) && ! currentChosenWeightedPositionsGainOrLoss <= - this.currentOversoldThreshold[i] && ! Math.Abs(currentChosenWeightedPositionsGainOrLoss) <= this.maxCoefficientForDegreeComputationOfCrossingThreshold * ! this.currentOversoldThreshold[i] ) ! // if it is requested that current tickers have to move together in the same direction ! // if current loss crosses oversold threshold but not ! // as maxCoefficientForDegreeComputationOfCrossingThreshold times ! // as oversold threshold (that is, it could be a reasonable ! // market inefficiency) { currentDegreeOfCrossingThreshold = ! ( Math.Abs(currentChosenWeightedPositionsGainOrLoss) - this.currentOversoldThreshold[i])/ ! this.currentOversoldThreshold[i]; } ! ! if(currentDegreeOfCrossingThreshold > currentMaxDegreeOfCrossingThreshold) ! // if a genome crosses a threshold without crossing ! // as maxCoefficientForDegreeComputationOfCrossingThreshold times ! // as oversold or overbought thresholds ! { currentMaxDegreeOfCrossingThreshold = currentDegreeOfCrossingThreshold; this.currentGenomeIndex = i; *************** *** 136,156 **** } } ! protected override void openPositions(IndexBasedEndOfDayTimer timer) { ! this.currentWeightedPositionsGainOrLoss = 999.0; // ! this.openPositions_chooseBestGenome(timer); ! if(this.currentWeightedPositionsGainOrLoss != 999.0) ! //currentWeightedPositionsGainOrLoss has been properly computed { ! if(this.currentWeightedPositionsGainOrLoss >= 1.0 + currentOverboughtThreshold[this.currentGenomeIndex] && ! this.portfolioType == PortfolioType.ShortAndLong) { this.weightedPositionsToEvaluateOutOfSample[this.currentGenomeIndex].Reverse(); try{ ! AccountManager.OpenPositions(this.weightedPositionsToEvaluateOutOfSample[this.currentGenomeIndex], ! this.account); ! this.portfolioHasBeenOverbought = true; ! this.portfolioHasBeenOversold = false; } catch(Exception ex){ --- 341,382 ---- } } + *///END OF OLD IMPLEMENTATION + + protected void openPositions_open(WeightedPositions weightedPositions, bool overboughtPortfolio) + { + if( this.lastWeightedPositionsClosed == null || + !this.doNotOpenReversedPositionsThatHaveJustBeenClosed || + !weightedPositions.HasTheOppositeSignedTickersAs(this.lastWeightedPositionsClosed) ) + //it is the first time positions are opening or + //positions that have been just closed can be reversed or + //positions to be opened are just the reversed + //positions that have just been closed + { + AccountManager.OpenPositions(weightedPositions, this.account); + this.portfolioHasBeenOverbought = overboughtPortfolio; + this.portfolioHasBeenOversold = !overboughtPortfolio; + } + } ! protected void openPositions(IndexBasedEndOfDayTimer timer) { ! this.currentWeightedPositionsGainOrLoss = double.MinValue; ! try{ ! this.openPositions_chooseGenome(timer); ! //if the genome has been chosen, then this.currentWeightedPositionsGainOrLoss ! //has been set to a value different from double.MinValue ! } ! catch(Exception ex){ ! ex=ex; ! } ! if(this.currentWeightedPositionsGainOrLoss != double.MinValue) ! //there is a genome that matches requested criteria { ! if(this.currentWeightedPositionsGainOrLoss >= currentOverboughtThreshold[this.currentGenomeIndex] && ! (this.portfolioType == PortfolioType.ShortAndLong || this.portfolioType == PortfolioType.OnlyMixed) ) { this.weightedPositionsToEvaluateOutOfSample[this.currentGenomeIndex].Reverse(); try{ ! this.openPositions_open(weightedPositionsToEvaluateOutOfSample[this.currentGenomeIndex],true); } catch(Exception ex){ *************** *** 161,184 **** } } ! else if (this.currentWeightedPositionsGainOrLoss <= 1.0 - currentOversoldThreshold[this.currentGenomeIndex]) { ! AccountManager.OpenPositions(this.weightedPositionsToEvaluateOutOfSample[this.currentGenomeIndex], ! this.account); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = true; } ! this.currentAccountValue = this.account.GetMarketValue(); } } ! public override void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { if(this.account.Portfolio.Count > 0) ! this.marketCloseEventHandler_closeIfItIsTimeToClose(); ! else if ( this.account.Portfolio.Count == 0 && ! this.weightedPositionsToEvaluateOutOfSample != null ) ! //portfolio is empty and optimization has been already launched ! this.openPositions((IndexBasedEndOfDayTimer)sender); } --- 387,443 ---- } } ! else if (this.currentWeightedPositionsGainOrLoss <= - currentOversoldThreshold[this.currentGenomeIndex]) { ! this.openPositions_open(weightedPositionsToEvaluateOutOfSample[this.currentGenomeIndex],false); } ! this.previousAccountValue = this.account.GetMarketValue(); } } ! ! ! private bool marketCloseEventHandler_isTimerStateValidForStrategy(IndexBasedEndOfDayTimer timer) ! { ! bool returnValue; ! DateTime currentTime = timer.GetCurrentTime().DateTime; ! DateTime firstDateOfOscillatingPeriod = ! timer.GetPreviousDateTime(this.numDaysForOscillatingPeriod); ! returnValue = currentTime.CompareTo(firstDateOfOscillatingPeriod) > 0; ! return returnValue; ! //currentTime is greater than the date at which previous close ! //has to be compared to the current close with respect to ! //the oscillating strategy's criteria ! } ! ! protected override void marketCloseEventHandler_closePositionsIfNeeded() ! { ! if( this.numDaysWithOpenPositions == this.numDaysOfStayingOnTheMarket || ! this.stopLossConditionReached || this.takeProfitConditionReached ) ! { ! this.lastWeightedPositionsClosed = AccountManager.GetWeightedPositions(this.account); ! AccountManager.ClosePositions(this.account); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = false; ! this.numDaysWithOpenPositions = 0; ! } ! } ! public override void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { if(this.account.Portfolio.Count > 0) ! { ! this.numDaysWithOpenPositions++; ! this.marketCloseEventHandler_updateStopLossAndTakeProfitConditions(); ! this.marketCloseEventHandler_closePositionsIfNeeded(); ! } ! ! if ( this.account.Portfolio.Count == 0 && ! this.weightedPositionsToEvaluateOutOfSample[0] != null && ! this.marketCloseEventHandler_isTimerStateValidForStrategy( (IndexBasedEndOfDayTimer)sender) ) ! //portfolio is empty and optimization has been already launched and ! //currentTime is greater than the date at which previous close ! //has to be compared to the current close with respect to ! //the oscillating strategy's criteria ! this.openPositions( (IndexBasedEndOfDayTimer)sender ); } *************** *** 188,192 **** #region OneHourAfterMarketCloseEventHandler ! private void setTickers_updateTickersWeightsAndThresholdsAndAddGenomesForLog(GeneticOptimizer GO, int eligibleTickersForGO) { --- 447,451 ---- #region OneHourAfterMarketCloseEventHandler ! protected void setTickers_updateTickersWeightsAndThresholdsAndAddGenomesForLog(GeneticOptimizer GO, int eligibleTickersForGO) { *************** *** 226,229 **** --- 485,516 ---- } + protected override DataTable getSetOfTickersToBeOptimized(DateTime currentDate) + { + SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); + DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); + int numOfTickersInGroupAtCurrentDate = tickersFromGroup.Rows.Count; + + SelectorByAverageRawOpenPrice byPrice = + new SelectorByAverageRawOpenPrice(tickersFromGroup,false,currentDate.AddDays(-15), + currentDate, + numOfTickersInGroupAtCurrentDate, + this.minPriceForTickersToBeChosen,this.maxPriceForTickersToBeChosen, + 0.0001,100); + + SelectorByLiquidity mostLiquidSelector = + new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), + false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, + this.numberOfEligibleTickers); + + SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromLastSelection = + new SelectorByQuotationAtEachMarketDay(mostLiquidSelector.GetTableOfSelectedTickers(), + false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, + this.numberOfEligibleTickers, this.benchmark); + + return quotedAtEachMarketDayFromLastSelection.GetTableOfSelectedTickers(); + + } + + protected override void setTickers(DateTime currentDate, bool setGenomeCounter) *************** *** 231,235 **** DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); this.iGenomeManager = ! new GenomeManagerWeightedBalancedPVO(setOfTickersToBeOptimized, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, --- 518,522 ---- DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); this.iGenomeManager = ! new GenomeManagerPVO(setOfTickersToBeOptimized, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, *************** *** 242,253 **** this.symmetricalThresholds, this.overboughtMoreThanOversoldForFixedPortfolio, ! this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer, this.seedForRandomGenerator); ! if(setGenomeCounter) ! this.genomeCounter = new GenomeCounter(GO); ! GO.MutationRate = 0.1; GO.CrossoverRate = 0.85; --- 529,539 ---- this.symmetricalThresholds, this.overboughtMoreThanOversoldForFixedPortfolio, ! this.portfolioType, this.benchmark); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer, this.seedForRandomGenerator); ! // if(setGenomeCounter) ! // this.genomeCounter = new GenomeCounter(GO); GO.MutationRate = 0.1; GO.CrossoverRate = 0.85; *************** *** 258,261 **** --- 544,625 ---- } + private void setTickersFromFile_updateWeightedPositionsToEvaluateOutOfSample_addGenomeRepresentation(GenomeRepresentation genomeRepresentation) + { + WeightedPositions weightedPositions = new WeightedPositions( + GenomeRepresentation.GetWeightsArray(genomeRepresentation.WeightsForSignedTickers), + new SignedTickers(GenomeRepresentation.GetSignedTickers(genomeRepresentation.SignedTickers)) ); + for(int i = 0; i<this.weightedPositionsToEvaluateOutOfSample.Length; i++) + { + if(this.weightedPositionsToEvaluateOutOfSample[i] == null) + { + this.weightedPositionsToEvaluateOutOfSample[i] = weightedPositions; + this.currentOversoldThreshold[i] = genomeRepresentation.OversoldThreshold; + this.currentOverboughtThreshold[i] = genomeRepresentation.OverboughtThreshold; + i = this.weightedPositionsToEvaluateOutOfSample.Length;//exit from for + } + } + } + + private void setTickersFromFile_updateWeightedPositionsToEvaluateOutOfSample(DateTime currentDate) + { + GenomeRepresentation currentGenomeRepresentation; + for(int i = 0; i<this.optimizationOutput.Count;i++) + { + currentGenomeRepresentation = (GenomeRepresentation)this.optimizationOutput[i]; + if(currentGenomeRepresentation.LastOptimizationDate == currentDate) + { + this.setTickersFromFile_updateWeightedPositionsToEvaluateOutOfSample_addGenomeRepresentation( + currentGenomeRepresentation); + } + } + } + + private void setTickersFromFile_loadGenomesFromFile() + { + if( this.optimizationOutput == null ) + this.optimizationOutput = + (OptimizationOutput)ObjectArchiver.Extract( + this.pathOfFileContainingGenomes); + } + + private void setTickersFromFile_clearWeightedPositionsToEvaluateOutOfSample() + { + for(int i = 0; i< this.weightedPositionsToEvaluateOutOfSample.Length; i++) + this.weightedPositionsToEvaluateOutOfSample[i] = null; + } + + private void setTickersFromFile(DateTime currentDate) + { + this.setTickersFromFile_loadGenomesFromFile(); + this.setTickersFromFile_clearWeightedPositionsToEvaluateOutOfSample(); + this.setTickersFromFile_updateWeightedPositionsToEvaluateOutOfSample(currentDate); + } + + /// <summary> + /// Handles a "One hour after market close" event. + /// </summary> + /// <param name="sender"></param> + /// <param name="eventArgs"></param> + public override void OneHourAfterMarketCloseEventHandler( + Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) + { + this.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; + this.seedForRandomGenerator++; + this.numDaysElapsedSinceLastOptimization++; + if((this.numDaysElapsedSinceLastOptimization == + this.numDaysBetweenEachOptimization)) + //num days without optimization has elapsed + { + if(this.pathOfFileContainingGenomes == null) + //tickers have to be set by a new optimization process (in sample) + this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); + //sets tickers to be chosen next Market Close event + else//this.pathOfFileContainingGenomes != null + this.setTickersFromFile(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime); + //set tickers from file + this.numDaysElapsedSinceLastOptimization = 0; + } + } + #endregion |
|
From: Marco M. <mi...@us...> - 2008-01-14 23:07:10
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv7110/b7_Scripts/WalkForwardTesting/LinearCombination Modified Files: FixedLevelOscBiasedOTC_PVONoThresholdsStrategy.cs FixedLevelOscillatorBiasedPVONoThresholdsStrategy.cs FixedLevelOscillatorBiasedPVOStrategy.cs FixedLevelOscillatorPVOStrategy.cs Log Message: Several changes applied to the classes implementing the Portfolio Value Oscillator strategy (the most important one relates to the use of ReturnsManager) Index: FixedLevelOscillatorBiasedPVOStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/FixedLevelOscillatorBiasedPVOStrategy.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** FixedLevelOscillatorBiasedPVOStrategy.cs 29 Aug 2007 09:43:36 -0000 1.3 --- FixedLevelOscillatorBiasedPVOStrategy.cs 14 Jan 2008 23:07:06 -0000 1.4 *************** *** 28,31 **** --- 28,32 ---- using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Timing; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; *************** *** 53,60 **** double maxAcceptableCloseToCloseDrawdown, double minimumAcceptableGain): ! base("", 0, ! weightedPositionsToEvaluateOutOfSample[0].Count, 0, accountPVO, 0, 0, ! "", numOfDifferentGenomesToEvaluateOutOfSample, ! numDaysForOscillatingPeriod,1,1,1,1,1,false,false,0, PortfolioType.ShortAndLong,maxAcceptableCloseToCloseDrawdown, minimumAcceptableGain) --- 54,66 ---- double maxAcceptableCloseToCloseDrawdown, double minimumAcceptableGain): ! base("", 0, 0, 0, ! weightedPositionsToEvaluateOutOfSample[0].Count, 0, accountPVO, null, 0, 0, ! "^GSPC", numOfDifferentGenomesToEvaluateOutOfSample, ! false,0, ! 1.0, ! 1000.0, ! false, ! false, ! numDaysForOscillatingPeriod,numDaysForOscillatingPeriod,1,1,1,1,1,false,false,0, PortfolioType.ShortAndLong,maxAcceptableCloseToCloseDrawdown, minimumAcceptableGain) *************** *** 73,81 **** } ! protected override double getCurrentWeightedPositionsGainOrLoss(IndexBasedEndOfDayTimer timer, ! int indexForChosenWeightedPositions) { double returnValue = 999.0; ! if(timer.CurrentDateArrayPosition + 2 >= this.numDaysForOscillatingPeriod) //if there are sufficient data for computing currentChosenTickersValue //that's why the method has been overriden --- 79,89 ---- } ! protected override double getCurrentWeightedPositionsGainOrLoss( ! IndexBasedEndOfDayTimer timer, ! ReturnsManager returnsManager, ! int indexForChosenWeightedPositions) { double returnValue = 999.0; ! if(timer.CurrentDateArrayPosition - this.numDaysForOscillatingPeriod >= 0) //if there are sufficient data for computing currentChosenTickersValue //that's why the method has been overriden *************** *** 88,93 **** (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - 1]["quDate"]; returnValue = ! this.weightedPositionsToEvaluateOutOfSample[indexForChosenWeightedPositions].GetCloseToCloseReturn( ! lastMarketDay, today); } catch(MissingQuotesException ex) --- 96,101 ---- (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - 1]["quDate"]; returnValue = ! this.weightedPositionsToEvaluateOutOfSample[indexForChosenWeightedPositions].GetReturn( ! 0, returnsManager); } catch(MissingQuotesException ex) Index: FixedLevelOscBiasedOTC_PVONoThresholdsStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/FixedLevelOscBiasedOTC_PVONoThresholdsStrategy.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** FixedLevelOscBiasedOTC_PVONoThresholdsStrategy.cs 29 Aug 2007 09:43:35 -0000 1.2 --- FixedLevelOscBiasedOTC_PVONoThresholdsStrategy.cs 14 Jan 2008 23:07:06 -0000 1.3 *************** *** 28,31 **** --- 28,32 ---- using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Timing; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; *************** *** 71,76 **** } ! protected override double getCurrentWeightedPositionsGainOrLoss(IndexBasedEndOfDayTimer timer, ! int indexForChosenWeightedPositions) { double returnValue = 999.0; --- 72,79 ---- } ! protected override double getCurrentWeightedPositionsGainOrLoss( ! IndexBasedEndOfDayTimer timer, ! ReturnsManager returnsManager, ! int indexForChosenWeightedPositions ) { double returnValue = 999.0; *************** *** 81,91 **** try { ! DateTime today = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; ! DateTime lastMarketDay = ! (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - 1]["quDate"]; ! ! returnValue = this.weightedPositionsToEvaluateOutOfSample[indexForChosenWeightedPositions].GetLastNightReturn( ! lastMarketDay, today); } catch(MissingQuotesException ex) --- 84,90 ---- try { ! returnValue = ! this.weightedPositionsToEvaluateOutOfSample[indexForChosenWeightedPositions].GetReturn( ! 0 , returnsManager); } catch(MissingQuotesException ex) Index: FixedLevelOscillatorPVOStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/FixedLevelOscillatorPVOStrategy.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** FixedLevelOscillatorPVOStrategy.cs 30 Aug 2007 18:15:37 -0000 1.6 --- FixedLevelOscillatorPVOStrategy.cs 14 Jan 2008 23:07:06 -0000 1.7 *************** *** 52,56 **** "^GSPC", 0, 0, 0, 0, 0, 0, false, false, 0, ! PortfolioType.ShortAndLong, 0.5) { this.chosenWeightedPositions = chosenWeightedPositions; --- 52,56 ---- "^GSPC", 0, 0, 0, 0, 0, 0, false, false, 0, ! PortfolioType.ShortAndLong, 0.5, 0.5) { this.chosenWeightedPositions = chosenWeightedPositions; *************** *** 65,92 **** } ! protected override double getCurrentChosenWeightedPositionsValue(IndexBasedEndOfDayTimer timer) { double returnValue = 999.0; ! if(timer.CurrentDateArrayPosition + 2 >= this.numDaysForOscillatingPeriod) ! //if there are sufficient data for computing currentChosenTickersValue //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"]; ! returnValue = ! this.chosenWeightedPositions.GetCloseToCloseReturn(initialDate,finalDate) ! + 1.0; ! } ! catch(Exception ex) ! { ! ex = ex; ! } ! } return returnValue; } --- 65,77 ---- } ! protected override double getCurrentChosenWeightedPositionsReturn(IndexBasedEndOfDayTimer timer) { double returnValue = 999.0; ! if(timer.CurrentDateArrayPosition - this.numDaysForOscillatingPeriod >= 0) ! //if there are sufficient data for computing currentChosenWeightedPositionsReturn //that's why the method has been overriden ! returnValue = ! base.getCurrentChosenWeightedPositionsReturn(timer); ! return returnValue; } Index: FixedLevelOscillatorBiasedPVONoThresholdsStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/FixedLevelOscillatorBiasedPVONoThresholdsStrategy.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** FixedLevelOscillatorBiasedPVONoThresholdsStrategy.cs 29 Aug 2007 09:43:35 -0000 1.2 --- FixedLevelOscillatorBiasedPVONoThresholdsStrategy.cs 14 Jan 2008 23:07:06 -0000 1.3 *************** *** 28,31 **** --- 28,32 ---- using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Timing; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; *************** *** 66,71 **** } ! protected override double getCurrentWeightedPositionsGainOrLoss(IndexBasedEndOfDayTimer timer, ! int indexForChosenWeightedPositions) { double returnValue = 999.0; --- 67,74 ---- } ! protected override double getCurrentWeightedPositionsGainOrLoss( ! IndexBasedEndOfDayTimer timer, ! ReturnsManager returnsManager, ! int indexForChosenWeightedPositions) { double returnValue = 999.0; |