[Quantproject-developers] QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/Drive
Brought to you by:
glauco_1
|
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(); } } } |