quantproject-developers Mailing List for QuantProject (Page 16)
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...> - 2009-08-31 20:40:41
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/OTC_Intraday In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20871/OTC_Intraday Added Files: OTCIntradayLogItem.cs OTCIntradayMain.cs OTCIntradayStrategy.cs Log Message: Added script files for the implementation of the OTC strategy --- NEW FILE: OTCIntradayStrategy.cs --- /* QuantProject - Quantitative Finance Library OTCIntradayStrategy.cs Copyright (C) 2008 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.EfficientPortfolios; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; namespace QuantProject.Scripts.TickerSelectionTesting.OTC.OTC_Intraday { /// <summary> /// Implements the open to close strategy (buy a portfolio at open /// and sell it at close) next to opening and closing time, /// using intraday bars /// </summary> [Serializable] public class OTCIntradayStrategy : 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; 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_Intraday"; return description; } } public bool StopBacktestIfMaxRunningHoursHasBeenReached { get { return true; } } private void otcIntradayStrategy_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) { 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; } public OTCIntradayStrategy(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) { this.inSampleChooser = inSampleChooser; this.otcIntradayStrategy_commonInitialization(eligiblesSelector, minimumNumberOfEligiblesForValidOptimization, inSampleDays, benchmark, numDaysBetweenEachOptimization, numDaysBeforeCurrentDateForRetrievingInSampleData, historicalMarketValueProviderForInSample, historicalMarketValueProviderForOutOfSample, openingTimesForAvailableBars, nearToOpeningTimeFrom, nearToOpeningTimeTo, nearToClosingTimeFrom, nearToClosingTimeTo, stopLoss, takeProfit, portfolioType, geneticChooserForFitnessDistributionEstimator, numberOfMinimumStdDeviationForOpeningPositions, numberOfMaxStdDeviationForOpeningPositions, estimator, sampleLength); } public OTCIntradayStrategy(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) { this.chosenOTCPositions = chosenOTCPositions; this.otcIntradayStrategy_commonInitialization(eligiblesSelector, 5, 5, benchmark, numDaysBetweenEachOptimization, 0, historicalMarketValueProviderForInSample, historicalMarketValueProviderForOutOfSample, openingTimesForAvailableBars, nearToOpeningTimeFrom, nearToOpeningTimeTo, nearToClosingTimeFrom, nearToClosingTimeTo, stopLoss, takeProfit, portfolioType, geneticChooserForFitnessDistributionEstimator, numberOfMinimumStdDeviationForOpeningPositions, numberOfMaxStdDeviationForOpeningPositions, estimator, sampleLength); } 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 #region newDateTimeEventHandler_openPositions 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; } private void newDateTimeEventHandler_openPositions(Time currentDailyTime) { if( this.chosenOTCPositions != null && this.allTickersAreExchanged( this.now(), this.chosenOTCPositions[idxForBestPositionsCompatibleWithPortfolioType].WeightedPositions.SignedTickers.Tickers) && this.newDateTimeEventHandler_openPositions_bestFitnessIsSignificantlyHigh() ) // && // this.allTickersAreExchangedInTheLastFiveMinutelyBars( this.now(), this.chosenOTCPositions[idxForBestPositionsCompatibleWithPortfolioType].WeightedPositions.SignedTickers.Tickers ) // ) { try { AccountManager.OpenPositions( this.chosenOTCPositions[idxForBestPositionsCompatibleWithPortfolioType].WeightedPositions, this.account ); this.lastEntryTime = currentDailyTime; 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(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_openPositions(currentTime); if( this.account.Portfolio.Count > 0 && ( nearToClosingTime || timeToProfitOrToStopLoss ) ) this.newDateTimeEventHandler_closePositions(currentTime); if( currentTime == getLastEventTimeWithCachedBars() ) //it's time for new optimization, if the case this.newDateTimeEventHandler_updateTestingPositions( dateTime ); } #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 ); } } } --- NEW FILE: OTCIntradayMain.cs --- /* QuantProject - Quantitative Finance Library OTCIntradayMain.cs Copyright (C) 2009 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.InSampleChoosers.Genetic; using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers.BruteForce; namespace QuantProject.Scripts.TickerSelectionTesting.OTC.OTC_Intraday { /// <summary> /// Entry point for the OTCIntradayMain. If any strategy /// parameter had to be changed, this is the place where it should /// be done /// </summary> public class OTCIntradayMain : 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 int stepInMinutesForTimer; private Timer timerForBackTester; private int intervalFrameInSeconds; private GenomeManagerType genomeManagerType; #region main public OTCIntradayMain() { this.numberOfPortfolioPositions = 2; // 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( 2000 , 1 , 1 ); this.lastDateTime = new DateTime( 2009 , 8, 27 ); //this.stepInMinutesForTimer = 1; this.intervalFrameInSeconds = 60; // 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("09:31:00")); this.dailyTimes.Add(new Time("09:32:00")); this.dailyTimes.Add(new Time("09:33:00")); this.dailyTimes.Add(new Time("09:34:00")); this.dailyTimes.Add(new Time("09:35:00")); this.dailyTimes.Add(new Time("15:55:00")); this.dailyTimes.Add(new Time("15:56:00")); this.dailyTimes.Add(new Time("15:57:00")); this.dailyTimes.Add(new Time("15:58:00")); this.dailyTimes.Add(new Time("15:59: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.10; double maxPrice = 2000; // 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 = 20; // parameters for the genetic optimizer // double crossoverRate = 0.85; // double mutationRate = 0.02; // double elitismRate = 0.001; // int populationSizeForGeneticOptimizer = 5000; // int generationNumberForGeneticOptimizer = 0; // 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); // IInSampleChooser inSampleChooser = // new OTCEndOfDayGeneticChooser(this.numberOfPortfolioPositions, numberOfBestTestingPositionsToBeReturned, // benchmark, decoderForTestingPositions , // 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 = 45; int numDaysBetweenEachOptimization = 1; int numDaysBeforeCurrentDateForRetrievingInSampleData = 0; int minNumOfEligiblesForValidOptimization = 10; int sampleLengthForFitnessDistributionEstimation = 100; double minimumNumberOfStdDevForSignificantFitness = 0.0; double maximumNumberOfStdDevForSignificantFitness = 8.0; 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; IStrategyForBacktester strategyForBacktester // = new PVO_OTCStrategyLessCorrelated(eligiblesSelector ,inSampleChooser , // inSampleDays , benchmark , numDaysBetweenEachOptimization , // oversoldThreshold , overboughtThreshold , historicalQuoteProvider); // = new OTCIntradayStrategy(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); ((OTCIntradayStrategy)strategyForBacktester).FindPositionsForToday( new DateTime(2009,8,31), new DateTime(2009,8,28) ); return strategyForBacktester; } #endregion strategy #region backTester protected override EndOfDayStrategyBackTester getEndOfDayStrategyBackTester() { string backTestId = "OTCIntradayStrategy"; 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 #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 "OTCIntradayStrategy"; } 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\OTC_Intraday\OTCIntradayMain.cs"; if( File.Exists(fullPathFileNameForMainAtHome) ) returnValue = fullPathFileNameForMainAtHome; else returnValue = @"C:\Utente\MarcoVarie\Vari\qP\QuantProject\b7_Scripts\TickerSelectionTesting\OTC\OTC_Intraday\OTCIntradayMain.cs"; return returnValue; } } } --- NEW FILE: OTCIntradayLogItem.cs --- /* QuantProject - Quantitative Finance Library OTCIntradayLogItem.cs Copyright (C) 2009 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.OTC.OTC_Intraday { /// <summary> /// LogItem for the Open To Close strategy /// It is "intraday" because the run method /// uses intraday bars /// </summary> [Serializable] public class OTCIntradayLogItem : LogItem { protected DummyTesterForTestingPositions[] dummyTestersForBestTestingPositionsInSample; protected TestingPositions[] bestOTCPositionsInSample; protected int numberOfEligibleTickers; protected double fitness; protected int generation; protected string tickers; protected int numberOfInSampleDays; public TestingPositions[] BestOTCPositionsInSample { get { if ( this.bestOTCPositionsInSample == 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.bestOTCPositionsInSample; } set { this.bestOTCPositionsInSample = 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 OTCIntradayLogItem(DateTime dateTime, int numberOfInSampleDays) : base( dateTime ) { this.numberOfInSampleDays = numberOfInSampleDays; this.numberOfEligibleTickers = int.MinValue; this.fitness = double.MinValue; } 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) ); 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); 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 ); } private void showTestingPositionsClickEventHandler_setDummyTesters_setTester( int currentIndex , TestingPositions testingPositions , DateTime simulatedCreationDateTime ) { this.dummyTestersForBestTestingPositionsInSample[ currentIndex ] = new DummyTesterForTestingPositions( testingPositions , this.numberOfInSampleDays , simulatedCreationDateTime ); } private void showTestingPositionsClickEventHandler_setDummyTesters() { this.dummyTestersForBestTestingPositionsInSample = new DummyTesterForTestingPositions[this.BestOTCPositionsInSample.Length]; for ( int i = 0 ; i < BestOTCPositionsInSample.Length; i++ ) this.showTestingPositionsClickEventHandler_setDummyTesters_setTester( i , BestOTCPositionsInSample[ 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...> - 2009-08-31 20:40:40
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/InSampleChoosers/Genetic In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20871/InSampleChoosers/Genetic Added Files: GenomeManagerForOTC_EndOfDay.cs OTCCTOFitnessEvaluator.cs OTCEndOfDayGeneticChooser.cs OTCFitnessEvaluator.cs Log Message: Added script files for the implementation of the OTC strategy --- NEW FILE: OTCCTOFitnessEvaluator.cs --- /* QuantProject - Quantitative Finance Library OTCCTOFitnessEvaluator.cs Copyright (C) 2009 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.OTC.InSampleChoosers.Genetic { /// <summary> /// Evaluates (in sample) the fitness for a given TestingPositions /// with respect to the "open to close" (OTC) strategy /// It evaluates the strategy: /// buy at open, sell at close; sell at close, buy at open /// </summary> [Serializable] public class OTCCTOFitnessEvaluator : IFitnessEvaluator { private IEquityEvaluator strategyEquityEvaluator; public string Description { get { string description = "OTCCTOFitnessEvaluatedWith_" + this.strategyEquityEvaluator.GetType().ToString(); return description; } } public OTCCTOFitnessEvaluator(IEquityEvaluator strategyEquityEvaluator) { this.strategyEquityEvaluator = strategyEquityEvaluator; } private float getFitnessValue_getFitnessValueActually( TestingPositions testingPositions, ReturnsManager returnsManager ) { float fitnessValue; float[] strategyReturns = testingPositions.WeightedPositions.GetReturns(returnsManager); for(int i = 0; i < strategyReturns.Length; i++) if(i%2 != 0) //strategyReturns[i] is a CloseToOpen return: //the OTCCTO strategy implies to reverse positions at night strategyReturns[i] = - strategyReturns[i]; fitnessValue = this.strategyEquityEvaluator.GetReturnsEvaluation(strategyReturns); return fitnessValue; } public double GetFitnessValue(object meaning , ReturnsManager returnsManager ) { float fitnessValue = -0.5f; TestingPositions testingPositions = (TestingPositions)meaning; if(testingPositions.WeightedPositions != null) fitnessValue = this.getFitnessValue_getFitnessValueActually( testingPositions, returnsManager ); return fitnessValue; } } } --- NEW FILE: OTCEndOfDayGeneticChooser.cs --- /* QuantProject - Quantitative Finance Library OTCEndOfDayGeneticChooser.cs Copyright (C) 2009 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.OTC.InSampleChoosers.Genetic { /// <summary> /// In sample genetic analyzer for the Open to Close strategy /// </summary> [Serializable] public class OTCEndOfDayGeneticChooser : GeneticChooser { protected GenomeManagerType genomeManagerType; public OTCEndOfDayGeneticChooser( 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 GenomeManagerForOTC_EndOfDay(eligibleTickers, this.numberOfPortfolioPositions, this.decoderForTestingPositions, this.fitnessEvaluator, this.genomeManagerType , returnsManager, this.seedForRandomGenerator); } } } --- NEW FILE: GenomeManagerForOTC_EndOfDay.cs --- /* QuantProject - Quantitative Finance Library GenomeManagerForOTC_EndOfDay.cs Copyright (C) 2009 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.OTC.InSampleChoosers.Genetic { /// <summary> /// Implements what needed to use the Genetic Optimizer /// for finding the portfolio that best suites /// the Open To Close strategy using EOD data /// </summary> [Serializable] public class GenomeManagerForOTC_EndOfDay : BasicGenomeManager { public GenomeManagerForOTC_EndOfDay(EligibleTickers eligibleTickers, int numberOfTickersInPortfolio, IDecoderForTestingPositions decoderForTestingPositions, IFitnessEvaluator fitnessEvaluator, GenomeManagerType genomeManagerType, ReturnsManager returnsManager, int seedForRandomGenerator) : base(eligibleTickers, numberOfTickersInPortfolio, decoderForTestingPositions, fitnessEvaluator, genomeManagerType, returnsManager, seedForRandomGenerator) { } // private bool getFitnessValue_isMixed_areSignsAllPositiveOrAllNegative(int[] signs) // { // bool returnValue = false; // int n = signs.Length; // int sumOfSigns = 0; // for(int i = 0; i < n ; i++) // sumOfSigns += signs[i]; // int absoluteOfSumOfSigns = Math.Abs(sumOfSigns); // if( absoluteOfSumOfSigns != n && // absoluteOfSumOfSigns != - n ) // returnValue = true; // return returnValue; // } // // private bool getFitnessValue_isMixed(Genome genome) // { // int[] signs = genome.Genes(); // int n = signs.Length; // for(int i = 0; i < n ; i++) // { // if(signs[i] >= 0) // signs[i] = 1; // else // signs[i] = -1; // } // return getFitnessValue_isMixed_areSignsAllPositiveOrAllNegative(signs); // } public override double GetFitnessValue(Genome genome) { double fitnessValue = double.MinValue; if( (this.genomeSize > 1 && this.genomeManagerType == GenomeManagerType.OnlyMixed && ((OTCPositions)genome.Meaning).BothLongAndShortPositions ) || this.genomeManagerType != GenomeManagerType.OnlyMixed ) //if the genomeManager has to evaluate only mixed portfolio, // with at least two tickers and //the current genome is not made of tickers with the same sign OR //the genomeManager can evaluate mixed or not mixed portfolios 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: OTCFitnessEvaluator.cs --- /* QuantProject - Quantitative Finance Library OTCFitnessEvaluator.cs Copyright (C) 2009 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.OTC.InSampleChoosers.Genetic { /// <summary> /// Evaluates (in sample) the fitness for a given TestingPositions /// with respect to the "open to close" (OTC) strategy /// </summary> [Serializable] public class OTCFitnessEvaluator : IFitnessEvaluator { private IEquityEvaluator strategyEquityEvaluator; public string Description { get { string description = "FitnessEvaluatedWith_" + this.strategyEquityEvaluator.GetType().ToString(); return description; } } public OTCFitnessEvaluator(IEquityEvaluator strategyEquityEvaluator) { this.strategyEquityEvaluator = strategyEquityEvaluator; } private float getFitnessValue_getFitnessValueActually( TestingPositions testingPositions, ReturnsManager 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[] strategyReturns = new float[ returns.Length / 2 ]; for( int i = 0; i < returns.Length; i++ ) if( i%2 == 0 ) //returns[i] is a OpenToClose return strategyReturns[ i / 2 ] = returns[ i ]; fitnessValue = this.strategyEquityEvaluator.GetReturnsEvaluation(strategyReturns); if( double.IsNaN(fitnessValue) ) fitnessValue = 0; return fitnessValue; } public double GetFitnessValue(object meaning , ReturnsManager 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...> - 2009-08-31 20:40:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/Decoding In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20871/Decoding Added Files: BasicDecoderForOTCPositions.cs Log Message: Added script files for the implementation of the OTC strategy --- NEW FILE: BasicDecoderForOTCPositions.cs --- /* QuantProject - Quantitative Finance Library BasicDecoderForOTCPositions.cs Copyright (C) 2009 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.Collections; using QuantProject.ADT.Optimizing.Decoding; using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.Optimizing.Decoding; namespace QuantProject.Scripts.TickerSelectionTesting.OTC { /// <summary> /// Decodes optimization candidates to a /// OTCPositions /// </summary> [Serializable] public class BasicDecoderForOTCPositions : BasicDecoderForTestingPositions { public BasicDecoderForOTCPositions() : base() { } protected override TestingPositions getMeaningForUndecodable() { return new OTCPositions(); } protected override TestingPositions decodeDecodable() { SignedTickers signedTickers = this.decodeSignedTickers(); OTCPositions otcPositions = new OTCPositions( new WeightedPositions( this.getUnsignedWeights(signedTickers), signedTickers) ); return otcPositions; } protected override string getDescription() { return "OTC_Dcdr_NoWghts"; } } } |
|
From: Marco M. <mi...@us...> - 2009-08-31 20:37:15
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/OTC_Intraday In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20426/OTC_Intraday Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/OTC_Intraday added to the repository |
|
From: Marco M. <mi...@us...> - 2009-08-31 20:37:04
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/InSampleChoosers/Genetic In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20408/Genetic Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/InSampleChoosers/Genetic added to the repository |
|
From: Marco M. <mi...@us...> - 2009-08-31 20:36:54
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/InSampleChoosers/BruteForce In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20398/BruteForce Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/InSampleChoosers/BruteForce added to the repository |
|
From: Marco M. <mi...@us...> - 2009-08-31 20:36:48
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/InSampleChoosers In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20358/InSampleChoosers Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/InSampleChoosers added to the repository |
|
From: Marco M. <mi...@us...> - 2009-08-31 20:36:35
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/Decoding In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20290/Decoding Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/Decoding added to the repository |
|
From: Marco M. <mi...@us...> - 2009-08-31 20:36:24
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20266/OTC Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC added to the repository |
|
From: Marco M. <mi...@us...> - 2009-08-30 22:08:26
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/EntryConditions In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv22818 Added Files: AlwaysTrueEntryCondition.cs IEntryCondition.cs InefficiencyMovingBackEntryCondition.cs PreviousPeriodsWereEfficientEntryCondition.cs PriceRatioEntryCondition.cs Log Message: Added IEntryCondition interface and some classes implementing it, for the PVO strategy --- NEW FILE: IEntryCondition.cs --- /* QuantProject - Quantitative Finance Library IEntryCondition.cs Copyright (C) 2009 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.OutOfSample; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.EntryConditions { /// <summary> /// decides if current positions satisfy the given condition /// </summary> public interface IEntryCondition { bool IsConditionSatisfiedByGivenPVOPositions( DateTime dateTime , PVOPositions pvoPositions ); } } --- NEW FILE: InefficiencyMovingBackEntryCondition.cs --- /* QuantProject - Quantitative Finance Library InefficiencyMovingBackEntryCondition.cs Copyright (C) 2009 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.DataProviders; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.TickersRelationships; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.EntryConditions { /// <summary> /// Description of InefficiencyMovingBackEntryCondition. /// </summary> [Serializable] public class InefficiencyMovingBackEntryCondition : IEntryCondition { private double coefficientForThresholdLevelComputationForMovingBackSignal; private HistoricalMarketValueProvider marketValueProvider; private Benchmark benchmark; public InefficiencyMovingBackEntryCondition(double coefficientForThresholdLevelComputationForMovingBackSignal, HistoricalMarketValueProvider marketValueProvider, Benchmark benchmark) { this.coefficientForThresholdLevelComputationForMovingBackSignal = coefficientForThresholdLevelComputationForMovingBackSignal; this.marketValueProvider = marketValueProvider; this.benchmark = benchmark; } public bool IsConditionSatisfiedByGivenPVOPositions(DateTime dateTime , PVOPositions pvoPositionsForOutOfSample ) { bool returnValue = false; DateTime beginOfOscillatingPeriod = pvoPositionsForOutOfSample.LastInefficiencyDateTime; DateTime endOfOscillatingPeriod = dateTime; PVOPositionsStatus currentStatusForCurrentPositions = PVOPositionsStatus.InTheMiddle; if( pvoPositionsForOutOfSample != null ) try{ currentStatusForCurrentPositions = pvoPositionsForOutOfSample.GetStatus( beginOfOscillatingPeriod, endOfOscillatingPeriod, this.benchmark.Ticker, this.marketValueProvider, pvoPositionsForOutOfSample.OversoldThreshold * coefficientForThresholdLevelComputationForMovingBackSignal, pvoPositionsForOutOfSample.OversoldThreshold, pvoPositionsForOutOfSample.OverboughtThreshold * coefficientForThresholdLevelComputationForMovingBackSignal, pvoPositionsForOutOfSample.OverboughtThreshold ); }catch{} returnValue = ( (currentStatusForCurrentPositions == PVOPositionsStatus.Overbought && pvoPositionsForOutOfSample.StatusAtLastInefficiencyTime == PVOPositionsStatus.Oversold) || (currentStatusForCurrentPositions == PVOPositionsStatus.Oversold && pvoPositionsForOutOfSample.StatusAtLastInefficiencyTime == PVOPositionsStatus.Overbought) ); return returnValue; } } } --- NEW FILE: PreviousPeriodsWereEfficientEntryCondition.cs --- /* QuantProject - Quantitative Finance Library PreviousPeriodsWereEfficientEntryCondition.cs Copyright (C) 2009 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.DataProviders; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies; //using QuantProject.Business.Strategies.TickersRelationships; using QuantProject.Business.Timing; using QuantProject.Business.Timing.TimingManagement; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.EntryConditions { /// <summary> /// Description of PreviousPeriodsWereEfficientEntryCondition. /// </summary> [Serializable] public class PreviousPeriodsWereEfficientEntryCondition : IEntryCondition { private int numberOfPreviousPeriods; private HistoricalMarketValueProvider marketValueProvider; private double numberOfIntervalsForEachPeriod; private MarketIntervalsManager marketIntervalsManager; private string tickerForBenchmark; public PreviousPeriodsWereEfficientEntryCondition(int numberOfPreviousPeriods, HistoricalMarketValueProvider marketValueProvider, double numberOfIntervalsForEachPeriod, MarketIntervalsManager marketIntervalsManager) { this.numberOfPreviousPeriods = numberOfPreviousPeriods; this.marketValueProvider = marketValueProvider; this.numberOfIntervalsForEachPeriod = numberOfIntervalsForEachPeriod; this.marketIntervalsManager = marketIntervalsManager; this.tickerForBenchmark = marketIntervalsManager.Benchmark.Ticker; } // public PreviousPeriodsWereEfficientEntryCondition(int numberOfPreviousPeriods, // HistoricalMarketValueProvider marketValueProvider, // double numberOfIntervalsForEachPeriod, // Benchmark benchmark) // { // this.numberOfPreviousPeriods = numberOfPreviousPeriods; // this.marketValueProvider = marketValueProvider; // this.numberOfIntervalsForEachPeriod = numberOfIntervalsForEachPeriod; // this.tickerForBenchmark = benchmark.Ticker; // this.marketIntervalsManager = new MarketDaysManager(benchmark, // } private PVOPositionsStatus isConditionSatisfiedByGivenPVOPositions_getStatus( DateTime beginOfOscillatingPeriod, DateTime endOfOscillatingPeriod, PVOPositions pvoPositionsForOutOfSample) { PVOPositionsStatus returnValue = PVOPositionsStatus.NotComputable; if(pvoPositionsForOutOfSample != null) try{ returnValue = pvoPositionsForOutOfSample.GetStatus(beginOfOscillatingPeriod, endOfOscillatingPeriod, this.tickerForBenchmark, this.marketValueProvider); }catch{} return returnValue; } public bool IsConditionSatisfiedByGivenPVOPositions(DateTime dateTime , PVOPositions pvoPositionsForOutOfSample ) { bool returnValue = true; PVOPositionsStatus statusForCurrentPreviousPeriod; for( int i = 1; i <= this.numberOfPreviousPeriods; i++ ) { DateTime beginOfOscillatingPeriod = this.marketIntervalsManager.AddMarketIntervals(dateTime, -(i+1)*(int)this.numberOfIntervalsForEachPeriod); DateTime endOfOscillatingPeriod = this.marketIntervalsManager.AddMarketIntervals (dateTime, -i*(int)this.numberOfIntervalsForEachPeriod); statusForCurrentPreviousPeriod = this.isConditionSatisfiedByGivenPVOPositions_getStatus( beginOfOscillatingPeriod, endOfOscillatingPeriod, pvoPositionsForOutOfSample ); if( statusForCurrentPreviousPeriod != PVOPositionsStatus.InTheMiddle ) { returnValue = false; i = this.numberOfPreviousPeriods; } } return returnValue; } } } --- NEW FILE: PriceRatioEntryCondition.cs --- /* QuantProject - Quantitative Finance Library PriceRatioEntryCondition.cs Copyright (C) 2009 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.DataProviders; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.TickersRelationships; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.EntryConditions { /// <summary> /// Description of PriceRatioEntryCondition. /// </summary> [Serializable] public class PriceRatioEntryCondition : IEntryCondition { private int lengthInDaysForAveragePriceRatioCalculation; private HistoricalMarketValueProvider marketValueProvider; private double numOfStdDevForSignificantPriceMovements; public PriceRatioEntryCondition(int lengthInDaysForAveragePriceRatioCalculation, HistoricalMarketValueProvider marketValueProvider, double numOfStdDevForSignificantPriceMovements) { this.lengthInDaysForAveragePriceRatioCalculation = lengthInDaysForAveragePriceRatioCalculation; this.marketValueProvider = marketValueProvider; this.numOfStdDevForSignificantPriceMovements = numOfStdDevForSignificantPriceMovements; } //da rifare usando marketIntervalsManager public bool IsConditionSatisfiedByGivenPVOPositions(DateTime dateTime , PVOPositions pvoPositionsForOutOfSample ) { bool returnValue = false; try{ if( pvoPositionsForOutOfSample.WeightedPositions.Count != 2 ) throw new Exception("Price ratio condition can be verified only by pairs"); SignedTickers signedTickers = pvoPositionsForOutOfSample.WeightedPositions.SignedTickers; double priceRatioAverage = PriceRatioProvider.GetPriceRatioAverage(signedTickers[0].Ticker, signedTickers[1].Ticker, dateTime.AddDays(-this.lengthInDaysForAveragePriceRatioCalculation), dateTime.AddDays(-1) ); double priceRatioStdDev = PriceRatioProvider.GetPriceRatioStandardDeviation(signedTickers[0].Ticker, signedTickers[1].Ticker, dateTime.AddDays(-this.lengthInDaysForAveragePriceRatioCalculation), dateTime.AddDays(-1) ); double currentPriceRatio = this.marketValueProvider.GetMarketValue(signedTickers[0].Ticker, dateTime ) / this.marketValueProvider.GetMarketValue(signedTickers[1].Ticker, dateTime ); if(currentPriceRatio > priceRatioAverage + this.numOfStdDevForSignificantPriceMovements * priceRatioStdDev || currentPriceRatio < priceRatioAverage - this.numOfStdDevForSignificantPriceMovements * priceRatioStdDev ) returnValue = true; } catch(Exception ex){ string s = ex.ToString(); } return returnValue; } } } --- NEW FILE: AlwaysTrueEntryCondition.cs --- /* QuantProject - Quantitative Finance Library AlwaysTrueEntryCondition.cs Copyright (C) 2009 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.DataProviders; using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.TickersRelationships; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.EntryConditions { /// <summary> /// Description of AlwaysTrueEntryCondition. /// </summary> [Serializable] public class AlwaysTrueEntryCondition : IEntryCondition { public AlwaysTrueEntryCondition() { } public bool IsConditionSatisfiedByGivenPVOPositions(DateTime dateTime , PVOPositions pvoPositionsForOutOfSample ) { return true; } } } |
|
From: Marco M. <mi...@us...> - 2009-08-30 22:06:59
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/EntryConditions In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv22706/EntryConditions Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/EntryConditions added to the repository |
|
From: Marco M. <mi...@us...> - 2009-08-30 22:06:51
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/InSampleChoosers/PriceRatioChooser In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv22696/PriceRatioChooser Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/InSampleChoosers/PriceRatioChooser added to the repository |
|
From: Marco M. <mi...@us...> - 2009-08-30 22:06:06
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/General/Strategies/Optimizing/FitnessEvaluation In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv22538 Added Files: DummyRandomFitnessEvaluator.cs Log Message: Added DummyRandomFitnessEvaluator, for testing purposes. It just returns a random fitness value. --- NEW FILE: DummyRandomFitnessEvaluator.cs --- /* QuantProject - Quantitative Finance Library DummyRandomFitnessEvaluator.cs Copyright (C) 2009 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.Optimizing.FitnessEvaluation; using QuantProject.Business.Strategies.ReturnsManagement; namespace QuantProject.Scripts.General.Strategies.Optimizing.FitnessEvaluation { /// <summary> /// Dummy fitness Evaluator for testing purposes. /// It computes a random fitness value (a number between 0 and 1) /// </summary> [Serializable] public class DummyRandomFitnessEvaluator : IFitnessEvaluator { public string Description { get { string description = "DummyRandomFitness"; return description; } } public DummyRandomFitnessEvaluator() { } public double GetFitnessValue(object meaning , ReturnsManager returnsManager ) { Random rnd = new Random(59); return rnd.NextDouble(); } } } |
|
From: Marco M. <mi...@us...> - 2009-08-30 22:04:43
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/General/Strategies/Optimizing/FitnessEvaluation In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv22452/FitnessEvaluation Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/General/Strategies/Optimizing/FitnessEvaluation added to the repository |
|
From: Marco M. <mi...@us...> - 2009-08-30 22:04:33
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/General/Strategies/Optimizing In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv22424/Optimizing Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/General/Strategies/Optimizing added to the repository |
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/InSample/InSampleFitnessDistributionEstimation In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv22168 Added Files: BasicInSampleFitnessDistributionEstimator.cs IInSampleFitnessDistributionEstimator.cs Log Message: Added IInSampleFitnessDistributionEstimator interface. --- NEW FILE: IInSampleFitnessDistributionEstimator.cs --- /* QuantProject - Quantitative Finance Library IInSampleFitnessDistributionEstimator.cs Copyright (C) 2009 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.Eligibles; using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Strategies.InSample; namespace QuantProject.Business.Strategies.InSample.InSampleFitnessDistributionEstimation { /// <summary> /// Interface for classes performing /// estimations of the distribution's features (mainly, /// average and variance) for the fitness of the population /// regarded by an optimization process. /// The classes should be used for Hypothesis tests /// on given fitnesses /// </summary> public interface IInSampleFitnessDistributionEstimator { /// <summary>Returns an estimation of the average fitness /// for a given population of fitnesses /// </summary> /// <param name="geneticChooser">Genetic chooser that targets the population /// through the way fitness has to be computed</param> /// <param name="eligibleTickers">eligible tickers used for the in sample optimization</param> /// <param name="returnsManager">manager to efficiently handle in sample optimization</param> /// <param name="sampleLength">number of samples that have to be drawn from /// the population for the estimation</param> /// <returns>Estimation of the average fitness of the population</returns> double GetAverage( GeneticChooser geneticChooser, EligibleTickers eligibleTickers , ReturnsManager returnsManager, int sampleLength ); double GetVariance( GeneticChooser geneticChooser, EligibleTickers eligibleTickers , ReturnsManager returnsManager, int sampleLength ); } } --- NEW FILE: BasicInSampleFitnessDistributionEstimator.cs --- /* QuantProject - Quantitative Finance Library BasicInSampleFitnessDistributionEstimator.cs Copyright (C) 2009 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using QuantProject.ADT; using QuantProject.ADT.Statistics; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Business.Strategies.InSample; //using QuantProject.Business.DataProviders; //using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.ReturnsManagement; namespace QuantProject.Business.Strategies.InSample.InSampleFitnessDistributionEstimation { /// <summary> /// Basic IInSampleFitnessDistributionEstimator for estimation /// of average and variance of the fitness for the population from /// which best fitnesses are retrieved through an optimization process /// </summary> [Serializable] public class BasicInSampleFitnessDistributionEstimator : IInSampleFitnessDistributionEstimator { protected IGenomeManager genomeManager; protected GeneticOptimizer geneticOptimizer; protected ArrayList sampleFitnesses; protected EligibleTickers currentEligibleTickers; protected ReturnsManager currentReturnsManager; protected int sampleLength; /// <summary> /// Basic IInSampleFitnessDistributionEstimator for estimation /// of average and variance of the fitness for the population from /// which best fitnesses are retrieved through an optimization process /// </summary> public BasicInSampleFitnessDistributionEstimator() { } private void newGenerationEventHandler( object sender , NewGenerationEventArgs e ) { ; } private void runGeneticOptimizerAndSetSampleFitnesses_setSampleFitnesses() { this.sampleFitnesses = new ArrayList(); for(int i = 0; i < this.geneticOptimizer.CurrentGeneration.Count; i++) if ( this.geneticOptimizer.CurrentGeneration[i] is Genome && !double.IsInfinity( ((Genome)this.geneticOptimizer.CurrentGeneration[i]).Fitness ) && !double.IsNaN( ((Genome)this.geneticOptimizer.CurrentGeneration[i]).Fitness ) && double.MinValue != ((Genome)this.geneticOptimizer.CurrentGeneration[i]).Fitness ) this.sampleFitnesses.Add( ((Genome)this.geneticOptimizer.CurrentGeneration[i]).Fitness); } private void runGeneticOptimizerAndSetSampleFitnesses(GeneticChooser geneticChooser , EligibleTickers eligibleTickers , ReturnsManager returnsManager , int sampleLength) { if( this.genomeManager == null || !ReferenceEquals(this.currentEligibleTickers, eligibleTickers) || !ReferenceEquals(this.currentReturnsManager, returnsManager) || this.sampleLength != sampleLength) { this.sampleLength = sampleLength; this.currentEligibleTickers = eligibleTickers; this.currentReturnsManager = returnsManager; this.genomeManager = geneticChooser.GetGenomeManager(eligibleTickers, returnsManager); this.geneticOptimizer = new GeneticOptimizer(this.genomeManager, sampleLength, 0, ConstantsProvider.SeedForRandomGenerator); this.geneticOptimizer.NewGeneration += new NewGenerationEventHandler( this.newGenerationEventHandler ); this.geneticOptimizer.Run( false ); this.runGeneticOptimizerAndSetSampleFitnesses_setSampleFitnesses(); } } /// <summary> /// Returns an estimation of the average fitness /// for the population of fitnesses targeted /// by the given geneticChooser (through IGenomeManager) /// </summary> public double GetAverage(GeneticChooser geneticChooser, EligibleTickers eligibleTickers , ReturnsManager returnsManager, int sampleLength) { this.runGeneticOptimizerAndSetSampleFitnesses(geneticChooser , eligibleTickers , returnsManager , sampleLength); double average = BasicFunctions.GetSimpleAverage(this.sampleFitnesses); return average; } /// <summary> /// Returns an estimation of the variance /// for the population of fitnesses targeted /// by the given geneticChooser (through IGenomeManager) /// </summary> public double GetVariance(GeneticChooser geneticChooser, EligibleTickers eligibleTickers , ReturnsManager returnsManager, int sampleLength) { this.runGeneticOptimizerAndSetSampleFitnesses(geneticChooser , eligibleTickers , returnsManager , sampleLength); double variance = BasicFunctions.GetVariance(this.sampleFitnesses); return variance; } } } |
|
From: Marco M. <mi...@us...> - 2009-08-30 21:49:47
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/FixedLengthTwoPhases/InSampleChoosers/Genetic In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv19476/b7_Scripts/WalkForwardTesting/FixedLengthTwoPhases/InSampleChoosers/Genetic Modified Files: FixedLengthTwoPhasesGeneticChooser.cs Log Message: getGenomeManager abstract method is now public (it has been renamed to GetGenomeManager) Index: FixedLengthTwoPhasesGeneticChooser.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/FixedLengthTwoPhases/InSampleChoosers/Genetic/FixedLengthTwoPhasesGeneticChooser.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** FixedLengthTwoPhasesGeneticChooser.cs 29 Sep 2008 21:18:43 -0000 1.8 --- FixedLengthTwoPhasesGeneticChooser.cs 30 Aug 2009 21:33:46 -0000 1.9 *************** *** 76,80 **** ! protected override IGenomeManager getGenomeManager( EligibleTickers eligibleTickers , ReturnsManager returnsManager ) --- 76,80 ---- ! public override IGenomeManager GetGenomeManager( EligibleTickers eligibleTickers , ReturnsManager returnsManager ) |
|
From: Marco M. <mi...@us...> - 2009-08-30 21:45:21
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/InSample/InSampleFitnessDistributionEstimation In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20619/InSampleFitnessDistributionEstimation Log Message: Directory /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/InSample/InSampleFitnessDistributionEstimation added to the repository |
|
From: Marco M. <mi...@us...> - 2009-08-30 21:43:45
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20419/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator Modified Files: PVOLogItem.cs PVOMain.cs PVOPositions.cs PVOStrategy.cs PVOStrategyIntraday.cs PVOStrategyIntradayMain.cs Log Message: PVO script files have been updated Index: PVOStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/PVOStrategy.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** PVOStrategy.cs 29 Sep 2008 21:18:34 -0000 1.7 --- PVOStrategy.cs 30 Aug 2009 21:43:34 -0000 1.8 *************** *** 23,26 **** --- 23,27 ---- using System.Data; using System.Collections; + using System.Collections.Generic; using QuantProject.ADT; *************** *** 46,49 **** --- 47,51 ---- using QuantProject.Data.DataTables; using QuantProject.ADT.Optimizing.Genetic; + using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.EntryConditions; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; *************** *** 81,86 **** protected PVOPositions pvoPositionsForOutOfSample; protected DateTime lastCloseDate; - protected bool portfolioHasBeenOverbought; - protected bool portfolioHasBeenOversold; protected Account account; public Account Account --- 83,86 ---- *************** *** 91,94 **** --- 91,97 ---- protected bool stopLossConditionReached; protected bool takeProfitConditionReached; + protected bool maxNumberOfDaysOnTheMarketReached; + protected int maxNumberOfDaysOnTheMarket; + protected int daysOnTheMarket; protected double currentAccountValue; protected double previousAccountValue; *************** *** 97,100 **** --- 100,108 ---- protected double oversoldThresholdMAX; protected double overboughtThresholdMAX; + protected double numOfStdDevForSignificantPriceMovements; + protected double leverage; + protected bool openOnlyLongPositions; + protected List<IEntryCondition> entryConditions; + protected bool allEntryConditionsHaveToBeSatisfied; private string description_GetDescriptionForChooser() *************** *** 138,144 **** double oversoldThresholdMAX, double overboughtThresholdMAX, HistoricalMarketValueProvider historicalQuoteProvider, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) { this.eligiblesSelector = eligiblesSelector; --- 146,158 ---- double oversoldThresholdMAX, double overboughtThresholdMAX, + double numOfStdDevForSignificantPriceMovements, + double leverage, + bool openOnlyLongPositions, + int maxNumberOfDaysOnTheMarket, HistoricalMarketValueProvider historicalQuoteProvider, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain, ! List<IEntryCondition> entryConditions, ! bool allEntryConditionsHaveToBeSatisfied) { this.eligiblesSelector = eligiblesSelector; *************** *** 155,163 **** this.oversoldThresholdMAX = oversoldThresholdMAX; this.overboughtThresholdMAX = overboughtThresholdMAX; this.stopLossConditionReached = false; this.currentAccountValue = 0.0; this.previousAccountValue = 0.0; ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = false; } --- 169,181 ---- this.oversoldThresholdMAX = oversoldThresholdMAX; this.overboughtThresholdMAX = overboughtThresholdMAX; + this.numOfStdDevForSignificantPriceMovements = numOfStdDevForSignificantPriceMovements; + this.leverage = leverage; + this.openOnlyLongPositions = openOnlyLongPositions; + this.maxNumberOfDaysOnTheMarket = maxNumberOfDaysOnTheMarket; this.stopLossConditionReached = false; this.currentAccountValue = 0.0; this.previousAccountValue = 0.0; ! this.entryConditions = entryConditions; ! this.allEntryConditionsHaveToBeSatisfied = allEntryConditionsHaveToBeSatisfied; } *************** *** 173,179 **** double oversoldThresholdMAX, double overboughtThresholdMAX, HistoricalMarketValueProvider historicalQuoteProvider, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) { --- 191,203 ---- double oversoldThresholdMAX, double overboughtThresholdMAX, + double numOfStdDevForSignificantPriceMovements, + double leverage, + bool openOnlyLongPositions, + int maxNumberOfDaysOnTheMarket, HistoricalMarketValueProvider historicalQuoteProvider, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain, ! List<IEntryCondition> entryConditions, ! bool allEntryConditionsHaveToBeSatisfied) { *************** *** 182,187 **** oversoldThreshold, overboughtThreshold, oversoldThresholdMAX, overboughtThresholdMAX, ! historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain ); this.inSampleChooser = inSampleChooser; } --- 206,217 ---- oversoldThreshold, overboughtThreshold, oversoldThresholdMAX, overboughtThresholdMAX, ! numOfStdDevForSignificantPriceMovements, ! leverage, ! openOnlyLongPositions, ! maxNumberOfDaysOnTheMarket, ! historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain, ! entryConditions, ! allEntryConditionsHaveToBeSatisfied); this.inSampleChooser = inSampleChooser; } *************** *** 196,202 **** double oversoldThreshold, double overboughtThreshold, HistoricalMarketValueProvider historicalQuoteProvider, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) { --- 226,238 ---- double oversoldThreshold, double overboughtThreshold, + double numOfStdDevForSignificantPriceMovements, + double leverage, + bool openOnlyLongPositions, + int maxNumberOfDaysOnTheMarket, HistoricalMarketValueProvider historicalQuoteProvider, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain, ! List<IEntryCondition> entryConditions, ! bool allEntryConditionsHaveToBeSatisfied) { *************** *** 205,210 **** oversoldThreshold, overboughtThreshold, double.MaxValue, double.MaxValue, historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain ); this.inSampleChooser = inSampleChooser; } --- 241,252 ---- oversoldThreshold, overboughtThreshold, double.MaxValue, double.MaxValue, + numOfStdDevForSignificantPriceMovements, + leverage, + openOnlyLongPositions, + maxNumberOfDaysOnTheMarket, historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain, ! entryConditions, ! allEntryConditionsHaveToBeSatisfied ); this.inSampleChooser = inSampleChooser; } *************** *** 221,227 **** double oversoldThresholdMAX, double overboughtThresholdMAX, HistoricalMarketValueProvider historicalQuoteProvider, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) { --- 263,275 ---- double oversoldThresholdMAX, double overboughtThresholdMAX, + double numOfStdDevForSignificantPriceMovements, + double leverage, + bool openOnlyLongPositions, + int maxNumberOfDaysOnTheMarket, HistoricalMarketValueProvider historicalQuoteProvider, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain, ! List<IEntryCondition> entryConditions, ! bool allEntryConditionsHaveToBeSatisfied) { *************** *** 230,235 **** oversoldThreshold, overboughtThreshold, oversoldThresholdMAX, overboughtThresholdMAX, historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain ); this.chosenPVOPositions = chosenPVOPositions; } --- 278,289 ---- oversoldThreshold, overboughtThreshold, oversoldThresholdMAX, overboughtThresholdMAX, + numOfStdDevForSignificantPriceMovements, + leverage, + openOnlyLongPositions, + maxNumberOfDaysOnTheMarket, historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain, ! entryConditions, ! allEntryConditionsHaveToBeSatisfied ); this.chosenPVOPositions = chosenPVOPositions; } *************** *** 244,250 **** double oversoldThreshold, double overboughtThreshold, HistoricalMarketValueProvider historicalQuoteProvider, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) { --- 298,310 ---- double oversoldThreshold, double overboughtThreshold, + double numOfStdDevForSignificantPriceMovements, + double leverage, + bool openOnlyLongPositions, + int maxNumberOfDaysOnTheMarket, HistoricalMarketValueProvider historicalQuoteProvider, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain, ! List<IEntryCondition> entryConditions, ! bool allEntryConditionsHaveToBeSatisfied) { *************** *** 253,258 **** oversoldThreshold, overboughtThreshold, double.MaxValue , double.MaxValue , historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain ); this.chosenPVOPositions = chosenPVOPositions; } --- 313,324 ---- oversoldThreshold, overboughtThreshold, double.MaxValue , double.MaxValue , + numOfStdDevForSignificantPriceMovements, + leverage, + openOnlyLongPositions, + maxNumberOfDaysOnTheMarket, historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain, ! entryConditions, ! allEntryConditionsHaveToBeSatisfied ); this.chosenPVOPositions = chosenPVOPositions; } *************** *** 279,325 **** { DateTime beginOfOscillatingPeriod = ! HistoricalEndOfDayTimer.GetMarketOpen( (DateTime)timer.IndexQuotes.Rows[ timer.CurrentDateArrayPosition-this.numDaysForOscillatingPeriod]["quDate"] ); return beginOfOscillatingPeriod; - // return new EndOfDayDateTime( (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition-this.numDaysForOscillatingPeriod]["quDate"], - // EndOfDaySpecificTime.MarketClose ); - } - - private void marketCloseEventHandler_reverseIfNeeded_reverse(PVOPositionsStatus currentStatus) - { - if(currentStatus == PVOPositionsStatus.Overbought) - { - this.portfolioHasBeenOversold = false; - this.portfolioHasBeenOverbought = true; - } - else if(currentStatus == PVOPositionsStatus.Oversold) - { - this.portfolioHasBeenOversold = true; - this.portfolioHasBeenOverbought = false; - } - AccountManager.ReversePositions(this.account); - this.previousAccountValue = this.account.GetMarketValue(); - } - - private void marketCloseEventHandler_reverseIfNeeded(IndexBasedEndOfDayTimer timer) - { - DateTime today = timer.GetCurrentDateTime(); - DateTime beginOfOscillatingPeriod = this.getBeginOfOscillatingPeriod(timer); - PVOPositionsStatus pvoPositionsStatus = - this.pvoPositionsForOutOfSample.GetStatus(beginOfOscillatingPeriod, today , this.benchmark.Ticker, this.historicalQuoteProvider, - double.MaxValue, double.MaxValue); - if(pvoPositionsStatus == PVOPositionsStatus.Overbought && - this.portfolioHasBeenOversold) - //open positions derive from an overSold period but now - //the overbought threshold has been reached - this.marketCloseEventHandler_reverseIfNeeded_reverse(pvoPositionsStatus); - - if(pvoPositionsStatus == PVOPositionsStatus.Oversold && - this.portfolioHasBeenOverbought) - //open positions derive from an overBought period but now - //the overSold threshold has been reached - this.marketCloseEventHandler_reverseIfNeeded_reverse(pvoPositionsStatus); } private PVOPositionsStatus marketCloseEventHandler_openPositions_getStatus(IndexBasedEndOfDayTimer timer) { --- 345,354 ---- { DateTime beginOfOscillatingPeriod = ! HistoricalEndOfDayTimer.GetMarketClose( (DateTime)timer.IndexQuotes.Rows[ timer.CurrentDateArrayPosition-this.numDaysForOscillatingPeriod]["quDate"] ); return beginOfOscillatingPeriod; } + private PVOPositionsStatus marketCloseEventHandler_openPositions_getStatus(IndexBasedEndOfDayTimer timer) { *************** *** 346,365 **** } ! protected void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) { PVOPositionsStatus pvoPositionsStatus = PVOPositionsStatus.InTheMiddle; if(timer.CurrentDateArrayPosition >= this.numDaysForOscillatingPeriod) pvoPositionsStatus = this.marketCloseEventHandler_openPositions_getStatus(timer); switch (pvoPositionsStatus){ case PVOPositionsStatus.Overbought: { #region manage Overbought case - this.pvoPositionsForOutOfSample.WeightedPositions.Reverse(); try{ ! AccountManager.OpenPositions( this.pvoPositionsForOutOfSample.WeightedPositions, ! this.account ); ! this.portfolioHasBeenOverbought = true; ! this.portfolioHasBeenOversold = false; this.previousAccountValue = this.account.GetMarketValue(); } --- 375,439 ---- } ! private bool areEntryConditionsSatisfied() ! { ! bool returnValue = true; ! if( this.allEntryConditionsHaveToBeSatisfied ) ! { ! for(int i = 0; i<this.entryConditions.Count; i++) ! if( !this.entryConditions[i].IsConditionSatisfiedByGivenPVOPositions(this.now(), ! this.pvoPositionsForOutOfSample) ) ! { ! returnValue = false; ! i = this.entryConditions.Count;//returnValue == false -> exit ! } ! } ! else // !this.allEntryConditionsHaveToBeSatisfied ! { ! for(int i = 0; i<this.entryConditions.Count; i++) ! if( this.entryConditions[i].IsConditionSatisfiedByGivenPVOPositions(this.now(), ! this.pvoPositionsForOutOfSample) ) ! i = this.entryConditions.Count;//returnValue == true -> exit ! } ! return returnValue; ! } ! ! private WeightedPositions marketCloseEventHandler_openPositionsIfTheCase_getWeightedPositionsToInvest() ! { ! WeightedPositions weightedPositions = ! this.pvoPositionsForOutOfSample.WeightedPositions; ! if(this.openOnlyLongPositions) ! { ! SignedTickers signedTickers = new SignedTickers(); ! foreach(WeightedPosition position in this.pvoPositionsForOutOfSample.WeightedPositions.GetValueList()) ! if(position.IsLong) ! { ! signedTickers.Add(new SignedTicker(position.Ticker)); ! weightedPositions = ! new WeightedPositions(signedTickers); ! } ! } ! return weightedPositions; ! } ! ! ! protected void marketCloseEventHandler_openPositionsIfTheCase(IndexBasedEndOfDayTimer timer) { PVOPositionsStatus pvoPositionsStatus = PVOPositionsStatus.InTheMiddle; if(timer.CurrentDateArrayPosition >= this.numDaysForOscillatingPeriod) + { pvoPositionsStatus = this.marketCloseEventHandler_openPositions_getStatus(timer); + } switch (pvoPositionsStatus){ case PVOPositionsStatus.Overbought: { #region manage Overbought case try{ ! if( this.areEntryConditionsSatisfied() ) ! { ! this.pvoPositionsForOutOfSample.WeightedPositions.Reverse(); ! AccountManager.OpenPositions( marketCloseEventHandler_openPositionsIfTheCase_getWeightedPositionsToInvest(), ! this.account, 10000.0, this.leverage ); ! } this.previousAccountValue = this.account.GetMarketValue(); } *************** *** 378,385 **** { #region manage Oversold case ! AccountManager.OpenPositions( this.pvoPositionsForOutOfSample.WeightedPositions, ! this.account ); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = true; this.previousAccountValue = this.account.GetMarketValue(); #endregion --- 452,459 ---- { #region manage Oversold case ! if( this.areEntryConditionsSatisfied() ) ! AccountManager.OpenPositions( marketCloseEventHandler_openPositionsIfTheCase_getWeightedPositionsToInvest(), ! this.account, 10000.0, this.leverage ); ! this.previousAccountValue = this.account.GetMarketValue(); #endregion *************** *** 403,421 **** protected virtual void marketCloseEventHandler_closePositionsIfNeeded() { ! if(this.stopLossConditionReached || ! this.takeProfitConditionReached || ! this.numDaysElapsedSinceLastOptimization + 1 == this.numDaysBetweenEachOptimization ) { AccountManager.ClosePositions(this.account); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = false; } } ! protected virtual void marketCloseEventHandler_updateStopLossAndTakeProfitConditions() { //this.previousAccountValue has been set at opening positions this.stopLossConditionReached = false; this.takeProfitConditionReached = false; this.currentAccountValue = this.account.GetMarketValue(); double portfolioGainOrLoss = (this.currentAccountValue - this.previousAccountValue) --- 477,497 ---- protected virtual void marketCloseEventHandler_closePositionsIfNeeded() { ! if( this.stopLossConditionReached || ! this.takeProfitConditionReached || ! this.maxNumberOfDaysOnTheMarketReached ) { AccountManager.ClosePositions(this.account); ! this.currentAccountValue = 0.0; ! this.previousAccountValue = 0.0; ! this.daysOnTheMarket = 0; } } ! protected virtual void marketCloseEventHandler_updateClosingConditions() { //this.previousAccountValue has been set at opening positions this.stopLossConditionReached = false; this.takeProfitConditionReached = false; + this.maxNumberOfDaysOnTheMarketReached = false; this.currentAccountValue = this.account.GetMarketValue(); double portfolioGainOrLoss = (this.currentAccountValue - this.previousAccountValue) *************** *** 435,438 **** --- 511,516 ---- this.takeProfitConditionReached = true; } + if ( this.maxNumberOfDaysOnTheMarket == this.daysOnTheMarket ) + this.maxNumberOfDaysOnTheMarketReached = true; } *************** *** 441,445 **** { try{ ! this.marketCloseEventHandler_updateStopLossAndTakeProfitConditions(); //this.marketCloseEventHandler_closePositionsIfNeeded(); if( this.chosenPVOPositions != null ) --- 519,523 ---- { try{ ! this.marketCloseEventHandler_updateClosingConditions(); //this.marketCloseEventHandler_closePositionsIfNeeded(); if( this.chosenPVOPositions != null ) *************** *** 447,455 **** { if(this.account.Portfolio.Count == 0) ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); //positions are opened only if thresholds are reached else//there are some opened positions this.marketCloseEventHandler_closePositionsIfNeeded(); - //this.marketCloseEventHandler_reverseIfNeeded((IndexBasedEndOfDayTimer)sender); } } --- 525,532 ---- { if(this.account.Portfolio.Count == 0) ! this.marketCloseEventHandler_openPositionsIfTheCase((IndexBasedEndOfDayTimer)sender); //positions are opened only if thresholds are reached else//there are some opened positions this.marketCloseEventHandler_closePositionsIfNeeded(); } } *************** *** 459,463 **** } } - #endregion --- 536,539 ---- *************** *** 573,577 **** this.numDaysElapsedSinceLastOptimization = 0; } ! } #endregion --- 649,654 ---- this.numDaysElapsedSinceLastOptimization = 0; } ! if( this.account.Portfolio.Count > 0 ) ! this.daysOnTheMarket++; } #endregion *************** *** 587,591 **** this.oneHourAfterMarketCloseEventHandler( sender , dateTime ); } - } } --- 664,667 ---- Index: PVOLogItem.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/PVOLogItem.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** PVOLogItem.cs 13 Mar 2009 15:11:23 -0000 1.7 --- PVOLogItem.cs 30 Aug 2009 21:43:34 -0000 1.8 *************** *** 22,25 **** --- 22,26 ---- using System; + using System.Collections.Generic; using System.Windows.Forms; *************** *** 33,36 **** --- 34,38 ---- using QuantProject.Business.Strategies.ReturnsManagement.Time; using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors; + using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.EntryConditions; using QuantProject.Business.Timing; using QuantProject.Presentation; *************** *** 185,188 **** --- 187,198 ---- //positionsToTest[0] = this.bestPVOPositionsInSample[0]; positionsToTest = this.BestPVOPositionsInSample; + List<IEntryCondition> entryConditions = new List<IEntryCondition>(); + IEntryCondition entryCondition = + new AlwaysTrueEntryCondition(); + // new PreviousPeriodsWereEfficientEntryCondition(1, historicalQuoteProviderForStrategy, + // numDaysForOscillatingPeriodForOutOfSample * 24 *60, + // new MarketDateTimeManager(benchmark, firstDateTime, lastDateTime, 60) ); + entryConditions.Add(entryCondition); + bool allEntryConditionsHaveToBeTrue = true; PVOStrategy strategy = new PVOStrategy(eligiblesSelector, *************** *** 193,198 **** ((PVOPositions)positionsToTest[0]).OversoldThreshold, ((PVOPositions)positionsToTest[0]).OverboughtThreshold, historicalQuoteProviderForStrategy , ! maxAcceptableCloseToCloseDrawdown , minimumAcceptableGain ); EndOfDayStrategyBackTester endOfDayStrategyBackTester = --- 203,210 ---- ((PVOPositions)positionsToTest[0]).OversoldThreshold, ((PVOPositions)positionsToTest[0]).OverboughtThreshold, + 0.0, 1.0, false, 1, historicalQuoteProviderForStrategy , ! maxAcceptableCloseToCloseDrawdown , minimumAcceptableGain, ! entryConditions, allEntryConditionsHaveToBeTrue); EndOfDayStrategyBackTester endOfDayStrategyBackTester = *************** *** 200,204 **** "PVO" , new QuantProject.Business.Timing.IndexBasedEndOfDayTimer( ! HistoricalEndOfDayTimer.GetMarketOpen( firstDateTime ) , benchmark.Ticker ) , strategy , --- 212,216 ---- "PVO" , new QuantProject.Business.Timing.IndexBasedEndOfDayTimer( ! HistoricalEndOfDayTimer.GetMarketClose( firstDateTime ) , benchmark.Ticker ) , strategy , Index: PVOMain.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/PVOMain.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** PVOMain.cs 12 Nov 2008 20:42:39 -0000 1.8 --- PVOMain.cs 30 Aug 2009 21:43:34 -0000 1.9 *************** *** 23,29 **** --- 23,31 ---- using System; using System.Collections; + using System.Collections.Generic; using System.IO; using QuantProject.ADT; + using QuantProject.ADT.Timing; using QuantProject.ADT.FileManaging; using QuantProject.Business.DataProviders; *************** *** 42,50 **** 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.General; using QuantProject.Scripts.General.Logging; using QuantProject.Scripts.General.Reporting; --- 44,55 ---- using QuantProject.Presentation; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.InSampleChoosers; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.FitnessEvaluators; + using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.InSampleChoosers.PriceRatioChooser; + using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.Decoding; + using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.EntryConditions; using QuantProject.Scripts.General; using QuantProject.Scripts.General.Logging; using QuantProject.Scripts.General.Reporting; + using QuantProject.Business.Timing.TimingManagement; *************** *** 60,88 **** private Benchmark benchmark; private HistoricalMarketValueProvider historicalQuoteProvider; public PVOMain() { ! this.benchmark = new Benchmark( "BMC" ); ! this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); ! ! // definition for the Fitness Evaluator ! // IEquityEvaluator equityEvaluator = new SharpeRatio(); } protected override IEligiblesSelector getEligiblesSelector() { ! ! int maxNumberOfEligiblesToBeChosen = 100; ! ! string tickersGroupId = "SP500"; bool temporizedGroup = true; int numDaysForAverageRawOpenPriceComputation = 10; ! double minPrice = 30; ! double maxPrice = 75; ! int maxNumberOfMostLiquidTickersToBeChosen = 150; int numDaysForVolatility = 10; IEligiblesSelector eligiblesSelector = --- 65,103 ---- private Benchmark benchmark; private HistoricalMarketValueProvider historicalQuoteProvider; + + private double maxAcceptableDrawDown; + private double minimumAcceptableGain; + private int closeToCloseIntervalLength; + private int numberOfPortfolioPositions; + private int numberOfBestTestingPositionsToBeReturned; + private IEquityEvaluator equityEvaluator; + private DateTime firstDateTime; + private DateTime lastDateTime; public PVOMain() { ! this.benchmark = new Benchmark( "ENI.MI" ); this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); ! this.maxAcceptableDrawDown = 0.03; ! this.minimumAcceptableGain = 0.01; ! this.closeToCloseIntervalLength = 2; ! this.numberOfPortfolioPositions = 2; ! this.numberOfBestTestingPositionsToBeReturned = 40; ! this.firstDateTime = new DateTime( 2004 , 1 , 1 ); ! this.lastDateTime = new DateTime( 2004 , 6, 30 ); } protected override IEligiblesSelector getEligiblesSelector() { ! int maxNumberOfEligiblesToBeChosen = 50; ! string tickersGroupId = "STOCKMI"; bool temporizedGroup = true; int numDaysForAverageRawOpenPriceComputation = 10; ! double minPrice = 0.1; ! double maxPrice = 1500; ! int maxNumberOfMostLiquidTickersToBeChosen = 100; int numDaysForVolatility = 10; IEligiblesSelector eligiblesSelector = *************** *** 94,112 **** 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; } --- 109,116 ---- numDaysForVolatility , minPrice , maxPrice ); ! ! // eligiblesSelector = ! // new DummyEligibleSelector(); ! return eligiblesSelector; } *************** *** 115,145 **** { // parameters for the genetic optimizer ! // double crossoverRate = 0.85; ! // double mutationRate = 0.02; ! // double elitismRate = 0.001; ! // int populationSizeForGeneticOptimizer = 3000; ! // int generationNumberForGeneticOptimizer = 4; ! // int seedForRandomGenerator = ! // QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator; ! ! // IDecoderForTestingPositions decoderForWeightedPositions = ! // new DecoderForPairsTradingTestingPositionsWithBalancedWeights(); ! ! double maxCorrelationAllowed = 0.96; ! int numberOfBestTestingPositionsToBeReturned = 50; ! numberOfBestTestingPositionsToBeReturned = 10; ! bool balancedWeightsOnVolatilityBase = true; ! float minimumAbsoluteReturnValue = 0.000001f; ! float maximumAbsoluteReturnValue = 100000f; ! // int closeToCloseIntervalLengthForCorrelation = 2; //correlation is computed only for returns //between minimum and maximum ! IInSampleChooser inSampleChooser = // new PVO_CTCCorrelationChooser(numberOfBestTestingPositionsToBeReturned, // closeToCloseIntervalLengthForCorrelation , maxCorrelationAllowed , balancedWeightsOnVolatilityBase, // minimumAbsoluteReturnValue , maximumAbsoluteReturnValue, this.benchmark.Ticker ); ! new PVO_CTCStrongCorrelationChooser(numberOfBestTestingPositionsToBeReturned, ! maxCorrelationAllowed , minimumAbsoluteReturnValue , maximumAbsoluteReturnValue, ! balancedWeightsOnVolatilityBase, this.benchmark.Ticker ); // IInSampleChooser inSampleChooser = // new PVO_OTCCTOCorrelationChooser(numberOfBestTestingPositionsToBeReturned, --- 119,166 ---- { // parameters for the genetic optimizer ! // ! double crossoverRate = 0.85; ! double mutationRate = 0.1; ! double elitismRate = 0.01; ! int populationSizeForGeneticOptimizer = 5000; ! int generationNumberForGeneticOptimizer = 5; ! int seedForRandomGenerator = ! QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator; ! int divisorForThresholdComputation = 1000; ! bool symmetricalThreshold = true; ! bool overboughtMoreThanOversoldThresholdsForStationaryPortfolios = false; ! IDecoderForTestingPositions decoderForWeightedPositions = ! new BasicDecoderForPVOPositions(symmetricalThreshold, divisorForThresholdComputation, ! this.closeToCloseIntervalLength); ! this.equityEvaluator = new SharpeRatio(); ! IFitnessEvaluator pvoFitnessEvaluator = ! new PVOFitnessEvaluator(this.equityEvaluator, this.minimumAcceptableGain, ! this.maxAcceptableDrawDown); ! IInSampleChooser inSampleChooser = ! new PVOGeneticChooser(this.closeToCloseIntervalLength, this.numberOfPortfolioPositions, ! this.numberOfBestTestingPositionsToBeReturned, this.benchmark, ! decoderForWeightedPositions, pvoFitnessEvaluator, ! this.historicalQuoteProvider, crossoverRate, mutationRate, ! elitismRate, populationSizeForGeneticOptimizer, generationNumberForGeneticOptimizer, ! seedForRandomGenerator, 5, 5, 5, 5, divisorForThresholdComputation, ! symmetricalThreshold, overboughtMoreThanOversoldThresholdsForStationaryPortfolios); ! // ! // double maxCorrelationAllowed = 0.96; ! // bool balancedWeightsOnVolatilityBase = true; ! // float minimumAbsoluteReturnValue = 0.000001f; ! // float maximumAbsoluteReturnValue = 100000f; ! // int closeToCloseIntervalLengthForCorrelation = 1; //correlation is computed only for returns //between minimum and maximum ! // IInSampleChooser inSampleChooser = // new PVO_CTCCorrelationChooser(numberOfBestTestingPositionsToBeReturned, // closeToCloseIntervalLengthForCorrelation , maxCorrelationAllowed , balancedWeightsOnVolatilityBase, // minimumAbsoluteReturnValue , maximumAbsoluteReturnValue, this.benchmark.Ticker ); ! ! // new PVOLessVolatilePriceRatioChooser(numberOfBestTestingPositionsToBeReturned, balancedWeightsOnVolatilityBase); ! ! // new PVO_CTCStrongCorrelationChooser(numberOfBestTestingPositionsToBeReturned, ! // maxCorrelationAllowed , minimumAbsoluteReturnValue , maximumAbsoluteReturnValue, ! // balancedWeightsOnVolatilityBase, this.benchmark.Ticker ); // IInSampleChooser inSampleChooser = // new PVO_OTCCTOCorrelationChooser(numberOfBestTestingPositionsToBeReturned, *************** *** 152,159 **** // numberOfBestTestingPositionsToBeReturned); //home ! inSampleChooser = ! new PVOChooserFromSavedBackTestLog( ! @"C:\Utente\MarcoVarie\Vari\qP\LogArchive\2008_06_03_18_33_29_PVO_CTC_from_2001_01_01_to_2004_12_31_annlRtrn_4.72_maxDD_13.57\2008_06_03_18_33_29_PVO_CTC_from_2001_01_01_to_2004_12_31_annlRtrn_4.72_maxDD_13.57.qpL", ! numberOfBestTestingPositionsToBeReturned); return inSampleChooser; } --- 173,180 ---- // numberOfBestTestingPositionsToBeReturned); //home ! // inSampleChooser = ! // new PVOChooserFromSavedBackTestLog( ! // @"C:\Utente\MarcoVarie\Vari\qP\LogArchive\2008_06_03_18_33_29_PVO_CTC_from_2001_01_01_to_2004_12_31_annlRtrn_4.72_maxDD_13.57\2008_06_03_18_33_29_PVO_CTC_from_2001_01_01_to_2004_12_31_annlRtrn_4.72_maxDD_13.57.qpL", ! // numberOfBestTestingPositionsToBeReturned); return inSampleChooser; } *************** *** 164,185 **** // uncomment the following line for a faster script //inSampleDays = 50; ! int numDaysBetweenEachOptimization = 5; ! double oversoldThreshold = 0.002; ! double overboughtThreshold = 0.002; ! double oversoldThresholdMAX = 0.02; ! double overboughtThresholdMAX = 0.02; ! double maxAcceptableDrawDown = 0.01; ! double minimumAcceptableGain = 0.002; ! int closeToCloseIntervalLength = 1; IStrategyForBacktester strategyForBacktester ! // = new PVO_OTCStrategyLessCorrelated(eligiblesSelector ,inSampleChooser , ! // inSampleDays , benchmark , numDaysBetweenEachOptimization , ! // oversoldThreshold , overboughtThreshold , historicalQuoteProvider); ! // = new PVOStrategy(eligiblesSelector , inSampleChooser , ! inSampleDays , closeToCloseIntervalLength , 2 , benchmark , numDaysBetweenEachOptimization , oversoldThreshold , overboughtThreshold , ! oversoldThresholdMAX , overboughtThresholdMAX , historicalQuoteProvider, ! maxAcceptableDrawDown, minimumAcceptableGain ); return strategyForBacktester; } --- 185,232 ---- // uncomment the following line for a faster script //inSampleDays = 50; ! int numDaysBetweenEachOptimization = 10; ! double oversoldThreshold = 0.015; ! double overboughtThreshold = 0.015; ! double oversoldThresholdMAX = 0.1; ! double overboughtThresholdMAX = 0.1; ! double numOfStdDevForSignificantPriceMovements = 1.5; ! double leverage = 1.0; ! bool openOnlyLongPositions = false; ! int maxNumberOfDaysOnTheMarket = 5; ! List<IEntryCondition> entryConditions = new List<IEntryCondition>(); ! IEntryCondition entryCondition = ! // new AlwaysTrueEntryCondition(); ! // new PriceRatioEntryCondition(45, this.historicalQuoteProvider, 1.0); ! new PreviousPeriodsWereEfficientEntryCondition(1, this.historicalQuoteProvider, ! this.closeToCloseIntervalLength, ! new MarketDaysManager(this.benchmark, ! this.firstDateTime, this.lastDateTime, ! new Time("16:00:00"))); ! entryConditions.Add(entryCondition); ! bool allEntryConditionsHaveToBeTrue = true; ! IStrategyForBacktester strategyForBacktester ! //pair trading ! // = new PVOStrategy(eligiblesSelector , inSampleChooser , ! // inSampleDays , closeToCloseIntervalLength , 2 , benchmark , numDaysBetweenEachOptimization , ! // oversoldThreshold , overboughtThreshold , ! // oversoldThresholdMAX , overboughtThresholdMAX , ! // numOfStdDevForSignificantPriceMovements, ! // leverage , openOnlyLongPositions , ! // maxNumberOfDaysOnTheMarket, ! // historicalQuoteProvider, ! // maxAcceptableDrawDown, minimumAcceptableGain ); = new PVOStrategy(eligiblesSelector , inSampleChooser , ! inSampleDays , closeToCloseIntervalLength , ! this.numberOfPortfolioPositions , benchmark , numDaysBetweenEachOptimization , oversoldThreshold , overboughtThreshold , ! oversoldThresholdMAX , overboughtThresholdMAX , ! numOfStdDevForSignificantPriceMovements, ! leverage , openOnlyLongPositions , ! maxNumberOfDaysOnTheMarket, ! historicalQuoteProvider, ! maxAcceptableDrawDown, minimumAcceptableGain, entryConditions, ! allEntryConditionsHaveToBeTrue); ! return strategyForBacktester; } *************** *** 192,200 **** // accountProvider = // new InteractiveBrokerAccountProvider(fixedPercentageSlippage); ! double cashToStart = 25000; ! DateTime firstDateTime = new DateTime( 2001 , 1 , 1 ); ! DateTime lastDateTime = new DateTime( 2004 , 12, 31 ); ! double maxRunningHours = 8; HistoricalMarketValueProvider quoteProviderForBackTester = this.historicalQuoteProvider; --- 239,245 ---- // accountProvider = // new InteractiveBrokerAccountProvider(fixedPercentageSlippage); ! double cashToStart = 10000; ! double maxRunningHours = 10; HistoricalMarketValueProvider quoteProviderForBackTester = this.historicalQuoteProvider; *************** *** 205,209 **** backTestId , new QuantProject.Business.Timing.IndexBasedEndOfDayTimer( ! HistoricalEndOfDayTimer.GetMarketOpen( firstDateTime ) , this.benchmark.Ticker ) , this.strategyForBacktester , --- 250,254 ---- backTestId , new QuantProject.Business.Timing.IndexBasedEndOfDayTimer( ! HistoricalEndOfDayTimer.GetMarketClose( firstDateTime ) , this.benchmark.Ticker ) , this.strategyForBacktester , Index: PVOPositions.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/PVOPositions.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** PVOPositions.cs 13 Mar 2009 15:11:23 -0000 1.6 --- PVOPositions.cs 30 Aug 2009 21:43:34 -0000 1.7 *************** *** 45,48 **** --- 45,50 ---- private int numOfDaysOrMinutesForOscillatingPeriod; private int generation; + private DateTime lastInefficiencyDateTime; + private PVOPositionsStatus statusAtLastInefficiencyTime; private static ReturnsManager returnsManager; *************** *** 64,67 **** --- 66,81 ---- } + public DateTime LastInefficiencyDateTime + { + get{return this.lastInefficiencyDateTime;} + set{this.lastInefficiencyDateTime = value;} + } + + public PVOPositionsStatus StatusAtLastInefficiencyTime + { + get{return this.statusAtLastInefficiencyTime;} + set{this.statusAtLastInefficiencyTime = value;} + } + //explicit interface implementation //the property can be used only by a interface *************** *** 98,103 **** --- 112,134 ---- this.numOfDaysOrMinutesForOscillatingPeriod = numDaysForOscillatingPeriod; this.generation = -1; + this.statusAtLastInefficiencyTime = PVOPositionsStatus.InTheMiddle; + this.lastInefficiencyDateTime = new DateTime(1900,1,1,0,0,0); } + public PVOPositions(WeightedPositions weightedPositions, + double oversoldThreshold, + double overboughtThreshold, + int numDaysForOscillatingPeriod, + DateTime lastInefficiencyDateTime) : + base(weightedPositions) + + { + this.oversoldThreshold = oversoldThreshold; + this.overboughtThreshold = overboughtThreshold; + this.numOfDaysOrMinutesForOscillatingPeriod = numDaysForOscillatingPeriod; + this.generation = -1; + this.lastInefficiencyDateTime = lastInefficiencyDateTime; + this.statusAtLastInefficiencyTime = PVOPositionsStatus.InTheMiddle; + } private void setReturnsManager(DateTime beginOfPeriod, DateTime endOfPeriod, *************** *** 165,169 **** this.overboughtThreshold, maxOverboughtThreshold ); } ! public bool AreAllTickersMovingTogetherUpOrDown(DateTime beginOfPeriod, DateTime endOfPeriod, --- 196,209 ---- this.overboughtThreshold, maxOverboughtThreshold ); } ! public PVOPositionsStatus GetStatus(DateTime beginOfPeriod, ! DateTime endOfPeriod, ! string benchmark, ! HistoricalMarketValueProvider quoteProvider) ! { ! return this.GetStatus(beginOfPeriod, endOfPeriod, ! benchmark, quoteProvider, ! this.oversoldThreshold, double.MaxValue, ! this.overboughtThreshold, double.MaxValue ); ! } public bool AreAllTickersMovingTogetherUpOrDown(DateTime beginOfPeriod, DateTime endOfPeriod, Index: PVOStrategyIntraday.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/PVOStrategyIntraday.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** PVOStrategyIntraday.cs 29 Mar 2009 18:31:00 -0000 1.5 --- PVOStrategyIntraday.cs 30 Aug 2009 21:43:34 -0000 1.6 *************** *** 45,48 **** --- 45,49 ---- using QuantProject.Data; using QuantProject.Data.DataProviders; + using QuantProject.Data.DataProviders.Bars.Caching; using QuantProject.Data.Selectors; using QuantProject.Data.DataTables; *************** *** 75,78 **** --- 76,80 ---- protected HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample; + protected HistoricalAdjustedBarProvider historicalAdjBarProvider; protected double oversoldThreshold; protected double overboughtThreshold; *************** *** 103,106 **** --- 105,110 ---- protected double inefficiencyLengthInMinutes; protected int numberOfPreviousEfficientPeriods; + protected int numberOfDaysForPriceRatioAnalysis; + protected double numberOfStdDeviationForSignificantPriceRatioMovements; protected double maxOpeningLengthInMinutes; protected double minutesFromLastInefficiencyTimeToWaitBeforeOpening; *************** *** 114,117 **** --- 118,122 ---- protected double stopLoss; protected double takeProfit; + protected double leverage; private string description_GetDescriptionForChooser() *************** *** 175,183 **** double inefficiencyLengthInMinutes, int numberOfPreviousEfficientPeriods, double minutesFromLastInefficiencyTimeToWaitBeforeOpening, double minutesFromLastLossOrProfitToWaitBeforeClosing, double maxOpeningLengthInMinutes, List<Time> openingTimesForAvailableBars, ! double stopLoss, double takeProfit) { this.eligiblesSelector = eligiblesSelector; --- 180,190 ---- double inefficiencyLengthInMinutes, int numberOfPreviousEfficientPeriods, + int numberOfDaysForPriceRatioAnalysis, + double numberOfStdDeviationForSignificantPriceRatioMovements, double minutesFromLastInefficiencyTimeToWaitBeforeOpening, double minutesFromLastLossOrProfitToWaitBeforeClosing, double maxOpeningLengthInMinutes, List<Time> openingTimesForAvailableBars, ! double stopLoss, double takeProfit, double leverage) { this.eligiblesSelector = eligiblesSelector; *************** *** 191,198 **** this.oversoldThresholdMAX = oversoldThresholdMAX; this.overboughtThresholdMAX = overboughtThresholdMAX; ! this.historicalMarketValueProviderForInSample = historicalMarketValueProviderForInSample; ! this.historicalMarketValueProviderForOutOfSample = historicalMarketValueProviderForOutOfSample; this.inefficiencyLengthInMinutes = inefficiencyLengthInMinutes; this.numberOfPreviousEfficientPeriods = numberOfPreviousEfficientPeriods; this.minutesFromLastInefficiencyTimeToWaitBeforeOpening = minutesFromLastInefficiencyTimeToWaitBeforeOpening; --- 198,210 ---- this.oversoldThresholdMAX = oversoldThresholdMAX; this.overboughtThresholdMAX = overboughtThresholdMAX; ! this.historicalMarketValueProviderForInSample = ! historicalMarketValueProviderForInSample; ! this.historicalMarketValueProviderForOutOfSample = ! historicalMarketValueProviderForOutOfSample; this.inefficiencyLengthInMinutes = inefficiencyLengthInMinutes; this.numberOfPreviousEfficientPeriods = numberOfPreviousEfficientPeriods; + this.numberOfDaysForPriceRatioAnalysis = numberOfDaysForPriceRatioAnalysis; + this.numberOfStdDeviationForSignificantPriceRatioMovements = + numberOfStdDeviationForSignificantPriceRatioMovements; this.minutesFromLastInefficiencyTimeToWaitBeforeOpening = minutesFromLastInefficiencyTimeToWaitBeforeOpening; *************** *** 203,208 **** --- 215,225 ---- this.stopLoss = stopLoss; this.takeProfit = takeProfit; + this.leverage = leverage; this.lastOptimizationDateTime = DateTime.MinValue; + this.historicalAdjBarProvider = + new HistoricalAdjustedBarProvider( new HistoricalBarProvider( new SimpleBarCache(60) ), + new HistoricalRawQuoteProvider(), + new HistoricalAdjustedQuoteProvider() ); this.pvoStrategyIntraday_checkTimeParameters(); this.lastEntryTime = new Time("00:00:00"); *************** *** 225,233 **** double inefficiencyLengthInMinutes, int numberOfPreviousEfficientPeriods, double minutesFromLastInefficiencyTimeToWaitBeforeOpening, double minutesFromLastLossOrProfitToWaitBeforeClosing, double maxOpeningLengthInMinutes, List<Time> openingTimesForAvailableBars, ! double stopLoss, double takeProfit) { --- 242,253 ---- double inefficiencyLengthInMinutes, int numberOfPreviousEfficientPeriods, + int numberOfDaysForPriceRatioAnalysis, + double numberOfStdDeviationForSignificantPriceRatioMovements, double minutesFromLastInefficiencyTimeToWaitBeforeOpening, double minutesFromLastLossOrProfitToWaitBeforeClosing, double maxOpeningLengthInMinutes, List<Time> openingTimesForAvailableBars, ! double stopLoss, double takeProfit, ! double leverage) { *************** *** 240,248 **** inefficiencyLengthInMinutes, numberOfPreviousEfficientPeriods, minutesFromLastInefficiencyTimeToWaitBeforeOpening, minutesFromLastLossOrProfitToWaitBeforeClosing, maxOpeningLengthInMinutes, openingTimesForAvailableBars, ! stopLoss, takeProfit); this.inSampleChooser = inSampleChooser; } --- 260,270 ---- inefficiencyLengthInMinutes, numberOfPreviousEfficientPeriods, + numberOfDaysForPriceRatioAnalysis, + numberOfStdDeviationForSignificantPriceRatioMovements, minutesFromLastInefficiencyTimeToWaitBeforeOpening, minutesFromLastLossOrProfitToWaitBeforeClosing, maxOpeningLengthInMinutes, openingTimesForAvailableBars, ! stopLoss, takeProfit, leverage); this.inSampleChooser = inSampleChooser; } *************** *** 260,268 **** double inefficiencyLengthInMinutes, int numberOfPreviousEfficientPeriods, double minutesFromLastInefficiencyTimeToWaitBeforeOpening, double minutesFromLastLossOrProfitToWaitBeforeClosing, double maxOpeningLengthInMinutes, List<Time> openingTimesForAvailableBars, ! double stopLoss, double takeProfit) { --- 282,292 ---- double inefficiencyLengthInMinutes, int numberOfPreviousEfficientPeriods, + int numberOfDaysForPriceRatioAnalysis, + double numberOfStdDeviationForSignificantPriceRatioMovements, double minutesFromLastInefficiencyTimeToWaitBeforeOpening, double minutesFromLastLossOrProfitToWaitBeforeClosing, double maxOpeningLengthInMinutes, List<Time> openingTimesForAvailableBars, ! double stopLoss, double takeProfit, double leverage) { *************** *** 275,283 **** inefficiencyLengthInMinutes, numberOfPreviousEfficientPeriods, minutesFromLastInefficiencyTimeToWaitBeforeOpening, minutesFromLastLossOrProfitToWaitBeforeClosing, maxOpeningLengthInMinutes, openingTimesForAvailableBars, ! stopLoss, takeProfit); this.inSampleChooser = inSampleChooser; } --- 299,309 ---- inefficiencyLengthInMinutes, numberOfPreviousEfficientPeriods, + numberOfDaysForPriceRatioAnalysis, + numberOfStdDeviationForSignificantPriceRatioMovements, minutesFromLastInefficiencyTimeToWaitBeforeOpening, minutesFromLastLossOrProfitToWaitBeforeClosing, maxOpeningLengthInMinutes, openingTimesForAvailableBars, ! stopLoss, takeProfit, leverage); this.inSampleChooser = inSampleChooser; } *************** *** 296,304 **** double inefficiencyLengthInMinutes, int numberOfPreviousEfficientPeriods, double minutesFromLastInefficiencyTimeToWaitBeforeOpening, double minutesFromLastLossOrProfitToWaitBeforeClosing, double maxOpeningLengthInMinutes, List<Time> openingTimesForAvailableBars, ! double stopLoss, double takeProfit) { --- 322,332 ---- double inefficiencyLengthInMinutes, int numberOfPreviousEfficientPeriods, + int numberOfDaysForPriceRatioAnalysis, + double numberOfStdDeviationForSignificantPriceRatioMovements, double minutesFromLastInefficiencyTimeToWaitBeforeOpening, double minutesFromLastLossOrProfitToWaitBeforeClosing, double maxOpeningLengthInMinutes, List<Time> openingTimesForAvailableBars, ! double stopLoss, double takeProfit, double leverage) { *************** *** 311,319 **** inefficiencyLengthInMinutes, numberOfPreviousEfficientPeriods, minutesFromLastInefficiencyTimeToWaitBeforeOpening, minutesFromLastLossOrProfitToWaitBeforeClosing, maxOpeningLengthInMinutes, openingTimesForAvailableBars, ! stopLoss, takeProfit); this.chosenPVOPositions = chosenPVOPositions; } --- 339,349 ---- inefficiencyLengthInMinutes, numberOfPreviousEfficientPeriods, + numberOfDaysForPriceRatioAnalysis, + numberOfStdDeviationForSignificantPriceRatioMovements, minutesFromLastInefficiencyTimeToWaitBeforeOpening, minutesFromLastLossOrProfitToWaitBeforeClosing, maxOpeningLengthInMinutes, openingTimesForAvailableBars, ! stopLoss, takeProfit, leverage); this.chosenPVOPositions = chosenPVOPositions; } *************** *** 330,338 **** double inefficiencyLengthInMinutes, int numberOfPreviousEfficientPeriods, double minutesFromLastInefficiencyTimeToWaitBeforeOpening, double minutesFromLastLossOrProfitToWaitBeforeClosing, double maxOpeningLengthInMinutes, List<Time> openingTimesForAvailableBars, ! double stopLoss, double takeProfit) { this.pvoStrategyIntraday(eligiblesSelector, minimumNumberOfEligiblesForValidOptimization, --- 360,370 ---- double inefficiencyLengthInMinutes, int numberOfPreviousEfficientPeriods, + int numberOfDaysForPriceRatioAnalysis, + double numberOfStdDeviationForSignificantPriceRatioMovements, double minutesFromLastInefficiencyTimeToWaitBeforeOpening, double minutesFromLastLossOrProfitToWaitBeforeClosing, double maxOpeningLengthInMinutes, List<Time> openingTimesForAvailableBars, ! double stopLoss, double takeProfit, double leverage) { this.pvoStrategyIntraday(eligiblesSelector, minimumNumberOfEligiblesForValidOptimization, *************** *** 344,352 **** inefficiencyLengthInMinutes, numberOfPreviousEfficientPeriods, minutesFromLastInefficiencyTimeToWaitBeforeOpening, minutesFromLastLossOrProfitToWaitBeforeClosing, maxOpeningLengthInMinutes, openingTimesForAvailableBars, ! stopLoss, takeProfit); this.chosenPVOPositions = chosenPVOPositions; } --- 376,386 ---- inefficiencyLengthInMinutes, numberOfPreviousEfficientPeriods, + numberOfDaysForPriceRatioAnalysis, + numberOfStdDeviationForSignificantPriceRatioMovements, minut... [truncated message content] |
|
From: Marco M. <mi...@us...> - 2009-08-30 21:42:42
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/FitnessEvaluators In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20386/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/FitnessEvaluators Modified Files: PVOFitnessEvaluator.cs Log Message: GetFitnessValue method has been updated (it is now more similar to what should happen out of sample) Index: PVOFitnessEvaluator.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/FitnessEvaluators/PVOFitnessEvaluator.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** PVOFitnessEvaluator.cs 9 Mar 2008 22:49:24 -0000 1.1 --- PVOFitnessEvaluator.cs 30 Aug 2009 21:42:33 -0000 1.2 *************** *** 35,41 **** /// Evaluates (in sample) the fitness for a given TestingPositions /// </summary> ! public class PVOFitnessEvaluator : IFitnessEvaluator { private IEquityEvaluator strategyEquityEvaluator; public string Description --- 35,44 ---- /// Evaluates (in sample) the fitness for a given TestingPositions /// </summary> ! [Serializable] ! public class PVOFitnessEvaluator : IFitnessEvaluator { private IEquityEvaluator strategyEquityEvaluator; + private float takeProfit; + private float stopLoss; public string Description *************** *** 49,60 **** } ! public PVOFitnessEvaluator(IEquityEvaluator strategyEquityEvaluator) { this.strategyEquityEvaluator = strategyEquityEvaluator; } #region GetFitnessValue //returns true if the strategy gets effective positions on ! //the market for at least half the market days private bool getFitnessValue_getFitnessValueActually_strategyGetsSufficientPositions(float[] strategyReturns) { --- 52,66 ---- } ! public PVOFitnessEvaluator(IEquityEvaluator strategyEquityEvaluator, ! double takeProfit, double stopLoss) { this.strategyEquityEvaluator = strategyEquityEvaluator; + this.takeProfit = Convert.ToSingle(takeProfit); + this.stopLoss = Convert.ToSingle(stopLoss); } #region GetFitnessValue //returns true if the strategy gets effective positions on ! //the market for at least a quarter of the market days private bool getFitnessValue_getFitnessValueActually_strategyGetsSufficientPositions(float[] strategyReturns) { *************** *** 68,71 **** --- 74,92 ---- } + private bool getFitnessValue_getFitnessValueActually_itIsTimeToExit( + float[] strategyReturns, int currentIndex, int indexOfLastSignal ) + { + bool returnValue = false; + float gainOrLoss; + float equityValue = 1; + if(indexOfLastSignal >= 1 ) + for(int i = 0; i + indexOfLastSignal < currentIndex; i++) + equityValue = equityValue + equityValue * strategyReturns[indexOfLastSignal + 1 + i]; + gainOrLoss = equityValue - 1; + if(gainOrLoss >= this.takeProfit || gainOrLoss <= -this.stopLoss) + returnValue = true; + return returnValue; + } + private float getFitnessValue_getFitnessValueActually( TestingPositions testingPositions, ReturnsManager returnsManager ) *************** *** 78,95 **** testingPositions.WeightedPositions.GetReturns(returnsManager); float[] strategyReturns = new float[ plainWeightedPositionsReturns.Length ]; ! strategyReturns[0] = 0; //a the very first day the ! //strategy return is equal to 0 because no position //has been entered float coefficient = 0; ! for(int i = 0; i < strategyReturns.Length - 1; i++) { ! if( plainWeightedPositionsReturns[i] >= overboughtThreshold ) ! //portfolio has been overbought coefficient = -1; ! else if( plainWeightedPositionsReturns[i] <= - oversoldThreshold ) ! //portfolio has been oversold coefficient = 1; ! //else the previous coeff is kept or, if no threshold has been ! //reached, then no positions will be opened (coefficient = 0) strategyReturns[i + 1] = coefficient * plainWeightedPositionsReturns[i + 1]; } --- 99,135 ---- testingPositions.WeightedPositions.GetReturns(returnsManager); float[] strategyReturns = new float[ plainWeightedPositionsReturns.Length ]; ! strategyReturns[0] = 0; ! strategyReturns[1] = 0;//at the two first days the ! //strategy returns is equal to 0 because no position //has been entered float coefficient = 0; ! int indexOfLastSignal = 0;// the last position where a threshold has been reached ! for(int i = 1; i < strategyReturns.Length - 1; i++) { ! if( plainWeightedPositionsReturns[i] >= overboughtThreshold && ! (plainWeightedPositionsReturns[i - 1] > - oversoldThreshold && ! plainWeightedPositionsReturns[i - 1] < overboughtThreshold ) && ! indexOfLastSignal == 0 ) ! //portfolio has been overbought and in the previous period ! //it was efficient ! { coefficient = -1; ! indexOfLastSignal = i; ! } ! if( plainWeightedPositionsReturns[i] <= - oversoldThreshold && ! (plainWeightedPositionsReturns[i - 1] > - oversoldThreshold && ! plainWeightedPositionsReturns[i - 1] < overboughtThreshold ) && ! indexOfLastSignal == 0 ) ! //portfolio has been oversold and in the previous period ! //it was efficient ! { coefficient = 1; ! indexOfLastSignal = i; ! } ! if ( getFitnessValue_getFitnessValueActually_itIsTimeToExit(strategyReturns, i, indexOfLastSignal) ) ! { ! coefficient = 0; ! indexOfLastSignal = 0; ! } strategyReturns[i + 1] = coefficient * plainWeightedPositionsReturns[i + 1]; } |
|
From: Marco M. <mi...@us...> - 2009-08-30 21:39:17
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/AccountProviding In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv20043/b4_Business/a1_Financial/a2_Accounting/AccountProviding Modified Files: InteractiveBrokerAccountProvider.cs Log Message: Serializable attribute has been added Index: InteractiveBrokerAccountProvider.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a2_Accounting/AccountProviding/InteractiveBrokerAccountProvider.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** InteractiveBrokerAccountProvider.cs 22 Nov 2008 18:23:12 -0000 1.4 --- InteractiveBrokerAccountProvider.cs 30 Aug 2009 21:39:07 -0000 1.5 *************** *** 40,43 **** --- 40,44 ---- /// lost at each stock-transaction /// </summary> + [Serializable] public class InteractiveBrokerAccountProvider : IAccountProvider { |
|
From: Marco M. <mi...@us...> - 2009-08-30 21:34:18
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/InSampleChoosers In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv19578/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/InSampleChoosers Modified Files: PVOGeneticChooser.cs Log Message: getGenomeManager abstract method is now public (it has been renamed to GetGenomeManager) Index: PVOGeneticChooser.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/InSampleChoosers/PVOGeneticChooser.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** PVOGeneticChooser.cs 9 Nov 2008 16:36:21 -0000 1.3 --- PVOGeneticChooser.cs 30 Aug 2009 21:34:10 -0000 1.4 *************** *** 92,96 **** } ! protected override IGenomeManager getGenomeManager(EligibleTickers eligibleTickers , ReturnsManager returnsManager) { --- 92,96 ---- } ! public override IGenomeManager GetGenomeManager(EligibleTickers eligibleTickers , ReturnsManager returnsManager) { |
|
From: Marco M. <mi...@us...> - 2009-08-30 21:33:54
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/PairsTrading/InSample/InSampleChoosers/Genetic In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv19476/b7_Scripts/WalkForwardTesting/PairsTrading/InSample/InSampleChoosers/Genetic Modified Files: PairsTradingGeneticChooser.cs Log Message: getGenomeManager abstract method is now public (it has been renamed to GetGenomeManager) Index: PairsTradingGeneticChooser.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/PairsTrading/InSample/InSampleChoosers/Genetic/PairsTradingGeneticChooser.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** PairsTradingGeneticChooser.cs 29 Sep 2008 21:20:46 -0000 1.2 --- PairsTradingGeneticChooser.cs 30 Aug 2009 21:33:46 -0000 1.3 *************** *** 70,74 **** // } ! protected override IGenomeManager getGenomeManager( EligibleTickers eligibleTickers , ReturnsManager returnsManager ) --- 70,74 ---- // } ! public override IGenomeManager GetGenomeManager( EligibleTickers eligibleTickers , ReturnsManager returnsManager ) |
|
From: Marco M. <mi...@us...> - 2009-08-30 21:31:48
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/Decoding In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv19292/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/Decoding Modified Files: BasicDecoderForPVOPositions.cs Log Message: PVO script has been updated Index: BasicDecoderForPVOPositions.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/Decoding/BasicDecoderForPVOPositions.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** BasicDecoderForPVOPositions.cs 18 May 2008 22:07:19 -0000 1.4 --- BasicDecoderForPVOPositions.cs 30 Aug 2009 21:31:38 -0000 1.5 *************** *** 36,39 **** --- 36,40 ---- /// In this implementation, only tickers and thresholds are decoded /// </summary> + [Serializable] public class BasicDecoderForPVOPositions : BasicDecoderForTestingPositions { *************** *** 85,89 **** this.decodeDecodable_setThresholds(); PVOPositions pvoPositions = new PVOPositions( ! new WeightedPositions( this.getWeights(signedTickers), signedTickers), this.oversoldThreshold, this.overboughtThreshold, this.numDaysForOscillatingPeriod); --- 86,90 ---- this.decodeDecodable_setThresholds(); PVOPositions pvoPositions = new PVOPositions( ! new WeightedPositions( this.getUnsignedWeights(signedTickers), signedTickers), this.oversoldThreshold, this.overboughtThreshold, this.numDaysForOscillatingPeriod); |
|
From: Marco M. <mi...@us...> - 2009-08-30 15:58:41
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/OutOfSample In directory ddv4jf1.ch3.sourceforge.com:/tmp/cvs-serv23451/b4_Business/a2_Strategies/OutOfSample Modified Files: TestingPositions.cs Log Message: Some useful properties have been added Index: TestingPositions.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/OutOfSample/TestingPositions.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** TestingPositions.cs 7 Mar 2008 23:27:13 -0000 1.4 --- TestingPositions.cs 30 Aug 2009 15:58:30 -0000 1.5 *************** *** 39,42 **** --- 39,43 ---- private WeightedPositions weightedPositions; private string hashCodeForTickerComposition; + private string hashCode; private double fitnessInSample; *************** *** 60,64 **** //the current instance is not empty { ! ArrayList listOfTickers = new ArrayList(this.weightedPositions.SignedTickers.Tickers); listOfTickers.Sort(); --- 61,65 ---- //the current instance is not empty { ! ArrayList listOfTickers = new ArrayList(this.weightedPositions.SignedTickers.Tickers); listOfTickers.Sort(); *************** *** 69,72 **** --- 70,143 ---- } } + /// <summary> + /// Hash code for the current instance + /// Two instances have the same Hash code iif + /// they have the same tickers with the same signed weights + /// </summary> + public string HashCode + { + get + { + if(this.hashCode == null && + this.weightedPositions != null) + //if hashCode has not been computed yet and + //the current instance is not empty + { + ArrayList listOfTickers = + new ArrayList(this.weightedPositions.SignedTickers.Tickers); + listOfTickers.Sort(); + foreach(string tickerCode in listOfTickers) + this.hashCode += + tickerCode + "_" + + this.weightedPositions.GetWeightedPosition(tickerCode).Weight.ToString() + + ";"; + } + return this.hashCode; + } + } + public bool OnlyLongPositions + { + get + { + bool returnValue = false; + int numOfWeightedPositions = this.weightedPositions.Count; + int numOfLongPositions = this.weightedPositions.NumberOfLongPositions; + if(numOfLongPositions == numOfWeightedPositions) + //there are only long positions + returnValue = true; + + return returnValue; + } + } + public bool OnlyShortPositions + { + get + { + bool returnValue = false; + int numOfWeightedPositions = this.weightedPositions.Count; + int numOfShortPositions = this.weightedPositions.NumberOfShortPositions; + if(numOfShortPositions == numOfWeightedPositions) + //there are only short positions + returnValue = true; + + return returnValue; + } + } + public bool BothLongAndShortPositions + { + get + { + bool returnValue = false; + int numOfWeightedPositions = this.weightedPositions.Count; + int numOfShortPositions = this.weightedPositions.NumberOfShortPositions; + int numOfLongPositions = this.weightedPositions.NumberOfLongPositions; + if(numOfShortPositions != numOfWeightedPositions && + numOfLongPositions != numOfWeightedPositions) + //there are both long and short positions + returnValue = true; + + return returnValue; + } + } public TestingPositions(WeightedPositions weightedPositions) *************** *** 89,92 **** this.fitnessInSample = double.MinValue; } ! } } --- 160,163 ---- this.fitnessInSample = double.MinValue; } ! } } |