quantproject-developers Mailing List for QuantProject (Page 90)
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...> - 2006-05-14 18:21:50
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv32410/b7_Scripts/TickerSelectionTesting Modified Files: RunEfficientOTCPortfolio.cs RunEfficientCTOPortfolio.cs Log Message: Minor changes for some RunScript files Index: RunEfficientOTCPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/RunEfficientOTCPortfolio.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunEfficientOTCPortfolio.cs 7 Jan 2006 10:35:39 -0000 1.1 --- RunEfficientOTCPortfolio.cs 14 May 2006 18:21:47 -0000 1.2 *************** *** 70,74 **** //this.ScriptName = "OpenCloseScriptsSharpeRatioWithCoeff"; //this.ScriptName = "OpenCloseScriptsSharpeRatio"; ! this.ScriptName = "OpenCloseScriptsWithCoeff"; //this.ScriptName = "OpenCloseScripts"; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; --- 70,74 ---- //this.ScriptName = "OpenCloseScriptsSharpeRatioWithCoeff"; //this.ScriptName = "OpenCloseScriptsSharpeRatio"; ! this.ScriptName = "OpenCloseScriptsSharpeRatioNoCoeff"; //this.ScriptName = "OpenCloseScripts"; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; *************** *** 85,92 **** this.historicalQuoteProvider ) , new HistoricalEndOfDayOrderExecutor(this.endOfDayTimer , ! this.historicalQuoteProvider, ! new FixedPercentageSlippageManager(this.historicalQuoteProvider, ! this.endOfDayTimer,0.08)), ! new IBCommissionManager()); } --- 85,93 ---- this.historicalQuoteProvider ) , new HistoricalEndOfDayOrderExecutor(this.endOfDayTimer , ! this.historicalQuoteProvider)//, ! // new FixedPercentageSlippageManager(this.historicalQuoteProvider, ! // this.endOfDayTimer,0.08)), ! ); ! //new IBCommissionManager()); } Index: RunEfficientCTOPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/RunEfficientCTOPortfolio.cs,v retrieving revision 1.26 retrieving revision 1.27 diff -C2 -d -r1.26 -r1.27 *** RunEfficientCTOPortfolio.cs 7 Jan 2006 10:35:39 -0000 1.26 --- RunEfficientCTOPortfolio.cs 14 May 2006 18:21:47 -0000 1.27 *************** *** 68,72 **** portfolioType, maxRunningHours) { ! this.ScriptName = "CloseToOpenScriptsNoCoeff"; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } --- 68,72 ---- portfolioType, maxRunningHours) { ! this.ScriptName = "CloseToOpenScriptsNoCoeffSharpeRatioCombined"; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } |
|
From: Marco M. <mi...@us...> - 2006-05-14 18:21:49
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/SimpleSelection In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv32410/b7_Scripts/TickerSelectionTesting/SimpleSelection Modified Files: RunSimpleSelectionOpenToClose.cs Log Message: Minor changes for some RunScript files Index: RunSimpleSelectionOpenToClose.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/SimpleSelection/RunSimpleSelectionOpenToClose.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunSimpleSelectionOpenToClose.cs 21 Oct 2005 17:54:11 -0000 1.1 --- RunSimpleSelectionOpenToClose.cs 14 May 2006 18:21:47 -0000 1.2 *************** *** 64,68 **** portfolioType, maxRunningHours) { ! this.ScriptName = "SimpleSelectionOpenToClose"; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } --- 64,68 ---- portfolioType, maxRunningHours) { ! this.ScriptName = "SimpleSelectionOpenToCloseSharpeRatio"; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } |
|
From: Marco M. <mi...@us...> - 2006-05-14 18:18:27
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv31410/b7_Scripts/WalkForwardTesting/LinearCombination Modified Files: TestDisplayer.cs StrategyType.cs LinearCombinationTest.cs Log Message: With the TestDisplayer is now possible to test genomes optimized for the FixedPeriodOscillator and the ExtremeCounterTrend strategies Index: LinearCombinationTest.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/LinearCombinationTest.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** LinearCombinationTest.cs 14 Mar 2006 14:53:54 -0000 1.5 --- LinearCombinationTest.cs 14 May 2006 18:18:23 -0000 1.6 *************** *** 46,49 **** --- 46,50 ---- // private bool openToCloseDaily; private StrategyType strategyType; + private int numDaysForOscillatorStrategy; private IHistoricalQuoteProvider historicalQuoteProvider; *************** *** 61,66 **** this.strategyType = strategyType; } ! ! private void oneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { --- 62,79 ---- this.strategyType = strategyType; } ! ! public LinearCombinationTest( DateTime firstDate , DateTime lastDate , ! GenomeRepresentation genomeRepresentation , StrategyType strategyType, ! int numDaysForOscillatorStrategy) ! { ! this.firstDate = firstDate; ! this.lastDate = lastDate; ! this.genomeRepresentation = genomeRepresentation; ! // this.openToCloseDaily = openToCloseDaily; ! this.strategyType = strategyType; ! this.numDaysForOscillatorStrategy = numDaysForOscillatorStrategy; ! } ! ! private void oneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { *************** *** 95,98 **** --- 108,121 ---- this.account , signedTickers ); break; + + case StrategyType.FixedPeriodOscillator: + this.endOfDayStrategy = new FixedPeriodOscillatorStrategy( + this.account , signedTickers , this.numDaysForOscillatorStrategy , this.numDaysForOscillatorStrategy ); + break; + + case StrategyType.ExtremeCounterTrend: + this.endOfDayStrategy = new ExtremeCounterTrendStrategy( + this.account , signedTickers , this.numDaysForOscillatorStrategy ); + break; } } *************** *** 121,125 **** new IndexBasedEndOfDayTimer( new EndOfDayDateTime( this.firstDate , ! EndOfDaySpecificTime.MarketOpen ) , "MSFT" ); run_setHistoricalQuoteProvider(); this.account = new Account( "LinearCombination" , historicalEndOfDayTimer , --- 144,148 ---- new IndexBasedEndOfDayTimer( new EndOfDayDateTime( this.firstDate , ! EndOfDaySpecificTime.MarketOpen ) , "^GSPC" ); run_setHistoricalQuoteProvider(); this.account = new Account( "LinearCombination" , historicalEndOfDayTimer , *************** *** 148,152 **** report.Create( "Linear Combination" , 1 , new EndOfDayDateTime( this.lastDate , EndOfDaySpecificTime.MarketClose ) , ! "MSFT" ); // ObjectArchiver.Archive( report.AccountReport , // @"C:\Documents and Settings\Glauco\Desktop\reports\runOneRank.qPr" ); --- 171,176 ---- report.Create( "Linear Combination" , 1 , new EndOfDayDateTime( this.lastDate , EndOfDaySpecificTime.MarketClose ) , ! "^GSPC"); ! // ObjectArchiver.Archive( report.AccountReport , // @"C:\Documents and Settings\Glauco\Desktop\reports\runOneRank.qPr" ); Index: StrategyType.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/StrategyType.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** StrategyType.cs 8 Jan 2006 23:33:52 -0000 1.1 --- StrategyType.cs 14 May 2006 18:18:23 -0000 1.2 *************** *** 32,36 **** OpenToCloseDaily, OpenToCloseWeekly, ! CloseToOpenDaily } } --- 32,38 ---- OpenToCloseDaily, OpenToCloseWeekly, ! CloseToOpenDaily, ! FixedPeriodOscillator, ! ExtremeCounterTrend } } Index: TestDisplayer.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination/TestDisplayer.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** TestDisplayer.cs 8 Jan 2006 23:33:52 -0000 1.6 --- TestDisplayer.cs 14 May 2006 18:18:23 -0000 1.7 *************** *** 35,38 **** --- 35,48 ---- public class TestDisplayer : System.Windows.Forms.Form { + private System.Windows.Forms.Label labelDays; + private System.Windows.Forms.TextBox textBoxDaysFPOscillatorAndRevOneRank; + private System.Windows.Forms.Label label1; + private System.Windows.Forms.RadioButton radioButtonOpenToCloseDaily; + private System.Windows.Forms.RadioButton radioButtonReversalOneRank; + private System.Windows.Forms.DateTimePicker dtpLastDate; + private System.Windows.Forms.DateTimePicker dtpFirstDate; + private System.Windows.Forms.RadioButton radioButtonFixedPeriodOscillator; + private System.Windows.Forms.RadioButton radioButtonOpenToCloseWeekly; + private System.Windows.Forms.RadioButton radioButtonCloseToOpenDaily; private System.Windows.Forms.DataGrid dgBestGenomes; /// <summary> *************** *** 40,52 **** /// </summary> private System.ComponentModel.Container components = null; - private System.Windows.Forms.DateTimePicker dtpFirstDate; - private System.Windows.Forms.DateTimePicker dtpLastDate; // Glauco code private ArrayList bestGenomes; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.RadioButton radioButtonOpenToCloseDaily; - private System.Windows.Forms.RadioButton radioButtonOpenToCloseWeekly; - private System.Windows.Forms.RadioButton radioButtonCloseToOpenDaily; private GenomeRepresentation lastSelectedGenomeRepresentation; private StrategyType selectedStrategyType = StrategyType.OpenToCloseDaily; --- 50,56 ---- *************** *** 98,193 **** /// the contents of this method with the code editor. /// </summary> ! private void InitializeComponent() ! { ! this.dgBestGenomes = new System.Windows.Forms.DataGrid(); ! this.dtpFirstDate = new System.Windows.Forms.DateTimePicker(); ! this.dtpLastDate = new System.Windows.Forms.DateTimePicker(); ! this.label1 = new System.Windows.Forms.Label(); ! this.radioButtonOpenToCloseDaily = new System.Windows.Forms.RadioButton(); ! this.radioButtonOpenToCloseWeekly = new System.Windows.Forms.RadioButton(); ! this.radioButtonCloseToOpenDaily = new System.Windows.Forms.RadioButton(); ! ((System.ComponentModel.ISupportInitialize)(this.dgBestGenomes)).BeginInit(); ! this.SuspendLayout(); ! // ! // dgBestGenomes ! // ! this.dgBestGenomes.DataMember = ""; ! this.dgBestGenomes.Dock = System.Windows.Forms.DockStyle.Bottom; ! this.dgBestGenomes.HeaderForeColor = System.Drawing.SystemColors.ControlText; ! this.dgBestGenomes.Location = new System.Drawing.Point(0, 157); ! this.dgBestGenomes.Name = "dgBestGenomes"; ! this.dgBestGenomes.Size = new System.Drawing.Size(584, 216); ! this.dgBestGenomes.TabIndex = 0; ! this.dgBestGenomes.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dgBestGenomes_MouseUp); ! // ! // dtpFirstDate ! // ! this.dtpFirstDate.Location = new System.Drawing.Point(16, 24); ! this.dtpFirstDate.Name = "dtpFirstDate"; ! this.dtpFirstDate.TabIndex = 1; ! // ! // dtpLastDate ! // ! this.dtpLastDate.Location = new System.Drawing.Point(264, 24); ! this.dtpLastDate.Name = "dtpLastDate"; ! this.dtpLastDate.Size = new System.Drawing.Size(208, 20); ! this.dtpLastDate.TabIndex = 2; ! // ! // label1 ! // ! this.label1.Location = new System.Drawing.Point(32, 64); ! this.label1.Name = "label1"; ! this.label1.Size = new System.Drawing.Size(400, 40); ! this.label1.TabIndex = 3; ! this.label1.Text = "Left click data grid rows to reset dates to the optimization period. Right click " + ! "to preserve date displacements and backtest."; ! // ! // radioButtonOpenToCloseDaily ! // ! this.radioButtonOpenToCloseDaily.Checked = true; ! this.radioButtonOpenToCloseDaily.Location = new System.Drawing.Point(64, 96); ! this.radioButtonOpenToCloseDaily.Name = "radioButtonOpenToCloseDaily"; ! this.radioButtonOpenToCloseDaily.Size = new System.Drawing.Size(144, 24); ! this.radioButtonOpenToCloseDaily.TabIndex = 4; ! this.radioButtonOpenToCloseDaily.TabStop = true; ! this.radioButtonOpenToCloseDaily.Text = "Open To Close Daily"; ! this.radioButtonOpenToCloseDaily.CheckedChanged += new System.EventHandler(this.radioButtonOpenToCloseDaily_CheckedChanged); ! // ! // radioButtonOpenToCloseWeekly ! // ! this.radioButtonOpenToCloseWeekly.Location = new System.Drawing.Point(224, 96); ! this.radioButtonOpenToCloseWeekly.Name = "radioButtonOpenToCloseWeekly"; ! this.radioButtonOpenToCloseWeekly.Size = new System.Drawing.Size(144, 24); ! this.radioButtonOpenToCloseWeekly.TabIndex = 5; ! this.radioButtonOpenToCloseWeekly.Text = "Open To Close Weekly"; ! this.radioButtonOpenToCloseWeekly.CheckedChanged += new System.EventHandler(this.radioButtonOpenToCloseWeekly_CheckedChanged); ! // ! // radioButtonCloseToOpenDaily ! // ! this.radioButtonCloseToOpenDaily.Location = new System.Drawing.Point(64, 128); ! this.radioButtonCloseToOpenDaily.Name = "radioButtonCloseToOpenDaily"; ! this.radioButtonCloseToOpenDaily.Size = new System.Drawing.Size(144, 24); ! this.radioButtonCloseToOpenDaily.TabIndex = 6; ! this.radioButtonCloseToOpenDaily.Text = "Close To Open Daily"; ! this.radioButtonCloseToOpenDaily.CheckedChanged += new System.EventHandler(this.radioButtonCloseToOpenDaily_CheckedChanged); ! // ! // TestDisplayer ! // ! this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); ! this.ClientSize = new System.Drawing.Size(584, 373); ! this.Controls.AddRange(new System.Windows.Forms.Control[] { ! this.radioButtonCloseToOpenDaily, ! this.radioButtonOpenToCloseWeekly, ! this.radioButtonOpenToCloseDaily, ! this.label1, ! this.dtpLastDate, ! this.dtpFirstDate, ! this.dgBestGenomes}); ! this.Name = "TestDisplayer"; ! this.Text = "TestDisplayer"; ! ((System.ComponentModel.ISupportInitialize)(this.dgBestGenomes)).EndInit(); ! this.ResumeLayout(false); ! ! } #endregion --- 102,234 ---- /// the contents of this method with the code editor. /// </summary> ! private void InitializeComponent() { ! this.dgBestGenomes = new System.Windows.Forms.DataGrid(); ! this.radioButtonCloseToOpenDaily = new System.Windows.Forms.RadioButton(); ! this.radioButtonOpenToCloseWeekly = new System.Windows.Forms.RadioButton(); ! this.radioButtonFixedPeriodOscillator = new System.Windows.Forms.RadioButton(); ! this.dtpFirstDate = new System.Windows.Forms.DateTimePicker(); ! this.dtpLastDate = new System.Windows.Forms.DateTimePicker(); ! this.radioButtonReversalOneRank = new System.Windows.Forms.RadioButton(); ! this.radioButtonOpenToCloseDaily = new System.Windows.Forms.RadioButton(); ! this.label1 = new System.Windows.Forms.Label(); ! this.textBoxDaysFPOscillatorAndRevOneRank = new System.Windows.Forms.TextBox(); ! this.labelDays = new System.Windows.Forms.Label(); ! ((System.ComponentModel.ISupportInitialize)(this.dgBestGenomes)).BeginInit(); ! this.SuspendLayout(); ! // ! // dgBestGenomes ! // ! this.dgBestGenomes.DataMember = ""; ! this.dgBestGenomes.Dock = System.Windows.Forms.DockStyle.Bottom; ! this.dgBestGenomes.HeaderForeColor = System.Drawing.SystemColors.ControlText; ! this.dgBestGenomes.Location = new System.Drawing.Point(0, 205); ! this.dgBestGenomes.Name = "dgBestGenomes"; ! this.dgBestGenomes.Size = new System.Drawing.Size(584, 168); ! this.dgBestGenomes.TabIndex = 0; ! this.dgBestGenomes.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dgBestGenomes_MouseUp); ! // ! // radioButtonCloseToOpenDaily ! // ! this.radioButtonCloseToOpenDaily.Location = new System.Drawing.Point(64, 120); ! this.radioButtonCloseToOpenDaily.Name = "radioButtonCloseToOpenDaily"; ! this.radioButtonCloseToOpenDaily.Size = new System.Drawing.Size(144, 24); ! this.radioButtonCloseToOpenDaily.TabIndex = 6; ! this.radioButtonCloseToOpenDaily.Text = "Close To Open Daily"; ! this.radioButtonCloseToOpenDaily.CheckedChanged += new System.EventHandler(this.radioButtonCloseToOpenDaily_CheckedChanged); ! // ! // radioButtonOpenToCloseWeekly ! // ! this.radioButtonOpenToCloseWeekly.Location = new System.Drawing.Point(64, 144); ! this.radioButtonOpenToCloseWeekly.Name = "radioButtonOpenToCloseWeekly"; ! this.radioButtonOpenToCloseWeekly.Size = new System.Drawing.Size(144, 24); ! this.radioButtonOpenToCloseWeekly.TabIndex = 5; ! this.radioButtonOpenToCloseWeekly.Text = "Open To Close Weekly"; ! this.radioButtonOpenToCloseWeekly.CheckedChanged += new System.EventHandler(this.radioButtonOpenToCloseWeekly_CheckedChanged); ! // ! // radioButtonFixedPeriodOscillator ! // ! this.radioButtonFixedPeriodOscillator.Location = new System.Drawing.Point(232, 96); ! this.radioButtonFixedPeriodOscillator.Name = "radioButtonFixedPeriodOscillator"; ! this.radioButtonFixedPeriodOscillator.Size = new System.Drawing.Size(192, 24); ! this.radioButtonFixedPeriodOscillator.TabIndex = 7; ! this.radioButtonFixedPeriodOscillator.Text = "Fixed Period n-days oscillator"; ! this.radioButtonFixedPeriodOscillator.CheckedChanged += new System.EventHandler(this.radioButtonFixedPeriodOscillator_CheckedChanged); ! // ! // dtpFirstDate ! // ! this.dtpFirstDate.Location = new System.Drawing.Point(16, 24); ! this.dtpFirstDate.Name = "dtpFirstDate"; ! this.dtpFirstDate.TabIndex = 1; ! // ! // dtpLastDate ! // ! this.dtpLastDate.Location = new System.Drawing.Point(264, 24); ! this.dtpLastDate.Name = "dtpLastDate"; ! this.dtpLastDate.Size = new System.Drawing.Size(208, 21); ! this.dtpLastDate.TabIndex = 2; ! // ! // radioButtonReversalOneRank ! // ! this.radioButtonReversalOneRank.Location = new System.Drawing.Point(232, 120); ! this.radioButtonReversalOneRank.Name = "radioButtonReversalOneRank"; ! this.radioButtonReversalOneRank.Size = new System.Drawing.Size(192, 24); ! this.radioButtonReversalOneRank.TabIndex = 10; ! this.radioButtonReversalOneRank.Text = "Extreme counter trend"; ! this.radioButtonReversalOneRank.CheckedChanged += new System.EventHandler(this.radioButtonReversalOneRank_CheckedChanged); ! // ! // radioButtonOpenToCloseDaily ! // ! this.radioButtonOpenToCloseDaily.Location = new System.Drawing.Point(64, 96); ! this.radioButtonOpenToCloseDaily.Name = "radioButtonOpenToCloseDaily"; ! this.radioButtonOpenToCloseDaily.Size = new System.Drawing.Size(144, 24); ! this.radioButtonOpenToCloseDaily.TabIndex = 4; ! this.radioButtonOpenToCloseDaily.Text = "Open To Close Daily"; ! this.radioButtonOpenToCloseDaily.CheckedChanged += new System.EventHandler(this.radioButtonOpenToCloseDaily_CheckedChanged); ! // ! // label1 ! // ! this.label1.Location = new System.Drawing.Point(32, 64); ! this.label1.Name = "label1"; ! this.label1.Size = new System.Drawing.Size(400, 40); ! this.label1.TabIndex = 3; ! this.label1.Text = "Left click data grid rows to reset dates to the optimization period. Right click " + ! "to preserve date displacements and backtest."; ! // ! // textBoxDaysFPOscillatorAndRevOneRank ! // ! this.textBoxDaysFPOscillatorAndRevOneRank.Location = new System.Drawing.Point(320, 152); ! this.textBoxDaysFPOscillatorAndRevOneRank.Name = "textBoxDaysFPOscillatorAndRevOneRank"; ! this.textBoxDaysFPOscillatorAndRevOneRank.Size = new System.Drawing.Size(56, 21); ! this.textBoxDaysFPOscillatorAndRevOneRank.TabIndex = 8; ! this.textBoxDaysFPOscillatorAndRevOneRank.Text = ""; ! // ! // labelDays ! // ! this.labelDays.Location = new System.Drawing.Point(272, 152); ! this.labelDays.Name = "labelDays"; ! this.labelDays.Size = new System.Drawing.Size(40, 16); ! this.labelDays.TabIndex = 9; ! this.labelDays.Text = "days"; ! // ! // TestDisplayer ! // ! this.AutoScaleBaseSize = new System.Drawing.Size(5, 14); ! this.ClientSize = new System.Drawing.Size(584, 373); ! this.Controls.Add(this.radioButtonReversalOneRank); ! this.Controls.Add(this.labelDays); ! this.Controls.Add(this.textBoxDaysFPOscillatorAndRevOneRank); ! this.Controls.Add(this.radioButtonFixedPeriodOscillator); ! this.Controls.Add(this.radioButtonCloseToOpenDaily); ! this.Controls.Add(this.radioButtonOpenToCloseWeekly); ! this.Controls.Add(this.radioButtonOpenToCloseDaily); ! this.Controls.Add(this.label1); ! this.Controls.Add(this.dtpLastDate); ! this.Controls.Add(this.dtpFirstDate); ! this.Controls.Add(this.dgBestGenomes); ! this.Name = "TestDisplayer"; ! this.Text = "TestDisplayer"; ! ((System.ComponentModel.ISupportInitialize)(this.dgBestGenomes)).EndInit(); ! this.ResumeLayout(false); ! } #endregion *************** *** 239,243 **** new LinearCombinationTest( this.dtpFirstDate.Value , this.dtpLastDate.Value , genomeRepresentation , ! this.selectedStrategyType); linearCombinationTest.Run(); this.lastSelectedGenomeRepresentation = genomeRepresentation; --- 280,284 ---- new LinearCombinationTest( this.dtpFirstDate.Value , this.dtpLastDate.Value , genomeRepresentation , ! this.selectedStrategyType, Convert.ToInt32(this.textBoxDaysFPOscillatorAndRevOneRank.Text)); linearCombinationTest.Run(); this.lastSelectedGenomeRepresentation = genomeRepresentation; *************** *** 278,282 **** --- 319,328 ---- else if(this.radioButtonCloseToOpenDaily.Checked) this.selectedStrategyType = StrategyType.CloseToOpenDaily; + else if(this.radioButtonFixedPeriodOscillator.Checked) + this.selectedStrategyType = StrategyType.FixedPeriodOscillator; + else if(this.radioButtonReversalOneRank.Checked) + this.selectedStrategyType = StrategyType.ExtremeCounterTrend; } + private void radioButtonOpenToCloseDaily_CheckedChanged(object sender, System.EventArgs e) { *************** *** 293,296 **** --- 339,352 ---- this.update_selectedStrategyType(); } + + private void radioButtonFixedPeriodOscillator_CheckedChanged(object sender, System.EventArgs e) + { + this.update_selectedStrategyType(); + } + + private void radioButtonReversalOneRank_CheckedChanged(object sender, System.EventArgs e) + { + this.update_selectedStrategyType(); + } } } |
|
From: Marco M. <mi...@us...> - 2006-05-14 18:13:20
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearCombination In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv29793/b7_Scripts/WalkForwardTesting/LinearCombination Added Files: FixedPeriodOscillatorStrategy.cs ExtremeCounterTrendStrategy.cs Log Message: Added strategies FixedPeriodOscillator and ExtremeCounterTrend, to be used by the TestDisplayer (for testing best genomes found during genetic optimization process) --- NEW FILE: FixedPeriodOscillatorStrategy.cs --- /* QuantProject - Quantitative Finance Library FixedPeriodOscillatorStrategy.cs Copyright (C) 2003 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Strategies; using QuantProject.Business.Timing; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.WalkForwardTesting.LinearCombination { /// <summary> /// Close To Close Oscillator strategy /// </summary> [Serializable] public class FixedPeriodOscillatorStrategy : IEndOfDayStrategy { private Account account; private string[] signedTickers; private int daysForRightPeriod; private int daysForReversalPeriod; //length for movement upwards or downwards of the given tickers private int daysCounterWithRightPositions; private int daysCounterWithReversalPositions; private bool isReversalPeriodOn = false; private int numOfClosesElapsed = 0; public FixedPeriodOscillatorStrategy( Account account , string[] signedTickers, int daysForRightPeriod, int daysForReversalPeriod) { this.account = account; this.signedTickers = signedTickers; this.daysForRightPeriod = daysForRightPeriod; this.daysForReversalPeriod = daysForReversalPeriod; } private long marketCloseEventHandler_addOrder_getQuantity( string ticker ) { double accountValue = this.account.GetMarketValue(); double currentTickerAsk = this.account.DataStreamer.GetCurrentAsk( ticker ); double maxPositionValueForThisTicker = accountValue/this.signedTickers.Length; long quantity = Convert.ToInt64( Math.Floor( maxPositionValueForThisTicker / currentTickerAsk ) ); return quantity; } private void marketCloseEventHandler_addOrder( string signedTicker ) { OrderType orderType = GenomeRepresentation.GetOrderType( signedTicker ); string ticker = GenomeRepresentation.GetTicker( signedTicker ); long quantity = marketCloseEventHandler_addOrder_getQuantity( ticker ); Order order = new Order( orderType , new Instrument( ticker ) , quantity ); this.account.AddOrder( order ); } private void marketCloseEventHandler_addOrders() { foreach ( string signedTicker in this.signedTickers ) marketCloseEventHandler_addOrder( signedTicker ); } public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { } private void marketCloseEventHandler_closePositions() { ArrayList tickers = new ArrayList(); foreach ( Position position in this.account.Portfolio.Positions ) tickers.Add( position.Instrument.Key ); foreach ( string ticker in tickers ) this.account.ClosePosition( ticker ); } public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { } private void marketCloseEventHandler_reverseSignOfTickers() { for(int i = 0; i<this.signedTickers.Length; i++) { if(this.signedTickers[i] != null) { if(this.signedTickers[i].StartsWith("-")) this.signedTickers[i] = GenomeManagerForEfficientPortfolio.GetCleanTickerCode(this.signedTickers[i]); else this.signedTickers[i] = "-" + this.signedTickers[i]; } } } private void marketCloseEventHandler_updateCounters(bool isTheFirstClose) { if(this.account.Portfolio.Count > 0 && isTheFirstClose == false) { if(this.isReversalPeriodOn) this.daysCounterWithReversalPositions++ ; else this.daysCounterWithRightPositions++ ; } } public void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { bool firstClose = false; if( (this.numOfClosesElapsed + 1) >= (this.daysForRightPeriod + this.daysForReversalPeriod) ) //strategy can now be applied because it is tuned with the optimization's results { if (this.account.Transactions.Count == 0) // it is the first close { firstClose = true; this.account.AddCash( 30000 ); this.marketCloseEventHandler_addOrders(); } this.marketCloseEventHandler_updateCounters(firstClose); if(firstClose == false && this.isReversalPeriodOn == false && this.daysCounterWithRightPositions == this.daysForRightPeriod) { this.marketCloseEventHandler_closePositions(); this.daysCounterWithRightPositions = 0; this.marketCloseEventHandler_reverseSignOfTickers(); this.marketCloseEventHandler_addOrders(); this.isReversalPeriodOn = true; } if(this.isReversalPeriodOn == true && this.daysCounterWithReversalPositions == this.daysForReversalPeriod) { this.marketCloseEventHandler_closePositions(); this.daysCounterWithReversalPositions = 0; this.marketCloseEventHandler_reverseSignOfTickers(); this.marketCloseEventHandler_addOrders(); this.isReversalPeriodOn = false; } } this.numOfClosesElapsed++; } public void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { } } } --- NEW FILE: ExtremeCounterTrendStrategy.cs --- /* QuantProject - Quantitative Finance Library ExtremeCounterTrendStrategy.cs Copyright (C) 2003 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.Data; using QuantProject.Data.DataTables; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Strategies; using QuantProject.Business.Timing; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.WalkForwardTesting.LinearCombination { /// <summary> /// Strategy that implies an immediate reversal in gain /// for the next period /// </summary> [Serializable] public class ExtremeCounterTrendStrategy : IEndOfDayStrategy { private Account account; private string[] signedTickers; private int numDaysForReturnCalculation; private int numOfClosesElapsed = 0; private int numOfDaysWithOpenPosition = 0; public ExtremeCounterTrendStrategy( Account account , string[] signedTickers, int numDaysForReturnCalculation) { this.account = account; this.signedTickers = signedTickers; this.numDaysForReturnCalculation = numDaysForReturnCalculation; } public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { } public void FiveMinutesBeforeMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { } private long marketCloseEventHandler_addOrder_getQuantity( string ticker ) { double accountValue = this.account.GetMarketValue(); double currentTickerAsk = this.account.DataStreamer.GetCurrentAsk( ticker ); double maxPositionValueForThisTicker = accountValue/this.signedTickers.Length; long quantity = Convert.ToInt64( Math.Floor( maxPositionValueForThisTicker / currentTickerAsk ) ); return quantity; } private void marketCloseEventHandler_addOrder( string signedTicker ) { OrderType orderType = GenomeRepresentation.GetOrderType( signedTicker ); string ticker = GenomeRepresentation.GetTicker( signedTicker ); long quantity = marketCloseEventHandler_addOrder_getQuantity( ticker ); Order order = new Order( orderType , new Instrument( ticker ) , quantity ); this.account.AddOrder( order ); } private void marketCloseEventHandler_addOrders() { foreach ( string signedTicker in this.signedTickers ) marketCloseEventHandler_addOrder( signedTicker ); } private double marketCloseEventHandler_openPositions_getLastHalfPeriodGain(IndexBasedEndOfDayTimer timer) { double returnValue = 999.0; try { DateTime initialDateForHalfPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation + 1]["quDate"]; DateTime finalDateForHalfPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; returnValue = SignedTicker.GetCloseToClosePortfolioReturn( this.signedTickers,initialDateForHalfPeriod,finalDateForHalfPeriod); } catch(MissingQuotesException ex) { ex = ex; } return returnValue; } private void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) { double lastHalfPeriodGain = this.marketCloseEventHandler_openPositions_getLastHalfPeriodGain(timer); if(lastHalfPeriodGain != 999.0) //last half period gain has been properly computed { if(lastHalfPeriodGain < 0.0) this.marketCloseEventHandler_addOrders(); else { SignedTicker.ChangeSignOfEachTicker(this.signedTickers); //short the portfolio try{this.marketCloseEventHandler_addOrders();} catch(Exception ex){ex = ex;} finally{SignedTicker.ChangeSignOfEachTicker(this.signedTickers);} } } } private void marketCloseEventHandler_closePositions() { ArrayList tickers = new ArrayList(); foreach ( Position position in this.account.Portfolio.Positions ) tickers.Add( position.Instrument.Key ); foreach ( string ticker in tickers ) this.account.ClosePosition( ticker ); this.numOfDaysWithOpenPosition = 0; } public void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { if(this.account.Transactions.Count == 0) this.account.AddCash(30000); if(this.account.Portfolio.Count > 0) this.numOfDaysWithOpenPosition++; if(this.numOfDaysWithOpenPosition == this.numDaysForReturnCalculation) this.marketCloseEventHandler_closePositions(); if(this.account.Portfolio.Count == 0 && (this.numOfClosesElapsed + 1) >= this.numDaysForReturnCalculation) //portfolio is empty and previous closes can be now checked if(this.account.Portfolio.Count == 0) this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); this.numOfClosesElapsed++; } public void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { } } } |
|
From: Marco M. <mi...@us...> - 2006-05-14 18:10:36
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv28845/EfficientPortfolio Modified Files: RunTestingOptimizationOpenToClose.cs RunTestingOptimizationCloseToOpen.cs Log Message: Updated the way fitness out of sample is computed for the OTC and CTO strategies Index: RunTestingOptimizationOpenToClose.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio/RunTestingOptimizationOpenToClose.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** RunTestingOptimizationOpenToClose.cs 7 Jan 2006 10:35:39 -0000 1.7 --- RunTestingOptimizationOpenToClose.cs 14 May 2006 18:10:31 -0000 1.8 *************** *** 29,32 **** --- 29,33 ---- using QuantProject.Data.Selectors; using QuantProject.Data.DataTables; + using QuantProject.ADT.Statistics; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; *************** *** 141,164 **** //Quotes tickerQuotes = new Quotes(ticker, dateOutOfSample, // dateOutOfSample); - //returnValue += // (tickerQuotes.GetFirstValidRawClose(dateOutOfSample)/ // tickerQuotes.GetFirstValidRawOpen(dateOutOfSample) - 1.0)*coefficient; ! // //returnValue is the average return for the interval between //the given market date and the numDaysAfterLastOptimizationDay - th //day after the given market date ! Quotes tickerQuotes = new Quotes(ticker, this.marketDate, dateOutOfSample); double close, open; ! for(int i = 0; i<this.numDaysAfterLastOptimizationDay; i++) ! { ! close = tickerQuotes.GetFirstValidRawClose(this.marketDate.AddDays(i)); ! open = tickerQuotes.GetFirstValidRawOpen(this.marketDate.AddDays(i)); ! returnValue += ! (close/open - 1.0)*coefficient/this.numDaysAfterLastOptimizationDay; ! ! } } return returnValue/genome.Size; --- 142,180 ---- //Quotes tickerQuotes = new Quotes(ticker, dateOutOfSample, // dateOutOfSample); //returnValue += // (tickerQuotes.GetFirstValidRawClose(dateOutOfSample)/ // tickerQuotes.GetFirstValidRawOpen(dateOutOfSample) - 1.0)*coefficient; ! //returnValue is the average return for the interval between //the given market date and the numDaysAfterLastOptimizationDay - th //day after the given market date ! //Quotes tickerQuotes = new Quotes(ticker, this.marketDate, ! // dateOutOfSample); ! //double close, open; ! //for(int i = 0; i<this.numDaysAfterLastOptimizationDay; i++) ! //{ ! //close = tickerQuotes.GetFirstValidRawClose(this.marketDate.AddDays(i)); ! //open = tickerQuotes.GetFirstValidRawOpen(this.marketDate.AddDays(i)); ! //returnValue += ! //(close/open - 1.0)*coefficient/this.numDaysAfterLastOptimizationDay; ! ! //} ! ! //returnValue is the sharpe ratio for the interval between ! //the given market date and the numDaysAfterLastOptimizationDay - th ! //day after the given market date ! Quotes tickerQuotes = new Quotes(ticker, this.marketDate, dateOutOfSample); double close, open; ! double[] returns = new double[this.numDaysAfterLastOptimizationDay]; ! for(int i = 0; i<this.numDaysAfterLastOptimizationDay; i++) ! { ! close = tickerQuotes.GetFirstValidRawClose(this.marketDate.AddDays(i)); ! open = tickerQuotes.GetFirstValidRawOpen(this.marketDate.AddDays(i)); ! returns[i] = (close/open - 1.0)*coefficient; ! } ! returnValue += BasicFunctions.SimpleAverage(returns) / BasicFunctions.StdDev(returns); } + return returnValue/genome.Size; *************** *** 260,264 **** DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(this.marketDate); ! IGenomeManager genManEfficientOTCPortfolio = new GenomeManagerForEfficientOTCPortfolio(setOfTickersToBeOptimized, this.marketDate.AddDays(-this.numDaysForOptimization), --- 276,280 ---- DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(this.marketDate); ! IGenomeManager genManEfficientOTC = new GenomeManagerForEfficientOTCPortfolio(setOfTickersToBeOptimized, this.marketDate.AddDays(-this.numDaysForOptimization), *************** *** 268,272 **** this.portfolioType); ! this.setFitnesses_setFitnessesActually(genManEfficientOTCPortfolio); } --- 284,288 ---- this.portfolioType); ! this.setFitnesses_setFitnessesActually(genManEfficientOTC); } *************** *** 298,302 **** int differentEvaluatedGenomes = genomeCounter.TotalEvaluatedGenomes; string pathFile = System.Configuration.ConfigurationSettings.AppSettings["GenericArchive"] + ! "\\OpenToCloseOptimizationEvaluation.txt"; StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); --- 314,318 ---- int differentEvaluatedGenomes = genomeCounter.TotalEvaluatedGenomes; string pathFile = System.Configuration.ConfigurationSettings.AppSettings["GenericArchive"] + ! "\\OptimizationEvaluation.txt"; StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); *************** *** 304,312 **** w.Write("\r\nNum days for optimization {0}\r", this.numDaysForOptimization.ToString()); w.Write("\r\nOptimizing market date {0}\r", this.marketDate.ToLongDateString()); ! w.Write("\r\nMarket date for test (out of sample){0}\r", this.marketDate.AddDays(this.numDaysAfterLastOptimizationDay).ToLongDateString()); w.Write("\r\nNumber of tickers: {0}\r", this.numberOfTickersToBeChosen.ToString()); w.WriteLine ("\n----------------------------------------------"); ! w.Write("\r\nFitnesses compared: {0}\r", this.fitnessesInSample.Length.ToString()); w.Write("\r\nDifferent evaluated genomes: {0}\r", differentEvaluatedGenomes.ToString()); w.Write("\r\nAverages of the {0} sub sets of fitnesses In Sample:\r", --- 320,328 ---- w.Write("\r\nNum days for optimization {0}\r", this.numDaysForOptimization.ToString()); w.Write("\r\nOptimizing market date {0}\r", this.marketDate.ToLongDateString()); ! w.Write("\r\nMarket date for test out of sample (sharpe ratio as fitness OS){0}\r", this.marketDate.AddDays(this.numDaysAfterLastOptimizationDay).ToLongDateString()); w.Write("\r\nNumber of tickers: {0}\r", this.numberOfTickersToBeChosen.ToString()); w.WriteLine ("\n----------------------------------------------"); ! w.Write("\r\nFitnesses compared (sharpe r. OTC): {0}\r", this.fitnessesInSample.Length.ToString()); w.Write("\r\nDifferent evaluated genomes: {0}\r", differentEvaluatedGenomes.ToString()); w.Write("\r\nAverages of the {0} sub sets of fitnesses In Sample:\r", Index: RunTestingOptimizationCloseToOpen.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio/RunTestingOptimizationCloseToOpen.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunTestingOptimizationCloseToOpen.cs 8 Jan 2006 23:36:05 -0000 1.1 --- RunTestingOptimizationCloseToOpen.cs 14 May 2006 18:10:31 -0000 1.2 *************** *** 27,30 **** --- 27,31 ---- using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; + using QuantProject.ADT.Statistics; using QuantProject.Data.Selectors; using QuantProject.Data.DataTables; *************** *** 120,134 **** //the given market date and the numDaysAfterLastOptimizationDay - th //day after the given market date ! Quotes tickerQuotes = new Quotes(ticker, this.marketDate, ! dateOutOfSample); ! double close, open; ! for(int i = 0; i<this.numDaysAfterLastOptimizationDay; i++) ! { ! close = tickerQuotes.GetFirstValidAdjustedClose(this.marketDate.AddDays(i)); ! open = tickerQuotes.GetFirstValidAdjustedOpen(this.marketDate.AddDays(i+1)); ! returnValue += ! (open/close - 1.0)*coefficient/this.numDaysAfterLastOptimizationDay; ! } } return returnValue/genome.Size; --- 121,150 ---- //the given market date and the numDaysAfterLastOptimizationDay - th //day after the given market date ! //Quotes tickerQuotes = new Quotes(ticker, this.marketDate, ! // dateOutOfSample); ! //double close, open; ! //for(int i = 0; i<this.numDaysAfterLastOptimizationDay; i++) ! //{ ! //close = tickerQuotes.GetFirstValidAdjustedClose(this.marketDate.AddDays(i)); ! //open = tickerQuotes.GetFirstValidAdjustedOpen(this.marketDate.AddDays(i+1)); ! //returnValue += ! //(open/close - 1.0)*coefficient/this.numDaysAfterLastOptimizationDay; ! //} ! ! //returnValue is the sharpe ratio for the interval between ! //the given market date and the numDaysAfterLastOptimizationDay - th ! //day after the given market date ! Quotes tickerQuotes = new Quotes(ticker, this.marketDate, ! dateOutOfSample); ! double close, open; ! double[] returns = new double[this.numDaysAfterLastOptimizationDay]; ! for(int i = 0; i<this.numDaysAfterLastOptimizationDay; i++) ! { ! close = tickerQuotes.GetFirstValidAdjustedClose(this.marketDate.AddDays(i)); ! open = tickerQuotes.GetFirstValidAdjustedOpen(this.marketDate.AddDays(i+1)); ! returns[i] = (open/close - 1.0)*coefficient; ! } ! returnValue += BasicFunctions.SimpleAverage(returns) / BasicFunctions.StdDev(returns); } return returnValue/genome.Size; *************** *** 269,273 **** int differentEvaluatedGenomes = genomeCounter.TotalEvaluatedGenomes; string pathFile = System.Configuration.ConfigurationSettings.AppSettings["GenericArchive"] + ! "\\CloseToOpenOptimizationEvaluation.txt"; StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); --- 285,289 ---- int differentEvaluatedGenomes = genomeCounter.TotalEvaluatedGenomes; string pathFile = System.Configuration.ConfigurationSettings.AppSettings["GenericArchive"] + ! "\\OptimizationEvaluation.txt"; StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); *************** *** 275,283 **** w.Write("\r\nNum days for optimization {0}\r", this.numDaysForOptimization.ToString()); w.Write("\r\nOptimizing market date {0}\r", this.marketDate.ToLongDateString()); ! w.Write("\r\nMarket date for test (out of sample){0}\r", this.marketDate.AddDays(this.numDaysAfterLastOptimizationDay).ToLongDateString()); w.Write("\r\nNumber of tickers: {0}\r", this.numberOfTickersToBeChosen.ToString()); w.WriteLine ("\n----------------------------------------------"); ! w.Write("\r\nFitnesses compared: {0}\r", this.fitnessesInSample.Length.ToString()); w.Write("\r\nDifferent evaluated genomes: {0}\r", differentEvaluatedGenomes.ToString()); w.Write("\r\nAverages of the {0} sub sets of fitnesses In Sample:\r", --- 291,299 ---- w.Write("\r\nNum days for optimization {0}\r", this.numDaysForOptimization.ToString()); w.Write("\r\nOptimizing market date {0}\r", this.marketDate.ToLongDateString()); ! w.Write("\r\nMarket date for test out of sample (sharpe ratio as fitness OS){0}\r", this.marketDate.AddDays(this.numDaysAfterLastOptimizationDay).ToLongDateString()); w.Write("\r\nNumber of tickers: {0}\r", this.numberOfTickersToBeChosen.ToString()); w.WriteLine ("\n----------------------------------------------"); ! w.Write("\r\nFitnesses compared (sharpe ratio CTO): {0}\r", this.fitnessesInSample.Length.ToString()); w.Write("\r\nDifferent evaluated genomes: {0}\r", differentEvaluatedGenomes.ToString()); w.Write("\r\nAverages of the {0} sub sets of fitnesses In Sample:\r", |
|
From: Marco M. <mi...@us...> - 2006-05-14 18:07:50
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/TechnicalAnalysis In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv27853/TechnicalAnalysis Added Files: RunTestingOptimizationExtremeCounterTrend.cs Log Message: Added Script to compare fitness in sample with fitness out of sample, for the extreme counter trend strategy (it's only a "skeleton file" at the moment) --- NEW FILE: RunTestingOptimizationExtremeCounterTrend.cs --- /* QuantProject - Quantitative Finance Library RunTestingOptimizationExtremeCounterTrend.cs Copyright (C) 2003 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.IO; using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Data.Selectors; using QuantProject.Data.DataTables; using QuantProject.ADT.Statistics; using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.ExtremeCounterTrend; namespace QuantProject.Scripts.EvaluatingOptimizationTechnique.TechnicalAnalysis { /// <summary> /// For the evaluation of the optimization technique used by the script /// for the extreme counter trend strategy /// </summary> [Serializable] public class RunTestingOptimizationExtremeCounterTrend { private double[] fitnessesInSample; private double[] fitnessesOutOfSample; private string tickerGroupID; private int numberOfEligibleTickers; private int numberOfTickersToBeChosen; private int numDaysForOptimization; private int populationSizeForGeneticOptimizer; private int generationNumberForGeneticOptimizer; private string benchmark; private DateTime marketDate; private double targetReturn; private PortfolioType portfolioType; private int numDaysAfterLastOptimizationDay; private int numberOfSubsets; private Genome[] genomesToTestOutOfSample; private int numberOfGenomesToTest; public RunTestingOptimizationExtremeCounterTrend(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimization, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime marketDate, double targetReturn, PortfolioType portfolioType, int numDaysAfterLastOptimizationDay, int numberOfSubsets, int numberOfGenomesToTest) { this.numberOfGenomesToTest = numberOfGenomesToTest; this.genomesToTestOutOfSample = new Genome[numberOfGenomesToTest]; this.fitnessesInSample = new double[numberOfGenomesToTest]; this.fitnessesOutOfSample = new double[numberOfGenomesToTest]; this.tickerGroupID = tickerGroupID; this.numberOfEligibleTickers = numberOfEligibleTickers; this.numberOfTickersToBeChosen = numberOfTickersToBeChosen; this.numDaysForOptimization = numDaysForOptimization; this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; this.benchmark = benchmark; this.marketDate = marketDate; this.targetReturn = targetReturn; this.portfolioType = portfolioType; this.numDaysAfterLastOptimizationDay = numDaysAfterLastOptimizationDay; this.numberOfSubsets = numberOfSubsets; } private DataTable getSetOfTickersToBeOptimized(DateTime date) { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, date); SelectorByQuotationAtEachMarketDay quotedAtEachMarketFromTemporized = new SelectorByQuotationAtEachMarketDay(temporizedGroup.GetTableOfSelectedTickers(), false, date.AddDays(-this.numDaysForOptimization), date, this.numberOfEligibleTickers, this.benchmark); return quotedAtEachMarketFromTemporized.GetTableOfSelectedTickers(); } private double setFitnesses_setFitnessesActually_getFitnessOutOfSample(Genome genome) { double returnValue = 0; foreach(string tickerCode in ((GenomeMeaning)genome.Meaning).Tickers) { double coefficient = 1.0; string ticker = tickerCode; if(ticker.StartsWith("-")) { ticker = ticker.Substring(1,ticker.Length -1); coefficient = -1.0; } DateTime dateOutOfSample = this.marketDate.AddDays(this.numDaysAfterLastOptimizationDay); //returnValue is the single return for the numDaysAfterLastOptimizationDay - th day //after the given market date //Quotes tickerQuotes = new Quotes(ticker, dateOutOfSample, // dateOutOfSample); //returnValue += // (tickerQuotes.GetFirstValidRawClose(dateOutOfSample)/ // tickerQuotes.GetFirstValidRawOpen(dateOutOfSample) - 1.0)*coefficient; //returnValue is the average return for the interval between //the given market date and the numDaysAfterLastOptimizationDay - th //day after the given market date //Quotes tickerQuotes = new Quotes(ticker, this.marketDate, // dateOutOfSample); //double close, open; //for(int i = 0; i<this.numDaysAfterLastOptimizationDay; i++) //{ //close = tickerQuotes.GetFirstValidRawClose(this.marketDate.AddDays(i)); //open = tickerQuotes.GetFirstValidRawOpen(this.marketDate.AddDays(i)); //returnValue += //(close/open - 1.0)*coefficient/this.numDaysAfterLastOptimizationDay; //} //returnValue is the sharpe ratio for the interval between //the given market date and the numDaysAfterLastOptimizationDay - th //day after the given market date Quotes tickerQuotes = new Quotes(ticker, this.marketDate, dateOutOfSample); double close, open; double[] returns = new double[this.numDaysAfterLastOptimizationDay]; for(int i = 0; i<this.numDaysAfterLastOptimizationDay; i++) { close = tickerQuotes.GetFirstValidRawClose(this.marketDate.AddDays(i)); open = tickerQuotes.GetFirstValidRawOpen(this.marketDate.AddDays(i)); returns[i] = (close/open - 1.0)*coefficient; } returnValue += BasicFunctions.SimpleAverage(returns) / BasicFunctions.StdDev(returns); } return returnValue/genome.Size; } private bool setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample_addGenomes_sharesNoGeneWithGenomesAlreadyAdded(Genome genomeToBeAdded, bool addWorstGenomes) { bool returnValue = true; if(addWorstGenomes) //the first half containing the worst genomes has to be checked { for(int i = 0; i<this.numberOfGenomesToTest/2; i++) { if(this.genomesToTestOutOfSample[i]==null) return true; if(!genomeToBeAdded.SharesNoGeneWith(this.genomesToTestOutOfSample[i])) return false; } } else //the second half containing the best genomes has to be checked { for(int i = 0; i<this.numberOfGenomesToTest/2; i++) { if(this.genomesToTestOutOfSample[this.numberOfGenomesToTest-1-i]==null) return true; if(!genomeToBeAdded.SharesNoGeneWith(this.genomesToTestOutOfSample[this.numberOfGenomesToTest-1-i])) return false; } } return returnValue; } private void setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample_addGenomes(GeneticOptimizer optimizer, bool addWorstGenomes) { Genome currentGenome; Genome previousGenome = null; int numOfDifferentGenomesFound = 0; for(int j = 0; j<this.populationSizeForGeneticOptimizer && numOfDifferentGenomesFound<this.numberOfGenomesToTest/2; j++) { if(addWorstGenomes == true) currentGenome = (Genome)optimizer.CurrentGeneration[j]; else currentGenome = (Genome)optimizer.CurrentGeneration[this.populationSizeForGeneticOptimizer-j-1]; if(this.setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample_addGenomes_sharesNoGeneWithGenomesAlreadyAdded(currentGenome, addWorstGenomes)) //no genes of the current genome are present in the relative half { if(this.genomesToTestOutOfSample[numOfDifferentGenomesFound]!= null) //the first half of the array has already been filled this.genomesToTestOutOfSample[this.numberOfGenomesToTest-1-numOfDifferentGenomesFound]=currentGenome; else//the first half is still empty this.genomesToTestOutOfSample[numOfDifferentGenomesFound] = currentGenome; previousGenome = currentGenome; numOfDifferentGenomesFound++; } } } private void setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample(IGenomeManager genomeManager) { GeneticOptimizer optimizer = new GeneticOptimizer(genomeManager, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer, ConstantsProvider.SeedForRandomGenerator); optimizer.Run(false); this.setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample_addGenomes(optimizer, true); this.setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample_addGenomes(optimizer, false); Array.Sort(this.genomesToTestOutOfSample); } private void setFitnesses_setFitnessesActually(IGenomeManager genomeManager) { this.setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample(genomeManager); for(int i = 0; i<this.numberOfGenomesToTest; i++) { this.fitnessesInSample[i]=(this.genomesToTestOutOfSample[i]).Fitness; this.fitnessesOutOfSample[i]= this.setFitnesses_setFitnessesActually_getFitnessOutOfSample(this.genomesToTestOutOfSample[i]); } } private void setFitnesses() { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(this.marketDate); IGenomeManager genManEfficientOTCTypes = new GenomeManagerForEfficientOTCTypes(setOfTickersToBeOptimized, this.marketDate.AddDays(-this.numDaysForOptimization), this.marketDate, this.numberOfTickersToBeChosen, this.targetReturn, this.portfolioType); this.setFitnesses_setFitnessesActually(genManEfficientOTCTypes); } public void Run() { try { this.setFitnesses(); OptimizationTechniqueEvaluator evaluator = new OptimizationTechniqueEvaluator(this.fitnessesInSample, this.fitnessesOutOfSample); this.run_writeToLogFile(evaluator); } catch(Exception ex) { ex = ex; } } private void run_writeToLogFile(OptimizationTechniqueEvaluator evaluator) { double[] averagesInSample = evaluator.GetAveragesOfSubsetsInSample(this.numberOfSubsets); double[] averagesOutOfSample = evaluator.GetAveragesOfSubsetsOutOfSample(this.numberOfSubsets); double r = evaluator.GetCorrelationBetweenFitnesses(); GenomeCounter genomeCounter = new GenomeCounter(this.genomesToTestOutOfSample); int differentEvaluatedGenomes = genomeCounter.TotalEvaluatedGenomes; string pathFile = System.Configuration.ConfigurationSettings.AppSettings["GenericArchive"] + "\\OptimizationEvaluation.txt"; StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); w.Write("\r\nNew Test for Evaluation of Open To Close Optimization {0}\r", DateTime.Now.ToLongDateString()+ " " +DateTime.Now.ToLongTimeString()); w.Write("\r\nNum days for optimization {0}\r", this.numDaysForOptimization.ToString()); w.Write("\r\nOptimizing market date {0}\r", this.marketDate.ToLongDateString()); w.Write("\r\nMarket date for test out of sample (sharpe ratio as fitness OS){0}\r", this.marketDate.AddDays(this.numDaysAfterLastOptimizationDay).ToLongDateString()); w.Write("\r\nNumber of tickers: {0}\r", this.numberOfTickersToBeChosen.ToString()); w.WriteLine ("\n----------------------------------------------"); w.Write("\r\nFitnesses compared (sharpe r. OTC - sharpe r. CTO): {0}\r", this.fitnessesInSample.Length.ToString()); w.Write("\r\nDifferent evaluated genomes: {0}\r", differentEvaluatedGenomes.ToString()); w.Write("\r\nAverages of the {0} sub sets of fitnesses In Sample:\r", this.numberOfSubsets); // for(int i = 0; i<averagesInSample.Length; i++) w.WriteLine("\n{0}-->{1}", i.ToString(), averagesInSample[i].ToString()); w.WriteLine ("\n\n----------------------------------------------"); w.Write("\r\nAverages of the {0} sub sets of fitnesses Out of Sample:\r", this.numberOfSubsets); // for(int i = 0; i<averagesOutOfSample.Length; i++) w.WriteLine("\n{0}-->{1}", i.ToString(), averagesOutOfSample[i].ToString()); w.WriteLine ("\n\n----------------------------------------------"); // w.Write("\r\nCorrelation coefficient between fitnesses: {0}\r", r.ToString()); w.WriteLine ("\n-----------------End of Test------------------\r\n"); // Update the underlying file. w.Flush(); w.Close(); } } } |
|
From: Marco M. <mi...@us...> - 2006-05-14 18:06:42
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv27529/EfficientPortfolio Added Files: RunTestingOptimizationOpenToCloseFitnessCombined.cs Log Message: Added Script to compare Open to close fitness in sample with fitness out of sample --- NEW FILE: RunTestingOptimizationOpenToCloseFitnessCombined.cs --- /* QuantProject - Quantitative Finance Library RunTestingOptimizationOpenToCloseFitnessCombined.cs Copyright (C) 2003 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.IO; using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Data.Selectors; using QuantProject.Data.DataTables; using QuantProject.ADT.Statistics; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.EvaluatingOptimizationTechnique.EfficientPortfolio { /// <summary> /// For the evaluation of the optimization technique used by the script /// for the efficient open to close portfolio /// </summary> [Serializable] public class RunTestingOptimizationOpenToCloseFitnessCombined { private double[] fitnessesInSample; private double[] fitnessesOutOfSample; private string tickerGroupID; private int numberOfEligibleTickers; private int numberOfTickersToBeChosen; private int numDaysForOptimization; private int populationSizeForGeneticOptimizer; private int generationNumberForGeneticOptimizer; private string benchmark; private DateTime marketDate; private double targetReturn; private PortfolioType portfolioType; private int numDaysAfterLastOptimizationDay; private int numberOfSubsets; private Genome[] genomesToTestOutOfSample; private int numberOfGenomesToTest; public RunTestingOptimizationOpenToCloseFitnessCombined(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimization, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime marketDate, double targetReturn, PortfolioType portfolioType, int numDaysAfterLastOptimizationDay, int numberOfSubsets, int numberOfGenomesToTest) { this.numberOfGenomesToTest = numberOfGenomesToTest; this.genomesToTestOutOfSample = new Genome[numberOfGenomesToTest]; this.fitnessesInSample = new double[numberOfGenomesToTest]; this.fitnessesOutOfSample = new double[numberOfGenomesToTest]; this.tickerGroupID = tickerGroupID; this.numberOfEligibleTickers = numberOfEligibleTickers; this.numberOfTickersToBeChosen = numberOfTickersToBeChosen; this.numDaysForOptimization = numDaysForOptimization; this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; this.benchmark = benchmark; this.marketDate = marketDate; this.targetReturn = targetReturn; this.portfolioType = portfolioType; this.numDaysAfterLastOptimizationDay = numDaysAfterLastOptimizationDay; this.numberOfSubsets = numberOfSubsets; } private DataTable getSetOfTickersToBeOptimized(DateTime date) { /* SelectorByAverageRawOpenPrice selectorByOpenPrice = new SelectorByAverageRawOpenPrice(this.tickerGroupID, false, currentDate.AddDays(-this.numDaysForOptimization), currentDate, this.numberOfEligibleTickers, this.minPriceForMinimumCommission, this.maxPriceForMinimumCommission, 0, 2); DataTable tickersByPrice = selectorByOpenPrice.GetTableOfSelectedTickers(); */ SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, date); SelectorByOpenCloseCorrelationToBenchmark lessCorrelatedFromTemporizedGroup = new SelectorByOpenCloseCorrelationToBenchmark(temporizedGroup.GetTableOfSelectedTickers(), this.benchmark,true, date.AddDays(-this.numDaysForOptimization ), date, this.numberOfEligibleTickers); DataTable eligibleTickers; eligibleTickers = lessCorrelatedFromTemporizedGroup.GetTableOfSelectedTickers(); //eligibleTickers = temporizedGroup.GetTableOfSelectedTickers(); SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromEligible = new SelectorByQuotationAtEachMarketDay( eligibleTickers, false, date.AddDays(-this.numDaysForOptimization), date, this.numberOfEligibleTickers, this.benchmark); //SelectorByWinningOpenToClose winners = //new SelectorByWinningOpenToClose(quotedAtEachMarketDayFromEligible.GetTableOfSelectedTickers(), // false, date.AddDays(-1), // date.AddDays(-1), this.numberOfEligibleTickers/2, // true); //return winners.GetTableOfSelectedTickers(); return quotedAtEachMarketDayFromEligible.GetTableOfSelectedTickers(); //return lessCorrelated.GetTableOfSelectedTickers(); } private double setFitnesses_setFitnessesActually_getFitnessOutOfSample(Genome genome) { double returnValue = 0; foreach(string tickerCode in ((GenomeMeaning)genome.Meaning).Tickers) { double coefficient = 1.0; string ticker = tickerCode; if(ticker.StartsWith("-")) { ticker = ticker.Substring(1,ticker.Length -1); coefficient = -1.0; } DateTime dateOutOfSample = this.marketDate.AddDays(this.numDaysAfterLastOptimizationDay); //returnValue is the single return for the numDaysAfterLastOptimizationDay - th day //after the given market date //Quotes tickerQuotes = new Quotes(ticker, dateOutOfSample, // dateOutOfSample); //returnValue += // (tickerQuotes.GetFirstValidRawClose(dateOutOfSample)/ // tickerQuotes.GetFirstValidRawOpen(dateOutOfSample) - 1.0)*coefficient; //returnValue is the average return for the interval between //the given market date and the numDaysAfterLastOptimizationDay - th //day after the given market date //Quotes tickerQuotes = new Quotes(ticker, this.marketDate, // dateOutOfSample); //double close, open; //for(int i = 0; i<this.numDaysAfterLastOptimizationDay; i++) //{ //close = tickerQuotes.GetFirstValidRawClose(this.marketDate.AddDays(i)); //open = tickerQuotes.GetFirstValidRawOpen(this.marketDate.AddDays(i)); //returnValue += //(close/open - 1.0)*coefficient/this.numDaysAfterLastOptimizationDay; //} //returnValue is the sharpe ratio for the interval between //the given market date and the numDaysAfterLastOptimizationDay - th //day after the given market date Quotes tickerQuotes = new Quotes(ticker, this.marketDate, dateOutOfSample); double close, open; double[] returns = new double[this.numDaysAfterLastOptimizationDay]; for(int i = 0; i<this.numDaysAfterLastOptimizationDay; i++) { close = tickerQuotes.GetFirstValidRawClose(this.marketDate.AddDays(i)); open = tickerQuotes.GetFirstValidRawOpen(this.marketDate.AddDays(i)); returns[i] = (close/open - 1.0)*coefficient; } returnValue += BasicFunctions.SimpleAverage(returns) / BasicFunctions.StdDev(returns); } return returnValue/genome.Size; } private bool setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample_addGenomes_sharesNoGeneWithGenomesAlreadyAdded(Genome genomeToBeAdded, bool addWorstGenomes) { bool returnValue = true; if(addWorstGenomes) //the first half containing the worst genomes has to be checked { for(int i = 0; i<this.numberOfGenomesToTest/2; i++) { if(this.genomesToTestOutOfSample[i]==null) return true; if(!genomeToBeAdded.SharesNoGeneWith(this.genomesToTestOutOfSample[i])) return false; } } else //the second half containing the best genomes has to be checked { for(int i = 0; i<this.numberOfGenomesToTest/2; i++) { if(this.genomesToTestOutOfSample[this.numberOfGenomesToTest-1-i]==null) return true; if(!genomeToBeAdded.SharesNoGeneWith(this.genomesToTestOutOfSample[this.numberOfGenomesToTest-1-i])) return false; } } return returnValue; } private void setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample_addGenomes(GeneticOptimizer optimizer, bool addWorstGenomes) { Genome currentGenome; Genome previousGenome = null; int numOfDifferentGenomesFound = 0; for(int j = 0; j<this.populationSizeForGeneticOptimizer && numOfDifferentGenomesFound<this.numberOfGenomesToTest/2; j++) { if(addWorstGenomes == true) currentGenome = (Genome)optimizer.CurrentGeneration[j]; else currentGenome = (Genome)optimizer.CurrentGeneration[this.populationSizeForGeneticOptimizer-j-1]; if(this.setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample_addGenomes_sharesNoGeneWithGenomesAlreadyAdded(currentGenome, addWorstGenomes)) //no genes of the current genome are present in the relative half { if(this.genomesToTestOutOfSample[numOfDifferentGenomesFound]!= null) //the first half of the array has already been filled this.genomesToTestOutOfSample[this.numberOfGenomesToTest-1-numOfDifferentGenomesFound]=currentGenome; else//the first half is still empty this.genomesToTestOutOfSample[numOfDifferentGenomesFound] = currentGenome; previousGenome = currentGenome; numOfDifferentGenomesFound++; } } } private void setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample(IGenomeManager genomeManager) { GeneticOptimizer optimizer = new GeneticOptimizer(genomeManager, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer, ConstantsProvider.SeedForRandomGenerator); optimizer.Run(false); this.setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample_addGenomes(optimizer, true); this.setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample_addGenomes(optimizer, false); Array.Sort(this.genomesToTestOutOfSample); } private void setFitnesses_setFitnessesActually(IGenomeManager genomeManager) { this.setFitnesses_setFitnessesActually_setGenomesToTestOutOfSample(genomeManager); for(int i = 0; i<this.numberOfGenomesToTest; i++) { this.fitnessesInSample[i]=(this.genomesToTestOutOfSample[i]).Fitness; this.fitnessesOutOfSample[i]= this.setFitnesses_setFitnessesActually_getFitnessOutOfSample(this.genomesToTestOutOfSample[i]); } } private void setFitnesses() { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(this.marketDate); IGenomeManager genManEfficientOTCTypes = new GenomeManagerForEfficientOTCTypes(setOfTickersToBeOptimized, this.marketDate.AddDays(-this.numDaysForOptimization), this.marketDate, this.numberOfTickersToBeChosen, this.targetReturn, this.portfolioType); this.setFitnesses_setFitnessesActually(genManEfficientOTCTypes); } public void Run() { try { this.setFitnesses(); OptimizationTechniqueEvaluator evaluator = new OptimizationTechniqueEvaluator(this.fitnessesInSample, this.fitnessesOutOfSample); this.run_writeToLogFile(evaluator); } catch(Exception ex) { ex = ex; } } private void run_writeToLogFile(OptimizationTechniqueEvaluator evaluator) { double[] averagesInSample = evaluator.GetAveragesOfSubsetsInSample(this.numberOfSubsets); double[] averagesOutOfSample = evaluator.GetAveragesOfSubsetsOutOfSample(this.numberOfSubsets); double r = evaluator.GetCorrelationBetweenFitnesses(); GenomeCounter genomeCounter = new GenomeCounter(this.genomesToTestOutOfSample); int differentEvaluatedGenomes = genomeCounter.TotalEvaluatedGenomes; string pathFile = System.Configuration.ConfigurationSettings.AppSettings["GenericArchive"] + "\\OptimizationEvaluation.txt"; StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); w.Write("\r\nNew Test for Evaluation of Open To Close Optimization {0}\r", DateTime.Now.ToLongDateString()+ " " +DateTime.Now.ToLongTimeString()); w.Write("\r\nNum days for optimization {0}\r", this.numDaysForOptimization.ToString()); w.Write("\r\nOptimizing market date {0}\r", this.marketDate.ToLongDateString()); w.Write("\r\nMarket date for test out of sample (sharpe ratio as fitness OS){0}\r", this.marketDate.AddDays(this.numDaysAfterLastOptimizationDay).ToLongDateString()); w.Write("\r\nNumber of tickers: {0}\r", this.numberOfTickersToBeChosen.ToString()); w.WriteLine ("\n----------------------------------------------"); w.Write("\r\nFitnesses compared (sharpe r. OTC - sharpe r. CTO): {0}\r", this.fitnessesInSample.Length.ToString()); w.Write("\r\nDifferent evaluated genomes: {0}\r", differentEvaluatedGenomes.ToString()); w.Write("\r\nAverages of the {0} sub sets of fitnesses In Sample:\r", this.numberOfSubsets); // for(int i = 0; i<averagesInSample.Length; i++) w.WriteLine("\n{0}-->{1}", i.ToString(), averagesInSample[i].ToString()); w.WriteLine ("\n\n----------------------------------------------"); w.Write("\r\nAverages of the {0} sub sets of fitnesses Out of Sample:\r", this.numberOfSubsets); // for(int i = 0; i<averagesOutOfSample.Length; i++) w.WriteLine("\n{0}-->{1}", i.ToString(), averagesOutOfSample[i].ToString()); w.WriteLine ("\n\n----------------------------------------------"); // w.Write("\r\nCorrelation coefficient between fitnesses: {0}\r", r.ToString()); w.WriteLine ("\n-----------------End of Test------------------\r\n"); // Update the underlying file. w.Flush(); w.Close(); } } } |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:37:42
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/TechnicalAnalysis In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv11492/TechnicalAnalysis Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/TechnicalAnalysis added to the repository |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:36:16
|
Update of /cvsroot/quantproject/QuantProject/b3_Data In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv11143 Added Files: MissingQuotesException.cs Log Message: Added MissingQuotesException class --- NEW FILE: MissingQuotesException.cs --- /* QuantProject - Quantitative Finance Library MissingQuotesException.cs Copyright (C) 2003 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; namespace QuantProject.Data { /// <summary> /// Thrown when needed if an object DataTables.Quotes has no quotes /// for a given TimeFrame /// </summary> public class MissingQuotesException : Exception { private string ticker; private DateTime initialDateTime; private DateTime finalDateTime; public override string Message { get { return "No quotes available for ticker " + this.ticker + ", between " + this.initialDateTime.ToShortDateString() + " and " + this.finalDateTime.ToShortDateString(); } } public MissingQuotesException( string ticker,DateTime initialDateTime, DateTime finalDateTime ) { this.ticker = ticker; this.initialDateTime = initialDateTime; this.finalDateTime = finalDateTime; } } } |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv10183 Added Files: RunExtremeCounterTrend.cs GenomeManagerECT.cs EndOfDayTimerHandlerECT.cs Log Message: Added ExtremeCounterTrend strategy --- NEW FILE: EndOfDayTimerHandlerECT.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerECT.cs Copyright (C) 2003 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.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.Strategies; 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; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.ExtremeCounterTrend { /// <summary> /// Implements MarketOpenEventHandler and MarketCloseEventHandler /// These handlers contain the core strategy for the extreme /// counter trend strategy! /// </summary> [Serializable] public class EndOfDayTimerHandlerECT : EndOfDayTimerHandler { private int numDaysForReturnCalculation; private double maxAcceptableCloseToCloseDrawdown; private bool stopLossConditionReached; private double currentAccountValue; private double previousAccountValue; private int numDaysBetweenEachOptimization; private int numDaysElapsedSinceLastOptimization; private int daysCounterWithPositions; // private int daysCounterWithRightPositions; // private int daysCounterWithReversalPositions; // private bool isReversalPeriodOn = false; // private bool isTheFirstClose = false; private DateTime lastCloseDate; private IGenomeManager iGenomeManager; public EndOfDayTimerHandlerECT(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, int numDaysForReturnCalculation, int numDaysBetweenEachOptimization, PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, 0.0, portfolioType) { this.numDaysForReturnCalculation = numDaysForReturnCalculation; // this.daysCounterWithRightPositions = 0; // this.daysCounterWithReversalPositions = 0; // this.isReversalPeriodOn = false; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; this.stopLossConditionReached = false; this.currentAccountValue = 0.0; this.previousAccountValue = 0.0; // this.numDaysBetweenEachOptimization = 2* numDaysForReturnCalculation; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } #region MarketCloseEventHandler protected void marketCloseEventHandler_updateStopLossCondition() { this.previousAccountValue = this.currentAccountValue; this.currentAccountValue = this.account.GetMarketValue(); if((this.currentAccountValue - this.previousAccountValue) /this.previousAccountValue < -this.maxAcceptableCloseToCloseDrawdown) { this.stopLossConditionReached = true; } else { this.stopLossConditionReached = false; } } private double marketCloseEventHandler_openPositions_getLastHalfPeriodGain(IndexBasedEndOfDayTimer timer) { double returnValue = 999.0; try { DateTime initialDateForHalfPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation + 1]["quDate"]; DateTime finalDateForHalfPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; returnValue = SignedTicker.GetCloseToClosePortfolioReturn( this.chosenTickers, this.chosenTickersPortfolioWeights, initialDateForHalfPeriod,finalDateForHalfPeriod); } catch(MissingQuotesException ex) { ex = ex; } return returnValue; } private void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) { double lastHalfPeriodGain = this.marketCloseEventHandler_openPositions_getLastHalfPeriodGain(timer); if(lastHalfPeriodGain != 999.0) //last half period gain has been properly computed { if(lastHalfPeriodGain < 0.0) base.openPositions(); else { SignedTicker.ChangeSignOfEachTicker(this.chosenTickers); //short the portfolio try{ base.openPositions(); } catch(Exception ex){ ex = ex; } finally{SignedTicker.ChangeSignOfEachTicker(this.chosenTickers);} } } } private void marketCloseEventHandler_closePositions() { this.daysCounterWithPositions++; if(this.daysCounterWithPositions == this.numDaysForReturnCalculation || this.stopLossConditionReached) { //Close if halfPeriod has elapsed or stop loss condition reached base.closePositions(); this.daysCounterWithPositions = 0; } } public override void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { //this.marketCloseEventHandler_updateStopLossCondition(); this.marketCloseEventHandler_closePositions(); if(this.chosenTickers[0] != null) //tickers to buy have been chosen { if(this.account.Portfolio.Count == 0) this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); } } #endregion #region OneHourAfterMarketCloseEventHandler protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); SelectorByQuotationAtEachMarketDay quotedAtEachMarketFromTemporized = new SelectorByQuotationAtEachMarketDay(temporizedGroup.GetTableOfSelectedTickers(), false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfEligibleTickers, this.benchmark); return quotedAtEachMarketFromTemporized.GetTableOfSelectedTickers(); } protected virtual void setTickers(DateTime currentDate, bool setGenomeCounter) { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); if(setOfTickersToBeOptimized.Rows.Count > this.chosenTickers.Length*2) //the optimization process is meaningful only if the initial set of tickers is //larger than the number of tickers to be chosen { this.iGenomeManager = new GenomeManagerECT(setOfTickersToBeOptimized, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, this.numDaysForReturnCalculation, this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer, ConstantsProvider.SeedForRandomGenerator); if(setGenomeCounter) this.genomeCounter = new GenomeCounter(GO); GO.Run(false); this.addGenomeToBestGenomes(GO.BestGenome,((GenomeManagerForEfficientPortfolio)this.iGenomeManager).FirstQuoteDate, ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate); this.chosenTickers = ((GenomeMeaning)GO.BestGenome.Meaning).Tickers; this.chosenTickersPortfolioWeights = ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights; } //else it will be buyed again the previous optimized portfolio //that's it the actual chosenTickers member } /// <summary> /// Handles a "One hour after market close" event. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> public override void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { this.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ConstantsProvider.SeedForRandomGenerator++; this.numDaysElapsedSinceLastOptimization++; this.orders.Clear(); if((this.numDaysElapsedSinceLastOptimization - 1 == this.numDaysBetweenEachOptimization)) //|| this.isTheFirstClose ) //num days without optimization has elapsed or //it is the first close (OLD IMPLEMENTATION) { this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); //sets tickers to be chosen next Market Close event this.numDaysElapsedSinceLastOptimization = 0; } } #endregion } } --- NEW FILE: GenomeManagerECT.cs --- /* QuantProject - Quantitative Finance Library GenomeManagerECT.cs Copyright (C) 2003 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.Statistics; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Data; using QuantProject.Data.DataTables; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.ExtremeCounterTrend { /// <summary> /// Implements what needed to use the Genetic Optimizer /// for finding the portfolio that best suites /// the extreme counter trend strategy /// </summary> [Serializable] public class GenomeManagerECT : GenomeManagerForEfficientPortfolio { private int numDaysForReturnCalculation; public GenomeManagerECT(DataTable setOfInitialTickers, DateTime firstQuoteDate, DateTime lastQuoteDate, int numberOfTickersInPortfolio, int numDaysForReturnCalculation, PortfolioType portfolioType) : base(setOfInitialTickers, firstQuoteDate, lastQuoteDate, numberOfTickersInPortfolio, 0.0, portfolioType) { this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.retrieveData(); } protected override float[] getArrayOfRatesOfReturn(string ticker) { float[] returnValue = null; Quotes tickerQuotes = new Quotes(ticker, this.firstQuoteDate, this.lastQuoteDate); returnValue = ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuotes, Quotes.AdjustedCloseToCloseRatio); for(int i = 0; i<returnValue.Length; i++) returnValue[i] = returnValue[i] - 1.0f; this.numberOfExaminedReturns = returnValue.Length; return returnValue; } public override object Decode(Genome genome) { string[] arrayOfTickers = new string[genome.Genes().Length]; int indexOfTicker; for(int index = 0; index < genome.Genes().Length; index++) { indexOfTicker = (int)genome.Genes().GetValue(index); arrayOfTickers[index] = this.decode_getTickerCodeForLongOrShortTrade(indexOfTicker); } GenomeMeaning meaning = new GenomeMeaning(arrayOfTickers); return meaning; } //fitness is a sharpe-ratio based indicator for the equity line resulting //from applying the strategy public override double GetFitnessValue(Genome genome) { this.portfolioRatesOfReturn = this.getPortfolioRatesOfReturn(genome.Genes()); double[] equityLine = this.getFitnessValue_getEquityLineRates(); double sharpeRatioAll = BasicFunctions.SimpleAverage(equityLine)/ BasicFunctions.StdDev(equityLine); // double[] equityLineSecondHalf = new double[equityLine.Length/2]; // for(int i = 0; i<equityLine.Length/2; i++) // equityLineSecondHalf[i] = equityLine[i+equityLine.Length/2]; // double sharpeRatioSecondHalf = BasicFunctions.SimpleAverage(equityLineSecondHalf)/ // Math.Pow(BasicFunctions.StdDev(equityLineSecondHalf),1.2); return sharpeRatioAll;//*sharpeRatioSecondHalf; } private double[] getFitnessValue_getEquityLineRates() { double[] returnValue = new double[this.PortfolioRatesOfReturn.Length]; double gainForTheLastHalfPeriod = 0.0; for(int i = this.numDaysForReturnCalculation - 1; i<this.PortfolioRatesOfReturn.Length - this.numDaysForReturnCalculation; i += this.numDaysForReturnCalculation) { gainForTheLastHalfPeriod = 0.0; for(int j=this.numDaysForReturnCalculation - 1; j > -1; j--) { gainForTheLastHalfPeriod = (1.0+gainForTheLastHalfPeriod) * this.PortfolioRatesOfReturn[i-j]; } for(int t=1;t<this.numDaysForReturnCalculation + 1;t++) { if(gainForTheLastHalfPeriod<0.0) // if gain of first half period is negative returnValue[i+t] = this.PortfolioRatesOfReturn[i+t]; else returnValue[i+t] = - this.PortfolioRatesOfReturn[i+t]; } } return returnValue; } } } --- NEW FILE: RunExtremeCounterTrend.cs --- /* QuantProject - Quantitative Finance Library RunExtremeCounterTrend.cs Copyright (C) 2003 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.Data; using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Scripting; using QuantProject.Business.Strategies; using QuantProject.Business.Testing; using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; using QuantProject.ADT.FileManaging; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.ExtremeCounterTrend { /// <summary> /// Script that implements an oscillating strategy, /// for finding tickers that tend to /// earn (lose) from previous losses (gains), using efficient portfolios /// </summary> [Serializable] public class RunExtremeCounterTrend : RunEfficientPortfolio { private int numDaysForReturnCalculation; private double maxAcceptableCloseToCloseDrawdown; private int numDaysBetweenEachOptimization; public RunExtremeCounterTrend(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, int numDaysForReturnCalculation, int numDaysBetweenEachOptimization, PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown, double maxRunningHours): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, startDate, endDate, 0.0, portfolioType, maxRunningHours) { this.ScriptName = "ExtremeCounterTrendScriptWithSharpe"; this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } #region auxiliary overriden methods for Run protected override void run_initializeEndOfDayTimerHandler() { this.endOfDayTimerHandler = new EndOfDayTimerHandlerECT(this.tickerGroupID, this.numberOfEligibleTickers, this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, this.account, this.generationNumberForGeneticOptimizer, this.populationSizeForGeneticOptimizer, this.benchmark, this.numDaysForReturnCalculation, this.numDaysBetweenEachOptimization, this.portfolioType, this.maxAcceptableCloseToCloseDrawdown); } protected override void run_initializeHistoricalQuoteProvider() { this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); } protected override void run_addEventHandlers() { this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.endOfDayTimerHandler.MarketCloseEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); this.endOfDayTimer.OneHourAfterMarketClose += new OneHourAfterMarketCloseEventHandler( this.endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler); } public override void SaveScriptResults() { string fileName = "From"+this.numberOfEligibleTickers + "OptDays" + this.numDaysForOptimizationPeriod + "Portfolio" + this.numberOfTickersToBeChosen + "GenNum" + this.generationNumberForGeneticOptimizer + "PopSize" + this.populationSizeForGeneticOptimizer + "HalfPeriodDays" + Convert.ToString(this.numDaysForReturnCalculation) + Convert.ToString(this.portfolioType); string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.ScriptName + "\\"; string dirNameWhereToSaveTransactions = System.Configuration.ConfigurationSettings.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; string dirNameWhereToSaveBestGenomes = System.Configuration.ConfigurationSettings.AppSettings["GenomesArchive"] + "\\" + this.ScriptName + "\\"; //default report with numIntervalDays = 1 AccountReport accountReport = this.account.CreateReport(fileName,1, this.endOfDayTimer.GetCurrentTime(), this.benchmark, new HistoricalAdjustedQuoteProvider()); this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ObjectArchiver.Archive(accountReport, dirNameWhereToSaveReports + fileName + ".qPr"); // // this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveTransactions); // ObjectArchiver.Archive(this.account.Transactions, // dirNameWhereToSaveTransactions + // fileName + ".qPt"); // this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); OptimizationOutput optimizationOutput = new OptimizationOutput(); foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) optimizationOutput.Add(genomeRepresentation); ObjectArchiver.Archive(optimizationOutput, dirNameWhereToSaveBestGenomes + fileName + ".bgn"); this.endOfDayTimer.Stop(); } #endregion } } |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv8867 Added Files: RunFPOscillatorCTC.cs GenomeManagerForFPOscillatorCTC.cs EndOfDayTimerHandlerFPOscillatorCTC.cs Log Message: Added FixedPeriodOscillator strategy, based on technical analysis concepts. --- NEW FILE: EndOfDayTimerHandlerFPOscillatorCTC.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerFPOscillatorCTC.cs Copyright (C) 2003 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.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.Strategies; 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; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedPeriodOscillators { /// <summary> /// Implements MarketOpenEventHandler and MarketCloseEventHandler /// These handlers contain the core strategy for the oscillator /// close to close strategy! /// </summary> [Serializable] public class EndOfDayTimerHandlerFPOscillatorCTC : EndOfDayTimerHandler { private int numDaysForReturnCalculation; private double maxAcceptableCloseToCloseDrawdown; private bool stopLossConditionReached; private double currentAccountValue; private double previousAccountValue; private int numDaysBetweenEachOptimization; private int numDaysElapsedSinceLastOptimization; private int daysCounterWithPositions; private int daysCounterWithRightPositions; private int daysCounterWithReversalPositions; private bool isReversalPeriodOn = false; // private bool isTheFirstClose = false; private DateTime lastCloseDate; private IGenomeManager iGenomeManager; public EndOfDayTimerHandlerFPOscillatorCTC(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, int numDaysForReturnCalculation, PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, 0.0, portfolioType) { this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.daysCounterWithRightPositions = 0; this.daysCounterWithReversalPositions = 0; this.isReversalPeriodOn = false; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; this.stopLossConditionReached = false; this.currentAccountValue = 0.0; this.previousAccountValue = 0.0; this.numDaysBetweenEachOptimization = 2* numDaysForReturnCalculation; this.numDaysBetweenEachOptimization = numDaysForReturnCalculation; } #region MarketCloseEventHandler protected void marketCloseEventHandler_updateStopLossCondition() { this.previousAccountValue = this.currentAccountValue; this.currentAccountValue = this.account.GetMarketValue(); if((this.currentAccountValue - this.previousAccountValue) /this.previousAccountValue < -this.maxAcceptableCloseToCloseDrawdown) { this.stopLossConditionReached = true; } else { this.stopLossConditionReached = false; } } private void marketCloseEventHandler_reverseSignOfTickers(string[] signedTickers) { for(int i = 0; i<signedTickers.Length; i++) if(signedTickers[i] != null) signedTickers[i] = SignedTicker.GetOppositeSignedTicker(signedTickers[i]); } private void marketCloseEventHandler_updateCounters(bool isTheFirstClose) { if(this.account.Portfolio.Count > 0 && isTheFirstClose == false) { if(this.isReversalPeriodOn) this.daysCounterWithReversalPositions++ ; else this.daysCounterWithRightPositions++ ; } } private bool marketCloseEventHandler_openPositionsIfTuned_isTuned(IndexBasedEndOfDayTimer timer) { bool returnValue = false; try { double gainForTheLastHalfPeriod; DateTime initialDateForHalfPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition - this.numDaysForReturnCalculation + 1]["quDate"]; DateTime finalDateForHalfPeriod = (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition]["quDate"]; gainForTheLastHalfPeriod = SignedTicker.GetCloseToClosePortfolioReturn( this.chosenTickers, this.chosenTickersPortfolioWeights, initialDateForHalfPeriod,finalDateForHalfPeriod); if(gainForTheLastHalfPeriod < 0.0) //in the last periods the combination has lost, so //it should gain the next days returnValue = true; return returnValue; } catch(MissingQuotesException ex) { ex = ex; return returnValue; } } private void marketCloseEventHandler_openPositionsIfTuned(IndexBasedEndOfDayTimer timer) { if(this.marketCloseEventHandler_openPositionsIfTuned_isTuned(timer)) base.openPositions(); } private void marketCloseEventHandler_closePositions() { this.daysCounterWithPositions++; if(this.daysCounterWithPositions == this.numDaysForReturnCalculation || this.stopLossConditionReached) { //Close if halfPeriod has elapsed or stop loss condition reached base.closePositions(); this.daysCounterWithPositions = 0; } } public override void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { this.marketCloseEventHandler_updateStopLossCondition(); if(this.account.Portfolio.Count == 0 && this.chosenTickers[0] != null) //portfolio is empty and tickers to buy have been chosen this.marketCloseEventHandler_openPositionsIfTuned((IndexBasedEndOfDayTimer)sender); else this.marketCloseEventHandler_closePositions(); //OLD IMPLEMENTATION: always on the market // //update isTheFirstClose and optimize after adding cash // //(this first optimization could be done also after market close) // if (this.account.Transactions.Count == 0) // { // this.isTheFirstClose = true; // this.marketCloseEventHandler_optimize(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime); // } // else // { // this.isTheFirstClose = false; // } // this.marketCloseEventHandler_updateCounters(this.isTheFirstClose); // this.marketCloseEventHandler_updateStopLossCondition(); // // if(this.stopLossConditionReached) // { // this.orders.Clear(); // this.closePositions(); // this.daysCounterWithReversalPositions = 0; // this.daysCounterWithRightPositions = 0; // this.marketCloseEventHandler_optimize(this.lastCloseDate); // this.openPositions(); // } // else // { // if(this.account.Portfolio.Count == 0) // { // this.orders.Clear(); // this.openPositions(); // } // // if((this.isTheFirstClose == false && this.isReversalPeriodOn == false && // this.daysCounterWithRightPositions == this.numDaysForReturnCalculation)) // { // this.orders.Clear(); // this.closePositions(); // this.daysCounterWithRightPositions = 0; // this.marketCloseEventHandler_reverseSignOfTickers(this.chosenTickers); // this.openPositions(); // this.isReversalPeriodOn = true; // } // // if((this.isReversalPeriodOn == true && // this.daysCounterWithReversalPositions == this.numDaysForReturnCalculation)) // { // this.orders.Clear(); // this.closePositions(); // this.daysCounterWithReversalPositions = 0; // this.isReversalPeriodOn = false; // //code for only one optimization //// this.marketCloseEventHandler_reverseSignOfTickers(this.chosenTickers); //// this.openPositions(); // // // //normal strategy // this.marketCloseEventHandler_optimize(this.lastCloseDate); // this.openPositions(); // } // // } //END OF OLD IMPLEMENTATION } #endregion #region OneHourAfterMarketCloseEventHandler protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); SelectorByQuotationAtEachMarketDay quotedAtEachMarketFromTemporized = new SelectorByQuotationAtEachMarketDay(temporizedGroup.GetTableOfSelectedTickers(), false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfEligibleTickers, this.benchmark); // SelectorByCloseToCloseVolatility lessVolatile = new SelectorByCloseToCloseVolatility( // quotedAtEachMarketFromTemporized.GetTableOfSelectedTickers(),true, // currentDate.AddDays(-15), currentDate, // this.numberOfEligibleTickers); // // return lessVolatile.GetTableOfSelectedTickers(); return quotedAtEachMarketFromTemporized.GetTableOfSelectedTickers(); } protected virtual void setTickers(DateTime currentDate, bool setGenomeCounter) { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); if(setOfTickersToBeOptimized.Rows.Count > this.chosenTickers.Length*2) //the optimization process is meaningful only if the initial set of tickers is //larger than the number of tickers to be chosen { //double targetReturnForEachPeriodOfPortfolioLife = // Math.Pow(1.60,(double)(1.0/(360.0/this.numDaysOfPortfolioLife))) - 1.0; //the target has to be such that annual system return is minimum 50% //(with no commissions and bid-ask spreads) // IGenomeManager genManOscillatorCTC = // new GenomeManagerForEfficientCTCPortfolio(setOfTickersToBeOptimized, // currentDate.AddDays(-this.numDaysForOptimizationPeriod), // currentDate, this.numberOfTickersToBeChosen, // this.numDaysForReturnCalculation, 0.0, // this.portfolioType); this.iGenomeManager = new GenomeManagerForFPOscillatorCTC(setOfTickersToBeOptimized, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, this.numDaysForReturnCalculation, this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(this.iGenomeManager, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer, ConstantsProvider.SeedForRandomGenerator); if(setGenomeCounter) this.genomeCounter = new GenomeCounter(GO); GO.Run(false); this.addGenomeToBestGenomes(GO.BestGenome,((GenomeManagerForEfficientPortfolio)this.iGenomeManager).FirstQuoteDate, ((GenomeManagerForEfficientPortfolio)this.iGenomeManager).LastQuoteDate); this.chosenTickers = ((GenomeMeaning)GO.BestGenome.Meaning).Tickers; this.chosenTickersPortfolioWeights = ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights; } //else it will be buyed again the previous optimized portfolio //that's it the actual chosenTickers member } /// <summary> /// Handles a "One hour after market close" event. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> public override void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { this.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ConstantsProvider.SeedForRandomGenerator++; this.numDaysElapsedSinceLastOptimization++; this.orders.Clear(); if((this.numDaysElapsedSinceLastOptimization - 1 == this.numDaysBetweenEachOptimization)) //|| this.isTheFirstClose ) //num days without optimization has elapsed or //it is the first close (OLD IMPLEMENTATION) { this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); //sets tickers to be chosen next Market Close event this.numDaysElapsedSinceLastOptimization = 0; } } #endregion } } --- NEW FILE: RunFPOscillatorCTC.cs --- /* QuantProject - Quantitative Finance Library RunFPOscillatorCTC.cs Copyright (C) 2003 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.Data; using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Scripting; using QuantProject.Business.Strategies; using QuantProject.Business.Testing; using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; using QuantProject.ADT.FileManaging; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedPeriodOscillators { /// <summary> /// Script that implements an oscillating strategy, /// for all market days (fixed period), using efficient portfolios /// </summary> [Serializable] public class RunFPOscillatorCTC : RunEfficientPortfolio { private int numDaysForReturnCalculation; private double maxAcceptableCloseToCloseDrawdown; private int numDaysBetweenEachOptimization; public RunFPOscillatorCTC(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, int numDaysForReturnCalculation, PortfolioType portfolioType, double maxAcceptableCloseToCloseDrawdown, double maxRunningHours): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, startDate, endDate, 0.0, portfolioType, maxRunningHours) { this.ScriptName = "FixedPeriodOscillatorCTCScriptWithSharpe"; this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; this.numDaysBetweenEachOptimization = numDaysForReturnCalculation; } #region auxiliary overriden methods for Run protected override void run_initializeEndOfDayTimerHandler() { this.endOfDayTimerHandler = new EndOfDayTimerHandlerFPOscillatorCTC(this.tickerGroupID, this.numberOfEligibleTickers, this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, this.account, this.generationNumberForGeneticOptimizer, this.populationSizeForGeneticOptimizer, this.benchmark, this.numDaysForReturnCalculation, this.portfolioType, this.maxAcceptableCloseToCloseDrawdown); } protected override void run_initializeHistoricalQuoteProvider() { this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); } protected override void run_addEventHandlers() { this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.endOfDayTimerHandler.MarketCloseEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); this.endOfDayTimer.OneHourAfterMarketClose += new OneHourAfterMarketCloseEventHandler( this.endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler); } public override void SaveScriptResults() { string fileName = "From"+this.numberOfEligibleTickers + "OptDays" + this.numDaysForOptimizationPeriod + "Portfolio" + this.numberOfTickersToBeChosen + "GenNum" + this.generationNumberForGeneticOptimizer + "PopSize" + this.populationSizeForGeneticOptimizer + "HalfPeriodDays" + Convert.ToString(this.numDaysForReturnCalculation) + Convert.ToString(this.portfolioType); string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.ScriptName + "\\"; string dirNameWhereToSaveTransactions = System.Configuration.ConfigurationSettings.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; string dirNameWhereToSaveBestGenomes = System.Configuration.ConfigurationSettings.AppSettings["GenomesArchive"] + "\\" + this.ScriptName + "\\"; //default report with numIntervalDays = 1 AccountReport accountReport = this.account.CreateReport(fileName,1, this.endOfDayTimer.GetCurrentTime(), this.benchmark, new HistoricalAdjustedQuoteProvider()); this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ObjectArchiver.Archive(accountReport, dirNameWhereToSaveReports + fileName + ".qPr"); // // this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveTransactions); // ObjectArchiver.Archive(this.account.Transactions, // dirNameWhereToSaveTransactions + // fileName + ".qPt"); // this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); OptimizationOutput optimizationOutput = new OptimizationOutput(); foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) optimizationOutput.Add(genomeRepresentation); ObjectArchiver.Archive(optimizationOutput, dirNameWhereToSaveBestGenomes + fileName + ".bgn"); this.endOfDayTimer.Stop(); } #endregion } } --- NEW FILE: GenomeManagerForFPOscillatorCTC.cs --- /* QuantProject - Quantitative Finance Library GenomeManagerForFPOscillatorCTC.cs Copyright (C) 2003 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.Statistics; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Data; using QuantProject.Data.DataTables; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedPeriodOscillators { /// <summary> /// Implements what needed to use the Genetic Optimizer /// for finding the portfolio that best suites /// the fixed period Oscillator strategy /// </summary> [Serializable] public class GenomeManagerForFPOscillatorCTC : GenomeManagerForEfficientPortfolio { private int numDaysForReturnCalculation; public GenomeManagerForFPOscillatorCTC(DataTable setOfInitialTickers, DateTime firstQuoteDate, DateTime lastQuoteDate, int numberOfTickersInPortfolio, int numDaysForReturnCalculation, PortfolioType portfolioType) : base(setOfInitialTickers, firstQuoteDate, lastQuoteDate, numberOfTickersInPortfolio, 0.0, portfolioType) { this.numDaysForReturnCalculation = numDaysForReturnCalculation; this.retrieveData(); } private float[] getArrayOfRatesOfReturn_getAdjustedArray(Quotes sourceQuotes, int numDaysForHalfPeriod, ref DateTime firstQuoteDate) { float[] returnValue = ExtendedDataTable.GetArrayOfFloatFromColumn(sourceQuotes, Quotes.AdjustedCloseToCloseRatio); for(int i = 0;i<returnValue.Length;i++) returnValue[i] = returnValue[i]-1; //in order to be alligned at the following market day, //the array has to be long n, where n is such that //n%(2 * hp) + 1 = 2 * hp (hp = half period) //if some rates are deleted, first quote day has to be updated while( (returnValue.Length + 1) % (2*numDaysForHalfPeriod) != 0) { float[] newReturnValue = new float[returnValue.Length - 1]; for(int k = 0;k<returnValue.Length - 1;k++) newReturnValue[k] = returnValue[k + 1]; returnValue = newReturnValue; firstQuoteDate = firstQuoteDate.AddDays(1); firstQuoteDate = sourceQuotes.GetQuoteDateOrFollowing(firstQuoteDate); } return returnValue; } protected override float[] getArrayOfRatesOfReturn(string ticker) { float[] returnValue = null; Quotes tickerQuotes = new Quotes(ticker, this.firstQuoteDate, this.lastQuoteDate); returnValue = this.getArrayOfRatesOfReturn_getAdjustedArray(tickerQuotes, this.numDaysForReturnCalculation, ref this.firstQuoteDate); this.numberOfExaminedReturns = returnValue.Length; return returnValue; } // //implementation with fitness as average of modified sh for single tickers // private double getFitnessValue_getModifiedSharpeRatioForTicker(int[] genes, // int tickerPositionInGenes) // { // bool longReturns = false; // if(genes[tickerPositionInGenes] > 0) // //genes[tickerPositionInGenes], the code for ticker, points to a ticker for which long returns are to be examined // longReturns = true; // int position = this.getPortfolioRatesOfReturn_getRateOfTickerToBeAddedToTheArray_getPositionInArray(genes[tickerPositionInGenes]); // this.setOfCandidates[position].LongRatesOfReturn = longReturns; // float[] arrayOfRatesOfReturn = this.setOfCandidates[position].ArrayOfRatesOfReturn; // float[] strategyReturns = new float[arrayOfRatesOfReturn.Length]; // float sign = 1.0F; // for(int i=0; i<arrayOfRatesOfReturn.Length; i++) // { // if(i > 0 && (i % this.numDaysForReturnCalculation == 0) ) // sign = -sign; // // strategyReturns[i] = sign * arrayOfRatesOfReturn[i]; // } // double stdDev = BasicFunctions.StdDev(strategyReturns); // double powerForStdDev = 2.0; // // return BasicFunctions.SimpleAverage(strategyReturns)/ // Math.Pow(stdDev, powerForStdDev); // } // //// new implementation: fitness is the averaged sum of the "modified" sharpeRatios //// for each single ticker // public override double GetFitnessValue(Genome genome) // { // double returnValue = 0.0; // for(int i = 0; i<genome.Size; i++) // { // returnValue += this.getFitnessValue_getModifiedSharpeRatioForTicker( genome.Genes(),i ); // } // return returnValue/genome.Size; // } public override object Decode(Genome genome) { string[] arrayOfTickers = new string[genome.Genes().Length]; int indexOfTicker; for(int index = 0; index < genome.Genes().Length; index++) { indexOfTicker = (int)genome.Genes().GetValue(index); arrayOfTickers[index] = this.decode_getTickerCodeForLongOrShortTrade(indexOfTicker); } GenomeMeaning meaning = new GenomeMeaning(arrayOfTickers); return meaning; } //OLD IMPLEMENTATION - linear combination public override double GetFitnessValue(Genome genome) { double returnValue = 0.0; this.portfolioRatesOfReturn = this.getPortfolioRatesOfReturn(genome.Genes()); double[] oscillatorPortfolioRatesOfReturn = this.getFitnessValue_getOscillatorRates(); double averageOscillatorPortfolioRateOfReturn = BasicFunctions.SimpleAverage(oscillatorPortfolioRatesOfReturn); double oscillatorPortfolioStdDev = BasicFunctions.StdDev(oscillatorPortfolioRatesOfReturn); returnValue = averageOscillatorPortfolioRateOfReturn / Math.Pow(oscillatorPortfolioStdDev,1.2); return returnValue; } private double[] getFitnessValue_getOscillatorRates() { double[] returnValue = new double[this.PortfolioRatesOfReturn.Length]; double sign = 1.0; for(int i = 0;i<this.PortfolioRatesOfReturn.Length; i++) { if(i > 0 && (i % this.numDaysForReturnCalculation == 0) ) sign = -sign; returnValue[i] = sign*this.PortfolioRatesOfReturn[i]; } return returnValue; } //new implementation: changed how fitness is computed //now it is the sharpe ratio for the equity line resulting //from applying the strategy // public override double GetFitnessValue(Genome genome) // { // double returnValue = 0.0; // this.portfolioRatesOfReturn = this.getPortfolioRatesOfReturn(genome.Genes()); // // double[] equityLine = this.getFitnessValue_getEquityLineRates(); // // double averageEquityLineRateOfReturn = // BasicFunctions.SimpleAverage(equityLine); // // double equityLineStdDev = // BasicFunctions.StdDev(equityLine); // // returnValue = averageEquityLineRateOfReturn / // Math.Pow(equityLineStdDev,2.0); // // return returnValue; // } // // private double[] getFitnessValue_getEquityLineRates() // { // double[] returnValue = new double[this.PortfolioRatesOfReturn.Length]; // double sign = 1.0; // for(int i = this.numDaysForReturnCalculation - 1; // i<this.PortfolioRatesOfReturn.Length; // i++) // { // // if gain of last half period is negative, // // then add to the array the returns of the second half // } // // return returnValue; // } } } |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:27:22
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv8202/FixedPeriodOscillators Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators added to the repository |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:27:08
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv8014/ExtremeCounterTrend Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend added to the repository |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:26:53
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv7876/Oscillators Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators added to the repository |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:26:07
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv7552/TechnicalAnalysisTesting Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting added to the repository |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:25:34
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading/SimplePairTrading/InSample In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv7517/PairTrading/SimplePairTrading/InSample Added Files: RunSimplePairTradingIS.cs OutputDisplayer.cs OptimizationOutput.cs GenomeRepresentation.cs EndOfDayTimerHandlerSimplePTIS.cs Log Message: Added SimplePairTrading strategy, based on arbitrage concepts --- NEW FILE: OutputDisplayer.cs --- /* QuantProject - Quantitative Finance Library OutputDisplayer.cs Copyright (C) 2003 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.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; namespace QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading.InSample { /// <summary> /// Summary description for OutputDisplayer /// </summary> public class OutputDisplayer : System.Windows.Forms.Form { private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button buttonLoadFromFile; private System.Windows.Forms.DateTimePicker dtpLastDate; private System.Windows.Forms.DateTimePicker dtpFirstDate; private System.Windows.Forms.TextBox textBoxMaxNumOfStdDevForNormalGap; private System.Windows.Forms.DataGrid dgBestGenomes; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; // user code private ArrayList bestGenomes; private GenomeRepresentation lastSelectedGenomeRepresentation; private void outputDisplayer() { this.dgBestGenomes.DataSource = this.bestGenomes; DataGridTableStyle styleForGrid = new DataGridTableStyle(); styleForGrid.AllowSorting = true; this.dgBestGenomes.TableStyles.Add(styleForGrid); } public OutputDisplayer( DateTime firstDate , DateTime lastDate , ArrayList bestGenomes ) { if ( bestGenomes.Count == 0 ) throw new Exception( "bestGenomes is empty! It should contain " + "a genome, at least." ); // // Required for Windows Form Designer support // InitializeComponent(); // Marco code this.lastSelectedGenomeRepresentation = ((GenomeRepresentation)bestGenomes[0]); this.dtpFirstDate.Value = this.lastSelectedGenomeRepresentation.FirstOptimizationDate; this.dtpLastDate.Value = this.lastSelectedGenomeRepresentation.LastOptimizationDate; this.bestGenomes = bestGenomes; this.outputDisplayer(); } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.dgBestGenomes = new System.Windows.Forms.DataGrid(); this.textBoxMaxNumOfStdDevForNormalGap = new System.Windows.Forms.TextBox(); this.dtpFirstDate = new System.Windows.Forms.DateTimePicker(); this.dtpLastDate = new System.Windows.Forms.DateTimePicker(); this.buttonLoadFromFile = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dgBestGenomes)).BeginInit(); this.SuspendLayout(); // // dgBestGenomes // this.dgBestGenomes.DataMember = ""; this.dgBestGenomes.Dock = System.Windows.Forms.DockStyle.Bottom; this.dgBestGenomes.HeaderForeColor = System.Drawing.SystemColors.ControlText; this.dgBestGenomes.Location = new System.Drawing.Point(0, 173); this.dgBestGenomes.Name = "dgBestGenomes"; this.dgBestGenomes.Size = new System.Drawing.Size(584, 200); this.dgBestGenomes.TabIndex = 0; this.dgBestGenomes.MouseUp += new System.Windows.Forms.MouseEventHandler(this.dgBestGenomes_MouseUp); // // textBoxMaxNumOfStdDevForNormalGap // this.textBoxMaxNumOfStdDevForNormalGap.Location = new System.Drawing.Point(264, 88); this.textBoxMaxNumOfStdDevForNormalGap.Name = "textBoxMaxNumOfStdDevForNormalGap"; this.textBoxMaxNumOfStdDevForNormalGap.TabIndex = 5; this.textBoxMaxNumOfStdDevForNormalGap.Text = "1"; // // dtpFirstDate // this.dtpFirstDate.Location = new System.Drawing.Point(16, 48); this.dtpFirstDate.Name = "dtpFirstDate"; this.dtpFirstDate.TabIndex = 1; // // dtpLastDate // this.dtpLastDate.Location = new System.Drawing.Point(264, 48); this.dtpLastDate.Name = "dtpLastDate"; this.dtpLastDate.Size = new System.Drawing.Size(208, 20); this.dtpLastDate.TabIndex = 2; // // buttonLoadFromFile // this.buttonLoadFromFile.Location = new System.Drawing.Point(168, 8); this.buttonLoadFromFile.Name = "buttonLoadFromFile"; this.buttonLoadFromFile.Size = new System.Drawing.Size(136, 24); this.buttonLoadFromFile.TabIndex = 4; this.buttonLoadFromFile.Text = "Load genomes"; // // label1 // this.label1.Location = new System.Drawing.Point(32, 128); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(400, 32); this.label1.TabIndex = 3; this.label1.Text = "Left click data grid rows to reset dates to the optimization period. Right click " + "to preserve date displacements and backtest."; // // label2 // this.label2.Location = new System.Drawing.Point(16, 88); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(200, 23); this.label2.TabIndex = 6; this.label2.Text = "Max Num of StDev for normal Gap"; // // OutputDisplayer // this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(584, 373); this.Controls.Add(this.label2); this.Controls.Add(this.textBoxMaxNumOfStdDevForNormalGap); this.Controls.Add(this.buttonLoadFromFile); this.Controls.Add(this.label1); this.Controls.Add(this.dtpLastDate); this.Controls.Add(this.dtpFirstDate); this.Controls.Add(this.dgBestGenomes); this.Name = "OutputDisplayer"; this.Text = "OutputDisplayer SimplePairTrading"; ((System.ComponentModel.ISupportInitialize)(this.dgBestGenomes)).EndInit(); this.ResumeLayout(false); } #endregion private bool aRowHasBeenClicked( object sender, System.Windows.Forms.MouseEventArgs e ) { DataGrid dataGrid = (DataGrid)sender; Point point = new Point( e.X , e.Y ); DataGrid.HitTestInfo hitTestInfo = dataGrid.HitTest( point ); return hitTestInfo.Row>=0; } private GenomeRepresentation dgBestGenomes_MouseUp_getClickedGenomeRepresentation( object sender, System.Windows.Forms.MouseEventArgs e ) { GenomeRepresentation genomeRepresentation = null; DataGrid dataGrid = (DataGrid)sender; Point point = new Point( e.X , e.Y ); DataGrid.HitTestInfo hitTestInfo = dataGrid.HitTest( point ); ArrayList bestGenomes = (ArrayList)dataGrid.DataSource; // DataRow dataRow = dataTable.Rows[ hitTestInfo.Row ]; if ( hitTestInfo.Row >= 0 ) // a grid row has been clicked, not the header genomeRepresentation = (GenomeRepresentation)bestGenomes[ hitTestInfo.Row ]; return genomeRepresentation; } private void dgBestGenomes_MouseUp_rightButton_updateDates( GenomeRepresentation newSelectedGenomeRepresentation ) { TimeSpan currentFirstDateDisplacement = ( this.dtpFirstDate.Value - this.lastSelectedGenomeRepresentation.FirstOptimizationDate ); TimeSpan currentLastDateDisplacement = ( this.dtpLastDate.Value - this.lastSelectedGenomeRepresentation.LastOptimizationDate ); this.dtpFirstDate.Value = newSelectedGenomeRepresentation.FirstOptimizationDate + currentFirstDateDisplacement; this.dtpLastDate.Value = newSelectedGenomeRepresentation.LastOptimizationDate + currentLastDateDisplacement; } private void dgBestGenomes_MouseUp_rightButton(object sender, System.Windows.Forms.MouseEventArgs e) { GenomeRepresentation genomeRepresentation = this.dgBestGenomes_MouseUp_getClickedGenomeRepresentation( sender , e ); dgBestGenomes_MouseUp_rightButton_updateDates( genomeRepresentation ); RunSimplePairTradingIS runSimplePairTradingIS = new RunSimplePairTradingIS(Convert.ToDouble(this.textBoxMaxNumOfStdDevForNormalGap.Text), genomeRepresentation.NumDaysForGap, genomeRepresentation.AverageGap, genomeRepresentation.StdDevGap, genomeRepresentation.FirstTicker, genomeRepresentation.SecondTicker, this.dtpFirstDate.Value , this.dtpLastDate.Value); runSimplePairTradingIS.Run(); this.lastSelectedGenomeRepresentation = genomeRepresentation; } private void dgBestGenomes_MouseUp_leftButton_updateDates( GenomeRepresentation newSelectedGenomeRepresentation ) { this.dtpFirstDate.Value = newSelectedGenomeRepresentation.FirstOptimizationDate; this.dtpLastDate.Value = newSelectedGenomeRepresentation.LastOptimizationDate; } private void dgBestGenomes_MouseUp_leftButton(object sender, System.Windows.Forms.MouseEventArgs e) { if ( aRowHasBeenClicked( sender , e ) ) // a grid row has been clicked, not the header { GenomeRepresentation newSelectedGenomeRepresentation = this.dgBestGenomes_MouseUp_getClickedGenomeRepresentation( sender , e ); dgBestGenomes_MouseUp_leftButton_updateDates( newSelectedGenomeRepresentation ); this.lastSelectedGenomeRepresentation = newSelectedGenomeRepresentation; } } private void dgBestGenomes_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e) { if ( e.Button == MouseButtons.Right ) this.dgBestGenomes_MouseUp_rightButton( sender , e ); if ( e.Button == MouseButtons.Left ) this.dgBestGenomes_MouseUp_leftButton( sender , e ); } } } --- NEW FILE: OptimizationOutput.cs --- /* QuantProject - Quantitative Finance Library OptimizationOutput.cs Copyright (C) 2003 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; namespace QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading.InSample { /// <summary> /// Data to be saved/load to/from disk, resulting from the /// optimization process. /// </summary> [Serializable] public class OptimizationOutput : ArrayList { // public ArrayList BestGenomes // { // get { return this.bestGenomes; } // } public OptimizationOutput() { } /// <summary> /// Adds a genome representation /// </summary> /// <param name="genomeRepresentation"></param> public void Add( GenomeRepresentation genomeRepresentation ) { base.Add( genomeRepresentation ); } } } --- NEW FILE: EndOfDayTimerHandlerSimplePTIS.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerSimplePTIS.cs Copyright (C) 2003 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.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.DataProviders; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Data.DataTables; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading { /// <summary> /// Implements MarketOpenEventHandler, /// MarketCloseEventHandler and OneHourAfterMarketCloseEventHandler /// for the implementation of the simple pair trading strategy for /// two given tickers for a given time interval /// </summary> [Serializable] public class EndOfDayTimerHandlerSimplePTIS : EndOfDayTimerHandlerSimplePT { private int numDaysForGap; private double averageGap; private double stdDevGap; private void endOfDayTimeHandlerSimplePTIS_setChosenTickers(string firstTicker, string secondTicker, double averageGap, double stdDevGap) { for(int i = 0;i<this.averageGapsOfChosenTickers.Length;i++) { this.averageGapsOfChosenTickers[i] = averageGap; this.stdDevGapsOfChosenTickers[i] = stdDevGap; if(i%2 == 0) this.chosenTickers[i] = firstTicker; else this.chosenTickers[i] = secondTicker; } } public EndOfDayTimerHandlerSimplePTIS(double maxNumOfStdDevForNormalGap, int numDaysForGap, double averageGap, double stdDevGap, string firstTicker, string secondTicker, DateTime startDate, DateTime endDate, Account account) : base("",0,0,0,0, "^GSPC",startDate, endDate, maxNumOfStdDevForNormalGap, 0,0,0,0, account) { this.numDaysForGap = numDaysForGap; this.averageGap = averageGap; this.stdDevGap = stdDevGap; this.minimumGainForClosingPositions = 0.002; this.maximumToleratedLoss = 0.02; this.endOfDayTimeHandlerSimplePTIS_setChosenTickers(firstTicker, secondTicker, averageGap, stdDevGap); } /// <summary> /// Handles a "Market close" event. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> public override void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { if(((IndexBasedEndOfDayTimer)sender).GetPreviousDateTime() != endOfDayTimingEventArgs.EndOfDayDateTime.DateTime) //it is not the first date fired by the timer, so the // gap can be computed base.MarketCloseEventHandler(sender, endOfDayTimingEventArgs); } /// <summary> /// Handles a "One hour after market close" event. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> public override void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { } } } --- NEW FILE: GenomeRepresentation.cs --- /* QuantProject - Quantitative Finance Library GenomeRepresentation.cs Copyright (C) 2003 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.Financial.Ordering; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading; namespace QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading.InSample { /// <summary> /// Provides the genome relevant informations /// </summary> [Serializable] public class GenomeRepresentation { private double fitness; private string firstTicker; private string secondTicker; private DateTime firstOptimizationDate; private DateTime lastOptimizationDate; private int numDaysForGap; private double averageGap; private double stdDevGap; private double maxNumOfStdDevForNormalGap; private int generationCounter; public string FirstTicker { get{return this.firstTicker;} } public string SecondTicker { get{return this.secondTicker;} } public double Fitness { get { return this.fitness; } } public DateTime FirstOptimizationDate { get { return this.firstOptimizationDate; } } public DateTime LastOptimizationDate { get { return this.lastOptimizationDate; } } /// <summary> /// Number of the first generation containing the genome /// </summary> public int GenerationCounter { get { return this.generationCounter; } } public int NumDaysForGap { get { return this.numDaysForGap; } } public double AverageGap { get { return this.averageGap; } } public double StdDevGap { get { return this.stdDevGap; } } public double MaxNumOfStdDevForNormalGap { get { return this.maxNumOfStdDevForNormalGap; } } private void genomeRepresentation( double maxNumOfStdDevForNormalGap, Genome genome , DateTime firstOptimizationDate , DateTime lastOptimizationDate , int generationCounter ) { this.maxNumOfStdDevForNormalGap = maxNumOfStdDevForNormalGap; this.fitness = genome.Fitness; this.averageGap = ((GenomeMeaningSimplePT)genome.Meaning).AverageGap; this.stdDevGap = ((GenomeMeaningSimplePT)genome.Meaning).StdDevGap; this.firstTicker = ((GenomeMeaningSimplePT)genome.Meaning).FirstTicker; this.secondTicker = ((GenomeMeaningSimplePT)genome.Meaning).SecondTicker; this.numDaysForGap = ((GenomeMeaningSimplePT)genome.Meaning).NumOfDaysForGap; this.firstOptimizationDate = firstOptimizationDate; this.lastOptimizationDate = lastOptimizationDate; this.generationCounter = generationCounter; } public GenomeRepresentation( double maxNumOfStdDevForNormalGap, Genome genome , DateTime firstOptimizationDate , DateTime lastOptimizationDate ) { this.genomeRepresentation( maxNumOfStdDevForNormalGap, genome , firstOptimizationDate , lastOptimizationDate , -1 ); } public GenomeRepresentation( double maxNumOfStdDevForNormalGap, Genome genome , DateTime firstOptimizationDate , DateTime lastOptimizationDate , int generationCounter ) { this.genomeRepresentation( maxNumOfStdDevForNormalGap, genome , firstOptimizationDate , lastOptimizationDate , generationCounter ); } } } --- NEW FILE: RunSimplePairTradingIS.cs --- /* QuantProject - Quantitative Finance Library RunSimplePairTradingIS.cs Copyright (C) 2003 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.FileManaging; using QuantProject.Data.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Timing; using QuantProject.Business.Financial.Accounting.Commissions; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.DataProviders; using QuantProject.Presentation.Reporting.WindowsForm; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading; namespace QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading.InSample { /// <summary> /// Script to test the pair trading strategy for /// two tickers for a given time period /// </summary> [Serializable] public class RunSimplePairTradingIS { private double maxNumOfStdDevForNormalGap; private int numDaysForGap; private double averageGap; private double stdDevGap; private EndOfDayTimerHandlerSimplePT endOfDayTimerHandler; private string firstTicker; private string secondTicker; private DateTime startDateTime; private DateTime endDateTime; private IHistoricalQuoteProvider historicalQuoteProvider; private Account account; private IEndOfDayTimer endOfDayTimer; private string benchmark; private string scriptName; public RunSimplePairTradingIS(double maxNumOfStdDevForNormalGap, int numDaysForGap, double averageGap, double stdDevGap, string firstTicker, string secondTicker, DateTime startDate, DateTime endDate) { this.maxNumOfStdDevForNormalGap = maxNumOfStdDevForNormalGap; this.numDaysForGap = numDaysForGap; this.averageGap = averageGap; this.stdDevGap = stdDevGap; this.firstTicker = firstTicker; this.secondTicker = secondTicker; this.startDateTime = startDate; this.endDateTime = endDate; this.benchmark = "^GSPC"; this.scriptName = "SimplePairTradingForGivenTickers"; } #region Run private void run_initializeEndOfDayTimer() { //default endOfDayTimer this.endOfDayTimer = new IndexBasedEndOfDayTimer( new EndOfDayDateTime(this.startDateTime, EndOfDaySpecificTime.MarketOpen), this.benchmark ); } protected void run_initializeAccount() { //default account with no commissions and no slippage calculation this.account = new Account( this.scriptName , this.endOfDayTimer , new HistoricalEndOfDayDataStreamer( this.endOfDayTimer , this.historicalQuoteProvider ) , new HistoricalEndOfDayOrderExecutor( this.endOfDayTimer , this.historicalQuoteProvider )); } private void run_initializeHistoricalQuoteProvider() { this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); } private void checkDateForReport(Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { if(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime>=this.endDateTime) //last date is reached by the timer this.showReport(); } private void showReport() { AccountReport accountReport = this.account.CreateReport(this.scriptName, 1, this.endOfDayTimer.GetCurrentTime(), this.benchmark, new HistoricalAdjustedQuoteProvider()); Report report = new Report(accountReport); report.Show(); this.endOfDayTimer.Stop(); } private void run_initialize() { run_initializeHistoricalQuoteProvider(); run_initializeEndOfDayTimer(); run_initializeAccount(); run_initializeEndOfDayTimerHandler(); } public void Run() { this.run_initialize(); this.run_addEventHandlers(); this.endOfDayTimer.Start(); } private void run_initializeEndOfDayTimerHandler() { this.endOfDayTimerHandler = new EndOfDayTimerHandlerSimplePTIS(this.maxNumOfStdDevForNormalGap, this.numDaysForGap, this.averageGap, this.stdDevGap, this.firstTicker, this.secondTicker, this.startDateTime, this.endDateTime, this.account); } private void run_addEventHandlers() { this.endOfDayTimer.MarketOpen += new MarketOpenEventHandler( this.endOfDayTimerHandler.MarketOpenEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.endOfDayTimerHandler.MarketCloseEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); this.endOfDayTimer.OneHourAfterMarketClose += new OneHourAfterMarketCloseEventHandler( this.endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler ); } #endregion } } |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:25:34
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading/SimplePairTrading In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv7517/PairTrading/SimplePairTrading Added Files: SimplePTGenomeManipulator.cs RunSimplePairTrading.cs GenomeMeaningSimplePT.cs GenomeManagerForSimplePT.cs EndOfDayTimerHandlerSimplePT.cs Log Message: Added SimplePairTrading strategy, based on arbitrage concepts --- NEW FILE: EndOfDayTimerHandlerSimplePT.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerSimplePT.cs Copyright (C) 2003 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.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.DataProviders; 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.ArbitrageTesting.PairTrading.SimplePairTrading.InSample; namespace QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading { /// <summary> /// Implements MarketOpenEventHandler, /// MarketCloseEventHandler and OneHourAfterMarketCloseEventHandler /// for the implementation of the simple pair trading strategy /// </summary> [Serializable] public class EndOfDayTimerHandlerSimplePT { private string tickerGroupID; protected string[] chosenTickers = new string[10]; //this array is designed for containing //five couples of eligible tickers for //the pair trading strategy protected double[] averageGapsOfChosenTickers = new double[10]; protected double[] stdDevGapsOfChosenTickers = new double[10]; protected string[] lastOrderedTickers = new string[2]; protected int addedTickersCounter = 0; protected float currentPair_firstTickerGain = 0.0F; protected float currentPair_secondTickerGain = 0.0F; private int numberOfEligibleTickers; private int numDaysForOptimizationPeriod; private int generationNumberForGeneticOptimizer; private int populationSizeForGeneticOptimizer; protected string benchmark; protected DateTime startDate; protected DateTime endDate; protected double maxNumOfStdDevForNormalGap; private double maxLevelForNormalGap; private int minNumOfDaysForGapComputation; private int maxNumOfDaysForGapComputation; private int numDaysBetweenEachOptimization; private int numDaysElapsedSinceLastOptimization; private double maxRunningHours; protected Account account; private int seedForRandomGenerator; protected double minimumGainForClosingPositions; protected double maximumToleratedLoss; protected double initialAccountValue = 0.0; protected int counterForDaysWithPositions = 0; protected int currentNumDaysForGapComputation; //it stores the value for the new account protected HistoricalAdjustedQuoteProvider historicalAdjustedQuoteProvider; private OptimizationOutput optimizationOutput; public OptimizationOutput OptimizationOutput { get{return this.optimizationOutput;} } public EndOfDayTimerHandlerSimplePT(string tickerGroupID, int numberOfEligibleTickers, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, double maxNumOfStdDevForNormalGap, int minNumOfDaysForGapComputation, int maxNumOfDaysForGapComputation, int numDaysBetweenEachOptimization, double maxRunningHours, Account account) { this.tickerGroupID = tickerGroupID; this.numberOfEligibleTickers = numberOfEligibleTickers; this.numDaysForOptimizationPeriod = numDaysForOptimizationPeriod; this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; this.benchmark = benchmark; this.startDate = startDate; this.endDate = endDate; this.maxNumOfStdDevForNormalGap = maxNumOfStdDevForNormalGap; this.minNumOfDaysForGapComputation = minNumOfDaysForGapComputation; this.maxNumOfDaysForGapComputation = maxNumOfDaysForGapComputation; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.maxRunningHours = maxRunningHours; this.account = account; this.numDaysElapsedSinceLastOptimization = 0; this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; this.historicalAdjustedQuoteProvider = new HistoricalAdjustedQuoteProvider(); this.minimumGainForClosingPositions = 0.002; this.maximumToleratedLoss = 0.02; this.optimizationOutput = new OptimizationOutput(); } public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { } #region MarketCloseEventHandler public void marketCloseEventHandler_closePositions() { if(this.account.Portfolio[ this.lastOrderedTickers[0] ] != null) this.account.ClosePosition( this.lastOrderedTickers[0] ); if(this.account.Portfolio[ this.lastOrderedTickers[1] ] != null) this.account.ClosePosition( this.lastOrderedTickers[1] ); } private bool marketCloseEventHandler_isCurrentGainGoodEnoughOrStopLossConditionReached(EndOfDayDateTime currentEndOfDayDateTime) { bool returnValue = false; double currentGain = (this.account.GetMarketValue() - this.initialAccountValue)/ this.initialAccountValue; if(currentGain >= this.minimumGainForClosingPositions || -currentGain >= this.maximumToleratedLoss) //gain is good enough or loss is too high ... returnValue = true; return returnValue; } private float marketCloseEventHandler_openPositions_getGap(int indexForPair, DateTime firstDate, DateTime lastDate) { Quotes firstTickerQuotes = new Quotes(this.chosenTickers[indexForPair], firstDate, lastDate); Quotes secondTickerQuotes = new Quotes(this.chosenTickers[indexForPair+1], firstDate, lastDate); this.currentPair_firstTickerGain = (float)firstTickerQuotes.Rows[1]["quClose"]/(float)firstTickerQuotes.Rows[0]["quClose"]; this.currentPair_secondTickerGain = (float)secondTickerQuotes.Rows[1]["quClose"]/(float)secondTickerQuotes.Rows[0]["quClose"]; return (this.currentPair_firstTickerGain - this.currentPair_secondTickerGain); } private void marketCloseEventHandler_openPositions_open(int indexForPair) { double cashForSinglePosition = this.account.CashAmount/2; long quantityForFirstTicker = Convert.ToInt64( Math.Floor( cashForSinglePosition / this.account.DataStreamer.GetCurrentBid( this.chosenTickers[indexForPair] ) ) ); long quantityForSecondTicker = Convert.ToInt64( Math.Floor( cashForSinglePosition / this.account.DataStreamer.GetCurrentBid( this.chosenTickers[indexForPair+1] ) ) ); OrderType orderTypeForFirstTicker = OrderType.MarketBuy; OrderType orderTypeForSecondTicker = OrderType.MarketSellShort; if(this.currentPair_firstTickerGain > this.currentPair_secondTickerGain) { orderTypeForFirstTicker = OrderType.MarketSellShort; orderTypeForSecondTicker = OrderType.MarketBuy; } this.account.AddOrder(new Order( orderTypeForFirstTicker, new Instrument( this.chosenTickers[indexForPair] ) , quantityForFirstTicker )); this.account.AddOrder(new Order( orderTypeForSecondTicker, new Instrument( this.chosenTickers[indexForPair+1] ) , quantityForSecondTicker )); this.lastOrderedTickers[0] = this.chosenTickers[indexForPair]; this.lastOrderedTickers[1] = this.chosenTickers[indexForPair+1]; } private void marketCloseEventHandler_openPositions_setMaxLevelForNormalGap(int indexForPair) { this.maxLevelForNormalGap = this.averageGapsOfChosenTickers[indexForPair] + this.maxNumOfStdDevForNormalGap * this.stdDevGapsOfChosenTickers[indexForPair]; } private void marketCloseEventHandler_openPositions(EndOfDayDateTime currentEndOfDayDateTime, IndexBasedEndOfDayTimer timer) { if(this.chosenTickers[0] != null) //potential tickers for pair trading have been set { for(int i = 0; i<this.chosenTickers.Length - 1 && this.account.Portfolio.Count == 0; i++) { this.marketCloseEventHandler_openPositions_setMaxLevelForNormalGap(i); if(Math.Abs(this.marketCloseEventHandler_openPositions_getGap(i, timer.GetPreviousDateTime(), timer.GetCurrentTime().DateTime)) >= (float)this.maxLevelForNormalGap) //currentGap is too high for being considered rational //so there is an arbitrage opportunity this.marketCloseEventHandler_openPositions_open(i); } this.initialAccountValue = this.account.GetMarketValue(); //this.account.Portfolio.GetMarketValue(currentEndOfDayDateTime,this.historicalAdjustedQuoteProvider); } } public virtual void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { if(this.account.Portfolio.Count == 0) //portfolio is empty { if(this.account.Transactions.Count == 0) this.account.AddCash(30000); this.marketCloseEventHandler_openPositions(endOfDayTimingEventArgs.EndOfDayDateTime, (IndexBasedEndOfDayTimer)sender); } else // portfolio is not empty { this.counterForDaysWithPositions++; if(this.counterForDaysWithPositions == this.currentNumDaysForGapComputation || this.marketCloseEventHandler_isCurrentGainGoodEnoughOrStopLossConditionReached(endOfDayTimingEventArgs.EndOfDayDateTime)) //a number of days equal to the number of days //used for gap computation has elapsed or //the current gain is good enough or //loss is too high { this.marketCloseEventHandler_closePositions(); this.counterForDaysWithPositions = 0; } } } #endregion #region OneHourAfterMarketCloseEventHandler protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromEligible = new SelectorByQuotationAtEachMarketDay( temporizedGroup.GetTableOfSelectedTickers(), false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfEligibleTickers, this.benchmark); return quotedAtEachMarketDayFromEligible.GetTableOfSelectedTickers(); } private void setTickers_setChosenTickers_addGenomeForOptimizationOutput(Genome genome, DateTime currentDate) { this.optimizationOutput.Add(new GenomeRepresentation(this.maxNumOfStdDevForNormalGap, genome, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate)); } private void setTickers_setChosenTickers_addTickers(Genome genome) { this.chosenTickers[this.addedTickersCounter] = ((GenomeMeaningSimplePT)genome.Meaning).FirstTicker; this.chosenTickers[this.addedTickersCounter+1] = ((GenomeMeaningSimplePT)genome.Meaning).SecondTicker; this.averageGapsOfChosenTickers[this.addedTickersCounter] = ((GenomeMeaningSimplePT)genome.Meaning).AverageGap; this.stdDevGapsOfChosenTickers[this.addedTickersCounter] = ((GenomeMeaningSimplePT)genome.Meaning).StdDevGap; this.currentNumDaysForGapComputation = ((GenomeMeaningSimplePT)genome.Meaning).NumOfDaysForGap; this.addedTickersCounter += 2; } private bool setTickers_setChosenTickers_isAnyTickerOfGenomeInChosenTickers(Genome genome) { bool returnValue = false; foreach(string ticker in this.chosenTickers) { if(ticker == ((GenomeMeaningSimplePT)genome.Meaning).FirstTicker || ticker == ((GenomeMeaningSimplePT)genome.Meaning).SecondTicker) returnValue = true; } return returnValue; } private void setTickers_setChosenTickers(GeneticOptimizer GO, DateTime currentDate) { this.addedTickersCounter = 0; for(int i = 0; i<GO.CurrentGeneration.Count -1 && addedTickersCounter<this.chosenTickers.Length; i++) { Genome currentGenome = (Genome)GO.CurrentGeneration[GO.CurrentGeneration.Count-i-1]; if(!this.setTickers_setChosenTickers_isAnyTickerOfGenomeInChosenTickers(currentGenome)) { this.setTickers_setChosenTickers_addTickers(currentGenome); this.setTickers_setChosenTickers_addGenomeForOptimizationOutput(currentGenome, currentDate); } } } private void setTickers(DateTime currentDate) { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); IGenomeManager genManForSimplePT = new GenomeManagerForSimplePT(setOfTickersToBeOptimized, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.minNumOfDaysForGapComputation, this.maxNumOfDaysForGapComputation, this.maxNumOfStdDevForNormalGap); GeneticOptimizer GO = new GeneticOptimizer(genManForSimplePT, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer, this.seedForRandomGenerator); GO.Run(false); this.setTickers_setChosenTickers(GO, currentDate); } /// <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.seedForRandomGenerator++; if(this.numDaysElapsedSinceLastOptimization == this.numDaysBetweenEachOptimization - 1) { this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime); //sets tickers to be chosen at next Market Open event this.numDaysElapsedSinceLastOptimization = 0; } else { this.numDaysElapsedSinceLastOptimization++; } } #endregion } } --- NEW FILE: SimplePTGenomeManipulator.cs --- /* QuantProject - Quantitative Finance Library SimplePTGenomeManipulator.cs Copyright (C) 2003 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.Optimizing.Genetic; namespace QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading { /// <summary> /// Class providing static methods for manipulating Genomes /// (used by GenomeManagerForSimplePT) /// </summary> [Serializable] public sealed class SimplePTGenomeManipulator { public static Random RandomGenerator; private static int genomeSize; private static Genome[] childs; private static int[,] maskForChilds; static SimplePTGenomeManipulator() { RandomGenerator = new Random(ConstantsProvider.SeedForRandomGenerator); childs = new Genome[2]; } private static void initializeStaticMembers(Genome parent1, Genome parent2) { genomeSize = parent1.Size; childs[0]=parent1.Clone(); childs[1]=parent2.Clone(); maskForChilds = new int[childs.Length, genomeSize]; for(int i = 0; i<genomeSize; i++) { maskForChilds[0,i]=1; maskForChilds[1,i]=2; } //maskForChilds has been set in order to re-create //a copy of parents by using setChildsUsingMaskForChilds() } private static void setMaskForChildsForMixingWithoutDuplicates(Genome parent1, Genome parent2) { //exchange numOfDaysForGap maskForChilds[0, 0] = 2; maskForChilds[1, 0] = 1; //exchange tickers if possible if(!IsTickerContainedInGenome(parent1.GetGeneValue(1), parent2)) maskForChilds[1, 1] = 1; if(!IsTickerContainedInGenome(parent2.GetGeneValue(1), parent1)) maskForChilds[0, 1] = 2; } private static void setChildsUsingMaskForChilds(Genome parent1, Genome parent2) { for(int childIndex = 0; childIndex < 2; childIndex++) { for(int genePos = 0 ; genePos < SimplePTGenomeManipulator.genomeSize ; genePos++) { if(maskForChilds[childIndex,genePos]==1) childs[childIndex].SetGeneValue(parent1.GetGeneValue(genePos), genePos); else//maskForChilds[childIndex,genePos]==2 childs[childIndex].SetGeneValue(parent2.GetGeneValue(genePos), genePos); } } } /// <summary> /// This method returns an array of genomes based on /// a mix of the genes of parents, such that the 2 childs, /// if possible, are different from parents and, at /// the same time, childs' genes are not duplicated /// </summary> /// <param name="parent1">First genome parent from which genes are to be mixed in offspring</param> /// <param name="parents">Second genome parent from which genes are to be mixed in offspring</param> /// <param name="constToDiscoverGenesDuplicates">Gene y is a duplicate of gene x iff y = |x| - 1 /// or y = -|x| -1</param> public static Genome[] MixGenesWithoutDuplicates(Genome parent1, Genome parent2) { initializeStaticMembers(parent1, parent2); if(parent1.Size > (parent1.MaxValueForGenes - parent1.MinValueForGenes + 1)) //it is impossible not to duplicate genes if size is too // large for the range of variation of each gene throw new Exception("Impossible to avoid duplicates with the given size!"); if(parent1.Size != parent2.Size) throw new Exception("Genomes must have the same size!"); setMaskForChildsForMixingWithoutDuplicates(parent1, parent2); setChildsUsingMaskForChilds(parent1, parent2); //throwExcIfAChildHasDuplicateGenes(); //just for debugging purposes return childs; } /// <summary> /// Returns true if a given gene, when decoded by the /// GenomeManagerForSimplePT, refers to a /// ticker already contained in a given genome /// </summary> /// <param name="geneCorrespondingToATicker">Gene, corresponding to a certain ticker, that has to be checked</param> /// <param name="genome">Genome containing or not the ticker geneCorrespondingToATicker refers to</param> public static bool IsTickerContainedInGenome(int geneCorrespondingToATicker, Genome genome) { return geneCorrespondingToATicker == genome.GetGeneValue(1) || geneCorrespondingToATicker == genome.GetGeneValue(2); } } } --- NEW FILE: GenomeManagerForSimplePT.cs --- /* QuantProject - Quantitative Finance Library GenomeManagerForSimplePT.cs Copyright (C) 2003 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.Statistics; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.Data; using QuantProject.Data.DataTables; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading { /// <summary> /// This class implements IGenomeManager interface, in order to find /// tickers that best suite the pair trading strategy /// </summary> [Serializable] public class GenomeManagerForSimplePT : IGenomeManager { private DataTable setOfInitialTickers; private PairTradingCandidate[] candidates; private DateTime firstQuoteDate; private DateTime lastQuoteDate; private int minNumOfDaysForGapComputation; private int maxNumOfDaysForGapComputation; private double maxNumOfStdDevForNormalGap; private int genomeSize; private int minValueForGenes; private int maxValueForGenes; private GeneticOptimizer currentGeneticOptimizer; private float[] gaps; //it will contain absolute gaps of gain for tickers private double[] pairTradingPortfolioGains; //IGenomeManager implementation for properties public int GenomeSize { get{return this.genomeSize;} } public int MinValueForGenes { get{return this.minValueForGenes;} } public int MaxValueForGenes { get{return this.maxValueForGenes;} } public GeneticOptimizer CurrentGeneticOptimizer { get{return this.currentGeneticOptimizer;} set{this.currentGeneticOptimizer = value;} } //end of interface implementation for properties public GenomeManagerForSimplePT(DataTable setOfInitialTickers, DateTime firstQuoteDate, DateTime lastQuoteDate, int minNumOfDaysForGapComputation, int maxNumOfDaysForGapComputation, double maxNumOfStdDevForNormalGap) { this.genomeSize = 3;//1° pos for numIntervalDays; //2° and 3° positions for tickers this.setOfInitialTickers = setOfInitialTickers; this.setMinAndMaxValueForGenes(); this.firstQuoteDate = firstQuoteDate; this.lastQuoteDate = lastQuoteDate; this.minNumOfDaysForGapComputation = minNumOfDaysForGapComputation; this.maxNumOfDaysForGapComputation = maxNumOfDaysForGapComputation; this.maxNumOfStdDevForNormalGap = maxNumOfStdDevForNormalGap; this.candidates = new PairTradingCandidate[this.setOfInitialTickers.Rows.Count]; this.retrieveData(); this.pairTradingPortfolioGains = new double[this.candidates[0].ArrayOfAdjustedCloseQuotes.Length]; } private void setMinAndMaxValueForGenes() { this.minValueForGenes = 0; this.maxValueForGenes = this.setOfInitialTickers.Rows.Count - 1; } private float[] retrieveData_getArrayOfAdjustedCloseQuotes(string ticker) { float[] returnValue = null; Quotes tickerQuotes = new Quotes(ticker, this.firstQuoteDate, this.lastQuoteDate); returnValue = ExtendedDataTable.GetArrayOfFloatFromColumn(tickerQuotes,"quAdjustedClose"); return returnValue; } private void retrieveData() { for(int i = 0; i<this.setOfInitialTickers.Rows.Count; i++) { string ticker = (string)setOfInitialTickers.Rows[i][0]; this.candidates[i] = new PairTradingCandidate(ticker, this.retrieveData_getArrayOfAdjustedCloseQuotes(ticker)); } } private void getFitnessValue_setGaps(Genome genome) { int numOfDaysForGap = genome.GetGeneValue(0); int gapsLength = (this.candidates[0].ArrayOfAdjustedCloseQuotes.Length - 1)/numOfDaysForGap; this.gaps = new float[gapsLength]; int j = 0;//counter for gaps array for(int i = 0;i<gapsLength-numOfDaysForGap;i += numOfDaysForGap) { this.gaps[j] = this.candidates[genome.GetGeneValue(0)].ArrayOfAdjustedCloseQuotes[i+numOfDaysForGap]/ this.candidates[genome.GetGeneValue(0)].ArrayOfAdjustedCloseQuotes[i] - this.candidates[genome.GetGeneValue(1)].ArrayOfAdjustedCloseQuotes[i+numOfDaysForGap]/ this.candidates[genome.GetGeneValue(1)].ArrayOfAdjustedCloseQuotes[i] ; j++; } } public double GetFitnessValue(Genome genome) { double returnValue = 0.0; this.getFitnessValue_setGaps(genome); //float maxGap = this.maxNumOfStdDevForNormalGap * // foreach(float gap in this.gaps) //utilizzare l'equity line della strategia //individuare i giorni in cui si entra nel mercato //in base al segnale (gap > maxGap) ? ottimizzare il maxGap? //crea portafoglio di pair trading //calcola gain o stop loss ad ogni chiusura in base agli adjCloses //se gain o stopLoss non fanno uscire, //aggiungi ritorno al portafoglio di pair trading //se gain o stopLoss fanno uscire, azzera gain e stopLoss //ripeti ciclo esaminando primo gap utile //esauriti i gap, //calcolare sharpeRatio di equityLine returnValue = (1/Math.Abs(BasicFunctions.SimpleAverage(this.gaps)));// /BasicFunctions.StdDev(this.gaps); if(Double.IsNaN(returnValue) || Double.IsInfinity(returnValue)) returnValue = 0.0; return returnValue; } public Genome[] GetChilds(Genome parent1, Genome parent2) { return SimplePTGenomeManipulator.MixGenesWithoutDuplicates(parent1, parent2); } public int GetNewGeneValue(Genome genome, int genePosition) { int returnValue; if(genePosition == 0) //this positions needs the n° of days for the gap //between tickers'gains { returnValue = GenomeManagement.RandomGenerator.Next(this.minNumOfDaysForGapComputation, this.maxNumOfDaysForGapComputation + 1); } else //in 2° or 3° position there must be a ticker different from // the one contained in 3° or 2° position { returnValue = GenomeManagement.RandomGenerator.Next(genome.MinValueForGenes, genome.MaxValueForGenes + 1); while(genePosition>0 && SimplePTGenomeManipulator.IsTickerContainedInGenome(returnValue, genome)) //while in the given position has to be stored //a new gene pointing to a ticker and //the proposed returnValue points to a ticker //already stored in the given genome { // a new returnValue has to be generated returnValue = GenomeManagement.RandomGenerator.Next(genome.MinValueForGenes, genome.MaxValueForGenes + 1); } } return returnValue; } public void Mutate(Genome genome, double mutationRate) { int newValueForGene; int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size); if(genePositionToBeMutated == 0) //this positions needs the n° of days for the gap //between tickers'gains { newValueForGene = GenomeManagement.RandomGenerator.Next(this.minNumOfDaysForGapComputation, this.maxNumOfDaysForGapComputation + 1); } else { newValueForGene = GenomeManagement.RandomGenerator.Next(genome.MinValueForGenes, genome.MaxValueForGenes + 1); while(genePositionToBeMutated>0 && SimplePTGenomeManipulator.IsTickerContainedInGenome(newValueForGene, genome)) //while in the proposed genePositionToBeMutated has to be stored //a new gene pointing to a ticker and //the proposed newValueForGene points to a ticker //already stored in the given genome { newValueForGene = GenomeManagement.RandomGenerator.Next(genome.MinValueForGenes, genome.MaxValueForGenes + 1); } } GenomeManagement.MutateOneGene(genome, mutationRate, genePositionToBeMutated, newValueForGene); } public object Decode(Genome genome) { int numOfDaysForGap = genome.GetGeneValue(0); string firstTicker = this.candidates[genome.GetGeneValue(1)].Ticker; string secondTicker = this.candidates[genome.GetGeneValue(2)].Ticker; double averageGap = BasicFunctions.SimpleAverage(this.gaps); double stdDevGap = BasicFunctions.StdDev(this.gaps); return new GenomeMeaningSimplePT(numOfDaysForGap, averageGap, stdDevGap, firstTicker, secondTicker); } } } --- NEW FILE: RunSimplePairTrading.cs --- /* QuantProject - Quantitative Finance Library RunSimplePairTrading.cs Copyright (C) 2003 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.FileManaging; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Timing; using QuantProject.Business.Financial.Accounting.Commissions; using QuantProject.Data.DataProviders; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading.InSample; namespace QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading { /// <summary> /// Script to test the pair trading strategy on two single tickers /// </summary> [Serializable] public class RunSimplePairTrading : RunPairTrading { private EndOfDayTimerHandlerSimplePT endOfDayTimerHandler; public RunSimplePairTrading(string tickerGroupID, int numberOfEligibleTickers, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, double maxNumOfStdDevForNormalGap, int minNumOfDaysForGapComputation, int maxNumOfDaysForGapComputation, int numDaysBetweenEachOptimization, double maxRunningHours): base(tickerGroupID, numberOfEligibleTickers, numDaysForOptimizationPeriod, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, startDate, endDate, minNumOfDaysForGapComputation, maxNumOfDaysForGapComputation, maxNumOfStdDevForNormalGap, numDaysBetweenEachOptimization, maxRunningHours) { } #region auxiliary overriden methods for Run protected override void run_initializeEndOfDayTimerHandler() { this.endOfDayTimerHandler = new EndOfDayTimerHandlerSimplePT(this.tickerGroupID, this.numberOfEligibleTickers, this.numDaysForOptimizationPeriod, this.generationNumberForGeneticOptimizer, this.populationSizeForGeneticOptimizer, this.benchmark, this.startDateTime.DateTime, this.endDateTime.DateTime, this.maxNumOfStdDevForNormalGap, this.minNumOfDaysForGapComputation, this.maxNumOfDaysForGapComputation, this.numDaysBetweenEachOptimization, this.maxRunningHours, this.account); } protected override void run_addEventHandlers() { this.endOfDayTimer.MarketOpen += new MarketOpenEventHandler( this.endOfDayTimerHandler.MarketOpenEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.endOfDayTimerHandler.MarketCloseEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); this.endOfDayTimer.OneHourAfterMarketClose += new OneHourAfterMarketCloseEventHandler( this.endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler ); } #endregion //necessary far calling RunPairTrading.Run() //in classes that inherit from this class public override void Run() { base.Run(); } public override void SaveScriptResults() { string fileName = "From"+this.numberOfEligibleTickers + "OptDays" + this.numDaysForOptimizationPeriod + "GenNum" + this.generationNumberForGeneticOptimizer + "PopSize" + this.populationSizeForGeneticOptimizer; string dirNameWhereToSaveAccounts = System.Configuration.ConfigurationSettings.AppSettings["AccountsArchive"] + "\\" + this.ScriptName + "\\"; string dirNameWhereToSaveTransactions = System.Configuration.ConfigurationSettings.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; // string dirNameWhereToSaveBestGenomes = System.Configuration.ConfigurationSettings.AppSettings["GenomesArchive"] + // "\\" + this.ScriptName + "\\"; this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveAccounts); this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveTransactions); // this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); ObjectArchiver.Archive(this.account, dirNameWhereToSaveAccounts + fileName + ".qPa"); ObjectArchiver.Archive(this.account.Transactions, dirNameWhereToSaveTransactions + fileName + ".qPt"); // OptimizationOutput optimizationOutput = new OptimizationOutput(); // foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) // optimizationOutput.Add(genomeRepresentation); // ObjectArchiver.Archive(optimizationOutput, // dirNameWhereToSaveBestGenomes + // fileName + ".bgn"); this.endOfDayTimer.Stop(); new OutputDisplayer(this.startDateTime.DateTime, this.endDateTime.DateTime, this.endOfDayTimerHandler.OptimizationOutput).Show(); } } } --- NEW FILE: GenomeMeaningSimplePT.cs --- /* QuantProject - Quantitative Finance Library GenomeMeaningSimplePT.cs Copyright (C) 2003 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; namespace QuantProject.Scripts.ArbitrageTesting.PairTrading.SimplePairTrading { /// <summary> /// This is the class representing the meaning for genome /// found by a GeneticOptimizer initialized by GenomeManagerForSimplePT /// </summary> [Serializable] public class GenomeMeaningSimplePT { private string firstTicker; private string secondTicker; private int numOfDaysForGap; private double averageGap; private double stdDevGap; public string FirstTicker { get{return this.firstTicker;} } public string SecondTicker { get{return this.secondTicker;} } public int NumOfDaysForGap { get{return this.numOfDaysForGap;} } public double AverageGap { get{return this.averageGap;} } public double StdDevGap { get{return this.stdDevGap;} } public GenomeMeaningSimplePT(int numOfDaysForGap, double averageGap, double stdDevGap, string firstTicker, string secondTicker) { this.numOfDaysForGap = numOfDaysForGap; this.firstTicker = firstTicker; this.secondTicker = secondTicker; this.averageGap = averageGap; this.stdDevGap = stdDevGap; } } } |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:25:34
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv7517/PairTrading Added Files: RunPairTrading.cs PairTradingCandidate.cs Log Message: Added SimplePairTrading strategy, based on arbitrage concepts --- NEW FILE: PairTradingCandidate.cs --- /* QuantProject - Quantitative Finance Library PairTradingCandidate.cs Copyright (C) 2003 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; namespace QuantProject.Scripts.ArbitrageTesting.PairTrading { /// <summary> /// This is the class containing basic information /// for each candidate to be evaluated for the pair trading strategies /// </summary> [Serializable] public class PairTradingCandidate { protected string ticker; protected float[] arrayOfAdjustedCloseQuotes; public PairTradingCandidate(string ticker, float[] arrayOfAdjustedCloseQuotes) { this.ticker = ticker; this.arrayOfAdjustedCloseQuotes = arrayOfAdjustedCloseQuotes; } public float[] ArrayOfAdjustedCloseQuotes { get { return this.arrayOfAdjustedCloseQuotes; } } public string Ticker { get{return this.ticker;} } public float GetAdjustedCloseQuote( int arrayElementPosition ) { return this.arrayOfAdjustedCloseQuotes[ arrayElementPosition ]; } } } --- NEW FILE: RunPairTrading.cs --- /* QuantProject - Quantitative Finance Library RunPairTrading.cs Copyright (C) 2003 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.IO; using System.Collections; using System.Data; using System.Windows.Forms; using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.ADT.FileManaging; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Scripting; using QuantProject.Business.Strategies; using QuantProject.Business.Testing; using QuantProject.Business.Timing; using QuantProject.Business.Financial.Accounting.Commissions; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Presentation.Reporting.WindowsForm; using QuantProject.Scripts.WalkForwardTesting.LinearCombination; namespace QuantProject.Scripts.ArbitrageTesting.PairTrading { /// <summary> /// Base class for running scripts based /// on pair trading strategy /// </summary> [Serializable] public class RunPairTrading { protected string tickerGroupID; protected int numberOfEligibleTickers; protected int numDaysForOptimizationPeriod; protected int generationNumberForGeneticOptimizer; protected int populationSizeForGeneticOptimizer; protected EndOfDayDateTime startDateTime; protected EndOfDayDateTime endDateTime; protected IHistoricalQuoteProvider historicalQuoteProvider; protected Account account; protected IEndOfDayTimer endOfDayTimer; protected string benchmark; protected string scriptName; protected double maxNumOfStdDevForNormalGap; protected int minNumOfDaysForGapComputation; protected int maxNumOfDaysForGapComputation; protected int numDaysBetweenEachOptimization; protected DateTime startingTimeForScript; protected double maxRunningHours; //if MaxNumberOfHoursForScript has elapsed and the script //is still running, it will be stopped. public virtual string ScriptName { get{return this.scriptName;} set{this.scriptName = value;} } public DateTime TimerLastDate { get{return this.endOfDayTimer.GetCurrentTime().DateTime ;} } // public RunPairTrading(string benchmark, // DateTime startDate, DateTime endDate, // double maxLevelForNormalGap, // double maxRunningHours) // { // // this.startDateTime = new EndOfDayDateTime( // startDate, EndOfDaySpecificTime.FiveMinutesBeforeMarketClose ); // this.endDateTime = new EndOfDayDateTime( // endDate, EndOfDaySpecificTime.OneHourAfterMarketClose ); // this.maxLevelForNormalGap = maxLevelForNormalGap; // this.benchmark = benchmark; // this.ScriptName = "EfficientGeneric"; // this.startingTimeForScript = DateTime.Now; // this.maxRunningHours = maxRunningHours; // //this.numIntervalDays = 3; // } public RunPairTrading(string tickerGroupID, int numberOfEligibleTickers, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, int minNumOfDaysForGapComputation, int maxNumOfDaysForGapComputation, double maxNumOfStdDevForNormalGap, int numDaysBetweenEachOptimization, double maxRunningHours) { //this.progressBarForm = new ProgressBarForm(); this.tickerGroupID = tickerGroupID; this.numberOfEligibleTickers = numberOfEligibleTickers; this.numDaysForOptimizationPeriod = numDaysForOptimizationPeriod; this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; this.startDateTime = new EndOfDayDateTime( startDate, EndOfDaySpecificTime.FiveMinutesBeforeMarketClose ); this.endDateTime = new EndOfDayDateTime( endDate, EndOfDaySpecificTime.OneHourAfterMarketClose ); this.benchmark = benchmark; this.ScriptName = "PairTradingGeneric"; this.maxNumOfStdDevForNormalGap = maxNumOfStdDevForNormalGap; this.minNumOfDaysForGapComputation = minNumOfDaysForGapComputation; this.maxNumOfDaysForGapComputation = maxNumOfDaysForGapComputation; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.startingTimeForScript = DateTime.Now; this.maxRunningHours = maxRunningHours; //this.numIntervalDays = 3; } #region Run protected virtual void run_initializeEndOfDayTimer() { //default endOfDayTimer this.endOfDayTimer = new IndexBasedEndOfDayTimer( this.startDateTime, this.benchmark ); } protected virtual void run_initializeAccount() { //default account with no commissions and no slippage calculation this.account = new Account( this.scriptName , this.endOfDayTimer , new HistoricalEndOfDayDataStreamer( this.endOfDayTimer , this.historicalQuoteProvider ) , new HistoricalEndOfDayOrderExecutor( this.endOfDayTimer , this.historicalQuoteProvider )); } protected virtual void run_initializeEndOfDayTimerHandler() { //always needs specific implementation in inherited classes; } protected virtual void run_initializeHistoricalQuoteProvider() { this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); } protected void checkDateForReport_createDirIfNotPresent(string dirPath) { if(!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); } protected virtual void checkDateForReport(Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { if(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime>=this.endDateTime.DateTime || DateTime.Now >= this.startingTimeForScript.AddHours(this.maxRunningHours)) //last date is reached by the timer or maxRunning hours //are elapsed from the time script started this.SaveScriptResults(); } public virtual void SaveScriptResults() { string fileName = "From"+this.numberOfEligibleTickers + "OptDays" + this.numDaysForOptimizationPeriod + "GenNum" + this.generationNumberForGeneticOptimizer + "PopSize" + this.populationSizeForGeneticOptimizer; string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.ScriptName + "\\"; string dirNameWhereToSaveTransactions = System.Configuration.ConfigurationSettings.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; // string dirNameWhereToSaveBestGenomes = System.Configuration.ConfigurationSettings.AppSettings["GenomesArchive"] + // "\\" + this.ScriptName + "\\"; //default report with numIntervalDays = 1 AccountReport accountReport = this.account.CreateReport(fileName,1, this.endOfDayTimer.GetCurrentTime(), this.benchmark, new HistoricalAdjustedQuoteProvider()); this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ObjectArchiver.Archive(accountReport, dirNameWhereToSaveReports + fileName + ".qPr"); // this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveTransactions); ObjectArchiver.Archive(this.account.Transactions, dirNameWhereToSaveTransactions + fileName + ".qPt"); // // this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); this.endOfDayTimer.Stop(); } protected virtual void run_initialize() { run_initializeHistoricalQuoteProvider(); run_initializeEndOfDayTimer(); run_initializeAccount(); run_initializeEndOfDayTimerHandler(); //run_initializeProgressHandlers(); } protected virtual void run_addEventHandlers() { this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); //in inherited classes'override method: //add here TimerHandler's handlers to timer's events //example //this.endOfDayTimer.EVENT_NAME += // new EVENT_NAMEEventHandler( // this.endOfDayTimerHandler.EVENT_NAMEEventHandler); } public virtual void Run() { this.run_initialize(); this.run_addEventHandlers(); //this.progressBarForm.Show(); this.endOfDayTimer.Start(); } #endregion } } |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:23:53
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading/SimplePairTrading/InSample In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv6864/InSample Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading/SimplePairTrading/InSample added to the repository |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:23:38
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading/SimplePairTrading In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv6848/SimplePairTrading Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading/SimplePairTrading added to the repository |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:23:21
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv6837/PairTrading Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading added to the repository |
|
From: Marco M. <mi...@us...> - 2006-05-14 15:22:57
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv6520/ArbitrageTesting Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting added to the repository |
|
From: Marco M. <mi...@us...> - 2006-05-14 08:59:19
|
Update of /cvsroot/quantproject/QuantProject/b2_DataAccess In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv23641/b2_DataAccess Modified Files: DataAccess.prjx Log Message: Updated sharpdevelop project's files Index: DataAccess.prjx =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b2_DataAccess/DataAccess.prjx,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** DataAccess.prjx 7 Sep 2005 06:48:02 -0000 1.2 --- DataAccess.prjx 14 May 2006 08:59:15 -0000 1.3 *************** *** 19,22 **** --- 19,23 ---- <File name=".\Tables\VisuallyValidatedQuotes.cs" subtype="Code" buildaction="Compile" dependson="" data="" /> <File name=".\Tables\EventType.cs" subtype="Code" buildaction="Compile" dependson="" data="" /> + <File name=".\MissingQuoteException.cs" subtype="Code" buildaction="Compile" dependson="" data="" /> </Contents> <References> |
|
From: Marco M. <mi...@us...> - 2006-05-14 08:59:18
|
Update of /cvsroot/quantproject/QuantProject/b4_Business In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv23641/b4_Business Modified Files: Business.prjx Log Message: Updated sharpdevelop project's files Index: Business.prjx =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/Business.prjx,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** Business.prjx 20 Dec 2005 19:50:52 -0000 1.8 --- Business.prjx 14 May 2006 08:59:15 -0000 1.9 *************** *** 99,102 **** --- 99,103 ---- <File name=".\a1_Financial\a2_Accounting\Slippage\FixedPercentageSlippageManager.cs" subtype="Code" buildaction="Compile" dependson="" data="" /> <File name=".\a1_Financial\a2_Accounting\RebuildableAccount.cs" subtype="Code" buildaction="Compile" dependson="" data="" /> + <File name=".\a2_Strategies\SignedTicker.cs" subtype="Code" buildaction="Compile" dependson="" data="" /> </Contents> <References> |
|
From: Marco M. <mi...@us...> - 2006-05-14 08:59:18
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT In directory sc8-pr-cvs7.sourceforge.net:/tmp/cvs-serv23641/b1_ADT Modified Files: ADT.prjx Log Message: Updated sharpdevelop project's files Index: ADT.prjx =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/ADT.prjx,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** ADT.prjx 27 Jul 2005 22:37:14 -0000 1.6 --- ADT.prjx 14 May 2006 08:59:15 -0000 1.7 *************** *** 35,38 **** --- 35,39 ---- <File name=".\Optimizing\Genetic\NewGenerationEventArgs.cs" subtype="Code" buildaction="Compile" dependson="" data="" /> <File name=".\Optimizing\Genetic\GenomeCounter.cs" subtype="Code" buildaction="Compile" dependson="" data="" /> + <File name=".\Collections\QPHashtable.cs" subtype="Code" buildaction="Compile" dependson="" data="" /> </Contents> <References /> |