Thread: [Quantproject-developers] QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOs
Brought to you by:
glauco_1
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv7565 Added Files: PVO_OTCLogItem.cs PVO_OTCMain.cs PVO_OTCStrategy.cs Log Message: Added objects for the PVO implementation (OTC and CTC) --- NEW FILE: PVO_OTCLogItem.cs --- /* QuantProject - Quantitative Finance Library PVO_OTCLogItem.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 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.Business.Timing; using QuantProject.Scripts.General.Reporting; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator { /// <summary> /// LogItem for the PVO_OTC strategy /// portfolio value oscillator strategy /// </summary> [Serializable] public class PVO_OTCLogItem : PVOLogItem { public PVO_OTCLogItem(EndOfDayDateTime endOfDayDateTime ) : base( endOfDayDateTime ) { } public override void Run() { //general int inSampleDays = 120; DateTime firstDateTime = this.SimulatedCreationTime.DateTime.AddDays(-inSampleDays); DateTime lastDateTime = this.SimulatedCreationTime.DateTime; double maxRunningHours = 1; Benchmark benchmark = new Benchmark( "^GSPC" ); // definition for the Fitness Evaluator (for // objects that use it) int numberOfPortfolioPositions = this.BestPVOPositionsInSample[0].WeightedPositions.Count; //cash and portfolio type double cashToStart = 30000; HistoricalQuoteProvider historicalQuoteProviderForBackTester, historicalQuoteProviderForInSampleChooser, historicalQuoteProviderForStrategy; historicalQuoteProviderForBackTester = new HistoricalAdjustedQuoteProvider(); historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester; historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser; IEligiblesSelector eligiblesSelector = new DummyEligibleSelector(); //strategyParameters TestingPositions[] positionsToTest = new TestingPositions[this.bestPVOPositionsInSample.Length]; positionsToTest = this.bestPVOPositionsInSample; PVO_OTCStrategy strategy = new PVO_OTCStrategy(eligiblesSelector, positionsToTest, inSampleDays, benchmark , int.MaxValue , ((PVOPositions)positionsToTest[0]).OversoldThreshold, ((PVOPositions)positionsToTest[0]).OverboughtThreshold, historicalQuoteProviderForStrategy); EndOfDayStrategyBackTester endOfDayStrategyBackTester = new EndOfDayStrategyBackTester( "PVO_OTC" , strategy , historicalQuoteProviderForBackTester , new SimpleAccountProvider(), firstDateTime , lastDateTime , benchmark , cashToStart , maxRunningHours ); // TO DO check if you can do this assign in the EndOfDayStrategyBackTester // constructor strategy.Account = endOfDayStrategyBackTester.Account; endOfDayStrategyBackTester.Run(); BackTesterReportViewer.ShowReport( lastDateTime , endOfDayStrategyBackTester ); } } } --- NEW FILE: PVO_OTCMain.cs --- /* QuantProject - Quantitative Finance Library PVO_OTCMain.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.Collections; using System.IO; using QuantProject.ADT; using QuantProject.ADT.FileManaging; using QuantProject.Business.DataProviders; using QuantProject.Business.Strategies; using QuantProject.Business.Financial.Accounting.AccountProviding; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.EquityEvaluation; using QuantProject.Business.Strategies.Logging; using QuantProject.Business.Strategies.Optimizing.Decoding; 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.General.Logging; using QuantProject.Scripts.General.Reporting; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator { /// <summary> /// Entry point for the PVO_OTC strategy. If any strategy /// parameter had to be changed, this is the place where it should /// be done /// </summary> public class PVO_OTCMain { private string strategyIdentifier; private string fileNameWithoutExt; private string dirNameWhereToSaveResults; public PVO_OTCMain() { this.strategyIdentifier = "PVO_OTC"; } private void setFileNamesAndDirectory(EndOfDayStrategyBackTester endOfDayStrategyBackTester) { if(this.fileNameWithoutExt == null) { this.fileNameWithoutExt = this.strategyIdentifier + "_" + DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + DateTime.Now.Second.ToString().PadLeft(2,'0'); this.dirNameWhereToSaveResults = System.Configuration.ConfigurationSettings.AppSettings["LogArchive"] + "\\" + fileNameWithoutExt + "\\"; if( !Directory.Exists(dirNameWhereToSaveResults) ) Directory.CreateDirectory(dirNameWhereToSaveResults); } } #region Run private MessageManager setMessageManager( IEligiblesSelector eligiblesSelector , IInSampleChooser inSampleChooser , IEndOfDayStrategy endOfDayStrategy , EndOfDayStrategyBackTester endOfDayStrategyBackTester ) { this.setFileNamesAndDirectory(endOfDayStrategyBackTester); string fullPathFileNameForMessagesLog = dirNameWhereToSaveResults + this.fileNameWithoutExt + "LogMessages.txt"; MessageManager messageManager = new MessageManager( fullPathFileNameForMessagesLog ); messageManager.Monitor( eligiblesSelector ); messageManager.Monitor( inSampleChooser ); // messageManager.Monitor( endOfDayStrategy ); messageManager.Monitor( endOfDayStrategyBackTester ); return messageManager; } // TO DO check if you can add this to QuantProject.Presentation.Reporting.WindowsForm.Report // as a public method or as a new constructor // private void showReport( // DateTime lastDateTimeRequestedForTheScript , // EndOfDayStrategyBackTester endOfDayStrategyBackTester ) // { //// DateTime lastReportDateTime = ExtendedDateTime.Min( //// lastDateTimeRequestedForTheScript , //// endOfDayStrategyBackTester.EndOfDayTimer.GetCurrentTime().DateTime ); // DateTime lastReportDateTime = // endOfDayStrategyBackTester.ActualLastDateTime; // Report report = new Report( // endOfDayStrategyBackTester.AccountReport , // true ); // report.Create( endOfDayStrategyBackTester.DescriptionForLogFileName , 1 , // new EndOfDayDateTime( lastReportDateTime , // EndOfDaySpecificTime.OneHourAfterMarketClose ) , // endOfDayStrategyBackTester.Benchmark.Ticker ); // report.Show(); // } //Saves (in silent mode): //- a log file where the In Sample Analysis are // stored; //- a report; //- a txt file with a full description of the // strategy's features private void saveScriptResults( EndOfDayStrategyBackTester endOfDayStrategyBackTester ) { this.setFileNamesAndDirectory(endOfDayStrategyBackTester); string fullPathFileNameForLog = dirNameWhereToSaveResults + this.fileNameWithoutExt + ".qpL"; string fullPathFileNameForReport = dirNameWhereToSaveResults + this.fileNameWithoutExt + ".qpR"; string fullPathFileNameForParametersLog = dirNameWhereToSaveResults + this.fileNameWithoutExt + "_Parameters.txt"; ObjectArchiver.Archive(endOfDayStrategyBackTester.Log, fullPathFileNameForLog); ObjectArchiver.Archive(endOfDayStrategyBackTester.AccountReport, fullPathFileNameForReport); StreamWriter w = File.AppendText(fullPathFileNameForParametersLog); w.WriteLine ("\n---\r\n"); w.WriteLine ( endOfDayStrategyBackTester.Description ); w.WriteLine ("\n---\r\n"); w.Flush(); w.Close(); } public void Run() { //general DateTime firstDateTime = new DateTime( 2000 , 6 , 1 ); DateTime lastDateTime = new DateTime( 2005 , 12 , 31 ); double maxRunningHours = 1.5; Benchmark benchmark = new Benchmark( "^GSPC" ); // definition for the Fitness Evaluator (for // objects that use it) //IEquityEvaluator equityEvaluator = new SharpeRatio(); //cash and portfolio type double cashToStart = 30000; //int numberOfPortfolioPositions = 4; // parameters for the in sample Chooser //double crossoverRate = 0.85; //double mutationRate = 0.02; //double elitismRate = 0.001; //int populationSizeForGeneticOptimizer = 500; // int generationNumberForGeneticOptimizer = 10; int numberOfBestTestingPositionsToBeReturnedInSample = 8; // int seedForRandomGenerator = // QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator; int numDaysBetweenEachOptimization = 15; // int minLevelForOversoldThreshold = 50; // int maxLevelForOversoldThreshold = 100; // int minLevelForOverboughtThreshold = 50; // int maxLevelForOverboughtThreshold = 100; // int divisorForThresholdComputation = 10000; // int numDaysForOscillatingPeriodForChooser = 1; //for genetic optimization // bool symmetricalThresholds = true; // bool overboughtMoreThanOversoldForFixedPortfolio = false; // double maxAcceptableCloseToCloseDrawdown = 0.03; // double minimumAcceptableGain = 0.008; // IDecoderForTestingPositions decoderForTestingPositions // = new BasicDecoderForPVOPositions(symmetricalThresholds, divisorForThresholdComputation , // numDaysForOscillatingPeriodForChooser); // IFitnessEvaluator fitnessEvaluator = // new PVOFitnessEvaluator( equityEvaluator ); HistoricalQuoteProvider historicalQuoteProviderForBackTester, historicalQuoteProviderForInSampleChooser, historicalQuoteProviderForStrategy; historicalQuoteProviderForBackTester = new HistoricalAdjustedQuoteProvider(); historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester; historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser; IInSampleChooser inSampleChooser = new PVO_OTCCorrelationChooser(numberOfBestTestingPositionsToBeReturnedInSample); //parameters for eligiblesSelector bool temporizedGroup = true; double minRawOpenPrice = 25; double maxRawOpenPrice = 500; int numDaysForAverageOpenRawPrice = 20; string tickersGroupId = "SP500"; int maxNumberOfEligiblesToBeChosen = 100; IEligiblesSelector eligiblesSelector = new ByPriceMostLiquidAlwaysQuoted( tickersGroupId , temporizedGroup, maxNumberOfEligiblesToBeChosen, numDaysForAverageOpenRawPrice , minRawOpenPrice , maxRawOpenPrice ); //strategyParameters double oversoldThreshold = 0.0075; double overboughtThreshold = 0.0075; int inSampleDays = 120; PVO_OTCStrategy strategy = new PVO_OTCStrategy(eligiblesSelector, inSampleChooser, inSampleDays, benchmark , numDaysBetweenEachOptimization , oversoldThreshold , overboughtThreshold , historicalQuoteProviderForStrategy ); EndOfDayStrategyBackTester endOfDayStrategyBackTester = new EndOfDayStrategyBackTester( this.strategyIdentifier , strategy , historicalQuoteProviderForBackTester , new SimpleAccountProvider(),firstDateTime , lastDateTime , benchmark , cashToStart , maxRunningHours ); MessageManager messageManager = this.setMessageManager( eligiblesSelector , inSampleChooser , strategy , endOfDayStrategyBackTester ); endOfDayStrategyBackTester.Run(); this.saveScriptResults(endOfDayStrategyBackTester); } #endregion Run } } --- NEW FILE: PVO_OTCStrategy.cs --- /* QuantProject - Quantitative Finance Library PVO_OTCStrategy.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 QuantProject.ADT; using QuantProject.ADT.Messaging; 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.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.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator { /// <summary> /// Implements MarketOpenEventHandler and MarketCloseEventHandler /// These handlers contain the core strategy for the Portfolio Value /// Oscillator /// </summary> [Serializable] public class PVO_OTCStrategy : IEndOfDayStrategyForBacktester { public event NewLogItemEventHandler NewLogItem; public event NewMessageEventHandler NewMessage; //initialized by the constructor protected int inSampleDays; protected int numDaysBetweenEachOptimization; protected IInSampleChooser inSampleChooser; protected IEligiblesSelector eligiblesSelector; protected Benchmark benchmark; protected HistoricalQuoteProvider historicalQuoteProvider; protected double oversoldThreshold; protected double overboughtThreshold; //initialized after constructor's call protected int numDaysElapsedSinceLastOptimization; protected ReturnsManager returnsManager; protected TestingPositions[] chosenPVOPositions; //chosen in sample: these are the eligible positions for out //of sample testing protected PVOPositions pvoPositionsForOutOfSample; protected DateTime lastCloseDate; protected Account account; public Account Account { get { return this.account; } set { this.account = value; } } private string description_GetDescriptionForChooser() { if(this.inSampleChooser == null) return "ConstantChooser"; else return this.inSampleChooser.Description; } public string Description { get { string description = "PVO_OTC\n" + "Tickers_" + "2\n" + "_inSampleDays_" + this.inSampleDays.ToString() + "\n" + this.eligiblesSelector.Description + "\n" + "oversoldThreshold_" + this.oversoldThreshold.ToString() + "\n" + "overboughtThreshold_" + this.overboughtThreshold.ToString() + "\n" + this.description_GetDescriptionForChooser() + "\n" + "Optimization each " + this.numDaysBetweenEachOptimization.ToString() + " days"; return description; } } public bool StopBacktestIfMaxRunningHoursHasBeenReached { get { return true; } } private void pvo_otcStrategy(IEligiblesSelector eligiblesSelector, int inSampleDays, Benchmark benchmark, int numDaysBetweenEachOptimization, double oversoldThreshold, double overboughtThreshold, HistoricalQuoteProvider historicalQuoteProvider) { this.eligiblesSelector = eligiblesSelector; this.inSampleDays = inSampleDays; this.benchmark = benchmark; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.oversoldThreshold = oversoldThreshold; this.overboughtThreshold = overboughtThreshold; this.historicalQuoteProvider = historicalQuoteProvider; } public PVO_OTCStrategy(IEligiblesSelector eligiblesSelector, IInSampleChooser inSampleChooser, int inSampleDays, Benchmark benchmark, int numDaysBetweenEachOptimization, double oversoldThreshold, double overboughtThreshold, HistoricalQuoteProvider historicalQuoteProvider) { this.pvo_otcStrategy(eligiblesSelector, inSampleDays , benchmark , numDaysBetweenEachOptimization , oversoldThreshold, overboughtThreshold, historicalQuoteProvider); this.inSampleChooser = inSampleChooser; } public PVO_OTCStrategy(IEligiblesSelector eligiblesSelector, TestingPositions[] chosenPVOPositions, int inSampleDays, Benchmark benchmark, int numDaysBetweenEachOptimization, double oversoldThreshold, double overboughtThreshold, HistoricalQuoteProvider historicalQuoteProvider) { this.pvo_otcStrategy(eligiblesSelector, inSampleDays , benchmark , numDaysBetweenEachOptimization , oversoldThreshold, overboughtThreshold, historicalQuoteProvider); this.chosenPVOPositions = chosenPVOPositions; } #region MarketOpenEventHandler protected virtual EndOfDayDateTime getBeginOfOscillatingPeriod(IndexBasedEndOfDayTimer timer) { return new EndOfDayDateTime( (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition-1]["quDate"], EndOfDaySpecificTime.MarketClose ); } private PVOPositionsStatus marketOpenEventHandler_openPositions_getStatus(IndexBasedEndOfDayTimer timer) { EndOfDayDateTime today = timer.GetCurrentTime(); EndOfDayDateTime beginOfOscillatingPeriod = this.getBeginOfOscillatingPeriod(timer); PVOPositionsStatus currentStatus = PVOPositionsStatus.InTheMiddle; for(int i = 0; i<this.chosenPVOPositions.Length; i++) { if(this.chosenPVOPositions[i] != null) currentStatus = ((PVOPositions)this.chosenPVOPositions[i]).GetStatus(beginOfOscillatingPeriod, today, this.benchmark.Ticker, this.historicalQuoteProvider); if(currentStatus == PVOPositionsStatus.Oversold || currentStatus == PVOPositionsStatus.Overbought ) { this.pvoPositionsForOutOfSample = (PVOPositions)this.chosenPVOPositions[i]; i = this.chosenPVOPositions.Length;//exit from for } } return currentStatus; } protected void marketOpenEventHandler_openPositions(IndexBasedEndOfDayTimer timer) { PVOPositionsStatus pvoPositionsStatus = PVOPositionsStatus.InTheMiddle; if(timer.CurrentDateArrayPosition >= 1) pvoPositionsStatus = this.marketOpenEventHandler_openPositions_getStatus(timer); switch (pvoPositionsStatus) { case PVOPositionsStatus.Overbought: { #region manage Overbought case this.pvoPositionsForOutOfSample.WeightedPositions.Reverse(); try { AccountManager.OpenPositions( this.pvoPositionsForOutOfSample.WeightedPositions, this.account ); } catch(Exception ex) { ex = ex; } finally { this.pvoPositionsForOutOfSample.WeightedPositions.Reverse(); } #endregion break; } case PVOPositionsStatus.Oversold: { AccountManager.OpenPositions( this.pvoPositionsForOutOfSample.WeightedPositions, this.account ); break; } case PVOPositionsStatus.InTheMiddle://that is { //pvoPositionsForOutOfSample has not been set break; } default: { //it should never been reached break; } } } public virtual void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { if ( this.account.Portfolio.Count == 0 && this.chosenPVOPositions != null ) //portfolio is empty and optimization has //been already launched { try{ this.marketOpenEventHandler_openPositions( (IndexBasedEndOfDayTimer)sender ); } catch(TickerNotExchangedException ex) {ex=ex;} } } #endregion public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { } private EndOfDayDateTime now() { return this.account.EndOfDayTimer.GetCurrentTime(); } public virtual void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { if(this.account.Portfolio.Count > 0) AccountManager.ClosePositions(this.account); } #region OneHourAfterMarketCloseEventHandler protected virtual void updateReturnsManager(EndOfDayDateTime firstEndOfDayDateTime, EndOfDayDateTime lastEndOfDayDateTime) { this.returnsManager = new ReturnsManager( new DailyOpenToCloseIntervals(firstEndOfDayDateTime, lastEndOfDayDateTime, this.benchmark.Ticker ) , this.historicalQuoteProvider); } private PVO_OTCLogItem getLogItem( EligibleTickers eligibleTickers ) { PVO_OTCLogItem logItem = new PVO_OTCLogItem( this.now() ); logItem.BestPVOPositionsInSample = this.chosenPVOPositions; logItem.NumberOfEligibleTickers = eligibleTickers.Count; logItem.FitnessOfFirst = this.chosenPVOPositions[0].FitnessInSample; logItem.FitnessOfLast = this.chosenPVOPositions[this.chosenPVOPositions.Length - 1].FitnessInSample; // logItem.GenerationOfFirst = // ((IGeneticallyOptimizable)this.chosenPVOPositions[0]).Generation; // logItem.GenerationOfLast = // ((IGeneticallyOptimizable)this.chosenPVOPositions[this.chosenPVOPositions.Length - 1]).Generation; logItem.ThresholdsOfFirst = ((PVOPositions)this.chosenPVOPositions[0]).OversoldThreshold.ToString() + ";" + ((PVOPositions)this.chosenPVOPositions[0]).OverboughtThreshold.ToString(); logItem.ThresholdsOfLast = ((PVOPositions)this.chosenPVOPositions[this.chosenPVOPositions.Length - 1]).OversoldThreshold.ToString() + ";" + ((PVOPositions)this.chosenPVOPositions[this.chosenPVOPositions.Length - 1]).OverboughtThreshold.ToString(); logItem.TickersOfFirst = this.chosenPVOPositions[0].HashCodeForTickerComposition; logItem.TickersOfLast = this.chosenPVOPositions[this.chosenPVOPositions.Length - 1].HashCodeForTickerComposition; return logItem; } private void raiseNewLogItem( EligibleTickers eligibleTickers ) { PVO_OTCLogItem 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 ) { this.raiseNewLogItem( eligibleTickers ); this.notifyMessage( eligibleTickers ); } private void updateTestingPositions_updateThresholds() { for(int i = 0; i<this.chosenPVOPositions.Length; i++) { ((PVOPositions)this.chosenPVOPositions[i]).OversoldThreshold = this.oversoldThreshold; ((PVOPositions)this.chosenPVOPositions[i]).OverboughtThreshold = this.overboughtThreshold; } } protected virtual void updateTestingPositions(DateTime currentDate) { EndOfDayHistory endOfDayHistory = this.benchmark.GetEndOfDayHistory( new EndOfDayDateTime(currentDate.AddDays(-this.inSampleDays), EndOfDaySpecificTime.MarketOpen), new EndOfDayDateTime(currentDate, EndOfDaySpecificTime.MarketClose)); EligibleTickers eligibles = this.eligiblesSelector.GetEligibleTickers(endOfDayHistory); this.updateReturnsManager(endOfDayHistory.FirstEndOfDayDateTime, endOfDayHistory.LastEndOfDayDateTime); if(this.inSampleChooser != null) this.chosenPVOPositions = (TestingPositions[])inSampleChooser.AnalyzeInSample(eligibles, this.returnsManager); this.updateTestingPositions_updateThresholds(); this.logOptimizationInfo(eligibles); } /// <summary> /// Handles a "One hour after market close" event. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> public virtual void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { this.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; this.numDaysElapsedSinceLastOptimization++; if((this.numDaysElapsedSinceLastOptimization == this.numDaysBetweenEachOptimization)) //num days without optimization has elapsed { this.updateTestingPositions(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime); //sets tickers to be chosen next Market Close event this.numDaysElapsedSinceLastOptimization = 0; } } #endregion } } |