quantproject-developers Mailing List for QuantProject (Page 6)
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...> - 2011-01-16 19:52:39
|
Update of /cvsroot/quantproject/QuantProject/b4_Business In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv2823/b4_Business Modified Files: Business_SD.csproj Log Message: Updated sharp develop project files Index: Business_SD.csproj =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/Business_SD.csproj,v retrieving revision 1.42 retrieving revision 1.43 diff -C2 -d -r1.42 -r1.43 *** Business_SD.csproj 28 Mar 2010 13:34:21 -0000 1.42 --- Business_SD.csproj 16 Jan 2011 19:52:31 -0000 1.43 *************** *** 61,64 **** --- 61,65 ---- <Compile Include="a07_DataProviders\HistoricalQuoteProvider.cs" /> <Compile Include="a07_DataProviders\TickerNotExchangedException.cs" /> + <Compile Include="a1_Financial\a2_Accounting\AccountProviding\FixedCommissionsAndSlippageAccountProvider.cs" /> <Compile Include="a1_Financial\a2_Accounting\AccountProviding\IAccountProvider.cs" /> <Compile Include="a1_Financial\a2_Accounting\AccountProviding\InteractiveBrokerAccountProvider.cs" /> *************** *** 80,85 **** --- 81,97 ---- <Compile Include="a1_Financial\a2_Accounting\Transactions\TimedTransaction.cs" /> <Compile Include="a1_Financial\a3_Ordering\HistoricalOrderExecutor.cs" /> + <Compile Include="a1_Financial\a4_Fundamentals\FairValueProviders\IFairValueProvider.cs" /> + <Compile Include="a1_Financial\a4_Fundamentals\FairValueProviders\PEGRatioFairValueProvider.cs" /> + <Compile Include="a1_Financial\a4_Fundamentals\FundamentalDataProvider.cs" /> + <Compile Include="a1_Financial\a4_Fundamentals\RatioProviders\AverageAndDebtAdjustedGrowthRateProvider.cs" /> + <Compile Include="a1_Financial\a4_Fundamentals\RatioProviders\IGrowthRateProvider.cs" /> + <Compile Include="a1_Financial\a4_Fundamentals\RatioProviders\IRatioProvider_PE.cs" /> + <Compile Include="a1_Financial\a4_Fundamentals\RatioProviders\LastAvailableGrowthRateProvider.cs" /> + <Compile Include="a1_Financial\a4_Fundamentals\RatioProviders\LastAvailablePEProvider.cs" /> <Compile Include="a2_Strategies\BasicStrategyForBacktester.cs" /> <Compile Include="a2_Strategies\Benchmark.cs" /> + <Compile Include="a2_Strategies\Eligibles\ByGroup.cs" /> + <Compile Include="a2_Strategies\Eligibles\ByLiquidity.cs" /> + <Compile Include="a2_Strategies\Eligibles\ByMostDiscountedPrices.cs" /> <Compile Include="a2_Strategies\Eligibles\ByPriceLessLiquidAlwaysIntradayQuoted.cs" /> <Compile Include="a2_Strategies\Eligibles\ByPriceLessVolatileOTCAlwaysQuoted.cs" /> *************** *** 99,102 **** --- 111,115 ---- <Compile Include="a2_Strategies\EndOfDayStrategies\SymmetricEndOfDayStrategyForBacktester.cs" /> <Compile Include="a2_Strategies\EndOfDayStrategyBackTester.cs" /> + <Compile Include="a2_Strategies\EquityEvaluation\Variance.cs" /> <Compile Include="a2_Strategies\InSample\BruteForceChooser.cs" /> <Compile Include="a2_Strategies\InSample\ConstantWeightedPositionsChooser.cs" /> *************** *** 107,110 **** --- 120,124 ---- <Compile Include="a2_Strategies\InSample\InSampleFitnessDistributionEstimation\BasicInSampleFitnessDistributionEstimator.cs" /> <Compile Include="a2_Strategies\InSample\InSampleFitnessDistributionEstimation\IInSampleFitnessDistributionEstimator.cs" /> + <Compile Include="a2_Strategies\InSample\SelectTopEligiblesInSampleChooser.cs" /> <Compile Include="a2_Strategies\IStrategy.cs" /> <Compile Include="a2_Strategies\IStrategyForBacktester.cs" /> *************** *** 115,118 **** --- 129,133 ---- <Compile Include="a2_Strategies\Logging\NewLogItemEventArgs.cs" /> <Compile Include="a2_Strategies\Optimizing\BruteForce\BruteForceOptimizableParametersManagerForBalancedVolatility.cs" /> + <Compile Include="a2_Strategies\Optimizing\Decoding\BasicDecoderForGeneticallyOptimizableTestingPositions.cs" /> <Compile Include="a2_Strategies\Optimizing\Decoding\BasicDecoderForTestingPositions.cs" /> <Compile Include="a2_Strategies\Optimizing\Decoding\DecoderForBalancedWeightedPositions.cs" /> *************** *** 122,129 **** --- 137,146 ---- <Compile Include="a2_Strategies\Optimizing\Decoding\IDecoderForTestingPositions.cs" /> <Compile Include="a2_Strategies\Optimizing\Decoding\IDecoderForWeightedPositions.cs" /> + <Compile Include="a2_Strategies\Optimizing\FitnessEvaluation\BuyAndHoldFitnessEvaluator.cs" /> <Compile Include="a2_Strategies\Optimizing\FitnessEvaluation\IFitnessEvaluator.cs" /> <Compile Include="a2_Strategies\Optimizing\GenomeManagers\BasicGenomeManager.cs" /> <Compile Include="a2_Strategies\Optimizing\GenomeManagers\GenomeManagerWithDuplicateGenes.cs" /> <Compile Include="a2_Strategies\Optimizing\GenomeManagers\GenomeManagerType.cs" /> + <Compile Include="a2_Strategies\OutOfSample\GeneticallyOptimizableTestingPositions.cs" /> <Compile Include="a2_Strategies\OutOfSample\IEntryStrategy.cs" /> <Compile Include="a2_Strategies\OutOfSample\IExitStrategy.cs" /> *************** *** 277,280 **** --- 294,300 ---- <Folder Include="a1_Financial\a2_Accounting\h5_Reporting\DateTimeSelectorsForEquityLine" /> <Folder Include="a1_Financial\a2_Accounting\h5_Reporting\StatisticsSummaryRows" /> + <Folder Include="a1_Financial\a4_Fundamentals" /> + <Folder Include="a1_Financial\a4_Fundamentals\FairValueProviders" /> + <Folder Include="a1_Financial\a4_Fundamentals\RatioProviders" /> <Folder Include="a2_Strategies\EndOfDayStrategies" /> <Folder Include="a2_Strategies\InSample\InSampleFitnessDistributionEstimation" /> |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:50:31
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv2260/b1_ADT Modified Files: ExtendedDataTable.cs Log Message: Added GetArrayOfDoubleFromColumn method Index: ExtendedDataTable.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/ExtendedDataTable.cs,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** ExtendedDataTable.cs 7 Apr 2008 20:45:28 -0000 1.12 --- ExtendedDataTable.cs 16 Jan 2011 19:50:23 -0000 1.13 *************** *** 109,112 **** --- 109,137 ---- } /// <summary> + /// Get an array of double corresponding to a column compatible with the double type in a given data table + /// </summary> + public static double[] GetArrayOfDoubleFromColumn(DataTable table, + string columnName) + { + int numRows = table.Rows.Count; + double[] arrayOfDouble = new double[numRows]; + int index = 0; + try + { + for(; index!= numRows; index++) + { + arrayOfDouble[index] = (double) table.Rows[index][columnName]; + } + + } + catch(Exception ex) + { + string s = ex.ToString(); + index = numRows; + } + return arrayOfDouble; + } + + /// <summary> /// Get an array of string corresponding to a column compatible with the string type in a given data table /// </summary> |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:49:42
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a4_Fundamentals In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv1634/b4_Business/a1_Financial/a4_Fundamentals Added Files: FundamentalDataProvider.cs Log Message: Added FundamentalDataProvider --- NEW FILE: FundamentalDataProvider.cs --- /* QuantProject - Quantitative Finance Library FundamentalDataProvider.cs Copyright (C) 2010 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.*/ using System; namespace QuantProject.Business.Financial.Fundamentals { /// <summary> /// Base class for fundamental data providers /// </summary> [Serializable] public class FundamentalDataProvider { protected int daysForAvailabilityOfData; /// <summary> /// FundamentalDataProvider's constructor /// </summary> /// <param name="daysForAvailabilityOfData"> /// Each fundamental data refer to a specific date (for example: /// long term debts, equity, and so on) or to a specific period /// (for example: earnings). /// In any case, such data are available after a variable /// (depending on data source) amounts of days from the specific date or the /// last date of the period data refer to ///</param> public FundamentalDataProvider(int daysForAvailabilityOfData) { this.daysForAvailabilityOfData = daysForAvailabilityOfData; } } } |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:49:14
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearRegression/InSampleChoosers/FitnessEvaluation In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv1479/b7_Scripts/WalkForwardTesting/LinearRegression/InSampleChoosers/FitnessEvaluation Modified Files: LinearRegressionFitnessEvaluator.cs Log Message: Removed declaration for avoiding compilation warning Index: LinearRegressionFitnessEvaluator.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearRegression/InSampleChoosers/FitnessEvaluation/LinearRegressionFitnessEvaluator.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** LinearRegressionFitnessEvaluator.cs 6 Jan 2011 19:24:19 -0000 1.2 --- LinearRegressionFitnessEvaluator.cs 16 Jan 2011 19:49:06 -0000 1.3 *************** *** 159,163 **** if ( fitnessValue < -0.03 && fitnessValue > -2 ) { ! string forBreakpoint; // for breakpoint } return fitnessValue; --- 159,163 ---- if ( fitnessValue < -0.03 && fitnessValue > -2 ) { ! ; // for breakpoint } return fitnessValue; |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:46:36
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/Decoding In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv721 Removed Files: BasicDecoderForOTCPositions.cs DecoderForOTCPositionsWithWeights.cs Log Message: Removed script files added by mistake --- DecoderForOTCPositionsWithWeights.cs DELETED --- --- BasicDecoderForOTCPositions.cs DELETED --- |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:45:49
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/InSampleChoosers/BruteForce In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv512 Removed Files: OTCEndOfDayBruteForceChooser.cs OTCEndOfDayBruteForceOptimizableParametersManager.cs OTCOnlyLongEndOfDayBruteForceOptimizableParametersManager.cs OTCOnlyShortEndOfDayBruteForceOptimizableParametersManager.cs Log Message: Removed script files added by mistake --- OTCEndOfDayBruteForceOptimizableParametersManager.cs DELETED --- --- OTCEndOfDayBruteForceChooser.cs DELETED --- --- OTCOnlyLongEndOfDayBruteForceOptimizableParametersManager.cs DELETED --- --- OTCOnlyShortEndOfDayBruteForceOptimizableParametersManager.cs DELETED --- |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:38:29
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC_CTO/OTC_CTO_EOD In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv30008/OTC_CTO/OTC_CTO_EOD Added Files: OTC_CTO_EODMain.cs OTC_CTO_EODStrategy.cs Log Message: Added script files for the OTC_CTO_EndOfDay strategy --- NEW FILE: OTC_CTO_EODMain.cs --- /* QuantProject - Quantitative Finance Library OTC_CTO_EODMain.cs Copyright (C) 2010 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using QuantProject.ADT; using QuantProject.ADT.Statistics.Combinatorial; using QuantProject.ADT.FileManaging; using QuantProject.ADT.Timing; using QuantProject.Business.DataProviders; using QuantProject.Data.DataProviders.Bars.Caching; using QuantProject.Business.Strategies; using QuantProject.Business.Financial.Accounting.AccountProviding; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.EquityEvaluation; using QuantProject.Business.Strategies.InSample; using QuantProject.Business.Strategies.InSample.InSampleFitnessDistributionEstimation; using QuantProject.Business.Strategies.Logging; using QuantProject.Business.Strategies.Optimizing.Decoding; using QuantProject.Business.Strategies.Optimizing.GenomeManagers; using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation; using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors; using QuantProject.Business.Timing; using QuantProject.Presentation; //using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.InSampleChoosers; //using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.Decoding; //using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.FitnessEvaluators; using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers; using QuantProject.Scripts.General; using QuantProject.Scripts.General.Logging; using QuantProject.Scripts.General.Reporting; using QuantProject.Scripts.General.Strategies.Optimizing.FitnessEvaluation; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.TickerSelectionTesting.OTC; using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers.Genetic; using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers.BruteForce; namespace QuantProject.Scripts.TickerSelectionTesting.OTC_CTO.OTC_CTO_EOD { /// <summary> /// Entry point for the OTC_CTO_EODMain. If any strategy /// parameter had to be changed, this is the place where it should /// be done /// </summary> public class OTC_CTO_EODMain : BasicScriptForBacktesting { private int numberOfPortfolioPositions; private PortfolioType portfolioType; private int maxNumberOfEligiblesToBeChosen; private Benchmark benchmark; private DateTime firstDateTime; private DateTime lastDateTime; List<Time> dailyTimes;//intraday times for barCache and Timer private Time nearToOpeningTimeFrom; private Time nearToOpeningTimeTo; private Time nearToClosingTimeFrom; private Time nearToClosingTimeTo; private HistoricalMarketValueProvider historicalMarketValueProviderForInSample; private HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample; private HistoricalMarketValueProvider historicalMarketValueProviderForTheBackTester; private Timer timerForBackTester; private GenomeManagerType genomeManagerType; #region main public OTC_CTO_EODMain() { this.numberOfPortfolioPositions = 3; // this.benchmark = new Benchmark( "CCE" ); this.portfolioType = PortfolioType.ShortAndLong;//filter for out of sample this.genomeManagerType = GenomeManagerType.ShortAndLong;//filter for the genetic chooser this.benchmark = new Benchmark( "ENI.MI" ); this.firstDateTime = new DateTime( 2001 , 1 , 1 ); this.lastDateTime = new DateTime( 2008 , 12, 31 ); //this.stepInMinutesForTimer = 1; // this.dailyTimes = Time.GetIntermediateTimes(new Time("09:30:00"), // new Time("16:00:00"), // this.stepInMinutesForTimer); this.dailyTimes = new List<Time>(); this.dailyTimes.Add(new Time("09:30:00")); this.dailyTimes.Add(new Time("16:00:00")); this.nearToOpeningTimeFrom = new Time("09:30:00"); this.nearToOpeningTimeTo = new Time("09:35:00"); this.nearToClosingTimeFrom = new Time("15:55:00"); this.nearToClosingTimeTo = new Time("16:00:00"); this.historicalMarketValueProviderForInSample = // new HistoricalRawQuoteProvider(); new HistoricalAdjustedQuoteProvider(); this.historicalMarketValueProviderForOutOfSample = // this.getHistoricalBarProvider(); this.historicalMarketValueProviderForInSample; // new HistoricalRawQuoteProvider(); this.historicalMarketValueProviderForTheBackTester = this.historicalMarketValueProviderForOutOfSample; //new HistoricalBarProvider( //new SimpleBarCache( intervalFrameInSeconds, //BarComponent.Open ) ); //ricordarsi di togliere - mettere //commento nel gestore evento tempo this.timerForBackTester = new IndexBasedEndOfDayTimer( this.firstDateTime, this.lastDateTime, this.benchmark.Ticker); // new IndexBasedHistoricalTimer(this.benchmark.Ticker, // this.firstDateTime, // this.lastDateTime , // this.dailyTimes, // this.intervalFrameInSeconds); } #endregion main #region eligiblesSelector protected override IEligiblesSelector getEligiblesSelector() { this.maxNumberOfEligiblesToBeChosen = 50; // string tickersGroupId = "SP500"; string tickersGroupId = "STOCKMI"; bool temporizedGroup = true; int numDaysForAverageRawOpenPriceComputation = 10; double minPrice = 0.50; double maxPrice = 200; // int maxNumberOfMostLiquidTickersToBeChosen = 150; // int numDaysForVolatility = 10; // IEligiblesSelector eligiblesSelector = // new ByPriceMostLiquidQuotedAtEachDateTime( // tickersGroupId , temporizedGroup , // maxNumberOfEligiblesToBeChosen , // numDaysForAverageRawOpenPriceComputation , // minPrice , maxPrice, intervalFrameInSeconds , // this.benchmark.Ticker ); // // IEligiblesSelector eligiblesSelector = // new ByPriceMostLiquidLessVolatileOTCAlwaysQuoted( // tickersGroupId , temporizedGroup , // maxNumberOfEligiblesToBeChosen , // maxNumberOfMostLiquidTickersToBeChosen , // numDaysForAverageRawOpenPriceComputation , // numDaysForVolatility , // minPrice , maxPrice ); IEligiblesSelector eligiblesSelector = new ByPriceMostLiquidAlwaysQuoted( tickersGroupId , temporizedGroup , maxNumberOfEligiblesToBeChosen , numDaysForAverageRawOpenPriceComputation , minPrice , maxPrice ); // IEligiblesSelector eligiblesSelector = // new ByPriceLessVolatileOTCAlwaysQuoted( // tickersGroupId , temporizedGroup , // maxNumberOfEligiblesToBeChosen , // numDaysForAverageRawOpenPriceComputation , // minPrice , maxPrice ); // eligiblesSelector = // new DummyEligibleSelector(); // return eligiblesSelector; } #endregion eligiblesSelector #region inSampleChooser protected override IInSampleChooser getInSampleChooser() { // Combination combinations; // if(this.genomeManagerType == GenomeManagerType.ShortAndLong || // this.genomeManagerType == GenomeManagerType.OnlyMixed) // combinations = new Combination(-this.maxNumberOfEligiblesToBeChosen, this.maxNumberOfEligiblesToBeChosen - 1, this.numberOfPortfolioPositions); // else // combinations = new Combination(0, this.maxNumberOfEligiblesToBeChosen - 1, this.numberOfPortfolioPositions); // // int numberOfBestTestingPositionsToBeReturned = // (int)combinations.TotalNumberOfCombinations; int numberOfBestTestingPositionsToBeReturned = 50; // parameters for the genetic optimizer double crossoverRate = 0.85; double mutationRate = 0.02; double elitismRate = 0.001; int populationSizeForGeneticOptimizer = 10000; int generationNumberForGeneticOptimizer = 30; int seedForRandomGenerator = QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator; IDecoderForTestingPositions decoderForTestingPositions = new BasicDecoderForOTCPositions(); IFitnessEvaluator fitnessEvaluator = // new OTCFitnessEvaluator( new SharpeRatio() ); new OTCCTOFitnessEvaluator( new SharpeRatio() ); // new DummyRandomFitnessEvaluator(); // IInSampleChooser inSampleChooser = // new OTCIntradayGeneticChooser(numberOfBestTestingPositionsToBeReturned, // 1 , balancedWeightsOnVolatilityBase, // minimumAbsoluteReturnValue , maximumAbsoluteReturnValue, this.benchmark.Ticker); ADT.ConstantsProvider.AmountOfVariableWeightToBeAssignedToTickers = 0.40; IInSampleChooser inSampleChooser = new OTCEndOfDayGeneticChooser(this.numberOfPortfolioPositions, numberOfBestTestingPositionsToBeReturned, benchmark, decoderForTestingPositions , this.genomeManagerType , fitnessEvaluator , historicalMarketValueProviderForInSample, crossoverRate, mutationRate, elitismRate , populationSizeForGeneticOptimizer, generationNumberForGeneticOptimizer, seedForRandomGenerator); // new OTCEndOfDayGeneticChooserWithWeights(this.numberOfPortfolioPositions, numberOfBestTestingPositionsToBeReturned, // benchmark, // this.genomeManagerType , // fitnessEvaluator , // historicalMarketValueProviderForInSample, crossoverRate, // mutationRate, elitismRate , populationSizeForGeneticOptimizer, // generationNumberForGeneticOptimizer, seedForRandomGenerator); // IInSampleChooser inSampleChooser = // new OTCEndOfDayBruteForceChooser(this.portfolioType, // this.numberOfPortfolioPositions, // numberOfBestTestingPositionsToBeReturned, // this.benchmark, decoderForTestingPositions , fitnessEvaluator, // historicalMarketValueProviderForInSample); // //office // inSampleChooser = // new PVOChooserFromSavedBackTestLog( // @"C:\Utente\MarcoVarie\Vari\qP\LogArchive\2009_01_05_13_40_28_PVOIntraday_from_2006_01_01_to_2007_12_31_annlRtrn_17,84_maxDD_4,52\2009_01_05_13_40_28_PVOIntraday_from_2006_01_01_to_2007_12_31_annlRtrn_17,84_maxDD_4,52.qpL", // numberOfBestTestingPositionsToBeReturned); //home // inSampleChooser = // new PVOChooserFromSavedBackTestLog( // @"C:\Utente\MarcoVarie\Vari\qP\LogArchive\2009_01_01_18_57_36_PVOIntraday_from_2006_01_01_to_2007_12_31_annlRtrn_17.11_maxDD_3.80\2009_01_01_18_57_36_PVOIntraday_from_2006_01_01_to_2007_12_31_annlRtrn_17.11_maxDD_3.80.qpL", // numberOfBestTestingPositionsToBeReturned); return inSampleChooser; } #endregion inSampleChooser #region strategy protected override IStrategyForBacktester getStrategyForBacktester() { //int inSampleDays = 90; int inSampleDays = 90; int numDaysBetweenEachOptimization = 5; int numDaysBeforeCurrentDateForRetrievingInSampleData = 1; int minNumOfEligiblesForValidOptimization = 10; //disabilitato il controllo della fitness double minimumNumberOfStdDevForSignificantFitness = 0.0; double maximumNumberOfStdDevForSignificantFitness = 0.0; int sampleLengthForFitnessDistributionEstimation = 150; //disabilitato il controllo della fitness IInSampleFitnessDistributionEstimator estimator = new BasicInSampleFitnessDistributionEstimator(); GeneticChooser geneticChooserForEstimator = new OTCEndOfDayGeneticChooser(this.numberOfPortfolioPositions, 50, this.benchmark, new BasicDecoderForOTCPositions(), this.genomeManagerType , new OTCCTOFitnessEvaluator( new SharpeRatio() ) , historicalMarketValueProviderForInSample, 0.85, 0.01, 0.001 , 100, 0, QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator); double stopLoss = 0.015; double takeProfit = 0.03; object[] daysForPlayingTheStrategy = new object[5]{ DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday}; IStrategyForBacktester strategyForBacktester // = new PVO_OTCStrategyLessCorrelated(eligiblesSelector ,inSampleChooser , // inSampleDays , benchmark , numDaysBetweenEachOptimization , // oversoldThreshold , overboughtThreshold , historicalQuoteProvider); // = new OTC_CTO_EODStrategy(eligiblesSelector , minNumOfEligiblesForValidOptimization, inSampleChooser , inSampleDays , benchmark , numDaysBetweenEachOptimization , numDaysBeforeCurrentDateForRetrievingInSampleData, historicalMarketValueProviderForInSample, historicalMarketValueProviderForOutOfSample, this.dailyTimes, this.nearToOpeningTimeFrom, this.nearToOpeningTimeTo, this.nearToClosingTimeFrom, this.nearToClosingTimeTo, stopLoss , takeProfit, this.portfolioType, geneticChooserForEstimator, minimumNumberOfStdDevForSignificantFitness, maximumNumberOfStdDevForSignificantFitness, estimator, sampleLengthForFitnessDistributionEstimation, daysForPlayingTheStrategy); // ((OTCIntradayStrategy)strategyForBacktester).FindPositionsForToday( // new DateTime(2009,9,1), new DateTime(2009,8,28) ); return strategyForBacktester; } #endregion strategy #region backTester protected override EndOfDayStrategyBackTester getEndOfDayStrategyBackTester() { string backTestId = "OTC_CTO_EODStrategy"; IAccountProvider accountProvider; accountProvider = new SimpleAccountProvider(); // accountProvider = // new FixedCommissionsAndSlippageAccountProvider(5.0, 0.0); // double fixedPercentageSlippage = 0.05; // accountProvider = // new InteractiveBrokerAccountProvider(fixedPercentageSlippage); double cashToStart = 10000; double maxRunningHours = 15; EndOfDayStrategyBackTester endOfDayStrategyBackTester = new EndOfDayStrategyBackTester( backTestId , this.timerForBackTester, this.strategyForBacktester , this.historicalMarketValueProviderForTheBackTester , accountProvider , firstDateTime , lastDateTime , this.benchmark , cashToStart , maxRunningHours ); return endOfDayStrategyBackTester; } #endregion backTester #region getHistoricalBarProvider #region getBarCache // private IBarCache getBarCache() // { // IBarCache barCache = new DailyBarCache( this.intervalFrameInSeconds , dailyTimes ); // return barCache; // } #endregion getBarCache // private HistoricalBarProvider getHistoricalBarProvider() // { // IBarCache barCache = getBarCache(); // HistoricalBarProvider historicalBarProvider = // new HistoricalBarProvider( barCache ); // return historicalBarProvider; // } #endregion getHistoricalBarProvider protected override string getCustomSmallTextForFolderName() { return "OTC_CTO_EODStrategy"; } protected override string getPathForTheMainFolderWhereScriptsResultsAreToBeSaved() { string pathForTheMainFolderWhereScriptsResultsAreToBeSaved = System.Configuration.ConfigurationManager.AppSettings["LogArchive"]; return pathForTheMainFolderWhereScriptsResultsAreToBeSaved; } protected override string getFullPathFileNameForMain() { string returnValue; string fullPathFileNameForMainAtHome = @"C:\Quant\QuantProject\b7_Scripts\TickerSelectionTesting\OTC_CTO\OTC_CTO_EOD\OTC_CTO_EODMain.cs"; if( File.Exists(fullPathFileNameForMainAtHome) ) returnValue = fullPathFileNameForMainAtHome; else returnValue = @"C:\Utente\MarcoVarie\Vari\qP\QuantProject\b7_Scripts\TickerSelectionTesting\OTC_CTO\OTC_CTO_EOD\OTC_CTO_EODMain.cs"; return returnValue; } } } --- NEW FILE: OTC_CTO_EODStrategy.cs --- /* QuantProject - Quantitative Finance Library OTC_CTO_EODStrategy.cs Copyright (C) 2010 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using System.Collections.Generic; using System.IO; using QuantProject.ADT; using QuantProject.ADT.Statistics; using QuantProject.ADT.Histories; using QuantProject.ADT.Messaging; using QuantProject.ADT.Timing; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.InSample; using QuantProject.Business.Strategies.InSample.InSampleFitnessDistributionEstimation; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.Logging; using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Business.DataProviders; using QuantProject.Business.Strategies.TickersRelationships; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.Optimizing.Decoding; using QuantProject.Data; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Data.DataTables; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.InSampleChoosers; using QuantProject.Scripts.TickerSelectionTesting.OTC; using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers; using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers.Genetic; using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers.BruteForce; using QuantProject.Scripts.TickerSelectionTesting.OTC.OTC_Intraday; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; namespace QuantProject.Scripts.TickerSelectionTesting.OTC_CTO.OTC_CTO_EOD { /// <summary> /// Implements the open to close - clos to open strategy (buy a portfolio at open /// and sell it at close and then reverse positions during night) /// using EOD quotes and reducing at minimum the number /// of trades required for playing it /// </summary> [Serializable] public class OTC_CTO_EODStrategy : IStrategyForBacktester { public event NewLogItemEventHandler NewLogItem; public event NewMessageEventHandler NewMessage; //initialized by the constructor protected int inSampleDays; protected int numDaysBetweenEachOptimization; protected int numDaysBeforeCurrentDateForRetrievingInSampleData; protected IInSampleChooser inSampleChooser; protected GeneticChooser geneticChooserForFitnessDistributionEstimator; protected double numberOfMinStdDeviationForOpeningPositions; protected double numberOfMaxStdDeviationForOpeningPositions; protected IEligiblesSelector eligiblesSelector; protected IInSampleFitnessDistributionEstimator estimator; protected int sampleLength; protected Benchmark benchmark; protected HistoricalMarketValueProvider historicalMarketValueProviderForInSample; protected HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample; //initialized after constructor's call protected int numDaysElapsedSinceLastOptimization; protected ReturnsManager returnsManager; protected TestingPositions[] chosenOTCPositions; //chosen in sample by the chooser or passed //directly by the user using a form: //these are the positions to test out of sample protected PortfolioType portfolioType; protected DateTime lastOptimizationDateTime; protected Account account; public Account Account { get { return this.account; } set { this.account = value; } } private int minimumNumberOfEligiblesForValidOptimization; // private bool optimalPositionsHaveBeenUpdated; protected int idxForBestPositionsCompatibleWithPortfolioType; protected EligibleTickers currentEligibles; protected bool stopLossConditionReached; protected bool takeProfitConditionReached; protected double maxOpeningLengthInMinutes; protected Time lastEntryTime; protected Time lastProfitOrLossTime; protected List<Time> openingTimesForAvailableBars; protected Time nearToOpeningTimeFrom; protected Time nearToOpeningTimeTo; protected Time nearToClosingTimeFrom; protected Time nearToClosingTimeTo; protected double currentAccountValue; protected double previousAccountValue; protected double stopLoss; protected double takeProfit; protected object[] daysForPlayingTheStrategy; protected Portfolio currentCTOPortfolio; protected Portfolio currentOTCPortfolio; private string description_GetDescriptionForChooser() { if(this.inSampleChooser == null) return "NoChooserDefined"; else return this.inSampleChooser.Description; } private Time getLastEventTimeWithCachedBars() { return this.openingTimesForAvailableBars[openingTimesForAvailableBars.Count - 1]; } private Time getFirstEventTimeWithCachedBars() { return this.openingTimesForAvailableBars[0]; } public string Description { get { string description = "OTC_CTO_EODStrategy"; return description; } } public bool StopBacktestIfMaxRunningHoursHasBeenReached { get { return true; } } private void otc_cto_EODStrategy_commonInitialization(IEligiblesSelector eligiblesSelector, int minimumNumberOfEligiblesForValidOptimization, int inSampleDays, Benchmark benchmark, int numDaysBetweenEachOptimization, int numDaysBeforeCurrentDateForRetrievingInSampleData, HistoricalMarketValueProvider historicalMarketValueProviderForInSample, HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample, List<Time> openingTimesForAvailableBars, Time nearToOpeningTimeFrom, Time nearToOpeningTimeTo, Time nearToClosingTimeFrom, Time nearToClosingTimeTo, double stopLoss, double takeProfit, PortfolioType portfolioType, GeneticChooser geneticChooserForFitnessDistributionEstimator, double numberOfMinimumStdDeviationForOpeningPositions, double numberOfMaxStdDeviationForOpeningPositions, IInSampleFitnessDistributionEstimator estimator, int sampleLength, object[] daysForPlayingTheStrategy) { this.eligiblesSelector = eligiblesSelector; this.minimumNumberOfEligiblesForValidOptimization = minimumNumberOfEligiblesForValidOptimization; this.inSampleDays = inSampleDays; this.benchmark = benchmark; this.idxForBestPositionsCompatibleWithPortfolioType = 0; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.numDaysBeforeCurrentDateForRetrievingInSampleData = numDaysBeforeCurrentDateForRetrievingInSampleData; this.historicalMarketValueProviderForInSample = historicalMarketValueProviderForInSample; this.historicalMarketValueProviderForOutOfSample = historicalMarketValueProviderForOutOfSample; this.openingTimesForAvailableBars = openingTimesForAvailableBars; this.nearToOpeningTimeFrom = nearToOpeningTimeFrom; this.nearToOpeningTimeTo = nearToOpeningTimeTo; this.nearToClosingTimeFrom = nearToClosingTimeFrom; this.nearToClosingTimeTo = nearToClosingTimeTo; this.stopLoss = stopLoss; this.takeProfit = takeProfit; this.portfolioType = portfolioType; this.geneticChooserForFitnessDistributionEstimator = geneticChooserForFitnessDistributionEstimator; this.numberOfMinStdDeviationForOpeningPositions = numberOfMinimumStdDeviationForOpeningPositions; this.numberOfMaxStdDeviationForOpeningPositions = numberOfMaxStdDeviationForOpeningPositions; this.estimator = estimator; this.sampleLength = sampleLength; this.daysForPlayingTheStrategy = daysForPlayingTheStrategy; } public OTC_CTO_EODStrategy(IEligiblesSelector eligiblesSelector, int minimumNumberOfEligiblesForValidOptimization, IInSampleChooser inSampleChooser, int inSampleDays, Benchmark benchmark, int numDaysBetweenEachOptimization, int numDaysBeforeCurrentDateForRetrievingInSampleData, HistoricalMarketValueProvider historicalMarketValueProviderForInSample, HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample, List<Time> openingTimesForAvailableBars, Time nearToOpeningTimeFrom, Time nearToOpeningTimeTo, Time nearToClosingTimeFrom, Time nearToClosingTimeTo, double stopLoss, double takeProfit, PortfolioType portfolioType, GeneticChooser geneticChooserForFitnessDistributionEstimator, double numberOfMinimumStdDeviationForOpeningPositions, double numberOfMaxStdDeviationForOpeningPositions, IInSampleFitnessDistributionEstimator estimator, int sampleLength, object[] daysForPlayingTheStrategy) { this.inSampleChooser = inSampleChooser; this.otc_cto_EODStrategy_commonInitialization(eligiblesSelector, minimumNumberOfEligiblesForValidOptimization, inSampleDays, benchmark, numDaysBetweenEachOptimization, numDaysBeforeCurrentDateForRetrievingInSampleData, historicalMarketValueProviderForInSample, historicalMarketValueProviderForOutOfSample, openingTimesForAvailableBars, nearToOpeningTimeFrom, nearToOpeningTimeTo, nearToClosingTimeFrom, nearToClosingTimeTo, stopLoss, takeProfit, portfolioType, geneticChooserForFitnessDistributionEstimator, numberOfMinimumStdDeviationForOpeningPositions, numberOfMaxStdDeviationForOpeningPositions, estimator, sampleLength, daysForPlayingTheStrategy); } public OTC_CTO_EODStrategy(IEligiblesSelector eligiblesSelector, TestingPositions[] chosenOTCPositions, Benchmark benchmark, HistoricalMarketValueProvider historicalMarketValueProviderForInSample, HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample, List<Time> openingTimesForAvailableBars, double stopLoss, double takeProfit, PortfolioType portfolioType, GeneticChooser geneticChooserForFitnessDistributionEstimator, double numberOfMinimumStdDeviationForOpeningPositions, double numberOfMaxStdDeviationForOpeningPositions, IInSampleFitnessDistributionEstimator estimator, int sampleLength, object[] daysForPlayingTheStrategy) { this.chosenOTCPositions = chosenOTCPositions; this.otc_cto_EODStrategy_commonInitialization(eligiblesSelector, 5, 5, benchmark, numDaysBetweenEachOptimization, 0, historicalMarketValueProviderForInSample, historicalMarketValueProviderForOutOfSample, openingTimesForAvailableBars, nearToOpeningTimeFrom, nearToOpeningTimeTo, nearToClosingTimeFrom, nearToClosingTimeTo, stopLoss, takeProfit, portfolioType, geneticChooserForFitnessDistributionEstimator, numberOfMinimumStdDeviationForOpeningPositions, numberOfMaxStdDeviationForOpeningPositions, estimator, sampleLength, daysForPlayingTheStrategy); } private bool allTickersAreExchanged(DateTime dateTime, string[] tickers) { bool returnValue = true; try{ for( int i = 0; i < tickers.Length; i++ ) { if(!this.historicalMarketValueProviderForOutOfSample.WasExchanged( tickers[i], dateTime ) ) { returnValue = false; i = tickers.Length; //exit from for } } } catch(Exception ex){ string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; returnValue = false; } return returnValue; } private bool allTickersAreExchangedInTheLastFiveMinutelyBars(DateTime fromDateTime, string[] tickers) { bool returnValue = true; Time lastFiveMinutelyBarTime = this.openingTimesForAvailableBars[this.openingTimesForAvailableBars.Count-1].AddMinutes(-5); try{ for( int i = 0; i < tickers.Length; i++ ) { Bars currentTickerBars = new Bars(tickers[i], Time.GetDateTimeFromMerge(fromDateTime, lastFiveMinutelyBarTime), Time.GetDateTimeFromMerge(fromDateTime, this.openingTimesForAvailableBars[this.openingTimesForAvailableBars.Count-1]), 60); if( currentTickerBars.Rows.Count < 1 ) { returnValue = false; i = tickers.Length; //exit from for } } } catch(Exception ex){ string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; returnValue = false; } return returnValue; } #region newDateTimeEventHandler_closePositions private void newDateTimeEventHandler_closePositions(Time currentDailyTime) { if( allTickersAreExchanged( this.now(), AccountManager.GetTickersInOpenedPositions(this.account) ) ) { AccountManager.ClosePositions( this.account ); this.lastEntryTime = new Time("00:00:00"); } } #endregion newDateTimeEventHandler_closePositions private bool newDateTimeEventHandler_openPositions_bestFitnessIsSignificantlyHigh() { bool returnValue = false; double average, stdDev; if( this.geneticChooserForFitnessDistributionEstimator != null && this.estimator != null ) { average = estimator.GetAverage(this.geneticChooserForFitnessDistributionEstimator, this.currentEligibles, this.returnsManager, 100); stdDev = Math.Sqrt(estimator.GetVariance(this.geneticChooserForFitnessDistributionEstimator, this.currentEligibles, this.returnsManager, 100)); double bestFitness = this.chosenOTCPositions[idxForBestPositionsCompatibleWithPortfolioType].FitnessInSample; double minNumOfStdDev = this.numberOfMinStdDeviationForOpeningPositions; double maxNumOfStdDev = this.numberOfMaxStdDeviationForOpeningPositions; returnValue = bestFitness >= (average + minNumOfStdDev * stdDev) && bestFitness <= (average + maxNumOfStdDev * stdDev); } return returnValue; } #region newDateTimeEventHandler_openCTOPortfolio private void newDateTimeEventHandler_openCTOPortfolio(Time currentDailyTime) { if( this.chosenOTCPositions != null && this.allTickersAreExchanged( this.now(), this.chosenOTCPositions[0].WeightedPositions.SignedTickers.Tickers) // && // this.newDateTimeEventHandler_openPositions_bestFitnessIsSignificantlyHigh() // && this.newDateTimeEventHandler_openPositions_isTheRightDay() ) // && // this.allTickersAreExchangedInTheLastFiveMinutelyBars( this.now(), this.chosenOTCPositions[idxForBestPositionsCompatibleWithPortfolioType].WeightedPositions.SignedTickers.Tickers ) // ) { try { WeightedPositions oppositeWeightedPositions = this.chosenOTCPositions[0].WeightedPositions.Opposite; AccountManager.OpenPositions( oppositeWeightedPositions, this.account ); this.currentCTOPortfolio = this.account.Portfolio; this.lastEntryTime = currentDailyTime; this.previousAccountValue = this.account.GetMarketValue(); } catch(Exception ex) { string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } } } #endregion newDateTimeEventHandler_openCTOPortfolio #region newDateTimeEventHandler_openOTCPortfolio private void newDateTimeEventHandler_openOTCPortfolio(Time currentDailyTime) { if( this.chosenOTCPositions != null && this.allTickersAreExchanged( this.now(), this.chosenOTCPositions[0].WeightedPositions.SignedTickers.Tickers) ) { try { this.currentOTCPortfolio = new Portfolio(); foreach(Position position in this.currentCTOPortfolio.Values) { Position newOTCPosition = new Position(position.Instrument, - 2 * position.Quantity); OrderType orderTypeForNewOTCPosition; if(position.IsLong) orderTypeForNewOTCPosition = OrderType.MarketSellShort; else//position.IsShort orderTypeForNewOTCPosition = OrderType.MarketBuy; Order order = new Order(orderTypeForNewOTCPosition, position.Instrument, 2 * Math.Abs(position.Quantity)); this.account.AddOrder(order); this.currentOTCPortfolio.Add(position.Instrument.Key, newOTCPosition); } this.lastEntryTime = currentDailyTime; this.previousAccountValue = this.account.GetMarketValue(); } catch(Exception ex) { string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } } } #endregion newDateTimeEventHandler_openOTCPortfolio #region newDateTimeEventHandler_closeOTCPortfolio private void newDateTimeEventHandler_closeOTCPortfolio(Time currentDailyTime) { if( this.currentOTCPortfolio != null && this.allTickersAreExchanged( this.now(), this.chosenOTCPositions[0].WeightedPositions.SignedTickers.Tickers) ) { try { foreach(Position position in this.currentOTCPortfolio.Values) { OrderType orderTypeForClosingOTCPosition; if(position.IsLong) orderTypeForClosingOTCPosition = OrderType.MarketSellShort; else//position.IsShort orderTypeForClosingOTCPosition = OrderType.MarketBuy; Order order = new Order(orderTypeForClosingOTCPosition, position.Instrument, Math.Abs(position.Quantity)); this.account.AddOrder(order); } this.currentOTCPortfolio = null; this.previousAccountValue = this.account.GetMarketValue(); } catch(Exception ex) { string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } } } #endregion newDateTimeEventHandler_closeOTCPortfolio #region newDateTimeEventHandler_closeBothPortfolios private void newDateTimeEventHandler_closeBothPortfolios(Time currentDailyTime) { if( allTickersAreExchanged( this.now(), AccountManager.GetTickersInOpenedPositions(this.account) ) ) { try { AccountManager.ClosePositions( this.account ); this.lastEntryTime = new Time("00:00:00"); this.currentOTCPortfolio = null; this.currentCTOPortfolio = null; } catch(Exception ex) { string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } } } #endregion newDateTimeEventHandler_closeBothPortfolios #region newDateTimeEventHandler_updateStopLossAndTakeProfitConditions protected virtual void newDateTimeEventHandler_updateStopLossAndTakeProfitConditions(Time currentDailyTime) { //this.previousAccountValue has been set at opening positions this.stopLossConditionReached = false; this.takeProfitConditionReached = false; this.lastProfitOrLossTime = new Time("00:00:00"); if(this.account.Portfolio.Count > 0) { try{ this.currentAccountValue = this.account.GetMarketValue(); double portfolioGainOrLoss = (this.currentAccountValue - this.previousAccountValue) /this.previousAccountValue; if(!double.IsInfinity(portfolioGainOrLoss) && portfolioGainOrLoss <= -this.stopLoss ) { this.stopLossConditionReached = true; this.lastProfitOrLossTime = currentDailyTime; } else if (!double.IsInfinity(portfolioGainOrLoss) && portfolioGainOrLoss >= this.takeProfit ) { this.takeProfitConditionReached = true; this.lastProfitOrLossTime = currentDailyTime; } } catch(Exception ex) {string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + "";} } } #endregion newDateTimeEventHandler_updateStopLossAndTakeProfitConditions public virtual void NewDateTimeEventHandler( Object sender , DateTime dateTime ) { Time currentTime = new Time( dateTime ); bool nearToOpeningTime = currentTime >= this.nearToOpeningTimeFrom && currentTime <= this.nearToOpeningTimeTo; bool nearToClosingTime = currentTime >= this.nearToClosingTimeFrom && currentTime <= this.nearToClosingTimeTo; // this.newDateTimeEventHandler_updateStopLossAndTakeProfitConditions(currentTime); // bool timeToProfitOrToStopLoss = this.takeProfitConditionReached || // this.stopLossConditionReached; if( this.account.Portfolio.Count > 0 && nearToOpeningTime ) this.newDateTimeEventHandler_openOTCPortfolio(currentTime); if( this.account.Portfolio.Count > 0 && nearToClosingTime ) { if( this.optimalTestingPositionsAreToBeUpdated() ) { this.newDateTimeEventHandler_closeBothPortfolios(currentTime); this.updateTestingPositions( dateTime ); this.lastOptimizationDateTime = this.now(); } else this.newDateTimeEventHandler_closeOTCPortfolio(currentTime); } if( this.account.Portfolio.Count == 0 && nearToClosingTime ) this.newDateTimeEventHandler_openCTOPortfolio(currentTime); } #region FindPositionsForToday // private double[] findPositionsForToday_writePositionsToLogFile_getFitnesses(TestingPositions[] positionsToWrite) // { // int numOfValidFitnesses = 0; // double[] validFitnesses; // for(int i=0; i<positionsToWrite.Length; i++) // if( positionsToWrite[i] != null && // !double.IsInfinity(positionsToWrite[i].FitnessInSample) && // !double.IsNaN(positionsToWrite[i].FitnessInSample) && // positionsToWrite[i].FitnessInSample != double.MinValue ) // numOfValidFitnesses++; // // validFitnesses = new double[numOfValidFitnesses]; // int addedValidFitnesses = 0; // for(int i=0; i<positionsToWrite.Length; i++) // if( positionsToWrite[i] != null && // !double.IsInfinity(positionsToWrite[i].FitnessInSample) && // !double.IsNaN(positionsToWrite[i].FitnessInSample) && // positionsToWrite[i].FitnessInSample != double.MinValue ) // { // validFitnesses[addedValidFitnesses] = positionsToWrite[i].FitnessInSample; // addedValidFitnesses++; // } // return validFitnesses; // } private void findPositionsForToday_writePositionsToLogFile(DateTime today, EligibleTickers eligibles, TestingPositions[] positionsToWrite) { double averageRandomFitness = estimator.GetAverage(this.geneticChooserForFitnessDistributionEstimator, this.currentEligibles, this.returnsManager, this.sampleLength); double stdDevForRandomFitness = Math.Sqrt(estimator.GetVariance(this.geneticChooserForFitnessDistributionEstimator, this.currentEligibles, this.returnsManager, this.sampleLength)); string pathFile = System.Configuration.ConfigurationManager.AppSettings["LogArchive"] + "\\PositionsForOTCStrategyOn" + today.Day.ToString() + "_" + today.Month.ToString() + "_" + today.Year.ToString() + ".txt"; StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); w.Write("\r\nPositions for OTC Strategy on date: {0}\r", today.ToLongDateString() ); w.Write("\r\nNum days for optimization {0}\r", this.inSampleDays.ToString()); w.Write("\r\nEligibles: {0}\r", eligibles.Count.ToString() ); w.WriteLine ("\n----------------------------------------------"); // for(int i = 0; i<positionsToWrite.Length; i++) if(positionsToWrite[i] != null && positionsToWrite[i].FitnessInSample != double.MinValue) w.WriteLine("\n{0}-Positions: {1} --> fitness {2}", i.ToString(), positionsToWrite[i].WeightedPositions.Description, positionsToWrite[i].FitnessInSample.ToString() ); w.WriteLine ("\n\n----------------------------------------------"); w.WriteLine ("\n\nBest testing positions is {0}", this.idxForBestPositionsCompatibleWithPortfolioType.ToString()); w.Write("\r\nAverage random fitness (sample: {0}): {1}\r", this.sampleLength.ToString(), averageRandomFitness.ToString() ); w.Write("\r\nStandard deviation for random fitness: {0}\r", stdDevForRandomFitness.ToString()); w.Write("\r\nAverage + min num of std deviation ({0}) is: {1}\r", this.numberOfMinStdDeviationForOpeningPositions.ToString() , (averageRandomFitness + this.numberOfMinStdDeviationForOpeningPositions * stdDevForRandomFitness).ToString()); w.Write("\r\nAverage + max num of std deviation ({0}) is: {1}\r", this.numberOfMaxStdDeviationForOpeningPositions.ToString() , (averageRandomFitness + this.numberOfMaxStdDeviationForOpeningPositions * stdDevForRandomFitness).ToString()); // Update the underlying file. w.Flush(); w.Close(); } public void FindPositionsForToday(DateTime today, DateTime lastMarketDay) { History history = this.benchmark.GetEndOfDayHistory( HistoricalEndOfDayTimer.GetMarketOpen( lastMarketDay.AddDays( -this.inSampleDays ) ) , HistoricalEndOfDayTimer.GetMarketClose( lastMarketDay ) ); this.currentEligibles = this.eligiblesSelector.GetEligibleTickers(history); this.updateReturnsManager(history.FirstDateTime, history.LastDateTime); if( ( this.eligiblesSelector is DummyEligibleSelector && this.inSampleChooser != null ) || ( this.currentEligibles.Count > this.minimumNumberOfEligiblesForValidOptimization && this.inSampleChooser != null ) ) { this.chosenOTCPositions = (TestingPositions[])inSampleChooser.AnalyzeInSample(this.currentEligibles, this.returnsManager); // this.updateTestingPositions_updateIdxForBestPositionsCompatibleWithPortfolioType(); this.findPositionsForToday_writePositionsToLogFile(today, this.currentEligibles, this.chosenOTCPositions); this.chosenOTCPositions = null; } } #endregion FindPositionsForToday #region UpdateTestingPositions // private void updateTestingPositions_updateIdxForBestPositionsCompatibleWithPortfolioType() // { // for(int i = 0; i<this.chosenOTCPositions.Length; i++) // { // if(this.chosenOTCPositions[i] != null && // ( (this.chosenOTCPositions[i].BothLongAndShortPositions && // (this.portfolioType == PortfolioType.ShortAndLong || this.portfolioType == PortfolioType.OnlyMixed) ) || // (this.chosenOTCPositions[i].OnlyLongPositions && this.portfolioType == PortfolioType.OnlyLong) || // (this.chosenOTCPositions[i].OnlyShortPositions && this.portfolioType == PortfolioType.OnlyShort) ) ) // { // this.idxForBestPositionsCompatibleWithPortfolioType = i; // i = this.chosenOTCPositions.Length;//exit from for // } // } // } protected void updateTestingPositions(DateTime currentDateTime) { History history = this.benchmark.GetEndOfDayHistory( HistoricalEndOfDayTimer.GetMarketOpen( currentDateTime.AddDays( -this.inSampleDays ) ) , HistoricalEndOfDayTimer.GetMarketClose( currentDateTime.AddDays(-this.numDaysBeforeCurrentDateForRetrievingInSampleData) ) ); this.currentEligibles = this.eligiblesSelector.GetEligibleTickers(history); this.updateReturnsManager(history.FirstDateTime, history.LastDateTime); if( ( this.eligiblesSelector is DummyEligibleSelector && this.inSampleChooser != null ) || ( this.currentEligibles.Count > this.minimumNumberOfEligiblesForValidOptimization && this.inSampleChooser != null ) ) { this.chosenOTCPositions = (TestingPositions[])inSampleChooser.AnalyzeInSample(this.currentEligibles, this.returnsManager); // this.updateTestingPositions_updateIdxForBestPositionsCompatibleWithPortfolioType(); this.logOptimizationInfo(this.currentEligibles); } } private bool optimalTestingPositionsAreToBeUpdated() { bool areToBeUpdated = false; if(this.inSampleChooser != null) { DateTime dateTimeForNextOptimization = this.lastOptimizationDateTime.AddDays( this.numDaysBetweenEachOptimization ); areToBeUpdated = ( ( ( this.account.Portfolio.Count == 0 ) && ( ( this.lastOptimizationDateTime == DateTime.MinValue ) ) ) || ( this.now() >= dateTimeForNextOptimization ) ); } return areToBeUpdated; } // private void newDateTimeEventHandler_updateTestingPositions( // DateTime dateTime ) // { // if ( this.optimalTestingPositionsAreToBeUpdated() ) // { // this.updateTestingPositions( dateTime ); // this.lastOptimizationDateTime = this.now(); // } // } #endregion UpdateTestingPositions private DateTime now() { return this.account.Timer.GetCurrentDateTime(); } protected virtual void updateReturnsManager(DateTime firstDateTime, DateTime lastDayDateTime) { ReturnIntervals returnIntervals = // new DailyOpenToCloseIntervals( firstDateTime, lastDayDateTime, // this.benchmark.Ticker ); new OpenToCloseCloseToOpenIntervals( firstDateTime, lastDayDateTime, this.benchmark.Ticker ); this.returnsManager = new ReturnsManager( returnIntervals , this.historicalMarketValueProviderForInSample); } private OTCIntradayLogItem getLogItem( EligibleTickers eligibleTickers ) { OTCIntradayLogItem logItem = new OTCIntradayLogItem(this.now(), this.inSampleDays); logItem.BestOTCPositionsInSample = this.chosenOTCPositions; logItem.NumberOfEligibleTickers = eligibleTickers.Count; logItem.Fitness = this.chosenOTCPositions[idxForBestPositionsCompatibleWithPortfolioType].FitnessInSample; logItem.Generation = ((IGeneticallyOptimizable)this.chosenOTCPositions[idxForBestPositionsCompatibleWithPortfolioType]).Generation; logItem.Tickers = this.chosenOTCPositions[idxForBestPositionsCompatibleWithPortfolioType].HashCodeForTickerComposition; return logItem; } private void raiseNewLogItem( EligibleTickers eligibleTickers ) { OTCIntradayLogItem logItem = this.getLogItem( eligibleTickers ); NewLogItemEventArgs newLogItemEventArgs = new NewLogItemEventArgs( logItem ); this.NewLogItem( this , newLogItemEventArgs ); } private void notifyMessage( EligibleTickers eligibleTickers ) { string message = "Number of Eligible tickers: " + eligibleTickers.Count; NewMessageEventArgs newMessageEventArgs = new NewMessageEventArgs( message ); if ( this.NewMessage != null ) this.NewMessage( this , newMessageEventArgs ); } private void logOptimizationInfo( EligibleTickers eligibleTickers ) { if(eligibleTickers.Count > 0) this.raiseNewLogItem( eligibleTickers ); this.notifyMessage( eligibleTickers ); } } } |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/InSampleChoosers/Genetic In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv29821/DrivenBySharpeRatio/InSampleChoosers/Genetic Added Files: DrivenBySharpeRatioInSampleChooser.cs GenomeManagerForDrivenBySharpeRatio.cs Log Message: Added script files for the driven by sharpe ratio strategy --- NEW FILE: GenomeManagerForDrivenBySharpeRatio.cs --- /* QuantProject - Quantitative Finance Library GenomeManagerForDrivenBySharpeRatio.cs Copyright (C) 2011 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.ADT; using QuantProject.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.Business.Strategies.TickersRelationships; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation; using QuantProject.Business.Strategies.Optimizing.Decoding; using QuantProject.Business.Strategies.Optimizing.GenomeManagers; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio.InSampleChoosers.Genetic { /// <summary> /// Implements a simple GenomeManager for finding /// the portfolio with the highest Sharpe Ratio /// </summary> [Serializable] public class GenomeManagerForDrivenBySharpeRatio : BasicGenomeManager { public GenomeManagerForDrivenBySharpeRatio(EligibleTickers eligibleTickers, int numberOfTickersInPortfolio, IDecoderForTestingPositions decoderForTestingPositions, IFitnessEvaluator fitnessEvaluator, GenomeManagerType genomeManagerType, ReturnsManager returnsManager, int seedForRandomGenerator) : base(eligibleTickers, numberOfTickersInPortfolio, decoderForTestingPositions, fitnessEvaluator, genomeManagerType, returnsManager, seedForRandomGenerator) { } public override double GetFitnessValue(Genome genome) { double fitnessValue = double.MinValue; fitnessValue = this.fitnessEvaluator.GetFitnessValue(genome.Meaning, this.returnsManager); return fitnessValue; } public override Genome[] GetChilds(Genome parent1, Genome parent2) { return GenomeManipulator.MixGenesWithoutDuplicates(parent1, parent2); } public override int GetNewGeneValue(Genome genome, int genePosition) { // in this implementation new gene values must be different from // the others already stored in the given genome int returnValue = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePosition), genome.GetMaxValueForGenes(genePosition) + 1); while( GenomeManipulator.IsTickerContainedInGenome(returnValue,genome) ) //the portfolio can't have a long position and a short one for the same ticker { returnValue = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePosition), genome.GetMaxValueForGenes(genePosition) + 1); } return returnValue; } public override void Mutate(Genome genome) { // in this implementation only one gene is mutated // the new value has to be different from all the other genes of the genome int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); int newValueForGene = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePositionToBeMutated), genome.GetMaxValueForGenes(genePositionToBeMutated) + 1); while( GenomeManipulator.IsTickerContainedInGenome(newValueForGene,genome) ) //the portfolio can't have a long position and a short one for the same ticker { newValueForGene = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePositionToBeMutated), genome.GetMaxValueForGenes(genePositionToBeMutated) + 1); } GenomeManagement.MutateOneGene(genome, genePositionToBeMutated, newValueForGene); } } } --- NEW FILE: DrivenBySharpeRatioInSampleChooser.cs --- /* QuantProject - Quantitative Finance Library DrivenBySharpeRatioInSampleChooser.cs Copyright (C) 2011 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Business.Strategies; using QuantProject.Business.DataProviders; using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation; using QuantProject.Business.Strategies.Optimizing.Decoding; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.InSample; using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.Optimizing.GenomeManagers; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio.InSampleChoosers.Genetic { /// <summary> /// In sample genetic analyzer for the /// Driven by Sharpe Ratio strategy /// </summary> [Serializable] public class DrivenBySharpeRatioInSampleChooser : GeneticChooser { protected GenomeManagerType genomeManagerType; public DrivenBySharpeRatioInSampleChooser( int numberOfPortfolioPositions , int numberOfBestTestingPositionsToBeReturned , Benchmark benchmark , IDecoderForTestingPositions decoderForTestingPositions , GenomeManagerType genomeManagerType , IFitnessEvaluator fitnessEvaluator , HistoricalMarketValueProvider historicalMarketValueProvider , double crossoverRate , double mutationRate , double elitismRate , int populationSizeForGeneticOptimizer , int generationNumberForGeneticOptimizer , int seedForRandomGenerator) : base(numberOfPortfolioPositions, numberOfBestTestingPositionsToBeReturned, benchmark , decoderForTestingPositions , fitnessEvaluator , historicalMarketValueProvider , crossoverRate , mutationRate , elitismRate , populationSizeForGeneticOptimizer , generationNumberForGeneticOptimizer , seedForRandomGenerator ) { this.genomeManagerType = genomeManagerType; } protected override string getHashCodeForGenome(QuantProject.ADT.Optimizing.Genetic.Genome genome) { string returnValue = ((TestingPositions)genome.Meaning).HashCodeForTickerComposition; return returnValue; } public override IGenomeManager GetGenomeManager(EligibleTickers eligibleTickers , ReturnsManager returnsManager) { return new GenomeManagerForDrivenBySharpeRatio(eligibleTickers, this.numberOfPortfolioPositions, this.decoderForTestingPositions, this.fitnessEvaluator, this.genomeManagerType , returnsManager, this.seedForRandomGeneratorForTheGeneticOptimizer); } } } |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv29693/DrivenBySharpeRatio Added Files: DrivenBySharpeRatioLogItem.cs DrivenBySharpeRatioMain.cs DrivenBySharpeRatioStrategy.cs Log Message: Added script files for the driven by sharpe ratio strategy --- NEW FILE: DrivenBySharpeRatioStrategy.cs --- /* QuantProject - Quantitative Finance Library DrivenBySharpeRatioStrategy.cs Copyright (C) 2011 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using System.Collections.Generic; using System.IO; using QuantProject.ADT; using QuantProject.ADT.Statistics; using QuantProject.ADT.Histories; using QuantProject.ADT.Messaging; using QuantProject.ADT.Timing; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.InSample; using QuantProject.Business.Strategies.InSample.InSampleFitnessDistributionEstimation; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.Logging; using QuantProject.Business.Strategies.ReturnsManagement; //using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Business.DataProviders; using QuantProject.Business.Strategies.TickersRelationships; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.Optimizing.Decoding; using QuantProject.Data; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Data.DataTables; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.InSampleChoosers; using QuantProject.Scripts.TickerSelectionTesting.OTC; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio { /// <summary> /// Implements a strategy driven by Sharpe Ratio /// value over a given sample period /// </summary> [Serializable] public class DrivenBySharpeRatioStrategy : IStrategyForBacktester { public event NewLogItemEventHandler NewLogItem; public event NewMessageEventHandler NewMessage; protected int inSamplePeriodLengthInDays; protected int numDaysBetweenEachOptimization; protected IInSampleChooser inSampleChooser; protected IEligiblesSelector eligiblesSelector; protected Benchmark benchmark; protected HistoricalMarketValueProvider historicalMarketValueProviderForInSample; protected HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample; //initialized after constructor's call protected int numDaysElapsedSinceLastOptimization; protected ReturnsManager returnsManager; protected TestingPositions[] chosenPositions; //chosen in sample by the chooser or passed //directly by the user using a form: //these are the positions to test out of sample protected PortfolioType portfolioType; protected DateTime lastEntryTime; protected DateTime lastOptimizationDateTime; protected Account account; public Account Account { get { return this.account; } set { this.account = value; } } private int minimumNumberOfEligiblesForValidOptimization; protected EligibleTickers currentEligibles; protected bool stopLossConditionReached; protected bool takeProfitConditionReached; protected double currentAccountValue; protected double previousAccountValue; protected double stopLoss; protected double takeProfit; private string description_GetDescriptionForChooser() { if(this.inSampleChooser == null) return "NoChooserDefined"; else return this.inSampleChooser.Description; } public string Description { get { string description = "DrivenBySharpeRatio"; return description; } } public bool StopBacktestIfMaxRunningHoursHasBeenReached { get { return true; } } private void drivenBySharpeRatioStrategy_commonInitialization(IEligiblesSelector eligiblesSelector , int minNumOfEligiblesForValidOptimization, IInSampleChooser inSampleChooser , int inSamplePeriodLengthInDays , Benchmark benchmark , int numDaysBetweenEachOptimization , HistoricalMarketValueProvider historicalMarketValueProviderForInSample , HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample , PortfolioType portfolioType, double stopLoss, double takeProfit) { this.eligiblesSelector = eligiblesSelector; this.minimumNumberOfEligiblesForValidOptimization = minNumOfEligiblesForValidOptimization; this.inSampleChooser = inSampleChooser; this.inSamplePeriodLengthInDays = inSamplePeriodLengthInDays; this.benchmark = benchmark; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.historicalMarketValueProviderForInSample = historicalMarketValueProviderForInSample; this.historicalMarketValueProviderForOutOfSample = historicalMarketValueProviderForOutOfSample; this.portfolioType = portfolioType; this.stopLoss = stopLoss; this.takeProfit = takeProfit; } public DrivenBySharpeRatioStrategy(IEligiblesSelector eligiblesSelector , int minNumOfEligiblesForValidOptimization, IInSampleChooser inSampleChooser , int inSamplePeriodLengthInDays , Benchmark benchmark , int numDaysBetweenEachOptimization , HistoricalMarketValueProvider historicalMarketValueProviderForInSample , HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample , PortfolioType portfolioType, double stopLoss, double takeProfit) { this.drivenBySharpeRatioStrategy_commonInitialization(eligiblesSelector , minNumOfEligiblesForValidOptimization, inSampleChooser , inSamplePeriodLengthInDays , benchmark , numDaysBetweenEachOptimization , historicalMarketValueProviderForInSample , historicalMarketValueProviderForOutOfSample , portfolioType, stopLoss, takeProfit); } public DrivenBySharpeRatioStrategy(TestingPositions[] testingPositionsToTest, int inSamplePeriodLengthInDays , Benchmark benchmark , HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample , PortfolioType portfolioType) { this.chosenPositions = testingPositionsToTest; this.drivenBySharpeRatioStrategy_commonInitialization(new DummyEligibleSelector() , 100, null , inSamplePeriodLengthInDays , benchmark , 1000 , null , historicalMarketValueProviderForOutOfSample , portfolioType, 1.50, -1.50); } private bool allTickersAreExchanged(DateTime dateTime, string[] tickers) { bool returnValue = true; try{ for( int i = 0; i < tickers.Length; i++ ) { if(!this.historicalMarketValueProviderForOutOfSample.WasExchanged( tickers[i], dateTime ) ) { returnValue = false; i = tickers.Length; //exit from for } } } catch(Exception ex){ string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; returnValue = false; } return returnValue; } #region newDateTimeEventHandler_closePositions private void newDateTimeEventHandler_closePositions() { DateTime currentDateTime = this.now(); if( allTickersAreExchanged( currentDateTime, AccountManager.GetTickersInOpenedPositions(this.account) ) ) { AccountManager.ClosePositions( this.account ); this.lastEntryTime = new DateTime(1900,1,1); } } #endregion newDateTimeEventHandler_closePositions #region newDateTimeEventHandler_openPositions private void newDateTimeEventHandler_openPositions() { if( this.chosenPositions != null && this.allTickersAreExchanged( this.now(), this.chosenPositions[0].WeightedPositions.SignedTickers.Tickers) ) { try { AccountManager.OpenPositions( this.chosenPositions[0].WeightedPositions, this.account ); this.lastEntryTime = this.now(); this.previousAccountValue = this.account.GetMarketValue(); } catch(Exception ex) { string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } } } #endregion newDateTimeEventHandler_openPositions #region newDateTimeEventHandler_updateStopLossAndTakeProfitConditions protected virtual void newDateTimeEventHandler_updateStopLossAndTakeProfitConditions() { //this.previousAccountValue has been set at opening positions this.stopLossConditionReached = false; this.takeProfitConditionReached = false; if(this.account.Portfolio.Count > 0 && this.stopLoss <= 1.00 && this.takeProfit > 0.0) { try{ this.currentAccountValue = this.account.GetMarketValue(); double portfolioGainOrLoss = (this.currentAccountValue - this.previousAccountValue) /this.previousAccountValue; if(!double.IsInfinity(portfolioGainOrLoss) && portfolioGainOrLoss <= -this.stopLoss ) { this.stopLossConditionReached = true; } else if (!double.IsInfinity(portfolioGainOrLoss) && portfolioGainOrLoss >= this.takeProfit ) { this.takeProfitConditionReached = true; } } catch(Exception ex) {string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + "";} } } #endregion newDateTimeEventHandler_updateStopLossAndTakeProfitConditions public virtual void NewDateTimeEventHandler( Object sender , DateTime dateTime ) { this.newDateTimeEventHandler_updateStopLossAndTakeProfitConditions(); bool timeToProfitOrToStopLoss = this.takeProfitConditionReached || this.stopLossConditionReached; if( this.account.Portfolio.Count == 0 ) this.newDateTimeEventHandler_openPositions(); if( (this.account.Portfolio.Count > 0 && timeToProfitOrToStopLoss) || this.optimalTestingPositionsAreToBeUpdated() ) this.newDateTimeEventHandler_closePositions(); this.newDateTimeEventHandler_updateTestingPositions( dateTime ); } private void findPositionsForToday_writePositionsToLogFile(DateTime today, EligibleTickers eligibles, TestingPositions[] positionsToWrite) { string pathFile = System.Configuration.ConfigurationManager.AppSettings["LogArchive"] + "\\PositionsForDrivenBySharpeRatioStrategy" + today.Day.ToString() + "_" + today.Month.ToString() + "_" + today.Year.ToString() + ".txt"; StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); w.Write("\r\nPositions for PositionsForDrivenBySharpeRatioStrategy on date: {0}\r", today.ToLongDateString() ); w.Write("\r\nNum days for in sample analysis {0}\r", this.inSamplePeriodLengthInDays.ToString()); w.Write("\r\nEligibles: {0}\r", eligibles.Count.ToString() ); w.WriteLine ("\n----------------------------------------------"); // for(int i = 0; i<positionsToWrite.Length; i++) if(positionsToWrite[i] != null && positionsToWrite[i].FitnessInSample != double.MinValue) w.WriteLine("\n{0}-Positions: {1} --> fitness {2}", i.ToString(), positionsToWrite[i].WeightedPositions.Description, positionsToWrite[i].FitnessInSample.ToString() ); // Update the underlying file. w.Flush(); w.Close(); } #region UpdateTestingPositions protected void updateTestingPositions(DateTime currentDateTime) { History historyForInSample = this.benchmark.GetEndOfDayHistory( HistoricalEndOfDayTimer.GetMarketClose( currentDateTime.AddDays( -this.inSamplePeriodLengthInDays ) ) , HistoricalEndOfDayTimer.GetMarketClose( currentDateTime.AddDays(-1) ) ); this.currentEligibles = this.eligiblesSelector.GetEligibleTickers(historyForInSample); this.updateReturnsManager(historyForInSample.FirstDateTime, historyForInSample.LastDateTime); if( ( this.eligiblesSelector is DummyEligibleSelector && this.inSampleChooser != null ) || ( this.currentEligibles.Count > this.minimumNumberOfEligiblesForValidOptimization && this.inSampleChooser != null ) ) { this.chosenPositions = (TestingPositions[])inSampleChooser.AnalyzeInSample(this.currentEligibles, this.returnsManager); this.logOptimizationInfo(this.currentEligibles); } } private bool optimalTestingPositionsAreToBeUpdated() { bool areToBeUpdated = false; if(this.inSampleChooser != null) { DateTime dateTimeForNextOptimization = this.lastOptimizationDateTime.AddDays( this.numDaysBetweenEachOptimization ); areToBeUpdated = ( ( ( this.account.Portfolio.Count == 0 ) && ( ( this.lastOptimizationDateTime == DateTime.MinValue ) ) ) || ( this.now() >= dateTimeForNextOptimization ) ); } return areToBeUpdated; } private void newDateTimeEventHandler_updateTestingPositions( DateTime dateTime ) { if ( this.optimalTestingPositionsAreToBeUpdated() ) { this.chosenPositions = null; this.updateTestingPositions( dateTime ); this.lastOptimizationDateTime = this.now(); } } #endregion UpdateTestingPositions private DateTime now() { return this.account.Timer.GetCurrentDateTime(); } protected virtual void updateReturnsManager(DateTime firstDateTime, DateTime lastDayDateTime) { ReturnIntervals returnIntervals = new CloseToCloseIntervals( firstDateTime, lastDayDateTime, this.benchmark.Ticker ); this.returnsManager = new ReturnsManager( returnIntervals , this.historicalMarketValueProviderForInSample); } private DrivenBySharpeRatioLogItem getLogItem( EligibleTickers eligibleTickers ) { DrivenBySharpeRatioLogItem logItem = new DrivenBySharpeRatioLogItem( this.now(), this.inSamplePeriodLengthInDays); logItem.BestPositionsInSample = this.chosenPositions; logItem.NumberOfEligibleTickers = eligibleTickers.Count; logItem.Fitness = this.chosenPositions[0].FitnessInSample; logItem.Generation = ((IGeneticallyOptimizable)this.chosenPositions[0]).Generation; logItem.Tickers = this.chosenPositions[0].HashCodeForTickerComposition; return logItem; } private void raiseNewLogItem( EligibleTickers eligibleTickers ) { DrivenBySharpeRatioLogItem logItem = this.getLogItem( eligibleTickers ); NewLogItemEventArgs newLogItemEventArgs = new NewLogItemEventArgs( logItem ); this.NewLogItem( this , newLogItemEventArgs ); } private void notifyMessage( EligibleTickers eligibleTickers ) { string message = "Number of Eligible tickers: " + eligibleTickers.Count; NewMessageEventArgs newMessageEventArgs = new NewMessageEventArgs( message ); if ( this.NewMessage != null ) this.NewMessage( this , newMessageEventArgs ); } private void logOptimizationInfo( EligibleTickers eligibleTickers ) { if(eligibleTickers.Count > 0) this.raiseNewLogItem( eligibleTickers ); this.notifyMessage( eligibleTickers ); } } } --- NEW FILE: DrivenBySharpeRatioMain.cs --- /* QuantProject - Quantitative Finance Library DrivenBySharpeRatioMain.cs Copyright (C) 2011 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using QuantProject.ADT; using QuantProject.ADT.Statistics.Combinatorial; using QuantProject.ADT.FileManaging; using QuantProject.ADT.Timing; using QuantProject.Business.DataProviders; //using QuantProject.Data.DataProviders.Bars.Caching; using QuantProject.Business.Strategies; using QuantProject.Business.Financial.Accounting.AccountProviding; using QuantProject.Business.Financial.Fundamentals.FairValueProviders; using QuantProject.Business.Financial.Fundamentals.RatioProviders; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.EquityEvaluation; using QuantProject.Business.Strategies.InSample; using QuantProject.Business.Strategies.Logging; using QuantProject.Business.Strategies.Optimizing.Decoding; using QuantProject.Business.Strategies.Optimizing.GenomeManagers; using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation; using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors; using QuantProject.Business.Timing; using QuantProject.Presentation; using QuantProject.Scripts.General; using QuantProject.Scripts.General.Logging; using QuantProject.Scripts.General.Reporting; using QuantProject.Scripts.General.Strategies.Optimizing.FitnessEvaluation; using QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio.InSampleChoosers.Genetic; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; //using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers.Genetic; //using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers.BruteForce; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio { /// <summary> /// Entry point for the DrivenBySharpeRatioStrategy. If any strategy /// parameter had to be changed, this is the place where it should /// be done /// </summary> public class DrivenBySharpeRatioMain : BasicScriptForBacktesting { private int numberOfPortfolioPositions; private double stopLoss; private double takeProfit; private PortfolioType portfolioType; private int maxNumberOfEligiblesToBeChosen; private int numDaysForInSample; private Benchmark benchmark; private DateTime firstDateTime; private DateTime lastDateTime; private HistoricalMarketValueProvider historicalMarketValueProviderForInSample; private HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample; private HistoricalMarketValueProvider historicalMarketValueProviderForTheBackTester; private Timer timerForBackTester; private GenomeManagerType genomeManagerType; #region main public DrivenBySharpeRatioMain() { this.numberOfPortfolioPositions = 4; this.benchmark = new Benchmark( "^MIBTEL" ); // this.benchmark = new Benchmark( "^GSPC" ); this.portfolioType = PortfolioType.OnlyLong;//filter for out of sample this.genomeManagerType = GenomeManagerType.OnlyLong;//filter for the genetic chooser // this.benchmark = new Benchmark( "ENI.MI" ); this.firstDateTime = new DateTime( 2001 , 1 , 1 ); this.lastDateTime = new DateTime( 2005 , 12 , 31 ); this.historicalMarketValueProviderForInSample = // new HistoricalRawQuoteProvider(); new HistoricalAdjustedQuoteProvider(); this.historicalMarketValueProviderForOutOfSample = this.historicalMarketValueProviderForInSample; this.historicalMarketValueProviderForTheBackTester = this.historicalMarketValueProviderForOutOfSample; //ricordarsi di togliere - mettere //commento nel gestore evento tempo this.numDaysForInSample = 180; this.timerForBackTester = new IndexBasedEndOfDayTimer( this.firstDateTime, this.lastDateTime, this.benchmark.Ticker); this.stopLoss = 1.50;//deactivated this.takeProfit = -0.20;//deactivated } #endregion main #region eligiblesSelector protected override IEligiblesSelector getEligiblesSelector() { this.maxNumberOfEligiblesToBeChosen = 200; // string tickersGroupId = "ticUSFin"; // string tickersGroupId = "USFunds"; // string tickersGroupId = "SP500"; string tickersGroupId = "STOCKMI"; bool temporizedGroup = false;//Attenzione! IEligiblesSelector eligiblesSelector = // new ByGroup( tickersGroupId , temporizedGroup); new ByLiquidity ( tickersGroupId , temporizedGroup , maxNumberOfEligiblesToBeChosen); // eligiblesSelector = // new DummyEligibleSelector(); // return eligiblesSelector; } #endregion eligiblesSelector #region inSampleChooser protected override IInSampleChooser getInSampleChooser() { int numberOfBestTestingPositionsToBeReturned = 5; // parameters for the genetic optimizer double crossoverRate = 0.85; double mutationRate = 0.02; double elitismRate = 0.001; int populationSizeForGeneticOptimizer = 25000; int generationNumberForGeneticOptimizer = 25; int seedForRandomGenerator = QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator; BuyAndHoldFitnessEvaluator fitnessEvaluator = new BuyAndHoldFitnessEvaluator( new SharpeRatio() ); BasicDecoderForGeneticallyOptimizableTestingPositions basicGenOptDecoder = new BasicDecoderForGeneticallyOptimizableTestingPositions(); IInSampleChooser inSampleChooser = new DrivenBySharpeRatioInSampleChooser(this.numberOfPortfolioPositions, numberOfBestTestingPositionsToBeReturned, benchmark, basicGenOptDecoder, this.genomeManagerType , fitnessEvaluator , historicalMarketValueProviderForInSample, crossoverRate, mutationRate, elitismRate , populationSizeForGeneticOptimizer, generationNumberForGeneticOptimizer, seedForRandomGenerator); return inSampleChooser; } #endregion inSampleChooser #region strategy protected override IStrategyForBacktester getStrategyForBacktester() { int numDaysBetweenEachOptimization = 60; int minNumOfEligiblesForValidOptimization = 15; IStrategyForBacktester strategyForBacktester = new DrivenBySharpeRatioStrategy(eligiblesSelector , minNumOfEligiblesForValidOptimization, inSampleChooser , numDaysForInSample , benchmark , numDaysBetweenEachOptimization , historicalMarketValueProviderForInSample , historicalMarketValueProviderForOutOfSample , this.portfolioType, this.stopLoss, this.takeProfit); return strategyForBacktester; } #endregion strategy #region backTester protected override EndOfDayStrategyBackTester getEndOfDayStrategyBackTester() { string backTestId = "DrivenBySharpeRatioStrategy"; IAccountProvider accountProvider; accountProvider = new SimpleAccountProvider(); // double fixedPercentageSlippage = 0.05; // accountProvider = // new InteractiveBrokerAccountProvider(fixedPercentageSlippage); double cashToStart = 10000; double maxRunningHours = 15; EndOfDayStrategyBackTester endOfDayStrategyBackTester = new EndOfDayStrategyBackTester( backTestId , this.timerForBackTester, this.strategyForBacktester , this.historicalMarketValueProviderForTheBackTester , accountProvider , firstDateTime , lastDateTime , this.benchmark , cashToStart , maxRunningHours ); return endOfDayStrategyBackTester; } #endregion backTester protected override string getCustomSmallTextForFolderName() { return "SharpeRatio"; } protected override string getPathForTheMainFolderWhereScriptsResultsAreToBeSaved() { string pathForTheMainFolderWhereScriptsResultsAreToBeSaved = System.Configuration.ConfigurationManager.AppSettings["LogArchive"]; return pathForTheMainFolderWhereScriptsResultsAreToBeSaved; } protected override string getFullPathFileNameForMain() { string returnValue; string fullPathFileNameForMainAtHome = @"C:\Quant\QuantProject\b7_Scripts\TickerSelectionTesting\DrivenBySharpeRatio\DrivenBySharpeRatioMain.cs"; if( File.Exists(fullPathFileNameForMainAtHome) ) returnValue = fullPathFileNameForMainAtHome; else returnValue = @"C:\Utente\MarcoTributi\Vari\Vari\qP\QuantProject\b7_Scripts\TickerSelectionTesting\DrivenBySharpeRatio\DrivenBySharpeRatioMain.cs"; return returnValue; } } } --- NEW FILE: DrivenBySharpeRatioLogItem.cs --- /* QuantProject - Quantitative Finance Library DrivenBySharpeRatioLogItem.cs Copyright (C) 2011 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections.Generic; using System.Windows.Forms; using QuantProject.ADT; using QuantProject.ADT.Timing; using QuantProject.Data.DataProviders.Bars.Caching; using QuantProject.Business.DataProviders; using QuantProject.Business.Strategies; using QuantProject.Business.Financial.Accounting.AccountProviding; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.InSample; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.Logging; using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors; using QuantProject.Scripts.TickerSelectionTesting.OTC.OTC_Intraday; using QuantProject.Business.Timing; using QuantProject.Presentation; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.General.Reporting; using QuantProject.Scripts.General.Logging; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio { /// <summary> /// LogItem for the Driven Sharpe Ratio strategy /// </summary> [Serializable] public class DrivenBySharpeRatioLogItem : LogItem { protected DummyTesterForTestingPositions[] dummyTestersForBestTestingPositionsInSample; protected TestingPositions[] bestPositionsInSample; protected int numberOfEligibleTickers; protected double fitness; protected int generation; protected string tickers; protected int inSamplePeriodLengthInDays; public TestingPositions[] BestPositionsInSample { get { if ( this.bestPositionsInSample == null ) throw new Exception( "This property has not " + "been assigned yet! If you are loading the LogItem from " + "a log, this property was not set before logging the LogItem." ); return this.bestPositionsInSample; } set { this.bestPositionsInSample = value; } } public int NumberOfEligibleTickers { get { if ( this.numberOfEligibleTickers == int.MinValue ) throw new Exception( "This property has not " + "been assigned yet! If you are loading the LogItem from " + "a log, this property was not set before logging the LogItem." ); return this.numberOfEligibleTickers; } set { this.numberOfEligibleTickers = value; } } public double Fitness { get { if ( this.fitness == double.MinValue ) throw new Exception( "This property has not " + "been assigned yet! If you are loading the LogItem from " + "a log, this property was not set before logging the LogItem." ); return this.fitness; } set { this.fitness = value; } } public int Generation { get{return this.generation;} set{this.generation = value;} } public string Tickers { get{return this.tickers;} set{this.tickers = value;} } public DrivenBySharpeRatioLogItem(DateTime dateTime, int inSamplePeriodLengthInDays) : base( dateTime ) { this.inSamplePeriodLengthInDays = inSamplePeriodLengthInDays; this.numberOfEligibleTickers = int.MinValue; this.fitness = double.MinValue; } #region runStrategyClickEventHandler protected virtual void runStrategyClickEventHandler(object sender, System.EventArgs e) { // ; //general DateTime firstDateTime = this.SimulatedCreationDateTime.AddDays(-this.inSamplePeriodLengthInDays); DateTime lastDateTime = this.SimulatedCreationDateTime; double maxRunningHours = 1; Benchmark benchmark = new Benchmark( "^GSPC" ); int numberOfPortfolioPositions = this.bestPositionsInSample[0].WeightedPositions.Count; //cash and portfolio type double cashToStart = 10000; HistoricalMarketValueProvider historicalQuoteProviderForBackTester, historicalQuoteProviderForInSampleChooser, historicalQuoteProviderForStrategy; historicalQuoteProviderForBackTester = new HistoricalAdjustedQuoteProvider(); historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester; historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser; //strategyParameters TestingPositions[] positionsToTest = this.BestPositionsInSample; DrivenBySharpeRatioStrategy strategy = new DrivenBySharpeRatioStrategy(positionsToTest, this.inSamplePeriodLengthInDays, benchmark, historicalQuoteProviderForBackTester, PortfolioType.OnlyLong); QuantProject.Business.Timing.Timer timer = new IndexBasedEndOfDayTimer( firstDateTime, lastDateTime.AddDays(this.inSamplePeriodLengthInDays), benchmark.Ticker); EndOfDayStrategyBackTester endOfDayStrategyBackTester = new EndOfDayStrategyBackTester( "BuyAndHold" , timer , strategy, historicalQuoteProviderForBackTester , new SimpleAccountProvider(), firstDateTime , lastDateTime.AddDays(this.inSamplePeriodLengthInDays) , benchmark , cashToStart , maxRunningHours ); endOfDayStrategyBackTester.Run(); BackTesterReportViewer.ShowReport( lastDateTime.AddDays(this.inSamplePeriodLengthInDays) , endOfDayStrategyBackTester ); } #endregion runStrategyClickEventHandler private void showTestingPositionsClickEventHandler_setDummyTesters_setTester( int currentIndex , TestingPositions testingPositions , DateTime simulatedCreationDateTime ) { this.dummyTestersForBestTestingPositionsInSample[ currentIndex ] = new DummyTesterForTestingPositions( testingPositions , this.inSamplePeriodLengthInDays , simulatedCreationDateTime ); } private void showTestingPositionsClickEventHandler_setDummyTesters() { this.dummyTestersForBestTestingPositionsInSample = new DummyTesterForTestingPositions[this.BestPositionsInSample.Length]; for ( int i = 0 ; i < BestPositionsInSample.Length; i++ ) this.showTestingPositionsClickEventHandler_setDummyTesters_setTester( i , BestPositionsInSample[ i ] , this.SimulatedCreationDateTime ); } protected virtual void showTestingPositionsClickEventHandler(object sender, System.EventArgs e) { this.showTestingPositionsClickEventHandler_setDummyTesters(); QuantProject.Presentation.ExecutablesListViewer executablesListViewer = new ExecutablesListViewer( this.dummyTestersForBestTestingPositionsInSample ); executablesListViewer.Show(); } protected virtual void createAndShowContextMenu() { MenuItem[] menuItems = new MenuItem[2]; menuItems[0] = new MenuItem("Run Strategy"); menuItems[1] = new MenuItem("Show TestingPositions"); menuItems[0].Click += new System.EventHandler(this.runStrategyClickEventHandler); menuItems[1].Click += new System.EventHandler(this.showTestingPositionsClickEventHandler); ContextMenu contextMenu = new ContextMenu(menuItems); contextMenu.Show(Form.ActiveForm, Form.MousePosition); } public override void Run() { this.createAndShowContextMenu(); } } } |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:36:33
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/InSampleChoosers/Genetic In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv29454/DrivenByFundamentals/DrivenByFairValueProvider/InSampleChoosers/Genetic Added Files: GenomeManagerForDrivenByFVProvider.cs Log Message: Added script files for the driven by fair value provider strategy --- NEW FILE: GenomeManagerForDrivenByFVProvider.cs --- /* QuantProject - Quantitative Finance Library GenomeManagerForDrivenByFVProvider.cs Copyright (C) 2010 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.ADT; using QuantProject.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.OutOfSample; using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Business.Strategies.TickersRelationships; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation; using QuantProject.Business.Strategies.Optimizing.Decoding; using QuantProject.Business.Strategies.Optimizing.GenomeManagers; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider.InSampleChoosers.Genetic { /// <summary> /// Implements what we need to use the Genetic Optimizer /// for finding the portfolio that fits /// the strategy driven by a particular IFairValueProvider object /// The optimazion that uses this genomeManager just seeks /// the less volatile portfolio /// </summary> [Serializable] public class GenomeManagerForDrivenByFVProvider : BasicGenomeManager { private HistoricalMarketValueProvider historicalMarketValueProvider; public GenomeManagerForDrivenByFVProvider(EligibleTickers eligibleTickers, int numberOfTickersInPortfolio, IDecoderForTestingPositions decoderForTestingPositions, IFitnessEvaluator fitnessEvaluator, GenomeManagerType genomeManagerType, ReturnsManager returnsManager, HistoricalMarketValueProvider historicalMarketValueProvider, int seedForRandomGenerator) : base(eligibleTickers, numberOfTickersInPortfolio, decoderForTestingPositions, fitnessEvaluator, genomeManagerType, returnsManager, seedForRandomGenerator) { this.historicalMarketValueProvider = historicalMarketValueProvider; } #region getFitnessByFundamentals private double getFitnessValue_getFundamentalFitness_getBuyPrice(WeightedPosition position) { double returnValue; returnValue = this.historicalMarketValueProvider.GetMarketValue(position.Ticker, new DateTime(2001,1,1) ); return returnValue; } private double getFitnessValue_getFundamentalFitness_getFairPrice(WeightedPosition position) { double returnValue; object[] keys = new object[1]; keys[0] = position.Ticker; DataRow foundRow = this.eligibleTickers.SourceDataTable.Rows.Find(keys); returnValue = (double)foundRow["FairPrice"]; return returnValue; } private double getFitnessValue_getFundamentalFitness(Genome genome) { double theoreticalProfit = 0.0; double buyPriceOfCurrentPosition, fairPriceOfCurrentPosition, weightOfCurrentPosition; WeightedPositions weightedPositionFromGenome = ((TestingPositions)genome.Meaning).WeightedPositions; foreach( WeightedPosition position in weightedPositionFromGenome ) { buyPriceOfCurrentPosition = getFitnessValue_getFundamentalFitness_getBuyPrice(position); fairPriceOfCurrentPosition = getFitnessValue_getFundamentalFitness_getFairPrice(position); weightOfCurrentPosition = position.Weight; theoreticalProfit += weightOfCurrentPosition*(fairPriceOfCurrentPosition-buyPriceOfCurrentPosition)/ buyPriceOfCurrentPosition; } return theoreticalProfit; } #endregion getFitnessByFundamentals public override double GetFitnessValue(Genome genome) { double fitnessValue = double.MinValue; double fitnessValueFromPastReturns = this.fitnessEvaluator.GetFitnessValue(genome.Meaning, this.returnsManager); double fitnessGivenByFundamentals = this.getFitnessValue_getFundamentalFitness(genome); fitnessValue = fitnessValueFromPastReturns * fitnessGivenByFundamentals; return fitnessValue; } public override Genome[] GetChilds(Genome parent1, Genome parent2) { return GenomeManipulator.MixGenesWithoutDuplicates(parent1, parent2); } public override int GetNewGeneValue(Genome genome, int genePosition) { // in this implementation new gene values must be different from // the others already stored in the given genome int returnValue = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePosition), genome.GetMaxValueForGenes(genePosition) + 1); while( GenomeManipulator.IsTickerContainedInGenome(returnValue,genome) ) //the portfolio can't have a long position and a short one for the same ticker { returnValue = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePosition), genome.GetMaxValueForGenes(genePosition) + 1); } return returnValue; } public override void Mutate(Genome genome) { // in this implementation only one gene is mutated // the new value has to be different from all the other genes of the genome int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); int newValueForGene = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePositionToBeMutated), genome.GetMaxValueForGenes(genePositionToBeMutated) + 1); while( GenomeManipulator.IsTickerContainedInGenome(newValueForGene,genome) ) //the portfolio can't have a long position and a short one for the same ticker { newValueForGene = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePositionToBeMutated), genome.GetMaxValueForGenes(genePositionToBeMutated) + 1); } GenomeManagement.MutateOneGene(genome, genePositionToBeMutated, newValueForGene); } } } |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:35:59
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv29318/DrivenByFundamentals/DrivenByFairValueProvider Added Files: DrivenByFVProviderLogItem.cs DrivenByFVProviderMain.cs DrivenByFVProviderPositions.cs DrivenByFVProviderStrategy.cs Log Message: Added script files for the driven by fair value provider strategy --- NEW FILE: DrivenByFVProviderPositions.cs --- /* QuantProject - Quantitative Finance Library DrivenByFVProviderPositions.cs Copyright (C) 2010 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Business.Timing; using QuantProject.Business.DataProviders; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider { /// <summary> /// This is the class representing a TestingPositions for the /// strategy based on fundamentals (driven by a IFairValueProvider object) /// </summary> [Serializable] public class DrivenByFVProviderPositions : TestingPositions, IGeneticallyOptimizable { private int generation; private double[] buyPricesForWeightedPositions; //explicit interface implementation //the property can be used only by a interface //instance or through a cast to the interface int IGeneticallyOptimizable.Generation { get{return this.generation;} set{this.generation = value;} } public DrivenByFVProviderPositions Copy() { return new DrivenByFVProviderPositions( this.WeightedPositions, this.generation ); } // creates an empty TestingPositions: to be used to give a meaning with // DrivenByFVProviderPositions type to undecodables public DrivenByFVProviderPositions() : base() { } public DrivenByFVProviderPositions(WeightedPositions weightedPositions, int generation) : base(weightedPositions) { this.generation = generation; } public DrivenByFVProviderPositions(WeightedPositions weightedPositions) : base(weightedPositions) { this.generation = -1; } } } --- NEW FILE: DrivenByFVProviderStrategy.cs --- /* QuantProject - Quantitative Finance Library DrivenByFVProviderStrategy.cs Copyright (C) 2010 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using System.Collections.Generic; using System.IO; using QuantProject.ADT; using QuantProject.ADT.Statistics; using QuantProject.ADT.Histories; using QuantProject.ADT.Messaging; using QuantProject.ADT.Timing; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.InSample; using QuantProject.Business.Strategies.InSample.InSampleFitnessDistributionEstimation; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.Logging; using QuantProject.Business.Strategies.ReturnsManagement; //using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Business.DataProviders; using QuantProject.Business.Strategies.TickersRelationships; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.Optimizing.Decoding; using QuantProject.Data; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Data.DataTables; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.InSampleChoosers; using QuantProject.Scripts.TickerSelectionTesting.OTC; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider { /// <summary> /// Implements a strategy driven by a fair value provider /// which uses the available fundamentals /// </summary> [Serializable] public class DrivenByFVProviderStrategy : IStrategyForBacktester { public event NewLogItemEventHandler NewLogItem; public event NewMessageEventHandler NewMessage; protected int numDaysForFundamentalAnalysis; protected int inSamplePeriodLengthInDays; protected int numDaysBetweenEachOptimization; protected IInSampleChooser inSampleChooser; protected IEligiblesSelector eligiblesSelector; protected Benchmark benchmark; protected HistoricalMarketValueProvider historicalMarketValueProviderForInSample; protected HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample; //initialized after constructor's call protected int numDaysElapsedSinceLastOptimization; protected ReturnsManager returnsManager; protected TestingPositions[] chosenPositions; //chosen in sample by the chooser or passed //directly by the user using a form: //these are the positions to test out of sample protected PortfolioType portfolioType; protected DateTime lastEntryTime; protected DateTime lastOptimizationDateTime; protected Account account; public Account Account { get { return this.account; } set { this.account = value; } } private int minimumNumberOfEligiblesForValidOptimization; // private bool optimalPositionsHaveBeenUpdated; protected EligibleTickers currentEligibles; protected bool stopLossConditionReached; protected bool takeProfitConditionReached; protected double currentAccountValue; protected double previousAccountValue; protected double stopLoss; protected double percentageOfTheoreticalProfit; protected double theoreticalProfit; //portfolio's profit if each position reaches its theoretical price protected double takeProfitLevelInAnyCase; //if current profit of the portfolio crosses this level, //the portfolio is sold, no matter what the current value //of percentageOfTheoreticalProfit is private string description_GetDescriptionForChooser() { if(this.inSampleChooser == null) return "NoChooserDefined"; else return this.inSampleChooser.Description; } public string Description { get { string description = "DrivenByFairValueProvider"; return description; } } public bool StopBacktestIfMaxRunningHoursHasBeenReached { get { return true; } } public DrivenByFVProviderStrategy(IEligiblesSelector eligiblesSelector , int minNumOfEligiblesForValidOptimization, IInSampleChooser inSampleChooser , int numDaysForFundamentalAnalysis , int numDaysForPortfolioVolatilityAnalysis , Benchmark benchmark , int numDaysBetweenEachOptimization , HistoricalMarketValueProvider historicalMarketValueProviderForInSample , HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample , PortfolioType portfolioType, double stopLoss, double percentageOfTheoreticalProfit, double takeProfitLevelInAnyCase) { this.eligiblesSelector = eligiblesSelector; this.minimumNumberOfEligiblesForValidOptimization = minNumOfEligiblesForValidOptimization; this.inSampleChooser = inSampleChooser; this.numDaysForFundamentalAnalysis = numDaysForFundamentalAnalysis; this.inSamplePeriodLengthInDays = numDaysForPortfolioVolatilityAnalysis; this.benchmark = benchmark; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.historicalMarketValueProviderForInSample = historicalMarketValueProviderForInSample; this.historicalMarketValueProviderForOutOfSample = historicalMarketValueProviderForOutOfSample; this.portfolioType = portfolioType; this.stopLoss = stopLoss; this.percentageOfTheoreticalProfit = percentageOfTheoreticalProfit; this.takeProfitLevelInAnyCase = takeProfitLevelInAnyCase; } private bool allTickersAreExchanged(DateTime dateTime, string[] tickers) { bool returnValue = true; try{ for( int i = 0; i < tickers.Length; i++ ) { if(!this.historicalMarketValueProviderForOutOfSample.WasExchanged( tickers[i], dateTime ) ) { returnValue = false; i = tickers.Length; //exit from for } } } catch(Exception ex){ string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; returnValue = false; } return returnValue; } #region newDateTimeEventHandler_closePositions private void newDateTimeEventHandler_closePositions() { DateTime currentDateTime = this.now(); if( allTickersAreExchanged( currentDateTime, AccountManager.GetTickersInOpenedPositions(this.account) ) ) { AccountManager.ClosePositions( this.account ); this.lastEntryTime = new DateTime(1900,1,1); } } #endregion newDateTimeEventHandler_closePositions #region newDateTimeEventHandler_openPositions private void newDateTimeEventHandler_openPositions() { if( this.chosenPositions != null && this.allTickersAreExchanged( this.now(), this.chosenPositions[0].WeightedPositions.SignedTickers.Tickers) ) { try { AccountManager.OpenPositions( this.chosenPositions[0].WeightedPositions, this.account ); this.lastEntryTime = this.now(); this.previousAccountValue = this.account.GetMarketValue(); } catch(Exception ex) { string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } } } #endregion newDateTimeEventHandler_openPositions #region newDateTimeEventHandler_updateStopLossAndTakeProfitConditions protected virtual void newDateTimeEventHandler_updateStopLossAndTakeProfitConditions() { //this.previousAccountValue has been set at opening positions this.stopLossConditionReached = false; this.takeProfitConditionReached = false; if(this.account.Portfolio.Count > 0) { try{ this.currentAccountValue = this.account.GetMarketValue(); double portfolioGainOrLoss = (this.currentAccountValue - this.previousAccountValue) /this.previousAccountValue; if(!double.IsInfinity(portfolioGainOrLoss) && portfolioGainOrLoss <= -this.stopLoss ) { this.stopLossConditionReached = true; } else if (!double.IsInfinity(portfolioGainOrLoss) && ( // portfolioGainOrLoss >= (this.percentageOfTheoreticalProfit * this.theoreticalProfit) || portfolioGainOrLoss >= this.takeProfitLevelInAnyCase) ) { this.takeProfitConditionReached = true; } } catch(Exception ex) {string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + "";} } } #endregion newDateTimeEventHandler_updateStopLossAndTakeProfitConditions public virtual void NewDateTimeEventHandler( Object sender , DateTime dateTime ) { this.newDateTimeEventHandler_updateStopLossAndTakeProfitConditions(); bool timeToProfitOrToStopLoss = this.takeProfitConditionReached || this.stopLossConditionReached; if( this.account.Portfolio.Count == 0 ) this.newDateTimeEventHandler_openPositions(); if( (this.account.Portfolio.Count > 0 && timeToProfitOrToStopLoss) || this.optimalTestingPositionsAreToBeUpdated() ) this.newDateTimeEventHandler_closePositions(); this.newDateTimeEventHandler_updateTestingPositions( dateTime ); } private void findPositionsForToday_writePositionsToLogFile(DateTime today, EligibleTickers eligibles, TestingPositions[] positionsToWrite) { string pathFile = System.Configuration.ConfigurationManager.AppSettings["LogArchive"] + "\\PositionsForDrivenByFVProviderStrategy" + today.Day.ToString() + "_" + today.Month.ToString() + "_" + today.Year.ToString() + ".txt"; StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); w.Write("\r\nPositions for PositionsForDrivenByFVProviderStrategy on date: {0}\r", today.ToLongDateString() ); w.Write("\r\nNum days for fundamental analysis {0}\r", this.numDaysForFundamentalAnalysis.ToString()); w.Write("\r\nNum days for portofolio analysis for volatility {0}\r", this.inSamplePeriodLengthInDays.ToString()); w.Write("\r\nEligibles: {0}\r", eligibles.Count.ToString() ); w.WriteLine ("\n----------------------------------------------"); // for(int i = 0; i<positionsToWrite.Length; i++) if(positionsToWrite[i] != null && positionsToWrite[i].FitnessInSample != double.MinValue) w.WriteLine("\n{0}-Positions: {1} --> fitness {2}", i.ToString(), positionsToWrite[i].WeightedPositions.Description, positionsToWrite[i].FitnessInSample.ToString() ); // Update the underlying file. w.Flush(); w.Close(); } #region UpdateTestingPositions private double updateTheoreticalProfit_getBuyPrice(WeightedPosition position) { double returnValue; returnValue = this.historicalMarketValueProviderForOutOfSample.GetMarketValue(position.Ticker, this.now() ); return returnValue; } private double updateTheoreticalProfit_getFairPrice(WeightedPosition position) { double returnValue; object[] keys = new object[1]; keys[0] = position.Ticker; DataRow foundRow = this.currentEligibles.SourceDataTable.Rows.Find(keys); returnValue = (double)foundRow["FairPrice"]; return returnValue; } private void updateTheoreticalProfit() { double buyPriceOfCurrentPosition; double fairPriceOfCurrentPosition; double weightOfCurrentPosition; foreach( WeightedPosition position in this.chosenPositions[0].WeightedPositions ) { buyPriceOfCurrentPosition = this.updateTheoreticalProfit_getBuyPrice(position); fairPriceOfCurrentPosition = this.updateTheoreticalProfit_getFairPrice(position); weightOfCurrentPosition = position.Weight; this.theoreticalProfit += weightOfCurrentPosition*(fairPriceOfCurrentPosition-buyPriceOfCurrentPosition)/ buyPriceOfCurrentPosition; } } protected void updateTestingPositions(DateTime currentDateTime) { History historyForEligiblesSelector = this.benchmark.GetEndOfDayHistory( HistoricalEndOfDayTimer.GetMarketClose( currentDateTime.AddDays( -this.numDaysForFundamentalAnalysis ) ) , HistoricalEndOfDayTimer.GetMarketClose( currentDateTime.AddDays(-1) ) ); History historyForReturnsManager = this.benchmark.GetEndOfDayHistory( HistoricalEndOfDayTimer.GetMarketClose( currentDateTime.AddDays( -this.inSamplePeriodLengthInDays ) ) , HistoricalEndOfDayTimer.GetMarketClose( currentDateTime.AddDays(-1) ) ); this.currentEligibles = this.eligiblesSelector.GetEligibleTickers(historyForEligiblesSelector); this.updateReturnsManager(historyForReturnsManager.FirstDateTime, historyForReturnsManager.LastDateTime); if( ( this.eligiblesSelector is DummyEligibleSelector && this.inSampleChooser != null ) || ( this.currentEligibles.Count > this.minimumNumberOfEligiblesForValidOptimization && this.inSampleChooser != null ) ) { this.chosenPositions = (TestingPositions[])inSampleChooser.AnalyzeInSample(this.currentEligibles, this.returnsManager); this.logOptimizationInfo(this.currentEligibles); } } private bool optimalTestingPositionsAreToBeUpdated() { bool areToBeUpdated = false; if(this.inSampleChooser != null) { DateTime dateTimeForNextOptimization = this.lastOptimizationDateTime.AddDays( this.numDaysBetweenEachOptimization ); areToBeUpdated = ( ( ( this.account.Portfolio.Count == 0 ) && ( ( this.lastOptimizationDateTime == DateTime.MinValue ) ) ) || ( this.now() >= dateTimeForNextOptimization ) ); } return areToBeUpdated; } private void newDateTimeEventHandler_updateTestingPositions( DateTime dateTime ) { if ( this.optimalTestingPositionsAreToBeUpdated() ) { this.chosenPositions = null; this.updateTestingPositions( dateTime ); this.lastOptimizationDateTime = this.now(); // if(this.chosenPositions != null) // this.updateTheoreticalProfit(); } } #endregion UpdateTestingPositions private DateTime now() { return this.account.Timer.GetCurrentDateTime(); } protected virtual void updateReturnsManager(DateTime firstDateTime, DateTime lastDayDateTime) { ReturnIntervals returnIntervals = // new DailyOpenToCloseIntervals( firstDateTime, lastDayDateTime, // this.benchmark.Ticker ); new CloseToCloseIntervals( firstDateTime, lastDayDateTime, this.benchmark.Ticker ); this.returnsManager = new ReturnsManager( returnIntervals , this.historicalMarketValueProviderForInSample); } private DrivenByFVProviderLogItem getLogItem( EligibleTickers eligibleTickers ) { DrivenByFVProviderLogItem logItem = new DrivenByFVProviderLogItem( this.now(), this.numDaysForFundamentalAnalysis, this.inSamplePeriodLengthInDays); logItem.BestPositionsInSample = this.chosenPositions; logItem.NumberOfEligibleTickers = eligibleTickers.Count; logItem.Fitness = this.chosenPositions[0].FitnessInSample; logItem.Generation = ((IGeneticallyOptimizable)this.chosenPositions[0]).Generation; logItem.Tickers = this.chosenPositions[0].HashCodeForTickerComposition; return logItem; } private void raiseNewLogItem( EligibleTickers eligibleTickers ) { DrivenByFVProviderLogItem logItem = this.getLogItem( eligibleTickers ); NewLogItemEventArgs newLogItemEventArgs = new NewLogItemEventArgs( logItem ); this.NewLogItem( this , newLogItemEventArgs ); } private void notifyMessage( EligibleTickers eligibleTickers ) { string message = "Number of Eligible tickers: " + eligibleTickers.Count; NewMessageEventArgs newMessageEventArgs = new NewMessageEventArgs( message ); if ( this.NewMessage != null ) this.NewMessage( this , newMessageEventArgs ); } private void logOptimizationInfo( EligibleTickers eligibleTickers ) { if(eligibleTickers.Count > 0) this.raiseNewLogItem( eligibleTickers ); this.notifyMessage( eligibleTickers ); } } } --- NEW FILE: DrivenByFVProviderMain.cs --- /* QuantProject - Quantitative Finance Library DrivenByFVProviderMain.cs Copyright (C) 2010 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using System.Collections.Generic; using System.IO; using QuantProject.ADT; using QuantProject.ADT.Statistics.Combinatorial; using QuantProject.ADT.FileManaging; using QuantProject.ADT.Timing; using QuantProject.Business.DataProviders; //using QuantProject.Data.DataProviders.Bars.Caching; using QuantProject.Business.Strategies; using QuantProject.Business.Financial.Accounting.AccountProviding; using QuantProject.Business.Financial.Fundamentals.FairValueProviders; using QuantProject.Business.Financial.Fundamentals.RatioProviders; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.EquityEvaluation; using QuantProject.Business.Strategies.InSample; using QuantProject.Business.Strategies.Logging; using QuantProject.Business.Strategies.Optimizing.Decoding; using QuantProject.Business.Strategies.Optimizing.GenomeManagers; using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation; using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors; using QuantProject.Business.Timing; using QuantProject.Presentation; using QuantProject.Scripts.General; using QuantProject.Scripts.General.Logging; using QuantProject.Scripts.General.Reporting; using QuantProject.Scripts.General.Strategies.Optimizing.FitnessEvaluation; using QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider.InSampleChoosers.Genetic; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; //using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers.Genetic; //using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers.BruteForce; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider { /// <summary> /// Entry point for the DrivenByFairValueProviderStrategy. If any strategy /// parameter had to be changed, this is the place where it should /// be done /// </summary> public class DrivenByFVProviderMain : BasicScriptForBacktesting { private int numberOfPortfolioPositions; private double stopLoss; private double percentageOfTheoreticalProfitForExit; private double takeProfitLevelInAnyCase; private PortfolioType portfolioType; private int maxNumberOfEligiblesToBeChosen; private IFairValueProvider fairValueProvider; private int numDaysForFundamentalAnalysis; private int numDaysForPortfolioVolatilityAnalysis; private int numDaysForFundamentalDataAvailability; private Benchmark benchmark; private DateTime firstDateTime; private DateTime lastDateTime; private HistoricalMarketValueProvider historicalMarketValueProviderForInSample; private HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample; private HistoricalMarketValueProvider historicalMarketValueProviderForTheBackTester; private Timer timerForBackTester; private GenomeManagerType genomeManagerType; #region main public DrivenByFVProviderMain() { this.numberOfPortfolioPositions = 4; this.benchmark = new Benchmark( "^GSPC" ); this.portfolioType = PortfolioType.OnlyLong;//filter for out of sample this.genomeManagerType = GenomeManagerType.OnlyLong;//filter for the genetic chooser // this.benchmark = new Benchmark( "ENI.MI" ); this.firstDateTime = new DateTime( 2002 , 4 , 1 ); this.lastDateTime = new DateTime( 2009 , 3, 31 ); this.historicalMarketValueProviderForInSample = // new HistoricalRawQuoteProvider(); new HistoricalAdjustedQuoteProvider(); this.historicalMarketValueProviderForOutOfSample = this.historicalMarketValueProviderForInSample; this.historicalMarketValueProviderForTheBackTester = this.historicalMarketValueProviderForOutOfSample; //ricordarsi di togliere - mettere //commento nel gestore evento tempo this.numDaysForFundamentalDataAvailability = 30; // double optimalDebtEquityRatioLevel = 0.1; // int maxNumOfGrowthRatesToTakeIntoAccount = 4; IGrowthRateProvider growthProvider = // new AverageAndDebtAdjustedGrowthRateProvider(numDaysForFundamentalDataAvailability, // maxNumOfGrowthRatesToTakeIntoAccount, // optimalDebtEquityRatioLevel); new LastAvailableGrowthRateProvider(numDaysForFundamentalDataAvailability); IRatioProvider_PE PEProvider = new LastAvailablePEProvider(this.historicalMarketValueProviderForInSample, numDaysForFundamentalDataAvailability); double fairPEGRatioLevel = 1.0; this.fairValueProvider = new PEGRatioFairValueProvider(fairPEGRatioLevel,PEProvider, growthProvider,this.historicalMarketValueProviderForInSample); this.numDaysForFundamentalAnalysis = 365; this.numDaysForPortfolioVolatilityAnalysis = 90; this.timerForBackTester = new IndexBasedEndOfDayTimer( this.firstDateTime, this.lastDateTime, this.benchmark.Ticker); this.stopLoss = 100.0; this.percentageOfTheoreticalProfitForExit = 0.50; // it determines the take profit level, by // multiplying the theoretical profit that would // be gained if each position in portfolio reached its // fair value computed by the IFairValueProvider this.takeProfitLevelInAnyCase = 100.0; } #endregion main #region eligiblesSelector protected override IEligiblesSelector getEligiblesSelector() { this.maxNumberOfEligiblesToBeChosen = 800; string tickersGroupId = "ticUSFin"; // string tickersGroupId = "SP500"; // string tickersGroupId = "STOCKMI"; bool temporizedGroup = true;//Attenzione! double minimumIncome = 10000000.0;//10 mln int numOfMinIncomeInARow = 4; double minimumRelativeDifferenceBetweenFairAndAverageMarketPrice = 0.05; int numDaysForAveragePriceComputation = 10; IEligiblesSelector eligiblesSelector = new ByMostDiscountedPrices( this.fairValueProvider , tickersGroupId , temporizedGroup , maxNumberOfEligiblesToBeChosen , this.numDaysForFundamentalAnalysis, this.numDaysForFundamentalDataAvailability, minimumIncome, numOfMinIncomeInARow, minimumRelativeDifferenceBetweenFairAndAverageMarketPrice, numDaysForAveragePriceComputation); // new ByLiquidity ( tickersGroupId , temporizedGroup , // maxNumberOfEligiblesToBeChosen ); // eligiblesSelector = // new DummyEligibleSelector(); // return eligiblesSelector; } #endregion eligiblesSelector #region inSampleChooser protected override IInSampleChooser getInSampleChooser() { int numberOfBestTestingPositionsToBeReturned = 1; // parameters for the genetic optimizer double crossoverRate = 0.85; double mutationRate = 0.02; double elitismRate = 0.001; int populationSizeForGeneticOptimizer = 40000; int generationNumberForGeneticOptimizer = 50; int seedForRandomGenerator = QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator; BuyAndHoldFitnessEvaluator fitnessEvaluator = // new BuyAndHoldFitnessEvaluator( new Variance() ); new BuyAndHoldFitnessEvaluator( new SharpeRatio() ); BasicDecoderForGeneticallyOptimizableTestingPositions basicGenOptDecoder = new BasicDecoderForGeneticallyOptimizableTestingPositions(); IInSampleChooser inSampleChooser = new DrivenByFVProviderInSampleChooser(this.numberOfPortfolioPositions, numberOfBestTestingPositionsToBeReturned, benchmark, basicGenOptDecoder, this.genomeManagerType , fitnessEvaluator , historicalMarketValueProviderForInSample, crossoverRate, mutationRate, elitismRate , populationSizeForGeneticOptimizer, generationNumberForGeneticOptimizer, seedForRandomGenerator); // new SelectTopEligiblesInSampleChooser( this.numberOfPortfolioPositions, // numberOfBestTestingPositionsToBeReturned); return inSampleChooser; } #endregion inSampleChooser #region strategy protected override IStrategyForBacktester getStrategyForBacktester() { int numDaysBetweenEachOptimization = 60; int minNumOfEligiblesForValidOptimization = 10; IStrategyForBacktester strategyForBacktester = new DrivenByFVProviderStrategy(eligiblesSelector , minNumOfEligiblesForValidOptimization, inSampleChooser , numDaysForFundamentalAnalysis , numDaysForPortfolioVolatilityAnalysis , benchmark , numDaysBetweenEachOptimization , historicalMarketValueProviderForInSample , historicalMarketValueProviderForOutOfSample , this.portfolioType, this.stopLoss, this.percentageOfTheoreticalProfitForExit, this.takeProfitLevelInAnyCase); return strategyForBacktester; } #endregion strategy #region backTester protected override EndOfDayStrategyBackTester getEndOfDayStrategyBackTester() { string backTestId = "DrivenByFairValueProviderStrategy"; IAccountProvider accountProvider; accountProvider = new SimpleAccountProvider(); // double fixedPercentageSlippage = 0.05; // accountProvider = // new InteractiveBrokerAccountProvider(fixedPercentageSlippage); double cashToStart = 10000; double maxRunningHours = 15; EndOfDayStrategyBackTester endOfDayStrategyBackTester = new EndOfDayStrategyBackTester( backTestId , this.timerForBackTester, this.strategyForBacktester , this.historicalMarketValueProviderForTheBackTester , accountProvider , firstDateTime , lastDateTime , this.benchmark , cashToStart , maxRunningHours ); return endOfDayStrategyBackTester; } #endregion backTester protected override string getCustomSmallTextForFolderName() { return "FairValuePrvStr"; } protected override string getPathForTheMainFolderWhereScriptsResultsAreToBeSaved() { string pathForTheMainFolderWhereScriptsResultsAreToBeSaved = System.Configuration.ConfigurationManager.AppSettings["LogArchive"]; return pathForTheMainFolderWhereScriptsResultsAreToBeSaved; } protected override string getFullPathFileNameForMain() { string returnValue; string fullPathFileNameForMainAtHome = @"C:\Quant\QuantProject\b7_Scripts\TickerSelectionTesting\DrivenByFundamentals\DrivenByFairValueProvider\DrivenByFVProviderMain.cs"; if( File.Exists(fullPathFileNameForMainAtHome) ) returnValue = fullPathFileNameForMainAtHome; else returnValue = @"C:\Utente\MarcoTributi\Vari\Vari\qP\QuantProject\b7_Scripts\TickerSelectionTesting\DrivenByFundamentals\DrivenByFairValueProvider\DrivenByFVProviderMain.cs"; return returnValue; } } } --- NEW FILE: DrivenByFVProviderLogItem.cs --- /* QuantProject - Quantitative Finance Library DrivenByFVProviderLogItem.cs Copyright (C) 2010 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections.Generic; using System.Windows.Forms; using QuantProject.ADT; using QuantProject.ADT.Timing; using QuantProject.Data.DataProviders.Bars.Caching; using QuantProject.Business.DataProviders; using QuantProject.Business.Strategies; using QuantProject.Business.Financial.Accounting.AccountProviding; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.InSample; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.Logging; using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors; using QuantProject.Scripts.TickerSelectionTesting.OTC.OTC_Intraday; using QuantProject.Business.Timing; using QuantProject.Presentation; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.General.Reporting; using QuantProject.Scripts.General.Logging; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider { /// <summary> /// LogItem for the Driven Fair Value Provider strategy /// </summary> [Serializable] public class DrivenByFVProviderLogItem : LogItem { protected DummyTesterForTestingPositions[] dummyTestersForBestTestingPositionsInSample; protected TestingPositions[] bestPositionsInSample; protected int numberOfEligibleTickers; protected double fitness; protected int generation; protected string tickers; protected int numberOfDaysForFundamentalAnalysis; protected int numberOfDaysForVolatilityAnalysis; public TestingPositions[] BestPositionsInSample { get { if ( this.bestPositionsInSample == null ) throw new Exception( "This property has not " + "been assigned yet! If you are loading the LogItem from " + "a log, this property was not set before logging the LogItem." ); return this.bestPositionsInSample; } set { this.bestPositionsInSample = value; } } public int NumberOfEligibleTickers { get { if ( this.numberOfEligibleTickers == int.MinValue ) throw new Exception( "This property has not " + "been assigned yet! If you are loading the LogItem from " + "a log, this property was not set before logging the LogItem." ); return this.numberOfEligibleTickers; } set { this.numberOfEligibleTickers = value; } } public double Fitness { get { if ( this.fitness == double.MinValue ) throw new Exception( "This property has not " + "been assigned yet! If you are loading the LogItem from " + "a log, this property was not set before logging the LogItem." ); return this.fitness; } set { this.fitness = value; } } public int Generation { get{return this.generation;} set{this.generation = value;} } public string Tickers { get{return this.tickers;} set{this.tickers = value;} } public DrivenByFVProviderLogItem(DateTime dateTime, int numberOfDaysForFundamentalAnalysis, int numberOfDaysForVolatilityAnalysis) : base( dateTime ) { this.numberOfDaysForFundamentalAnalysis = numberOfDaysForFundamentalAnalysis; this.numberOfDaysForVolatilityAnalysis = numberOfDaysForVolatilityAnalysis; this.numberOfEligibleTickers = int.MinValue; this.fitness = double.MinValue; } #region runStrategyClickEventHandler protected virtual void runStrategyClickEventHandler(object sender, System.EventArgs e) { ; /* //general DateTime firstDateTime = this.SimulatedCreationDateTime.AddDays(-this.numberOfInSampleDays); DateTime lastDateTime = this.SimulatedCreationDateTime; double maxRunningHours = 1; Benchmark benchmark = new Benchmark( "CCE" ); int numberOfPortfolioPositions = this.BestOTCPositionsInSample[0].WeightedPositions.Count; //cash and portfolio type double cashToStart = 30000; HistoricalMarketValueProvider historicalQuoteProviderForBackTester, historicalQuoteProviderForInSampleChooser, historicalQuoteProviderForStrategy; historicalQuoteProviderForBackTester = // new HistoricalBarProvider( // new SimpleBarCache( 60, // BarComponent.Open ) ); new HistoricalRawQuoteProvider(); historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester; historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser; IEligiblesSelector eligiblesSelector = new DummyEligibleSelector(); //strategyParameters TestingPositions[] positionsToTest = this.BestOTCPositionsInSample; // new PreviousPeriodsWereEfficientEntryCondition(1, historicalQuoteProviderForStrategy, // numDaysForOscillatingPeriodForOutOfSample * 24 *60, // new MarketDateTimeManager(benchmark, firstDateTime, lastDateTime, 60) ); object[] days = new object[5]{DayOfWeek.Monday, DayOfWeek.Tuesday, DayOfWeek.Wednesday, DayOfWeek.Thursday, DayOfWeek.Friday}; OTCIntradayStrategy strategy = new OTCIntradayStrategy(eligiblesSelector, positionsToTest, benchmark, historicalQuoteProviderForInSampleChooser, historicalQuoteProviderForBackTester, Time.GetIntermediateTimes(new Time("09:30:00"), new Time("16:00:00"), 1 ), 0.5, 0.5, PortfolioType.ShortAndLong, null, 2, 3, null, 100, days); QuantProject.Business.Timing.Timer timer = // new QuantProject.Business.Timing.IndexBasedHistoricalTimer( // benchmark.Ticker, firstDateTime , lastDateTime, // Time.GetIntermediateTimes(new Time("09:30:00"), // new Time("16:00:00"), 1 ) , // 60); new IndexBasedEndOfDayTimer( firstDateTime, lastDateTime.AddDays(10), benchmark.Ticker); EndOfDayStrategyBackTester endOfDayStrategyBackTester = new EndOfDayStrategyBackTester( "OTC" , timer , strategy, historicalQuoteProviderForBackTester , new SimpleAccountProvider(), firstDateTime , lastDateTime , benchmark , cashToStart , maxRunningHours ); endOfDayStrategyBackTester.Run(); BackTesterReportViewer.ShowReport( lastDateTime , endOfDayStrategyBackTester ); */ } #endregion runStrategyClickEventHandler private void showTestingPositionsClickEventHandler_setDummyTesters_setTester( int currentIndex , TestingPositions testingPositions , DateTime simulatedCreationDateTime ) { this.dummyTestersForBestTestingPositionsInSample[ currentIndex ] = new DummyTesterForTestingPositions( testingPositions , this.numberOfDaysForVolatilityAnalysis , simulatedCreationDateTime ); } private void showTestingPositionsClickEventHandler_setDummyTesters() { this.dummyTestersForBestTestingPositionsInSample = new DummyTesterForTestingPositions[this.BestPositionsInSample.Length]; for ( int i = 0 ; i < BestPositionsInSample.Length; i++ ) this.showTestingPositionsClickEventHandler_setDummyTesters_setTester( i , BestPositionsInSample[ i ] , this.SimulatedCreationDateTime ); } protected virtual void showTestingPositionsClickEventHandler(object sender, System.EventArgs e) { this.showTestingPositionsClickEventHandler_setDummyTesters(); QuantProject.Presentation.ExecutablesListViewer executablesListViewer = new ExecutablesListViewer( this.dummyTestersForBestTestingPositionsInSample ); executablesListViewer.Show(); } protected virtual void createAndShowContextMenu() { MenuItem[] menuItems = new MenuItem[2]; menuItems[0] = new MenuItem("Run Strategy"); menuItems[1] = new MenuItem("Show TestingPositions"); menuItems[0].Click += new System.EventHandler(this.runStrategyClickEventHandler); menuItems[1].Click += new System.EventHandler(this.showTestingPositionsClickEventHandler); ContextMenu contextMenu = new ContextMenu(menuItems); contextMenu.Show(Form.ActiveForm, Form.MousePosition); } public override void Run() { this.createAndShowContextMenu(); } } } |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:35:31
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/InSampleChoosers/Genetic In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv29202/DrivenByFundamentals/DrivenByFairValueProvider/InSampleChoosers/Genetic Added Files: DrivenByFVProviderFitnessEvaluator.cs DrivenByFVProviderInSampleChooser.cs Log Message: Added script files for the driven by fair value provider strategy --- NEW FILE: DrivenByFVProviderInSampleChooser.cs --- /* QuantProject - Quantitative Finance Library DrivenByFVProviderInSampleChooser.cs Copyright (C) 2010 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Business.Strategies; using QuantProject.Business.DataProviders; using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation; using QuantProject.Business.Strategies.Optimizing.Decoding; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.InSample; using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.Optimizing.GenomeManagers; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider.InSampleChoosers.Genetic { /// <summary> /// In sample genetic analyzer for the /// Driven by Fair Value Provider strategy /// </summary> [Serializable] public class DrivenByFVProviderInSampleChooser : GeneticChooser { protected GenomeManagerType genomeManagerType; public DrivenByFVProviderInSampleChooser( int numberOfPortfolioPositions , int numberOfBestTestingPositionsToBeReturned , Benchmark benchmark , IDecoderForTestingPositions decoderForTestingPositions , GenomeManagerType genomeManagerType , IFitnessEvaluator fitnessEvaluator , HistoricalMarketValueProvider historicalMarketValueProvider , double crossoverRate , double mutationRate , double elitismRate , int populationSizeForGeneticOptimizer , int generationNumberForGeneticOptimizer , int seedForRandomGenerator) : base(numberOfPortfolioPositions, numberOfBestTestingPositionsToBeReturned, benchmark , decoderForTestingPositions , fitnessEvaluator , historicalMarketValueProvider , crossoverRate , mutationRate , elitismRate , populationSizeForGeneticOptimizer , generationNumberForGeneticOptimizer , seedForRandomGenerator ) { this.genomeManagerType = genomeManagerType; } protected override string getHashCodeForGenome(QuantProject.ADT.Optimizing.Genetic.Genome genome) { string returnValue = ((TestingPositions)genome.Meaning).HashCodeForTickerComposition; return returnValue; } public override IGenomeManager GetGenomeManager(EligibleTickers eligibleTickers , ReturnsManager returnsManager) { return new GenomeManagerForDrivenByFVProvider(eligibleTickers, this.numberOfPortfolioPositions, this.decoderForTestingPositions, this.fitnessEvaluator, this.genomeManagerType , returnsManager, this.historicalMarketValueProvider, this.seedForRandomGeneratorForTheGeneticOptimizer); } } } --- NEW FILE: DrivenByFVProviderFitnessEvaluator.cs --- /* QuantProject - Quantitative Finance Library DrivenByFVProviderFitnessEvaluator.cs Copyright (C) 2011 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using QuantProject.ADT; using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation; using QuantProject.Business.Strategies.EquityEvaluation; using QuantProject.Business.Strategies.ReturnsManagement; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider.InSampleChoosers.Genetic { /// <summary> /// Evaluates (in sample) the fitness for a given TestingPositions /// combining fundamental analysis with the sharpe ratio /// of a given series of returns /// </summary> [Serializable] public class DrivenByFVProviderFitnessEvaluator : IFitnessEvaluator { private IEquityEvaluator pastReturnsEvaluator; public string Description { get { string description = "FitnessEvaluatedWith_" + this.pastReturnsEvaluator.GetType().ToString(); return description; } } public DrivenByFVProviderFitnessEvaluator(IEquityEvaluator strategyEquityEvaluator) { this.pastReturnsEvaluator = strategyEquityEvaluator; } private float getFitnessValue_getFitnessValueActually( TestingPositions testingPositions, IReturnsManager returnsManager ) { float fitnessValue; //the returnsManager is based on OTCCTO End Of Day intervals - //always an even number, by definition! float[] returns = testingPositions.WeightedPositions.GetReturns(returnsManager); float fitnessForPastReturns = this.pastReturnsEvaluator.GetReturnsEvaluation(returns); fitnessValue = fitnessForPastReturns * fitnessGivenByFundamentals; if( double.IsNaN(fitnessValue) ) fitnessValue = 0; return fitnessValue; } public double GetFitnessValue(object meaning , IReturnsManager returnsManager ) { float fitnessValue = -0.5f; TestingPositions testingPositions = (TestingPositions)meaning; if(testingPositions.WeightedPositions != null) fitnessValue = this.getFitnessValue_getFitnessValueActually( testingPositions, returnsManager ); return fitnessValue; } } } |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:28:01
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC_CTO/OTC_CTO_EOD In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv26087/OTC_CTO_EOD Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC_CTO/OTC_CTO_EOD added to the repository |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:25:03
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC_CTO In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv24849/OTC_CTO Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC_CTO added to the repository |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:24:04
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/InSampleChoosers/Genetic In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv24565/Genetic Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/InSampleChoosers/Genetic added to the repository |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:23:52
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/InSampleChoosers In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv24504/InSampleChoosers Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/InSampleChoosers added to the repository |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:23:38
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv24422/DrivenBySharpeRatio Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio added to the repository |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:22:40
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv24099/DrivenByFairValueProvider Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider added to the repository |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:22:26
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv24026/DrivenByFundamentals Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals added to the repository |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:20:00
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/EquityEvaluation In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv23048/EquityEvaluation Modified Files: Variance.cs Log Message: Updated Variance class: now the evaluation by variance is computed through sharpe ratio Index: Variance.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/EquityEvaluation/Variance.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** Variance.cs 20 Nov 2010 18:57:08 -0000 1.1 --- Variance.cs 16 Jan 2011 19:19:52 -0000 1.2 *************** *** 47,53 **** // } public float GetReturnsEvaluation( float[] returns ) { ! return Convert.ToSingle( BasicFunctions.Variance( returns ) ); } } --- 47,57 ---- // } + public float GetReturnsEvaluation( float[] returns ) { ! float returnsEvaluationByVariance = ! 1.0f / Convert.ToSingle( BasicFunctions.Variance( returns ) ); ! ! return returnsEvaluationByVariance ; } } |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:17:56
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv22473 Modified Files: EndOfDayStrategyBackTester.cs Log Message: Fixed bug in EndOfDayStrategyBackTester, when timer has been stopped not in market close time Index: EndOfDayStrategyBackTester.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/EndOfDayStrategyBackTester.cs,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** EndOfDayStrategyBackTester.cs 28 Mar 2010 14:18:03 -0000 1.16 --- EndOfDayStrategyBackTester.cs 16 Jan 2011 19:17:48 -0000 1.17 *************** *** 440,444 **** else this.newDateTime( sender , dateTime ); ! if ( HistoricalEndOfDayTimer.IsMarketClose( dateTime ) ) this.notifyProgress( ( Timer )sender ); } --- 440,445 ---- else this.newDateTime( sender , dateTime ); ! if ( HistoricalEndOfDayTimer.IsMarketClose( dateTime ) && ! !((Timer)sender).IsDone ) this.notifyProgress( ( Timer )sender ); } |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:11:39
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/Optimizing/FitnessEvaluation In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv20499/Optimizing/FitnessEvaluation Modified Files: BuyAndHoldFitnessEvaluator.cs Log Message: Updated BuyAndHoldFitnessEvaluator Index: BuyAndHoldFitnessEvaluator.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/Optimizing/FitnessEvaluation/BuyAndHoldFitnessEvaluator.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** BuyAndHoldFitnessEvaluator.cs 20 Nov 2010 18:51:27 -0000 1.1 --- BuyAndHoldFitnessEvaluator.cs 16 Jan 2011 19:11:31 -0000 1.2 *************** *** 73,80 **** public double GetFitnessValue(object meaning , IReturnsManager returnsManager ) { ! float fitnessValue = -0.5f; TestingPositions testingPositions = (TestingPositions)meaning; ! if(testingPositions.WeightedPositions != null) ! fitnessValue = this.getFitnessValue_getFitnessValueActually( testingPositions, returnsManager ); return fitnessValue; } --- 73,86 ---- public double GetFitnessValue(object meaning , IReturnsManager returnsManager ) { ! float fitnessValue = -10.0f; TestingPositions testingPositions = (TestingPositions)meaning; ! try{ ! if(testingPositions.WeightedPositions != null) ! fitnessValue = this.getFitnessValue_getFitnessValueActually( testingPositions, returnsManager ); ! } ! catch(Exception ex){ ! string s = ex.ToString(); ! } ! return fitnessValue; } |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:09:30
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/InSample In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv19523/InSample Added Files: SelectTopEligiblesInSampleChooser.cs Log Message: Added SelectTopEligiblesInSampleChooser, for selecting just a given number of GeneticallyOptimizableTestingPositions from the given Eligibles --- NEW FILE: SelectTopEligiblesInSampleChooser.cs --- /* QuantProject - Quantitative Finance Library SelectTopEligiblesInSampleChooser.cs Copyright (C) 2011 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using QuantProject.ADT; using QuantProject.ADT.Messaging; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.ReturnsManagement; namespace QuantProject.Business.Strategies.InSample { /// <summary> /// Selects no TestingPosition(s) at all. To be used for log item's /// debugging /// </summary> [Serializable] public class SelectTopEligiblesInSampleChooser : IInSampleChooser { public event NewMessageEventHandler NewMessage; public event NewProgressEventHandler NewProgress; private int maxNumOfTestingPositionsToBeReturned; private int numOfTickersInEachTestingPosition; public string Description { get{ return "TopElgblsInSmplChsr"; } } public SelectTopEligiblesInSampleChooser(int numOfTickersInEachTestingPosition, int maxNumOfTestingPositionsToBeReturned) { this.numOfTickersInEachTestingPosition = numOfTickersInEachTestingPosition; this.maxNumOfTestingPositionsToBeReturned = maxNumOfTestingPositionsToBeReturned; } private GeneticallyOptimizableTestingPositions[] analyzeInSample_getTestingPositionsArray(EligibleTickers eligibleTickers) { if( eligibleTickers.Count < (this.maxNumOfTestingPositionsToBeReturned * this.numOfTickersInEachTestingPosition) ) throw new Exception("Not enough eligibles !"); GeneticallyOptimizableTestingPositions[] returnValue = new GeneticallyOptimizableTestingPositions[ this.maxNumOfTestingPositionsToBeReturned ]; int idxEligible = 0; string[] signedTickers = new string[numOfTickersInEachTestingPosition]; for ( int i = 0; i < returnValue.Length ; i++) { for ( int j = 0; idxEligible < eligibleTickers.Count && j < numOfTickersInEachTestingPosition; j++ ) signedTickers[j] = eligibleTickers.Tickers[idxEligible + j]; returnValue[i] = new GeneticallyOptimizableTestingPositions(new WeightedPositions(new SignedTickers(signedTickers))); idxEligible =+ numOfTickersInEachTestingPosition; } return returnValue; } public object AnalyzeInSample( EligibleTickers eligibleTickers , ReturnsManager returnsManager ) { if ( this.NewMessage != null ) this.NewMessage( this , new NewMessageEventArgs( "New" ) ); if ( this.NewProgress != null ) this.NewProgress( this , new NewProgressEventArgs( 1 , 1 ) ); GeneticallyOptimizableTestingPositions[] returnValue = this.analyzeInSample_getTestingPositionsArray(eligibleTickers); return returnValue; } } } |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:05:27
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/Optimizing/Decoding In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv18359/Optimizing/Decoding Added Files: BasicDecoderForGeneticallyOptimizableTestingPositions.cs Log Message: Added a basic decoder for GeneticallyOptimizableTestingPositions --- NEW FILE: BasicDecoderForGeneticallyOptimizableTestingPositions.cs --- /* QuantProject - Quantitative Finance Library BasicDecoderForGeneticallyOptimizableTestingPositions.cs Copyright (C) 2010 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using QuantProject.ADT.Optimizing.Decoding; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.ReturnsManagement; namespace QuantProject.Business.Strategies.Optimizing.Decoding { /// <summary> /// Decodes optimization candidates to a GeneticallyOptimizableTestingPositions /// </summary> [Serializable] public class BasicDecoderForGeneticallyOptimizableTestingPositions : BasicDecoderForTestingPositions { public BasicDecoderForGeneticallyOptimizableTestingPositions() : base() { } protected override TestingPositions getMeaningForUndecodable() { return new GeneticallyOptimizableTestingPositions(); } protected override TestingPositions decodeDecodable() { SignedTickers signedTickers = this.decodeSignedTickers(); GeneticallyOptimizableTestingPositions genOptPositions = new GeneticallyOptimizableTestingPositions( new WeightedPositions( this.getUnsignedWeights(signedTickers), signedTickers) ); return genOptPositions; } protected override string getDescription() { return "GntclOptmzTstPstn_Dcdr_NoWghts"; } } } |
|
From: Marco M. <mi...@us...> - 2011-01-16 19:04:05
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/OutOfSample In directory sfp-cvsdas-2.v30.ch3.sourceforge.com:/tmp/cvs-serv17597/OutOfSample Added Files: GeneticallyOptimizableTestingPositions.cs Log Message: Added GeneticallyOptimizableTestingPositions class --- NEW FILE: GeneticallyOptimizableTestingPositions.cs --- /* QuantProject - Quantitative Finance Library GeneticallyOptimizableTestingPositions.cs Copyright (C) 2010 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using QuantProject.Business.Strategies; namespace QuantProject.Business.Strategies.OutOfSample { /// <summary> /// This is the class representing a generic genetically /// optimizable TestingPositions, which can be used /// in several different strategies /// </summary> [Serializable] public class GeneticallyOptimizableTestingPositions : TestingPositions, IGeneticallyOptimizable { private int generation; //explicit interface implementation //the property can be used only by a interface //instance or through a cast to the interface int IGeneticallyOptimizable.Generation { get{return this.generation;} set{this.generation = value;} } public GeneticallyOptimizableTestingPositions Copy() { return new GeneticallyOptimizableTestingPositions( this.WeightedPositions, this.generation ); } // creates an empty TestingPositions: to be used to give a meaning with // GeneticallyOptimizableTestingPositions type to undecodables public GeneticallyOptimizableTestingPositions() : base() { } public GeneticallyOptimizableTestingPositions(WeightedPositions weightedPositions, int generation) : base(weightedPositions) { this.generation = generation; } public GeneticallyOptimizableTestingPositions(WeightedPositions weightedPositions) : base(weightedPositions) { this.generation = -1; } } } |