quantproject-developers Mailing List for QuantProject (Page 37)
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: Glauco S. <gla...@us...> - 2008-09-29 20:49:46
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a07_DataProviders In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv24339/a07_DataProviders Removed Files: HistoricalQuoteProvider.cs Log Message: The new revision moves toward an intraday enabled framework. EndOfDayDate time has been removed, DateTime is used now. The code has been changed accordingly. --- HistoricalQuoteProvider.cs DELETED --- |
|
From: Marco M. <mi...@us...> - 2008-08-23 13:09:53
|
Update of /cvsroot/quantproject/QuantDownloader/Downloader/OpenTickDownloader/UserForms In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv15487/Downloader/OpenTickDownloader/UserForms Modified Files: OTWebDownloader.cs Log Message: OTWebDownloader should now repaint itself in a thread-safe manner (during downloading bars) Index: OTWebDownloader.cs =================================================================== RCS file: /cvsroot/quantproject/QuantDownloader/Downloader/OpenTickDownloader/UserForms/OTWebDownloader.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** OTWebDownloader.cs 29 Jul 2008 22:38:17 -0000 1.4 --- OTWebDownloader.cs 22 Aug 2008 22:57:43 -0000 1.5 *************** *** 58,61 **** --- 58,65 ---- private string textForStartingDownloadingTimeLabel; private string textForEndingDownloadingTimeLabel; + private string[] tickersToDownload; + private SortedList downloadingTickersSortedList; + private int indexOfCurrentUpdatingTicker; + private DateTime currentUpdatingTickerDateTimeOfLastBarUpdate; public OTWebDownloader(DataTable tableOfSelectedTickers) *************** *** 66,73 **** InitializeComponent(); this.commonInitialization(); - // - //this.Text = "Download quotes from OpenTick for the selected tickers"; this.tableOfSelectedTickers = tableOfSelectedTickers; ! // } --- 70,75 ---- InitializeComponent(); this.commonInitialization(); this.tableOfSelectedTickers = tableOfSelectedTickers; ! this.initializeDownloadingTickersSortedList(); } *************** *** 86,90 **** base.Dispose( disposing ); } - /// <summary> /// common initialization of the controls of the form --- 88,91 ---- *************** *** 97,102 **** --- 98,111 ---- this.dataGrid1.ContextMenu = new TickerViewerMenu(this); this.Closing += new CancelEventHandler(this.OTWebDownloader_Closing); + this.indexOfCurrentUpdatingTicker = -1; } + private void initializeDownloadingTickersSortedList() + { + this.downloadingTickersSortedList = new SortedList(); + for(int i = 0; i<this.tableOfSelectedTickers.Rows.Count; i++) + this.downloadingTickersSortedList.Add( this.tableOfSelectedTickers.Rows[i][0], i ); + } + #region Windows Form Designer generated code /// <summary> *************** *** 137,141 **** this.endingDownloadingTimeLabel = new System.Windows.Forms.Label(); this.startingDownloadingTimeLabel = new System.Windows.Forms.Label(); - this.timer1 = new System.Windows.Forms.Timer(this.components); this.signallingLabel = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit(); --- 146,149 ---- *************** *** 453,467 **** this.startingDownloadingTimeLabel.Text = "."; // - // timer1 - // - this.timer1.Enabled = true; - this.timer1.Interval = 1000; - this.timer1.Tick += new System.EventHandler(this.Timer1Tick); - // // signallingLabel // this.signallingLabel.Location = new System.Drawing.Point(84, 415); this.signallingLabel.Name = "signallingLabel"; ! this.signallingLabel.Size = new System.Drawing.Size(129, 11); this.signallingLabel.TabIndex = 38; // --- 461,469 ---- this.startingDownloadingTimeLabel.Text = "."; // // signallingLabel // this.signallingLabel.Location = new System.Drawing.Point(84, 415); this.signallingLabel.Name = "signallingLabel"; ! this.signallingLabel.Size = new System.Drawing.Size(274, 12); this.signallingLabel.TabIndex = 38; // *************** *** 499,502 **** --- 501,505 ---- this.Text = "OT Web downloader"; this.Load += new System.EventHandler(this.otWebDownloaderLoad); + this.Paint += new System.Windows.Forms.PaintEventHandler(this.OTWebDownloaderPaint); ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit(); this.groupBoxWebDownloaderOptions.ResumeLayout(false); *************** *** 510,514 **** } private System.Windows.Forms.Label signallingLabel; - private System.Windows.Forms.Timer timer1; private System.Windows.Forms.Label endingDownloadingTimeLabel; private System.Windows.Forms.Label startingDownloadingTimeLabel; --- 513,516 ---- *************** *** 571,576 **** #endregion - #region download thread - private void buttonDownloadQuotesOfSelectedTickers_Click(object sender, System.EventArgs e) { --- 573,576 ---- *************** *** 592,602 **** this.txtOpenTickPassword.Text); tickerDownloader.DownloadingStarted += ! new DownloadingStartedEventHandler(this.refreshForm_atDownloadedStarted); tickerDownloader.DatabaseUpdated += ! new DatabaseUpdatedEventHandler(this.refreshGrid); tickerDownloader.DownloadingCompleted += ! new DownloadingCompletedEventHandler(this.refreshForm_atDownloadedCompleted); this.buttonDownloadQuotesOfSelectedTickers.Enabled = false; - //tickerDownloader.DownloadTickers(); this.downloadThread = new Thread( tickerDownloader.DownloadTickers ); this.downloadThread.Start(); --- 592,601 ---- this.txtOpenTickPassword.Text); tickerDownloader.DownloadingStarted += ! new DownloadingStartedEventHandler(this.setStartingTime_atDownloadedStarted); tickerDownloader.DatabaseUpdated += ! new DatabaseUpdatedEventHandler(this.refreshIndexAndDateTimeForCurrentUpdatingTicker); tickerDownloader.DownloadingCompleted += ! new DownloadingCompletedEventHandler(this.setEndingTime_atDownloadedCompleted); this.buttonDownloadQuotesOfSelectedTickers.Enabled = false; this.downloadThread = new Thread( tickerDownloader.DownloadTickers ); this.downloadThread.Start(); *************** *** 608,640 **** } ! #endregion ! ! private void refreshGrid(object sender, DatabaseUpdatedEventArgs eventArgs) { ! DataTable tickersCurrentylDownloaded = ! this.DsTickerCurrentlyDownloaded.Tables["Tickers"]; ! for(int i = 0; i < tickersCurrentylDownloaded.Rows.Count; i++) { ! if( (string)tickersCurrentylDownloaded.Rows[i][0] == eventArgs.Ticker ) ! { ! tickersCurrentylDownloaded.Rows[i][1] = "Yes"; ! tickersCurrentylDownloaded.Rows[i][2] = eventArgs.DateTimeOfLastBarUpdated; ! } ! } } ! private void refreshForm_atDownloadedStarted(object sender, DownloadingStartedEventArgs eventArgs) { ! this.textForStartingDownloadingTimeLabel = ! "Downloading started at: " + eventArgs.StartingDateTime.ToString(); ! this.downloadingInProgress = true; } ! private void refreshForm_atDownloadedCompleted(object sender, DownloadingCompletedEventArgs eventArgs) { ! this.textForEndingDownloadingTimeLabel = "Downloading completed at: " + ! eventArgs.EndingDateTime.ToString(); ! this.downloadingInProgress = false; } ! #region properties --- 607,651 ---- } ! #region Form's methods called by the thread started at OTTickerDownloader's method ! ! private void refreshIndexAndDateTimeForCurrentUpdatingTicker(object sender, DatabaseUpdatedEventArgs eventArgs) { ! lock(this.downloadingTickersSortedList) { ! this.currentUpdatingTickerDateTimeOfLastBarUpdate = ! eventArgs.DateTimeOfLastBarUpdated; ! int sortedListIndexOfKey = ! this.downloadingTickersSortedList.IndexOfKey(eventArgs.Ticker); ! this.indexOfCurrentUpdatingTicker = ! (int)this.downloadingTickersSortedList.GetByIndex(sortedListIndexOfKey); ! this.downloadingInProgress = true; //if a database ! //update event has been risen, downloading has to be ! //in progress ! this.Invalidate();//this forces the form to repaint itself ! //in a thread - safe manner ! } } ! private void setStartingTime_atDownloadedStarted(object sender, DownloadingStartedEventArgs eventArgs) { ! lock(this.startingDownloadingTimeLabel) ! { ! this.textForStartingDownloadingTimeLabel = ! "Downloading started at: " + eventArgs.StartingDateTime.ToString(); ! this.downloadingInProgress = true; ! } } ! private void setEndingTime_atDownloadedCompleted(object sender, DownloadingCompletedEventArgs eventArgs) { ! lock(this.endingDownloadingTimeLabel) ! { ! this.textForEndingDownloadingTimeLabel = "Downloading completed at: " + ! eventArgs.EndingDateTime.ToString(); ! this.downloadingInProgress = false; ! } } ! ! #endregion ! #region properties *************** *** 669,678 **** get { ! string[] tickersToDownload = new string[this.tableOfSelectedTickers.Rows.Count]; ! for(int i = 0; i < tickersToDownload.Length; i++) ! tickersToDownload[i] = ! (string)this.tableOfSelectedTickers.Rows[i][0]; ! ! return tickersToDownload; } } --- 680,692 ---- get { ! if(this.tickersToDownload == null) ! { ! this.tickersToDownload = ! new string[this.tableOfSelectedTickers.Rows.Count]; ! for(int i = 0; i < this.tickersToDownload.Length; i++) ! this.tickersToDownload[i] = ! (string)this.tableOfSelectedTickers.Rows[i][0]; ! } ! return this.tickersToDownload; } } *************** *** 753,762 **** this.otWebDownloaderLoad_fillDataGridWithTickersToBeDownloaded(); } ! private void Timer1Tick_refreshSignallingLabel() { if(this.downloadingInProgress) { ! if(this.signallingLabel.Text.Length<40) this.signallingLabel.Text += "--"; else --- 767,789 ---- this.otWebDownloaderLoad_fillDataGridWithTickersToBeDownloaded(); } + + private void OTWebDownloader_Closing(Object sender, CancelEventArgs e) + { + if (this.downloadingInProgress) + { + e.Cancel = true; + MessageBox.Show("You can't close the form if downloading is still in progress!"); + } + else + { + e.Cancel = false; + } + } ! private void OTWebDownloaderPaint_refreshSignallingLabel() { if(this.downloadingInProgress) { ! if(this.signallingLabel.Text.Length<60) this.signallingLabel.Text += "--"; else *************** *** 769,791 **** } ! void Timer1Tick(object sender, EventArgs e) { ! this.Timer1Tick_refreshSignallingLabel(); ! this.startingDownloadingTimeLabel.Text = textForStartingDownloadingTimeLabel; ! this.endingDownloadingTimeLabel.Text = textForEndingDownloadingTimeLabel; ! } ! private void OTWebDownloader_Closing(Object sender, CancelEventArgs e) { ! if (this.downloadingInProgress) ! { ! e.Cancel = true; ! MessageBox.Show("You can't close the form if downloading is still in progress!"); ! } ! else ! { ! e.Cancel = false; ! } ! } } } --- 796,845 ---- } ! private void OTWebDownloaderPaint_refreshTableOfSelectedTickers() { ! lock(this.downloadingTickersSortedList) ! { ! DataTable tickersCurrentylDownloaded = ! this.DsTickerCurrentlyDownloaded.Tables["Tickers"]; ! if(this.indexOfCurrentUpdatingTicker != -1) ! //a databaseUpdated event has been risen ! { ! tickersCurrentylDownloaded.Rows[this.indexOfCurrentUpdatingTicker][1] = "Yes"; ! tickersCurrentylDownloaded.Rows[this.indexOfCurrentUpdatingTicker][2] = ! this.currentUpdatingTickerDateTimeOfLastBarUpdate; ! } ! } ! } ! private void OTWebDownloaderPaint_refreshEndingDownloadingTimeLabel() { ! lock(this.endingDownloadingTimeLabel) ! { ! this.endingDownloadingTimeLabel.Text = ! this.textForEndingDownloadingTimeLabel; ! } ! } ! ! private void OTWebDownloaderPaint_refreshStartingDownloadingTimeLabel() ! { ! lock(this.startingDownloadingTimeLabel) ! { ! this.startingDownloadingTimeLabel.Text = ! this.textForStartingDownloadingTimeLabel; ! } ! } ! ! //this event handler should be called only by the ! //thread that owns the form. With these locks, ! //information coming from the thread that owns the ! //OT ticker downloader should be "treated" ! //(written and displayed by the form) in a thread-safe manner ! void OTWebDownloaderPaint(object sender, PaintEventArgs e) ! { ! this.OTWebDownloaderPaint_refreshStartingDownloadingTimeLabel(); ! this.OTWebDownloaderPaint_refreshSignallingLabel(); ! this.OTWebDownloaderPaint_refreshTableOfSelectedTickers(); ! this.OTWebDownloaderPaint_refreshEndingDownloadingTimeLabel(); ! } } } |
|
From: Marco M. <mi...@us...> - 2008-08-23 10:57:12
|
Update of /cvsroot/quantproject/QuantDownloader/Downloader/OpenTickDownloader In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv15487/Downloader/OpenTickDownloader Modified Files: OTTickerDownloader.cs Log Message: OTWebDownloader should now repaint itself in a thread-safe manner (during downloading bars) Index: OTTickerDownloader.cs =================================================================== RCS file: /cvsroot/quantproject/QuantDownloader/Downloader/OpenTickDownloader/OTTickerDownloader.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** OTTickerDownloader.cs 20 Jul 2008 20:37:51 -0000 1.3 --- OTTickerDownloader.cs 22 Aug 2008 22:57:43 -0000 1.4 *************** *** 261,265 **** { string logFileName = ! @"C:\QuantProject\OpenTickDownloader\textFilesForLoggingNotification\textFileForLoggingNotification"; logFileName = logFileName + "_" + ExtendedDateTime.GetCompleteShortDescriptionForFileName( --- 261,265 ---- { string logFileName = ! @"C:\Quant\OpenTickDownloader\textFilesForLoggingNotification\textFileForLoggingNotification"; logFileName = logFileName + "_" + ExtendedDateTime.GetCompleteShortDescriptionForFileName( |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:27:08
|
Update of /cvsroot/quantproject/QuantProject/b91_QuantProject In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv13409/b91_QuantProject Modified Files: Main.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: Main.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b91_QuantProject/Main.cs,v retrieving revision 1.20 retrieving revision 1.21 diff -C2 -d -r1.20 -r1.21 *** Main.cs 18 Aug 2008 21:13:20 -0000 1.20 --- Main.cs 19 Aug 2008 17:27:01 -0000 1.21 *************** *** 3,7 **** Main.cs ! Copyright (C) 2003 Glauco Siliprandi --- 3,7 ---- Main.cs ! Copyright (C) 2003 Glauco Siliprandi *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 54,80 **** public class Principale : System.Windows.Forms.Form { ! // public static RunEfficientPorfolio runEfficientPortfolio; private System.Windows.Forms.MainMenu mainMenu1; ! private System.Windows.Forms.MenuItem menuItem1; ! private System.Windows.Forms.MenuItem menuItem2; ! private System.Windows.Forms.MenuItem menuItem3; ! private System.Windows.Forms.MenuItem menuItem4; ! private System.Windows.Forms.MenuItem menuItem5; ! private System.Windows.Forms.MenuItem menuItem6; ! private System.Windows.Forms.MenuItem menuItem7; ! private System.Windows.Forms.MenuItem menuItem8; ! private System.Windows.Forms.MenuItem menuItem10; ! private System.Windows.Forms.MenuItem menuItem11; ! private System.Windows.Forms.MenuItem menuItem13; ! private System.Windows.Forms.MenuItem menuItem14; ! private System.Windows.Forms.MenuItem menuItem9; ! private System.Windows.Forms.MenuItem menuItemRun; ! private System.Windows.Forms.MenuItem menuItemSavedTests; ! private System.Windows.Forms.MenuItem menuItemAccountViewer; ! private System.Windows.Forms.MenuItem menuItemShowReportFromAccount; ! private System.Windows.Forms.MenuItem menuItemRunReleasingMode; ! private System.Windows.Forms.MenuItem menuItemShowSavedReport; ! private System.Windows.Forms.MenuItem menuItemShowReportFromTransactions; /// <summary> /// Required designer variable. --- 54,80 ---- public class Principale : System.Windows.Forms.Form { ! // public static RunEfficientPorfolio runEfficientPortfolio; private System.Windows.Forms.MainMenu mainMenu1; ! private System.Windows.Forms.MenuItem menuItem1; ! private System.Windows.Forms.MenuItem menuItem2; ! private System.Windows.Forms.MenuItem menuItem3; ! private System.Windows.Forms.MenuItem menuItem4; ! private System.Windows.Forms.MenuItem menuItem5; ! private System.Windows.Forms.MenuItem menuItem6; ! private System.Windows.Forms.MenuItem menuItem7; ! private System.Windows.Forms.MenuItem menuItem8; ! private System.Windows.Forms.MenuItem menuItem10; ! private System.Windows.Forms.MenuItem menuItem11; ! private System.Windows.Forms.MenuItem menuItem13; ! private System.Windows.Forms.MenuItem menuItem14; ! private System.Windows.Forms.MenuItem menuItem9; ! private System.Windows.Forms.MenuItem menuItemRun; ! private System.Windows.Forms.MenuItem menuItemSavedTests; ! private System.Windows.Forms.MenuItem menuItemAccountViewer; ! private System.Windows.Forms.MenuItem menuItemShowReportFromAccount; ! private System.Windows.Forms.MenuItem menuItemRunReleasingMode; ! private System.Windows.Forms.MenuItem menuItemShowSavedReport; ! private System.Windows.Forms.MenuItem menuItemShowReportFromTransactions; /// <summary> /// Required designer variable. *************** *** 116,280 **** private void InitializeComponent() { ! this.mainMenu1 = new System.Windows.Forms.MainMenu(); ! this.menuItem8 = new System.Windows.Forms.MenuItem(); ! this.menuItem10 = new System.Windows.Forms.MenuItem(); ! this.menuItem9 = new System.Windows.Forms.MenuItem(); ! this.menuItem11 = new System.Windows.Forms.MenuItem(); ! this.menuItemRun = new System.Windows.Forms.MenuItem(); ! this.menuItemSavedTests = new System.Windows.Forms.MenuItem(); ! this.menuItemAccountViewer = new System.Windows.Forms.MenuItem(); ! this.menuItemShowReportFromAccount = new System.Windows.Forms.MenuItem(); ! this.menuItemShowSavedReport = new System.Windows.Forms.MenuItem(); ! this.menuItemRunReleasingMode = new System.Windows.Forms.MenuItem(); ! this.menuItem13 = new System.Windows.Forms.MenuItem(); ! this.menuItem14 = new System.Windows.Forms.MenuItem(); ! this.menuItem1 = new System.Windows.Forms.MenuItem(); ! this.menuItem2 = new System.Windows.Forms.MenuItem(); ! this.menuItem5 = new System.Windows.Forms.MenuItem(); ! this.menuItem3 = new System.Windows.Forms.MenuItem(); ! this.menuItem4 = new System.Windows.Forms.MenuItem(); ! this.menuItem6 = new System.Windows.Forms.MenuItem(); ! this.menuItem7 = new System.Windows.Forms.MenuItem(); ! this.menuItemShowReportFromTransactions = new System.Windows.Forms.MenuItem(); ! // ! // mainMenu1 ! // ! this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { ! this.menuItem8, ! this.menuItem11, ! this.menuItem13}); ! // ! // menuItem8 ! // ! this.menuItem8.Index = 0; ! this.menuItem8.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { ! this.menuItem10, ! this.menuItem9}); ! this.menuItem8.Text = "Data"; ! // ! // menuItem10 ! // ! this.menuItem10.Index = 0; ! this.menuItem10.Text = "Download"; ! this.menuItem10.Click += new System.EventHandler(this.menuItem10_Click); ! // ! // menuItem9 ! // ! this.menuItem9.Index = 1; ! this.menuItem9.Text = "Test"; ! this.menuItem9.Click += new System.EventHandler(this.menuItem9_Click); ! // ! // menuItem11 ! // ! this.menuItem11.Index = 1; ! this.menuItem11.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { ! this.menuItemRun, ! this.menuItemSavedTests, ! this.menuItemRunReleasingMode}); ! this.menuItem11.Text = "BackTest"; ! // ! // menuItemRun ! // ! this.menuItemRun.Index = 0; ! this.menuItemRun.Text = "Run (debugging mode)"; ! this.menuItemRun.Click += new System.EventHandler(this.menuItemRun_Click); ! // ! // menuItemSavedTests ! // ! this.menuItemSavedTests.Index = 1; ! this.menuItemSavedTests.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { ! this.menuItemAccountViewer, ! this.menuItemShowReportFromAccount, ! this.menuItemShowSavedReport, ! this.menuItemShowReportFromTransactions}); ! this.menuItemSavedTests.Text = "Saved Tests"; ! // ! // menuItemAccountViewer ! // ! this.menuItemAccountViewer.Index = 0; ! this.menuItemAccountViewer.Text = "Account viewer"; ! this.menuItemAccountViewer.Click += new System.EventHandler(this.menuItemAccountViewer_Click); ! // ! // menuItemShowReportFromAccount ! // ! this.menuItemShowReportFromAccount.Index = 1; ! this.menuItemShowReportFromAccount.Text = "Show report from account"; ! this.menuItemShowReportFromAccount.Click += new System.EventHandler(this.menuItemShowReportFromAccount_Click); ! // ! // menuItemShowSavedReport ! // ! this.menuItemShowSavedReport.Index = 2; ! this.menuItemShowSavedReport.Text = "Show saved report"; ! this.menuItemShowSavedReport.Click += new System.EventHandler(this.menuItemShowSavedReport_Click); ! // ! // menuItemRunReleasingMode ! // ! this.menuItemRunReleasingMode.Index = 2; ! this.menuItemRunReleasingMode.Text = "Run (releasing mode)"; ! this.menuItemRunReleasingMode.Click += new System.EventHandler(this.menuItemRunReleasingMode_Click); ! // ! // menuItem13 ! // ! this.menuItem13.Index = 2; ! this.menuItem13.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { ! this.menuItem14}); ! this.menuItem13.Text = "Trade"; ! // ! // menuItem14 ! // ! this.menuItem14.Index = 0; ! this.menuItem14.Text = "Go"; ! this.menuItem14.Click += new System.EventHandler(this.menuItem14_Click); ! // ! // menuItem1 ! // ! this.menuItem1.Index = -1; ! this.menuItem1.Text = ""; ! // ! // menuItem2 ! // ! this.menuItem2.Index = -1; ! this.menuItem2.Text = ""; ! // ! // menuItem5 ! // ! this.menuItem5.Index = -1; ! this.menuItem5.Text = ""; ! // ! // menuItem3 ! // ! this.menuItem3.Index = -1; ! this.menuItem3.Text = ""; ! // ! // menuItem4 ! // ! this.menuItem4.Index = -1; ! this.menuItem4.Text = ""; ! // ! // menuItem6 ! // ! this.menuItem6.Index = -1; ! this.menuItem6.Text = ""; ! // ! // menuItem7 ! // ! this.menuItem7.Index = -1; ! this.menuItem7.Text = ""; ! // ! // menuItemShowReportFromTransactions ! // ! this.menuItemShowReportFromTransactions.Index = 3; ! this.menuItemShowReportFromTransactions.Text = "Show report from transactions"; ! this.menuItemShowReportFromTransactions.Click += new System.EventHandler(this.menuItemShowReportFromTransactions_Click); ! // ! // Principale ! // ! this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); ! this.ClientSize = new System.Drawing.Size(292, 273); ! this.Menu = this.mainMenu1; ! this.Name = "Principale"; ! this.Text = "Main"; ! } #endregion --- 116,280 ---- private void InitializeComponent() { ! this.mainMenu1 = new System.Windows.Forms.MainMenu(); ! this.menuItem8 = new System.Windows.Forms.MenuItem(); ! this.menuItem10 = new System.Windows.Forms.MenuItem(); ! this.menuItem9 = new System.Windows.Forms.MenuItem(); ! this.menuItem11 = new System.Windows.Forms.MenuItem(); ! this.menuItemRun = new System.Windows.Forms.MenuItem(); ! this.menuItemSavedTests = new System.Windows.Forms.MenuItem(); ! this.menuItemAccountViewer = new System.Windows.Forms.MenuItem(); ! this.menuItemShowReportFromAccount = new System.Windows.Forms.MenuItem(); ! this.menuItemShowSavedReport = new System.Windows.Forms.MenuItem(); ! this.menuItemRunReleasingMode = new System.Windows.Forms.MenuItem(); ! this.menuItem13 = new System.Windows.Forms.MenuItem(); ! this.menuItem14 = new System.Windows.Forms.MenuItem(); ! this.menuItem1 = new System.Windows.Forms.MenuItem(); ! this.menuItem2 = new System.Windows.Forms.MenuItem(); ! this.menuItem5 = new System.Windows.Forms.MenuItem(); ! this.menuItem3 = new System.Windows.Forms.MenuItem(); ! this.menuItem4 = new System.Windows.Forms.MenuItem(); ! this.menuItem6 = new System.Windows.Forms.MenuItem(); ! this.menuItem7 = new System.Windows.Forms.MenuItem(); ! this.menuItemShowReportFromTransactions = new System.Windows.Forms.MenuItem(); ! // ! // mainMenu1 ! // ! this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { ! this.menuItem8, ! this.menuItem11, ! this.menuItem13}); ! // ! // menuItem8 ! // ! this.menuItem8.Index = 0; ! this.menuItem8.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { ! this.menuItem10, ! this.menuItem9}); ! this.menuItem8.Text = "Data"; ! // ! // menuItem10 ! // ! this.menuItem10.Index = 0; ! this.menuItem10.Text = "Download"; ! this.menuItem10.Click += new System.EventHandler(this.menuItem10_Click); ! // ! // menuItem9 ! // ! this.menuItem9.Index = 1; ! this.menuItem9.Text = "Test"; ! this.menuItem9.Click += new System.EventHandler(this.menuItem9_Click); ! // ! // menuItem11 ! // ! this.menuItem11.Index = 1; ! this.menuItem11.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { ! this.menuItemRun, ! this.menuItemSavedTests, ! this.menuItemRunReleasingMode}); ! this.menuItem11.Text = "BackTest"; ! // ! // menuItemRun ! // ! this.menuItemRun.Index = 0; ! this.menuItemRun.Text = "Run (debugging mode)"; ! this.menuItemRun.Click += new System.EventHandler(this.menuItemRun_Click); ! // ! // menuItemSavedTests ! // ! this.menuItemSavedTests.Index = 1; ! this.menuItemSavedTests.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { ! this.menuItemAccountViewer, ! this.menuItemShowReportFromAccount, ! this.menuItemShowSavedReport, ! this.menuItemShowReportFromTransactions}); ! this.menuItemSavedTests.Text = "Saved Tests"; ! // ! // menuItemAccountViewer ! // ! this.menuItemAccountViewer.Index = 0; ! this.menuItemAccountViewer.Text = "Account viewer"; ! this.menuItemAccountViewer.Click += new System.EventHandler(this.menuItemAccountViewer_Click); ! // ! // menuItemShowReportFromAccount ! // ! this.menuItemShowReportFromAccount.Index = 1; ! this.menuItemShowReportFromAccount.Text = "Show report from account"; ! this.menuItemShowReportFromAccount.Click += new System.EventHandler(this.menuItemShowReportFromAccount_Click); ! // ! // menuItemShowSavedReport ! // ! this.menuItemShowSavedReport.Index = 2; ! this.menuItemShowSavedReport.Text = "Show saved report"; ! this.menuItemShowSavedReport.Click += new System.EventHandler(this.menuItemShowSavedReport_Click); ! // ! // menuItemRunReleasingMode ! // ! this.menuItemRunReleasingMode.Index = 2; ! this.menuItemRunReleasingMode.Text = "Run (releasing mode)"; ! this.menuItemRunReleasingMode.Click += new System.EventHandler(this.menuItemRunReleasingMode_Click); ! // ! // menuItem13 ! // ! this.menuItem13.Index = 2; ! this.menuItem13.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] { ! this.menuItem14}); ! this.menuItem13.Text = "Trade"; ! // ! // menuItem14 ! // ! this.menuItem14.Index = 0; ! this.menuItem14.Text = "Go"; ! this.menuItem14.Click += new System.EventHandler(this.menuItem14_Click); ! // ! // menuItem1 ! // ! this.menuItem1.Index = -1; ! this.menuItem1.Text = ""; ! // ! // menuItem2 ! // ! this.menuItem2.Index = -1; ! this.menuItem2.Text = ""; ! // ! // menuItem5 ! // ! this.menuItem5.Index = -1; ! this.menuItem5.Text = ""; ! // ! // menuItem3 ! // ! this.menuItem3.Index = -1; ! this.menuItem3.Text = ""; ! // ! // menuItem4 ! // ! this.menuItem4.Index = -1; ! this.menuItem4.Text = ""; ! // ! // menuItem6 ! // ! this.menuItem6.Index = -1; ! this.menuItem6.Text = ""; ! // ! // menuItem7 ! // ! this.menuItem7.Index = -1; ! this.menuItem7.Text = ""; ! // ! // menuItemShowReportFromTransactions ! // ! this.menuItemShowReportFromTransactions.Index = 3; ! this.menuItemShowReportFromTransactions.Text = "Show report from transactions"; ! this.menuItemShowReportFromTransactions.Click += new System.EventHandler(this.menuItemShowReportFromTransactions_Click); ! // ! // Principale ! // ! this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); ! this.ClientSize = new System.Drawing.Size(292, 273); ! this.Menu = this.mainMenu1; ! this.Name = "Principale"; ! this.Text = "Main"; ! } #endregion *************** *** 290,300 **** } ! private void menuItem10_Click(object sender, System.EventArgs e) ! { ! } ! ! static void runMilloScripts() ! { ! /*QuantProject.Principale.Principale.runEfficientPortfolio = new RunEfficientCTCPorfolio("Test",150,4,60,10,15000,"^SPX", new DateTime(2004,3,1), --- 290,300 ---- } ! private void menuItem10_Click(object sender, System.EventArgs e) ! { ! } ! ! static void runMilloScripts() ! { ! /*QuantProject.Principale.Principale.runEfficientPortfolio = new RunEfficientCTCPorfolio("Test",150,4,60,10,15000,"^SPX", new DateTime(2004,3,1), *************** *** 302,306 **** PortfolioType.ShortAndLong,0.05, 2);*/ ! /*QuantProject.Principale.Principale.runEfficientPortfolio = new RunTestOptimizedCTCPortfolio("Test",150,4,60,10,25000,"^SPX", new DateTime(2004,3,1), --- 302,306 ---- PortfolioType.ShortAndLong,0.05, 2);*/ ! /*QuantProject.Principale.Principale.runEfficientPortfolio = new RunTestOptimizedCTCPortfolio("Test",150,4,60,10,25000,"^SPX", new DateTime(2004,3,1), *************** *** 314,326 **** new DateTime(2004,1,15), 0.0, PortfolioType.ShortAndLong, 2);*/ ! ! // QuantProject.Principale.Principale.runEfficientPortfolio = ! // new RunTestOptimizedCTOPorfolio("Test",150,5,45,10,50000, // "^SPX", // new DateTime(2004,3,1), // new DateTime(2004,3,1).AddDays(45), // 0.0005, PortfolioType.ShortAndLong, 12); ! ! /*new RunTestOptimizedCTCPortfolio("Test",150,6,90,10,20000, "^SPX", new DateTime(2002,10,1), --- 314,326 ---- new DateTime(2004,1,15), 0.0, PortfolioType.ShortAndLong, 2);*/ ! ! // QuantProject.Principale.Principale.runEfficientPortfolio = ! // new RunTestOptimizedCTOPorfolio("Test",150,5,45,10,50000, // "^SPX", // new DateTime(2004,3,1), // new DateTime(2004,3,1).AddDays(45), // 0.0005, PortfolioType.ShortAndLong, 12); ! ! /*new RunTestOptimizedCTCPortfolio("Test",150,6,90,10,20000, "^SPX", new DateTime(2002,10,1), *************** *** 328,334 **** 5,2,0.0, PortfolioType.ShortAndLong, 0.50, 10);*/ ! ! // QuantProject.Principale.Principale.runEfficientPortfolio.Run(); ! /* QuantProject.Principale.Principale.runEfficientPortfolio = new RunTestOptimizedCTOPorfolio("Test",150,6,45,10,150000, "^SPX", --- 328,334 ---- 5,2,0.0, PortfolioType.ShortAndLong, 0.50, 10);*/ ! ! // QuantProject.Principale.Principale.runEfficientPortfolio.Run(); ! /* QuantProject.Principale.Principale.runEfficientPortfolio = new RunTestOptimizedCTOPorfolio("Test",150,6,45,10,150000, "^SPX", *************** *** 338,342 **** QuantProject.Principale.Principale.runEfficientPortfolio.Run(); */ ! /* QuantProject.Principale.Principale.runEfficientPortfolio = new RunTestOptimizedCTCPortfolio("Test",100,5,120,10,150000, --- 338,342 ---- QuantProject.Principale.Principale.runEfficientPortfolio.Run(); */ ! /* QuantProject.Principale.Principale.runEfficientPortfolio = new RunTestOptimizedCTCPortfolio("Test",100,5,120,10,150000, *************** *** 365,372 **** PortfolioType.ShortAndLong, 0.50, 10); QuantProject.Principale.Principale.runEfficientPortfolio.Run(); ! */ ! ! /* ! QuantProject.Principale.Principale.runEfficientPortfolio = new RunEfficientCTOPorfolio("Test",500,6,45,15,50000, "^SPX", --- 365,372 ---- PortfolioType.ShortAndLong, 0.50, 10); QuantProject.Principale.Principale.runEfficientPortfolio.Run(); ! */ ! ! /* ! QuantProject.Principale.Principale.runEfficientPortfolio = new RunEfficientCTOPorfolio("Test",500,6,45,15,50000, "^SPX", *************** *** 376,561 **** QuantProject.Principale.Principale.runEfficientPortfolio.Run(); ! */ ! ! } ! [STAThread] ! static void Main() ! { ! // try ! // { ! //new RunMSFTsimpleTest().Run(); // new RunMSFTsimpleTest_2().Run(); ! //new RunOneRankWithExcelReport().Run(); ! //new RunOneRankWithWindowsReport().Run(); ! //new RunBestTwoIndipendent().Run(); ! //Principale.geneticOptimizerTest(); ! //new RunEfficientCTOPorfolio().Run(); ! //new RunEfficientCTCPorfolio().Run(); ! //new RunEfficientPorfolio().Run(); // QuantProject.Scripts.WalkForwardTesting.FixedLengthTwoPhases.FixedLengthTwoPhasesMain // myMain = // new QuantProject.Scripts.WalkForwardTesting.FixedLengthTwoPhases.FixedLengthTwoPhasesMain().Run; ! Application.Run(new Principale()); ! //geneticOptimizerTest(); ! //Application.Run(new OneRankForm()); ! //runMilloScripts(); ! ! //new RunEfficientCTOPorfolio("Test",200,5,60,10,5000, "^SPX", ! // new DateTime(2000,1,1), ! // new DateTime(2001,12,31)).Run(); ! // new RunMSFTwalkForward().Run(); ! // new RunOneRankWithWindowsReport().Run(); ! //new RunMSFTwalkForward().Run(); ! //new RunMultiTestOneRank().Run(); ! //new RunWalkForwardOneRank().Run(); ! //new RunEfficientCTOPorfolio().Run(); ! //new RunWalkForwardOneRank().Run(); ! // } ! // catch ( Exception ex ) ! // { ! //// QuantProject.Principale.Principale.runEfficientPortfolio.SaveScriptResults(); ! // writeExceptionToLogFile(ex); ! // } ! } ! static private void writeExceptionToLogFile(Exception ex) ! { ! string path = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\\')) ! + @"\ExceptionLog.txt"; ! if(File.Exists(path)) ! { ! StreamWriter w = File.AppendText(path); ! w.Write("\r\nTime of exception : "); ! w.WriteLine("{0} {1}", DateTime.Now.ToLongDateString(), ! DateTime.Now.ToLocalTime()); // w.Write("\r\nScript name: {0}", // QuantProject.Principale.Principale.runEfficientPortfolio.ScriptName ); // w.Write("\r\nTimer date: {0}", // QuantProject.Principale.Principale.runEfficientPortfolio.TimerLastDate.ToLongDateString() ); ! // ! w.WriteLine("\n :{0}", ex.ToString()); ! w.WriteLine("\n :{0}", ex.StackTrace.ToString()); ! w.WriteLine ("\n-----------------------------------"); ! // Update the underlying file. ! w.Flush(); ! w.Close(); ! } ! ! } ! ! private static void geneticOptimizerTest() ! { ! IGenomeManager genomeManagerTest = new GenomeManagerTest(5,1,10); ! GeneticOptimizer GO = new GeneticOptimizer(genomeManagerTest,1000,10); ! //GO.KeepOnRunningUntilConvergenceIsReached = true; ! GO.Run(true); ! System.Console.WriteLine("\n\nThe best solution found is: " + (string)GO.BestGenome.Meaning + ! " with {0} generations", GO.GenerationCounter); ! } ! ! private void menuItem14_Click(object sender, System.EventArgs e) ! { ! } ! //run scripts in debugging mode ! private void menuItemRun_Click(object sender, System.EventArgs e) ! { ! // try ! // {//call here your scripts ! //new RunWalkForwardOneRank().Run(); // new WFLagMain().ShowDialog(); new FixedLengthTwoPhasesMain().Run(); // new PairsTradingMain().Run(); ! // new RunOneRank().Run(); ! //new RunEfficientCTCPorfolio("Test",400,5,90,10,10000, ! // "^SPX", ! // new DateTime(2004,1,1), ! // new DateTime(2004,2,29), ! // 3).Run(); ! ! //this.Close(); ! // runMilloScripts(); ! ! //new RunEfficientCTOPorfolio("Test",200,5,60,2,500, "^SPX", ! // new DateTime(2004,1,1), ! // new DateTime(2004,1,15)).Run(); ! ! // } ! // catch ( Exception ex ) ! // { ! // string notUsed = ex.ToString(); ! // //in this way qP shouldn't stop if running a single script fails ... ! // } ! } ! private void menuItemAccountViewer_Click(object sender, System.EventArgs e) ! { ! AccountViewer accountViewer = new AccountViewer(); ! accountViewer.Show(); ! } ! private string getPath(string dialogTitle) ! { ! OpenFileDialog openFileDialog = new OpenFileDialog(); ! openFileDialog.Title = dialogTitle; ! openFileDialog.Multiselect = false; ! openFileDialog.CheckFileExists = true; ! openFileDialog.ShowDialog(); ! return openFileDialog.FileName; ! } ! private void menuItemShowReportFromAccount_Click(object sender, System.EventArgs e) ! { ! string chosenPath = this.getPath("Select a serialized account please ..."); ! if(chosenPath != "") ! ShowReportFromFile.ShowReportFromSerializedAccount(chosenPath); ! } ! ! private void menuItemRunReleasingMode_Click(object sender, System.EventArgs e) ! { ! try ! { ! this.Cursor = Cursors.WaitCursor; ! //call here your scripts ! //new RunWalkForwardOneRank().Run(); ! ! } ! catch ( Exception ex ) ! { ! ex = ex; ! //in this way qP shouldn't stop if running a single script fails ... ! } ! finally ! { ! this.Cursor = Cursors.Default; ! } ! } ! private void menuItemShowSavedReport_Click(object sender, System.EventArgs e) ! { ! string chosenPath = this.getPath("Select a serialized report please ..."); ! if(chosenPath != "") ! ShowReportFromFile.ShowReportFromSerializedAccountReport(chosenPath); ! } ! private void menuItemShowReportFromTransactions_Click(object sender, System.EventArgs e) ! { ! string chosenPath = this.getPath("Select a serialized TransactionHistory please ..."); ! if(chosenPath != "") ! ShowReportFromFile.ShowReportFromSerializedTransactionHistory(chosenPath); ! } --- 376,561 ---- QuantProject.Principale.Principale.runEfficientPortfolio.Run(); ! */ ! ! } ! [STAThread] ! static void Main() ! { ! // try ! // { ! //new RunMSFTsimpleTest().Run(); // new RunMSFTsimpleTest_2().Run(); ! //new RunOneRankWithExcelReport().Run(); ! //new RunOneRankWithWindowsReport().Run(); ! //new RunBestTwoIndipendent().Run(); ! //Principale.geneticOptimizerTest(); ! //new RunEfficientCTOPorfolio().Run(); ! //new RunEfficientCTCPorfolio().Run(); ! //new RunEfficientPorfolio().Run(); // QuantProject.Scripts.WalkForwardTesting.FixedLengthTwoPhases.FixedLengthTwoPhasesMain // myMain = // new QuantProject.Scripts.WalkForwardTesting.FixedLengthTwoPhases.FixedLengthTwoPhasesMain().Run; ! Application.Run(new Principale()); ! //geneticOptimizerTest(); ! //Application.Run(new OneRankForm()); ! //runMilloScripts(); ! ! //new RunEfficientCTOPorfolio("Test",200,5,60,10,5000, "^SPX", ! // new DateTime(2000,1,1), ! // new DateTime(2001,12,31)).Run(); ! // new RunMSFTwalkForward().Run(); ! // new RunOneRankWithWindowsReport().Run(); ! //new RunMSFTwalkForward().Run(); ! //new RunMultiTestOneRank().Run(); ! //new RunWalkForwardOneRank().Run(); ! //new RunEfficientCTOPorfolio().Run(); ! //new RunWalkForwardOneRank().Run(); ! // } ! // catch ( Exception ex ) ! // { ! //// QuantProject.Principale.Principale.runEfficientPortfolio.SaveScriptResults(); ! // writeExceptionToLogFile(ex); ! // } ! } ! static private void writeExceptionToLogFile(Exception ex) ! { ! string path = Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf('\\')) ! + @"\ExceptionLog.txt"; ! if(File.Exists(path)) ! { ! StreamWriter w = File.AppendText(path); ! w.Write("\r\nTime of exception : "); ! w.WriteLine("{0} {1}", DateTime.Now.ToLongDateString(), ! DateTime.Now.ToLocalTime()); // w.Write("\r\nScript name: {0}", // QuantProject.Principale.Principale.runEfficientPortfolio.ScriptName ); // w.Write("\r\nTimer date: {0}", // QuantProject.Principale.Principale.runEfficientPortfolio.TimerLastDate.ToLongDateString() ); ! // ! w.WriteLine("\n :{0}", ex.ToString()); ! w.WriteLine("\n :{0}", ex.StackTrace.ToString()); ! w.WriteLine ("\n-----------------------------------"); ! // Update the underlying file. ! w.Flush(); ! w.Close(); ! } ! ! } ! ! private static void geneticOptimizerTest() ! { ! IGenomeManager genomeManagerTest = new GenomeManagerTest(5,1,10); ! GeneticOptimizer GO = new GeneticOptimizer(genomeManagerTest,1000,10); ! //GO.KeepOnRunningUntilConvergenceIsReached = true; ! GO.Run(true); ! System.Console.WriteLine("\n\nThe best solution found is: " + (string)GO.BestGenome.Meaning + ! " with {0} generations", GO.GenerationCounter); ! } ! ! private void menuItem14_Click(object sender, System.EventArgs e) ! { ! } ! //run scripts in debugging mode ! private void menuItemRun_Click(object sender, System.EventArgs e) ! { ! // try ! // {//call here your scripts ! //new RunWalkForwardOneRank().Run(); // new WFLagMain().ShowDialog(); new FixedLengthTwoPhasesMain().Run(); // new PairsTradingMain().Run(); ! // new RunOneRank().Run(); ! //new RunEfficientCTCPorfolio("Test",400,5,90,10,10000, ! // "^SPX", ! // new DateTime(2004,1,1), ! // new DateTime(2004,2,29), ! // 3).Run(); ! ! //this.Close(); ! // runMilloScripts(); ! ! //new RunEfficientCTOPorfolio("Test",200,5,60,2,500, "^SPX", ! // new DateTime(2004,1,1), ! // new DateTime(2004,1,15)).Run(); ! ! // } ! // catch ( Exception ex ) ! // { ! // string notUsed = ex.ToString(); ! // //in this way qP shouldn't stop if running a single script fails ... ! // } ! } ! private void menuItemAccountViewer_Click(object sender, System.EventArgs e) ! { ! AccountViewer accountViewer = new AccountViewer(); ! accountViewer.Show(); ! } ! private string getPath(string dialogTitle) ! { ! OpenFileDialog openFileDialog = new OpenFileDialog(); ! openFileDialog.Title = dialogTitle; ! openFileDialog.Multiselect = false; ! openFileDialog.CheckFileExists = true; ! openFileDialog.ShowDialog(); ! return openFileDialog.FileName; ! } ! private void menuItemShowReportFromAccount_Click(object sender, System.EventArgs e) ! { ! string chosenPath = this.getPath("Select a serialized account please ..."); ! if(chosenPath != "") ! ShowReportFromFile.ShowReportFromSerializedAccount(chosenPath); ! } ! ! private void menuItemRunReleasingMode_Click(object sender, System.EventArgs e) ! { ! try ! { ! this.Cursor = Cursors.WaitCursor; ! //call here your scripts ! //new RunWalkForwardOneRank().Run(); ! ! } ! catch ( Exception ex ) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! //in this way qP shouldn't stop if running a single script fails ... ! } ! finally ! { ! this.Cursor = Cursors.Default; ! } ! } ! private void menuItemShowSavedReport_Click(object sender, System.EventArgs e) ! { ! string chosenPath = this.getPath("Select a serialized report please ..."); ! if(chosenPath != "") ! ShowReportFromFile.ShowReportFromSerializedAccountReport(chosenPath); ! } ! private void menuItemShowReportFromTransactions_Click(object sender, System.EventArgs e) ! { ! string chosenPath = this.getPath("Select a serialized TransactionHistory please ..."); ! if(chosenPath != "") ! ShowReportFromFile.ShowReportFromSerializedTransactionHistory(chosenPath); ! } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:51
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagDebugger In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagDebugger Modified Files: WFLagLogItem.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: WFLagLogItem.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagDebugger/WFLagLogItem.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** WFLagLogItem.cs 28 Oct 2007 18:43:38 -0000 1.1 --- WFLagLogItem.cs 19 Aug 2008 17:13:13 -0000 1.2 *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 74,78 **** } public WFLagLogItem( WFLagChosenTickers wFLagChosenTickers , ! DateTime lastOptimizationDate ) { // this.drivingPositions = --- 74,78 ---- } public WFLagLogItem( WFLagChosenTickers wFLagChosenTickers , ! DateTime lastOptimizationDate ) { // this.drivingPositions = *************** *** 95,100 **** /// <param name="lastOptimizationDate"></param> public WFLagLogItem( WFLagWeightedPositions wFLagWeightedPositions , ! int generationWhenTheBestGenomeWasFound , ! DateTime lastOptimizationDate ) { // this.drivingPositions = --- 95,100 ---- /// <param name="lastOptimizationDate"></param> public WFLagLogItem( WFLagWeightedPositions wFLagWeightedPositions , ! int generationWhenTheBestGenomeWasFound , ! DateTime lastOptimizationDate ) { // this.drivingPositions = *************** *** 103,107 **** // this.copy( wFLagChosenTickers.PortfolioWeightedPositions ); this.initialize( wFLagWeightedPositions , ! generationWhenTheBestGenomeWasFound , lastOptimizationDate ); } --- 103,107 ---- // this.copy( wFLagChosenTickers.PortfolioWeightedPositions ); this.initialize( wFLagWeightedPositions , ! generationWhenTheBestGenomeWasFound , lastOptimizationDate ); } *************** *** 112,120 **** // no generation number to log this.initialize( wFLagWeightedPositions , ! -999 , lastOptimizationDate ); } private void initialize( WFLagWeightedPositions wFLagWeightedPositions , ! int generationWhenTheBestGenomeWasFound , ! DateTime lastOptimizationDate ) { this.wFLagWeightedPositions = --- 112,120 ---- // no generation number to log this.initialize( wFLagWeightedPositions , ! -999 , lastOptimizationDate ); } private void initialize( WFLagWeightedPositions wFLagWeightedPositions , ! int generationWhenTheBestGenomeWasFound , ! DateTime lastOptimizationDate ) { this.wFLagWeightedPositions = *************** *** 138,142 **** // deserialize the fields from the info object, only if of the base clas ! for (Int32 i = 0 ; i < memberInfos.Length; i++) { // Don't deserialize fields for this class --- 138,142 ---- // deserialize the fields from the info object, only if of the base clas ! for (Int32 i = 0 ; i < memberInfos.Length; i++) { // Don't deserialize fields for this class *************** *** 147,151 **** // set the field to the deserialized value fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); } } --- 147,151 ---- // set the field to the deserialized value fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); } } *************** *** 170,174 **** catch( Exception ex1 ) { ! string exMessage = ex1.Message; } } --- 170,174 ---- catch( Exception ex1 ) { ! string exMessage = ex1.Message; } } *************** *** 197,204 **** // drivingWeightedPositions = this.getWeightedPositions( drivingPositions ); } ! catch( Exception ex2 ) { ! string errorMessage = ex2.Message; ! errorMessage = errorMessage; } } --- 197,203 ---- // drivingWeightedPositions = this.getWeightedPositions( drivingPositions ); } ! catch( Exception ex ) { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; } } *************** *** 241,245 **** { this.lastOptimizationDate = (DateTime)info.GetValue( "lastOptimizationDate" , ! this.lastOptimizationDate.GetType() ); this.deserializeWFLagWeightedPositions( info , context ); this.deserializeDrivingWeightedPositions( info , context ); --- 240,244 ---- { this.lastOptimizationDate = (DateTime)info.GetValue( "lastOptimizationDate" , ! this.lastOptimizationDate.GetType() ); this.deserializeWFLagWeightedPositions( info , context ); this.deserializeDrivingWeightedPositions( info , context ); *************** *** 248,261 **** } void ISerializable.GetObjectData( ! SerializationInfo info, StreamingContext context) { // get the set of serializable members for this class and base classes Type thisType = this.GetType(); ! MemberInfo[] mi = FormatterServices.GetSerializableMembers( thisType , context); // serialize the fields to the info object ! for (Int32 i = 0 ; i < mi.Length; i++) ! { string memberName = mi[i].Name; if ( ( memberName != "drivingPositions" ) && ( memberName != "portfolioPositions" ) ) --- 247,260 ---- } void ISerializable.GetObjectData( ! SerializationInfo info, StreamingContext context) { // get the set of serializable members for this class and base classes Type thisType = this.GetType(); ! MemberInfo[] mi = FormatterServices.GetSerializableMembers( thisType , context); // serialize the fields to the info object ! for (Int32 i = 0 ; i < mi.Length; i++) ! { string memberName = mi[i].Name; if ( ( memberName != "drivingPositions" ) && ( memberName != "portfolioPositions" ) ) |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:51
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/WeightedPVO In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/WeightedPVO Modified Files: RunWeightedPVO.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunWeightedPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/WeightedPVO/RunWeightedPVO.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunWeightedPVO.cs 14 Jan 2008 23:07:04 -0000 1.2 --- RunWeightedPVO.cs 19 Aug 2008 17:13:13 -0000 1.3 *************** *** 3,7 **** RunWeightedPVO.cs ! Copyright (C) 2006 Marco Milletti --- 3,7 ---- RunWeightedPVO.cs ! Copyright (C) 2006 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 36,40 **** using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; --- 36,40 ---- using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; *************** *** 47,192 **** /// <summary> /// Script that implements an oscillating strategy using weights for tickers, ! /// based on the classical technical indicator ! /// RelativeStrengthIndex - RSI /// </summary> [Serializable] public class RunWeightedPVO : RunEfficientPortfolio { ! protected int minLevelForOversoldThreshold; ! protected int maxLevelForOversoldThreshold; ! protected int minLevelForOverboughtThreshold; ! protected int maxLevelForOverboughtThreshold; ! protected int divisorForThresholdComputation; ! //to be used by the optimizer ! protected int numDaysBetweenEachOptimization; ! protected double maxAcceptableCloseToCloseDrawdown; ! protected double minimumAcceptableGain; ! protected int numDaysForOscillatingPeriod; ! protected bool symmetricalThresholds = false; ! protected bool overboughtMoreThanOversoldForFixedPortfolio = false; ! ! public RunWeightedPVO(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, string benchmark, ! DateTime startDate, DateTime endDate, ! int numDaysForOscillatingPeriod, ! int minLevelForOversoldThreshold, ! int maxLevelForOversoldThreshold, ! int minLevelForOverboughtThreshold, ! int maxLevelForOverboughtThreshold, ! int divisorForThresholdComputation, ! bool symmetricalThresholds, ! bool overboughtMoreThanOversoldForFixedPortfolio, ! int numDaysBetweenEachOptimization, ! PortfolioType inSamplePortfolioType, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain, ! double maxRunningHours): ! base(tickerGroupID, maxNumOfEligibleTickersForOptimization, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, benchmark, ! startDate, endDate, 0.0, ! inSamplePortfolioType, maxRunningHours) { ! this.ScriptName = "PVO_SR_WithWeights_PriceSel"; ! this.minLevelForOversoldThreshold = minLevelForOversoldThreshold; ! this.maxLevelForOversoldThreshold = maxLevelForOversoldThreshold; ! this.minLevelForOverboughtThreshold = minLevelForOverboughtThreshold; ! this.maxLevelForOverboughtThreshold = maxLevelForOverboughtThreshold; ! this.divisorForThresholdComputation = divisorForThresholdComputation; ! this.symmetricalThresholds = symmetricalThresholds; ! this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.minimumAcceptableGain = minimumAcceptableGain; ! this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } ! #region auxiliary overriden methods for Run ! ! protected override void run_initializeEndOfDayTimerHandler() ! { ! this.endOfDayTimerHandler = new EndOfDayTimerHandlerWeightedPVO(this.tickerGroupID, this.numberOfEligibleTickers, ! this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, ! this.account, ! this.generationNumberForGeneticOptimizer, ! this.populationSizeForGeneticOptimizer, this.benchmark, ! this.numDaysForOscillatingPeriod, ! this.minLevelForOversoldThreshold, ! this.maxLevelForOversoldThreshold, ! this.minLevelForOverboughtThreshold, ! this.maxLevelForOverboughtThreshold, ! this.divisorForThresholdComputation, ! this.symmetricalThresholds, ! this.overboughtMoreThanOversoldForFixedPortfolio, ! this.numDaysBetweenEachOptimization, ! this.portfolioType, this.maxAcceptableCloseToCloseDrawdown, ! this.minimumAcceptableGain); ! } ! ! 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 = DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + ! DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + ! this.scriptName + "OsDays_" + numDaysForOscillatingPeriod + ! "_From_" + this.tickerGroupID + "_" + this.numberOfEligibleTickers + ! "_DaysForOpt" + this.numDaysForOptimizationPeriod + "Tick" + ! this.numberOfTickersToBeChosen + "GenN°" + ! this.generationNumberForGeneticOptimizer + ! "PopSize" + this.populationSizeForGeneticOptimizer + ! 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 + "\\"; ! ! this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); ! OptimizationOutput optimizationOutput = new OptimizationOutput(); ! foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) ! optimizationOutput.Add(genomeRepresentation); ! ObjectArchiver.Archive(optimizationOutput, ! dirNameWhereToSaveBestGenomes + ! fileName + ".bgn"); ! ! //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.endOfDayTimer.Stop(); ! ! } ! ! ! #endregion } } --- 47,195 ---- /// <summary> /// Script that implements an oscillating strategy using weights for tickers, ! /// based on the classical technical indicator ! /// RelativeStrengthIndex - RSI /// </summary> [Serializable] public class RunWeightedPVO : RunEfficientPortfolio { ! protected int minLevelForOversoldThreshold; ! protected int maxLevelForOversoldThreshold; ! protected int minLevelForOverboughtThreshold; ! protected int maxLevelForOverboughtThreshold; ! protected int divisorForThresholdComputation; ! //to be used by the optimizer ! protected int numDaysBetweenEachOptimization; ! protected double maxAcceptableCloseToCloseDrawdown; ! protected double minimumAcceptableGain; ! protected int numDaysForOscillatingPeriod; ! protected bool symmetricalThresholds = false; ! protected bool overboughtMoreThanOversoldForFixedPortfolio = false; ! ! public RunWeightedPVO(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, string benchmark, ! DateTime startDate, DateTime endDate, ! int numDaysForOscillatingPeriod, ! int minLevelForOversoldThreshold, ! int maxLevelForOversoldThreshold, ! int minLevelForOverboughtThreshold, ! int maxLevelForOverboughtThreshold, ! int divisorForThresholdComputation, ! bool symmetricalThresholds, ! bool overboughtMoreThanOversoldForFixedPortfolio, ! int numDaysBetweenEachOptimization, ! PortfolioType inSamplePortfolioType, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain, ! double maxRunningHours): ! base(tickerGroupID, maxNumOfEligibleTickersForOptimization, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, benchmark, ! startDate, endDate, 0.0, ! inSamplePortfolioType, maxRunningHours) { ! this.ScriptName = "PVO_SR_WithWeights_PriceSel"; ! this.minLevelForOversoldThreshold = minLevelForOversoldThreshold; ! this.maxLevelForOversoldThreshold = maxLevelForOversoldThreshold; ! this.minLevelForOverboughtThreshold = minLevelForOverboughtThreshold; ! this.maxLevelForOverboughtThreshold = maxLevelForOverboughtThreshold; ! this.divisorForThresholdComputation = divisorForThresholdComputation; ! this.symmetricalThresholds = symmetricalThresholds; ! this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.minimumAcceptableGain = minimumAcceptableGain; ! this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } ! #region auxiliary overriden methods for Run ! ! protected override void run_initializeEndOfDayTimerHandler() ! { ! this.endOfDayTimerHandler = new EndOfDayTimerHandlerWeightedPVO(this.tickerGroupID, this.numberOfEligibleTickers, ! this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, ! this.account, ! this.generationNumberForGeneticOptimizer, ! this.populationSizeForGeneticOptimizer, this.benchmark, ! this.numDaysForOscillatingPeriod, ! this.minLevelForOversoldThreshold, ! this.maxLevelForOversoldThreshold, ! this.minLevelForOverboughtThreshold, ! this.maxLevelForOverboughtThreshold, ! this.divisorForThresholdComputation, ! this.symmetricalThresholds, ! this.overboughtMoreThanOversoldForFixedPortfolio, ! this.numDaysBetweenEachOptimization, ! this.portfolioType, this.maxAcceptableCloseToCloseDrawdown, ! this.minimumAcceptableGain); ! } ! ! 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 = DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + ! DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + ! this.scriptName + "OsDays_" + numDaysForOscillatingPeriod + ! "_From_" + this.tickerGroupID + "_" + this.numberOfEligibleTickers + ! "_DaysForOpt" + this.numDaysForOptimizationPeriod + "Tick" + ! this.numberOfTickersToBeChosen + "GenN°" + ! this.generationNumberForGeneticOptimizer + ! "PopSize" + this.populationSizeForGeneticOptimizer + ! Convert.ToString(this.portfolioType); ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveBestGenomes = ! System.Configuration.ConfigurationManager.AppSettings["GenomesArchive"] + ! "\\" + this.ScriptName + "\\"; ! ! this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); ! OptimizationOutput optimizationOutput = new OptimizationOutput(); ! foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) ! optimizationOutput.Add(genomeRepresentation); ! ObjectArchiver.Archive(optimizationOutput, ! dirNameWhereToSaveBestGenomes + ! fileName + ".bgn"); ! ! //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.endOfDayTimer.Stop(); ! ! } ! ! ! #endregion } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:50
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/WeightedPVO/WeightedBalancedPVO In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/WeightedPVO/WeightedBalancedPVO Modified Files: RunWeightedBalancedPVO.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunWeightedBalancedPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/WeightedPVO/WeightedBalancedPVO/RunWeightedBalancedPVO.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunWeightedBalancedPVO.cs 14 Jan 2008 23:07:05 -0000 1.2 --- RunWeightedBalancedPVO.cs 19 Aug 2008 17:13:13 -0000 1.3 *************** *** 3,7 **** RunWeightedBalancedPVO.cs ! Copyright (C) 2006 Marco Milletti --- 3,7 ---- RunWeightedBalancedPVO.cs ! Copyright (C) 2006 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 36,40 **** using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; --- 36,40 ---- using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; *************** *** 47,192 **** /// <summary> /// Script that implements an oscillating strategy using weights for tickers, ! /// based on the classical technical indicator ! /// RelativeStrengthIndex - RSI /// </summary> [Serializable] public class RunWeightedBalancedPVO : RunEfficientPortfolio { ! protected int minLevelForOversoldThreshold; ! protected int maxLevelForOversoldThreshold; ! protected int minLevelForOverboughtThreshold; ! protected int maxLevelForOverboughtThreshold; ! protected int divisorForThresholdComputation; ! //to be used by the optimizer ! protected int numDaysBetweenEachOptimization; ! protected double maxAcceptableCloseToCloseDrawdown; ! protected double minimumAcceptableGain; ! protected int numDaysForOscillatingPeriod; ! protected bool symmetricalThresholds = false; ! protected bool overboughtMoreThanOversoldForFixedPortfolio = false; ! ! public RunWeightedBalancedPVO(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, string benchmark, ! DateTime startDate, DateTime endDate, ! int numDaysForOscillatingPeriod, ! int minLevelForOversoldThreshold, ! int maxLevelForOversoldThreshold, ! int minLevelForOverboughtThreshold, ! int maxLevelForOverboughtThreshold, ! int divisorForThresholdComputation, ! bool symmetricalThresholds, ! bool overboughtMoreThanOversoldForFixedPortfolio, ! int numDaysBetweenEachOptimization, ! PortfolioType inSamplePortfolioType, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain, ! double maxRunningHours): ! base(tickerGroupID, maxNumOfEligibleTickersForOptimization, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, benchmark, ! startDate, endDate, 0.0, ! inSamplePortfolioType, maxRunningHours) { ! this.ScriptName = "PVO_SR_BalancedWeights_PriceSel"; ! this.minLevelForOversoldThreshold = minLevelForOversoldThreshold; ! this.maxLevelForOversoldThreshold = maxLevelForOversoldThreshold; ! this.minLevelForOverboughtThreshold = minLevelForOverboughtThreshold; ! this.maxLevelForOverboughtThreshold = maxLevelForOverboughtThreshold; ! this.divisorForThresholdComputation = divisorForThresholdComputation; ! this.symmetricalThresholds = symmetricalThresholds; ! this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.minimumAcceptableGain = minimumAcceptableGain; ! this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } ! #region auxiliary overriden methods for Run ! ! protected override void run_initializeEndOfDayTimerHandler() ! { ! this.endOfDayTimerHandler = new EndOfDayTimerHandlerWeightedBalancedPVO(this.tickerGroupID, this.numberOfEligibleTickers, ! this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, ! this.account, ! this.generationNumberForGeneticOptimizer, ! this.populationSizeForGeneticOptimizer, this.benchmark, ! this.numDaysForOscillatingPeriod, ! this.minLevelForOversoldThreshold, ! this.maxLevelForOversoldThreshold, ! this.minLevelForOverboughtThreshold, ! this.maxLevelForOverboughtThreshold, ! this.divisorForThresholdComputation, ! this.symmetricalThresholds, ! this.overboughtMoreThanOversoldForFixedPortfolio, ! this.numDaysBetweenEachOptimization, ! this.portfolioType, this.maxAcceptableCloseToCloseDrawdown, ! this.minimumAcceptableGain); ! } ! ! 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 = DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + ! DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + ! this.scriptName + "OsDays_" + numDaysForOscillatingPeriod + ! "_From_" + this.tickerGroupID + "_" + this.numberOfEligibleTickers + ! "_DaysForOpt" + this.numDaysForOptimizationPeriod + "Tick" + ! this.numberOfTickersToBeChosen + "GenN°" + ! this.generationNumberForGeneticOptimizer + ! "PopSize" + this.populationSizeForGeneticOptimizer + ! 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 + "\\"; ! ! this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); ! OptimizationOutput optimizationOutput = new OptimizationOutput(); ! foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) ! optimizationOutput.Add(genomeRepresentation); ! ObjectArchiver.Archive(optimizationOutput, ! dirNameWhereToSaveBestGenomes + ! fileName + ".bgn"); ! ! //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.endOfDayTimer.Stop(); ! ! } ! ! ! #endregion } } --- 47,195 ---- /// <summary> /// Script that implements an oscillating strategy using weights for tickers, ! /// based on the classical technical indicator ! /// RelativeStrengthIndex - RSI /// </summary> [Serializable] public class RunWeightedBalancedPVO : RunEfficientPortfolio { ! protected int minLevelForOversoldThreshold; ! protected int maxLevelForOversoldThreshold; ! protected int minLevelForOverboughtThreshold; ! protected int maxLevelForOverboughtThreshold; ! protected int divisorForThresholdComputation; ! //to be used by the optimizer ! protected int numDaysBetweenEachOptimization; ! protected double maxAcceptableCloseToCloseDrawdown; ! protected double minimumAcceptableGain; ! protected int numDaysForOscillatingPeriod; ! protected bool symmetricalThresholds = false; ! protected bool overboughtMoreThanOversoldForFixedPortfolio = false; ! ! public RunWeightedBalancedPVO(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, string benchmark, ! DateTime startDate, DateTime endDate, ! int numDaysForOscillatingPeriod, ! int minLevelForOversoldThreshold, ! int maxLevelForOversoldThreshold, ! int minLevelForOverboughtThreshold, ! int maxLevelForOverboughtThreshold, ! int divisorForThresholdComputation, ! bool symmetricalThresholds, ! bool overboughtMoreThanOversoldForFixedPortfolio, ! int numDaysBetweenEachOptimization, ! PortfolioType inSamplePortfolioType, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain, ! double maxRunningHours): ! base(tickerGroupID, maxNumOfEligibleTickersForOptimization, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, benchmark, ! startDate, endDate, 0.0, ! inSamplePortfolioType, maxRunningHours) { ! this.ScriptName = "PVO_SR_BalancedWeights_PriceSel"; ! this.minLevelForOversoldThreshold = minLevelForOversoldThreshold; ! this.maxLevelForOversoldThreshold = maxLevelForOversoldThreshold; ! this.minLevelForOverboughtThreshold = minLevelForOverboughtThreshold; ! this.maxLevelForOverboughtThreshold = maxLevelForOverboughtThreshold; ! this.divisorForThresholdComputation = divisorForThresholdComputation; ! this.symmetricalThresholds = symmetricalThresholds; ! this.overboughtMoreThanOversoldForFixedPortfolio = overboughtMoreThanOversoldForFixedPortfolio; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.minimumAcceptableGain = minimumAcceptableGain; ! this.numDaysForOscillatingPeriod = numDaysForOscillatingPeriod; ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } ! #region auxiliary overriden methods for Run ! ! protected override void run_initializeEndOfDayTimerHandler() ! { ! this.endOfDayTimerHandler = new EndOfDayTimerHandlerWeightedBalancedPVO(this.tickerGroupID, this.numberOfEligibleTickers, ! this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, ! this.account, ! this.generationNumberForGeneticOptimizer, ! this.populationSizeForGeneticOptimizer, this.benchmark, ! this.numDaysForOscillatingPeriod, ! this.minLevelForOversoldThreshold, ! this.maxLevelForOversoldThreshold, ! this.minLevelForOverboughtThreshold, ! this.maxLevelForOverboughtThreshold, ! this.divisorForThresholdComputation, ! this.symmetricalThresholds, ! this.overboughtMoreThanOversoldForFixedPortfolio, ! this.numDaysBetweenEachOptimization, ! this.portfolioType, this.maxAcceptableCloseToCloseDrawdown, ! this.minimumAcceptableGain); ! } ! ! 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 = DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + ! DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + ! this.scriptName + "OsDays_" + numDaysForOscillatingPeriod + ! "_From_" + this.tickerGroupID + "_" + this.numberOfEligibleTickers + ! "_DaysForOpt" + this.numDaysForOptimizationPeriod + "Tick" + ! this.numberOfTickersToBeChosen + "GenN°" + ! this.generationNumberForGeneticOptimizer + ! "PopSize" + this.populationSizeForGeneticOptimizer + ! Convert.ToString(this.portfolioType); ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveBestGenomes = ! System.Configuration.ConfigurationManager.AppSettings["GenomesArchive"] + ! "\\" + this.ScriptName + "\\"; ! ! this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); ! OptimizationOutput optimizationOutput = new OptimizationOutput(); ! foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) ! optimizationOutput.Add(genomeRepresentation); ! ObjectArchiver.Archive(optimizationOutput, ! dirNameWhereToSaveBestGenomes + ! fileName + ".bgn"); ! ! //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.endOfDayTimer.Stop(); ! ! } ! ! ! #endregion } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:46
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio Modified Files: RunTestingOptimizationCloseToOpen.cs RunTestingOptimizationOpenToClose.cs RunTestingOptimizationOpenToCloseFitnessCombined.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunTestingOptimizationOpenToClose.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio/RunTestingOptimizationOpenToClose.cs,v retrieving revision 1.9 retrieving revision 1.10 diff -C2 -d -r1.9 -r1.10 *** RunTestingOptimizationOpenToClose.cs 14 Jan 2008 23:28:58 -0000 1.9 --- RunTestingOptimizationOpenToClose.cs 19 Aug 2008 17:13:11 -0000 1.10 *************** *** 3,7 **** RunTestingOptimizationOpenToClose.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- RunTestingOptimizationOpenToClose.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 38,91 **** /// for the efficient open to close portfolio /// </summary> ! [Serializable] ! public class RunTestingOptimizationOpenToClose ! { ! 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 RunTestingOptimizationOpenToClose(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, --- 38,91 ---- /// for the efficient open to close portfolio /// </summary> ! [Serializable] ! public class RunTestingOptimizationOpenToClose ! { ! 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 RunTestingOptimizationOpenToClose(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, *************** *** 93,350 **** 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 genManEfficientOTC = ! new GenomeManagerForEfficientOTCPortfolio(setOfTickersToBeOptimized, ! this.marketDate.AddDays(-this.numDaysForOptimization), ! this.marketDate, ! this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType, ! this.benchmark); ! ! this.setFitnesses_setFitnessesActually(genManEfficientOTC); ! ! } ! ! 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): {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(); ! } } } --- 93,351 ---- 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 genManEfficientOTC = ! new GenomeManagerForEfficientOTCPortfolio(setOfTickersToBeOptimized, ! this.marketDate.AddDays(-this.numDaysForOptimization), ! this.marketDate, ! this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType, ! this.benchmark); ! ! this.setFitnesses_setFitnessesActually(genManEfficientOTC); ! ! } ! ! public void Run() ! { ! try ! { ! this.setFitnesses(); ! OptimizationTechniqueEvaluator evaluator = ! new OptimizationTechniqueEvaluator(this.fitnessesInSample, ! this.fitnessesOutOfSample); ! this.run_writeToLogFile(evaluator); ! } ! catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! } ! ! 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.ConfigurationManager.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): {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(); ! } } } Index: RunTestingOptimizationCloseToOpen.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio/RunTestingOptimizationCloseToOpen.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RunTestingOptimizationCloseToOpen.cs 14 Jan 2008 23:28:58 -0000 1.3 --- RunTestingOptimizationCloseToOpen.cs 19 Aug 2008 17:13:11 -0000 1.4 *************** *** 3,7 **** RunTestingOptimizationCloseToOpen.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- RunTestingOptimizationCloseToOpen.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 38,321 **** /// for the efficient close to open portfolio /// </summary> ! [Serializable] ! public class RunTestingOptimizationCloseToOpen ! { ! 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 RunTestingOptimizationCloseToOpen(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 quotedAtEachMarketDayFromEligible = ! new SelectorByQuotationAtEachMarketDay( temporizedGroup.GetTableOfSelectedTickers(), ! false, date.AddDays(-this.numDaysForOptimization), ! date, this.numberOfEligibleTickers, this.benchmark); ! return quotedAtEachMarketDayFromEligible.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.GetFirstValidAdjustedOpen(dateOutOfSample.AddDays(1))/ ! // tickerQuotes.GetFirstValidAdjustedClose(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.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; ! ! } ! ! 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 genManEfficientCTOPortfolio = ! new GenomeManagerForEfficientCTOPortfolio(setOfTickersToBeOptimized, ! this.marketDate.AddDays(-this.numDaysForOptimization), ! this.marketDate, ! this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType, ! this.benchmark); ! ! this.setFitnesses_setFitnessesActually(genManEfficientCTOPortfolio); ! ! } ! ! 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 Close To Open 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 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", ! 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(); ! } } } --- 38,322 ---- /// for the efficient close to open portfolio /// </summary> ! [Serializable] ! public class RunTestingOptimizationCloseToOpen ! { ! 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 RunTestingOptimizationCloseToOpen(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 quotedAtEachMarketDayFromEligible = ! new SelectorByQuotationAtEachMarketDay( temporizedGroup.GetTableOfSelectedTickers(), ! false, date.AddDays(-this.numDaysForOptimization), ! date, this.numberOfEligibleTickers, this.benchmark); ! return quotedAtEachMarketDayFromEligible.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.GetFirstValidAdjustedOpen(dateOutOfSample.AddDays(1))/ ! // tickerQuotes.GetFirstValidAdjustedClose(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.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; ! ! } ! ! 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 genManEfficientCTOPortfolio = ! new GenomeManagerForEfficientCTOPortfolio(setOfTickersToBeOptimized, ! this.marketDate.AddDays(-this.numDaysForOptimization), ! this.marketDate, ! this.numberOfTickersToBeChosen, ! this.targetReturn, ! this.portfolioType, ! this.benchmark); ! ! this.setFitnesses_setFitnessesActually(genManEfficientCTOPortfolio); ! ! } ! ! public void Run() ! { ! try ! { ! this.setFitnesses(); ! OptimizationTechniqueEvaluator evaluator = ! new OptimizationTechniqueEvaluator(this.fitnessesInSample, ! this.fitnessesOutOfSample); ! this.run_writeToLogFile(evaluator); ! } ! catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! } ! ! 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.ConfigurationManager.AppSettings["GenericArchive"] + ! "\\OptimizationEvaluation.txt"; ! StreamWriter w = File.AppendText(pathFile); ! w.WriteLine ("\n----------------------------------------------\r\n"); ! w.Write("\r\nNew Test for Evaluation of Close To Open 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 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", ! 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(); ! } } } Index: RunTestingOptimizationOpenToCloseFitnessCombined.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/EfficientPortfolio/RunTestingOptimizationOpenToCloseFitnessCombined.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RunTestingOptimizationOpenToCloseFitnessCombined.cs 14 Jan 2008 23:28:58 -0000 1.3 --- RunTestingOptimizationOpenToCloseFitnessCombined.cs 19 Aug 2008 17:13:11 -0000 1.4 *************** *** 3,7 **** RunTestingOptimizationOpenToCloseFitnessCombined.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- RunTestingOptimizationOpenToCloseFitnessCombined.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** along with this program; if not, ... [truncated message content] |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:46
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/SimpleSelection In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/TickerSelectionTesting/SimpleSelection Modified Files: RunSimpleSelection.cs RunSimpleSelectionOpenToClose.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunSimpleSelectionOpenToClose.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/SimpleSelection/RunSimpleSelectionOpenToClose.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunSimpleSelectionOpenToClose.cs 14 May 2006 18:21:47 -0000 1.2 --- RunSimpleSelectionOpenToClose.cs 19 Aug 2008 17:13:10 -0000 1.3 *************** *** 128,134 **** "Target" + Convert.ToString(this.targetReturn) + Convert.ToString(this.portfolioType); ! string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = System.Configuration.ConfigurationSettings.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; --- 128,136 ---- "Target" + Convert.ToString(this.targetReturn) + Convert.ToString(this.portfolioType); ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; Index: RunSimpleSelection.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/SimpleSelection/RunSimpleSelection.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunSimpleSelection.cs 29 Aug 2007 10:04:30 -0000 1.2 --- RunSimpleSelection.cs 19 Aug 2008 17:13:10 -0000 1.3 *************** *** 3,7 **** RunSimpleSelection.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- RunSimpleSelection.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 39,43 **** using QuantProject.Business.Financial.Accounting.Commissions; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; --- 39,43 ---- using QuantProject.Business.Financial.Accounting.Commissions; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; *************** *** 47,255 **** { /// <summary> ! /// Base class for simple selection test /// The strategy simply chooses the tickers with the highest fitness, /// for short or long trading /// </summary> [Serializable] ! public class RunSimpleSelection { ! protected string tickerGroupID; ! protected int numberOfEligibleTickers; ! protected int numberOfTickersToBeChosen; ! protected int numDaysForOptimizationPeriod; ! protected ReportTable reportTable; ! protected EndOfDayDateTime startDateTime; ! protected EndOfDayDateTime endDateTime; protected IHistoricalQuoteProvider historicalQuoteProvider; ! protected EndOfDayTimerHandlerSimpleSelection endOfDayTimerHandler; ! protected Account account; ! protected IEndOfDayTimer endOfDayTimer; ! protected string benchmark; ! ! protected string scriptName; ! ! protected double targetReturn; ! ! protected PortfolioType portfolioType; ! ! protected DateTime startingTimeForScript; ! protected double maxRunningHours; ! //if MaxNumberOfHoursForScript has elapsed and the script ! //is still running, it will be stopped. ! ! public PortfolioType TypeOfPortfolio ! { ! get { return this.portfolioType; } ! } ! ! public virtual string ScriptName ! { ! get{return this.scriptName;} ! set{this.scriptName = value;} ! } ! ! public DateTime TimerLastDate ! { ! get{return this.endOfDayTimer.GetCurrentTime().DateTime ;} ! } ! public RunSimpleSelection(string benchmark, ! DateTime startDate, DateTime endDate, ! PortfolioType portfolioType, ! double maxRunningHours) { ! ! this.startDateTime = new EndOfDayDateTime( ! startDate, EndOfDaySpecificTime.FiveMinutesBeforeMarketClose ); ! this.endDateTime = new EndOfDayDateTime( ! endDate, EndOfDaySpecificTime.OneHourAfterMarketClose ); ! this.benchmark = benchmark; ! this.ScriptName = "SimpleTestGeneric"; ! this.portfolioType = portfolioType; ! this.startingTimeForScript = DateTime.Now; ! this.maxRunningHours = maxRunningHours; ! //this.numIntervalDays = 3; } ! ! public RunSimpleSelection(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! string benchmark, ! DateTime startDate, DateTime endDate, ! double targetReturn, ! PortfolioType portfolioType, ! double maxRunningHours) { ! //this.progressBarForm = new ProgressBarForm(); ! this.tickerGroupID = tickerGroupID; ! this.numberOfEligibleTickers = numberOfEligibleTickers; ! this.numberOfTickersToBeChosen = numberOfTickersToBeChosen; ! this.numDaysForOptimizationPeriod = numDaysForOptimizationPeriod; ! this.reportTable = new ReportTable( "Summary_Reports" ); ! this.startDateTime = new EndOfDayDateTime( ! startDate, EndOfDaySpecificTime.FiveMinutesBeforeMarketClose ); ! this.endDateTime = new EndOfDayDateTime( ! endDate, EndOfDaySpecificTime.OneHourAfterMarketClose ); ! this.benchmark = benchmark; ! this.ScriptName = "SimpleTestGeneric"; ! this.targetReturn = targetReturn; ! this.portfolioType = portfolioType; ! 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 ! 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() ! { ! //always needs specific implementation in inherited classes; ! } ! ! 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 = "SimpleSelectionFrom"+this.numberOfEligibleTickers + ! "OptDays" + this.numDaysForOptimizationPeriod + "Portfolio" + ! this.numberOfTickersToBeChosen + ! "Target" + Convert.ToString(this.targetReturn) + ! Convert.ToString(this.portfolioType); ! string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = System.Configuration.ConfigurationSettings.AppSettings["TransactionsArchive"] + ! "\\" + 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.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 ! } } --- 47,257 ---- { /// <summary> ! /// Base class for simple selection test /// The strategy simply chooses the tickers with the highest fitness, /// for short or long trading /// </summary> [Serializable] ! public class RunSimpleSelection { ! protected string tickerGroupID; ! protected int numberOfEligibleTickers; ! protected int numberOfTickersToBeChosen; ! protected int numDaysForOptimizationPeriod; ! protected ReportTable reportTable; ! protected EndOfDayDateTime startDateTime; ! protected EndOfDayDateTime endDateTime; protected IHistoricalQuoteProvider historicalQuoteProvider; ! protected EndOfDayTimerHandlerSimpleSelection endOfDayTimerHandler; ! protected Account account; ! protected IEndOfDayTimer endOfDayTimer; ! protected string benchmark; ! ! protected string scriptName; ! ! protected double targetReturn; ! ! protected PortfolioType portfolioType; ! ! protected DateTime startingTimeForScript; ! protected double maxRunningHours; ! //if MaxNumberOfHoursForScript has elapsed and the script ! //is still running, it will be stopped. ! ! public PortfolioType TypeOfPortfolio ! { ! get { return this.portfolioType; } ! } ! ! public virtual string ScriptName ! { ! get{return this.scriptName;} ! set{this.scriptName = value;} ! } ! ! public DateTime TimerLastDate ! { ! get{return this.endOfDayTimer.GetCurrentTime().DateTime ;} ! } ! public RunSimpleSelection(string benchmark, ! DateTime startDate, DateTime endDate, ! PortfolioType portfolioType, ! double maxRunningHours) { ! ! this.startDateTime = new EndOfDayDateTime( ! startDate, EndOfDaySpecificTime.FiveMinutesBeforeMarketClose ); ! this.endDateTime = new EndOfDayDateTime( ! endDate, EndOfDaySpecificTime.OneHourAfterMarketClose ); ! this.benchmark = benchmark; ! this.ScriptName = "SimpleTestGeneric"; ! this.portfolioType = portfolioType; ! this.startingTimeForScript = DateTime.Now; ! this.maxRunningHours = maxRunningHours; ! //this.numIntervalDays = 3; } ! ! public RunSimpleSelection(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! string benchmark, ! DateTime startDate, DateTime endDate, ! double targetReturn, ! PortfolioType portfolioType, ! double maxRunningHours) { ! //this.progressBarForm = new ProgressBarForm(); ! this.tickerGroupID = tickerGroupID; ! this.numberOfEligibleTickers = numberOfEligibleTickers; ! this.numberOfTickersToBeChosen = numberOfTickersToBeChosen; ! this.numDaysForOptimizationPeriod = numDaysForOptimizationPeriod; ! this.reportTable = new ReportTable( "Summary_Reports" ); ! this.startDateTime = new EndOfDayDateTime( ! startDate, EndOfDaySpecificTime.FiveMinutesBeforeMarketClose ); ! this.endDateTime = new EndOfDayDateTime( ! endDate, EndOfDaySpecificTime.OneHourAfterMarketClose ); ! this.benchmark = benchmark; ! this.ScriptName = "SimpleTestGeneric"; ! this.targetReturn = targetReturn; ! this.portfolioType = portfolioType; ! 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 ! 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() ! { ! //always needs specific implementation in inherited classes; ! } ! ! 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 = "SimpleSelectionFrom"+this.numberOfEligibleTickers + ! "OptDays" + this.numDaysForOptimizationPeriod + "Portfolio" + ! this.numberOfTickersToBeChosen + ! "Target" + Convert.ToString(this.targetReturn) + ! Convert.ToString(this.portfolioType); ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + ! "\\" + 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.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: Glauco S. <gla...@us...> - 2008-08-19 17:13:46
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/WalkForwardTesting/WalkForwardLag Modified Files: RunWalkForwardLag.cs WFLagChosenTickers.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunWalkForwardLag.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/RunWalkForwardLag.cs,v retrieving revision 1.12 retrieving revision 1.13 diff -C2 -d -r1.12 -r1.13 *** RunWalkForwardLag.cs 19 Jan 2008 19:23:45 -0000 1.12 --- RunWalkForwardLag.cs 19 Aug 2008 17:13:11 -0000 1.13 *************** *** 52,57 **** private int numberDaysForInSampleOptimization; private int numDaysBetweenEachOptimization; ! private int generationNumberForGeneticOptimizer; ! private int populationSizeForGeneticOptimizer; private string benchmark; private DateTime firstDateTime; --- 52,57 ---- private int numberDaysForInSampleOptimization; private int numDaysBetweenEachOptimization; ! // private int generationNumberForGeneticOptimizer; ! // private int populationSizeForGeneticOptimizer; private string benchmark; private DateTime firstDateTime; *************** *** 84,89 **** wFLagWeightedPositionsChooser.NumberDaysForInSampleOptimization; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; ! this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; this.benchmark = this.wFLagWeightedPositionsChooser.Benchmark; --- 84,89 ---- wFLagWeightedPositionsChooser.NumberDaysForInSampleOptimization; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; ! // this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; ! // this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; this.benchmark = this.wFLagWeightedPositionsChooser.Benchmark; *************** *** 209,214 **** "PrtfPstns_" + this.wFLagWeightedPositionsChooser.NumberOfPortfolioPositions + "_" + - "GenNum_" + this.generationNumberForGeneticOptimizer + "_" + - "PopSize_" + this.populationSizeForGeneticOptimizer + "_" + "From_" + this.getShortStringForDateTime( (DateTime)this.account.Transactions.GetKey( 0 ) ) + "_" + --- 209,212 ---- Index: WFLagChosenTickers.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagChosenTickers.cs,v retrieving revision 1.10 retrieving revision 1.11 diff -C2 -d -r1.10 -r1.11 *** WFLagChosenTickers.cs 7 Oct 2007 13:24:37 -0000 1.10 --- WFLagChosenTickers.cs 19 Aug 2008 17:13:12 -0000 1.11 *************** *** 44,48 **** public event NewProgressEventHandler NewProgress; ! protected WFLagEligibleTickers eligibleTickers; protected int numberOfDrivingPositions; protected int numberOfPositionsToBeChosen; --- 44,48 ---- public event NewProgressEventHandler NewProgress; ! // protected WFLagEligibleTickers eligibleTickers; protected int numberOfDrivingPositions; protected int numberOfPositionsToBeChosen; *************** *** 118,122 **** ) { ! this.eligibleTickers = eligibleTickers; this.numberOfDrivingPositions = numberOfDrivingPositions; this.numberOfPositionsToBeChosen = numberOfPositionsToBeChosen; --- 118,122 ---- ) { ! // this.eligibleTickers = eligibleTickers; this.numberOfDrivingPositions = numberOfDrivingPositions; this.numberOfPositionsToBeChosen = numberOfPositionsToBeChosen; |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:46
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/TechnicalAnalysis In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/EvaluatingOptimizationTechnique/TechnicalAnalysis Modified Files: RunTestingOptimizationExtremeCounterTrend.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunTestingOptimizationExtremeCounterTrend.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/EvaluatingOptimizationTechnique/TechnicalAnalysis/RunTestingOptimizationExtremeCounterTrend.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** RunTestingOptimizationExtremeCounterTrend.cs 14 Jan 2008 23:28:58 -0000 1.3 --- RunTestingOptimizationExtremeCounterTrend.cs 19 Aug 2008 17:13:11 -0000 1.4 *************** *** 3,7 **** RunTestingOptimizationExtremeCounterTrend.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- RunTestingOptimizationExtremeCounterTrend.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 39,337 **** /// 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 numDaysForOptimizationPeriod; ! private int populationSizeForGeneticOptimizer; ! private int generationNumberForGeneticOptimizer; ! private string benchmark; ! private DateTime marketDate; ! private int numDaysForReturnCalculation; ! private PortfolioType portfolioType; ! private int numDaysAfterLastOptimizationDay; ! private int numberOfSubsets; ! private Genome[] genomesToTestOutOfSample; ! private int numberOfGenomesToTest; ! ! public RunTestingOptimizationExtremeCounterTrend(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, ! string benchmark, ! DateTime marketDate, int numDaysForReturnCalculation, ! 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.numDaysForOptimizationPeriod = numDaysForOptimizationPeriod; ! this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; ! this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; ! this.benchmark = benchmark; ! this.marketDate = marketDate; ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.portfolioType = portfolioType; ! this.numDaysAfterLastOptimizationDay = numDaysAfterLastOptimizationDay; ! this.numberOfSubsets = numberOfSubsets; ! } ! ! private DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { ! ! SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromTemporized = ! new SelectorByQuotationAtEachMarketDay(temporizedGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! 600, this.benchmark); ! // filter to be used with plain stocks ! // DataTable tickersQuotedAtEachMarketDay = quotedAtEachMarketDayFromTemporized.GetTableOfSelectedTickers(); ! // SelectorByLiquidity mostLiquid = ! // new SelectorByLiquidity(tickersQuotedAtEachMarketDay, ! // false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // tickersQuotedAtEachMarketDay.Rows.Count/2); ! // ! // DataTable mostLiquidTickers = mostLiquid.GetTableOfSelectedTickers(); ! // ! // SelectorByCloseToCloseVolatility lessVolatile = ! // new SelectorByCloseToCloseVolatility(mostLiquidTickers, ! // true,currentDate.AddDays(-30), currentDate, ! // Math.Min(this.numberOfEligibleTickers, mostLiquidTickers.Rows.Count/2)); ! //// return mostLiquid.GetTableOfSelectedTickers(); ! // return lessVolatile.GetTableOfSelectedTickers(); ! // ! return quotedAtEachMarketDayFromTemporized.GetTableOfSelectedTickers(); ! } ! ! private double setFitnesses_setFitnessesActually_getFitnessOutOfSample_PortfolioClose(Genome portfolioGenome, DateTime date) ! ! { ! double returnValue = 0.0; ! foreach(string tickerCode in ((GenomeMeaning)portfolioGenome.Meaning).Tickers) ! { ! double coefficient = 1.0; ! string ticker = tickerCode; ! if(ticker.StartsWith("-")) ! { ! ticker = ticker.Substring(1,ticker.Length -1); ! coefficient = -1.0; ! } ! Quotes tickerQuotes = new Quotes(ticker, date, ! date); ! returnValue += (tickerQuotes.GetFirstValidCloseToCloseRatio(date) - 1.0)*coefficient; ! } ! return returnValue/portfolioGenome.Size; ! } ! 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 endDateOutOfSample = this.marketDate.AddDays(this.numDaysAfterLastOptimizationDay); ! ! Quotes tickerQuotes = new Quotes(ticker, this.marketDate, ! endDateOutOfSample); ! double[] returns = new double[tickerQuotes.Rows.Count]; ! for(int i = 1; i<returns.Length; i++) ! { ! if(this.setFitnesses_setFitnessesActually_getFitnessOutOfSample_PortfolioClose( ! genome, (DateTime)tickerQuotes.Rows[i-1]["quDate"])>0.0) ! coefficient = -1.0 * coefficient; ! returns[i] = (tickerQuotes.GetFirstValidCloseToCloseRatio( ! (DateTime)tickerQuotes.Rows[i]["quDate"] ) - 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 genManExtremeCounterTrend = ! new GenomeManagerECT(setOfTickersToBeOptimized, ! this.marketDate.AddDays(-this.numDaysForOptimizationPeriod), ! this.marketDate, ! this.numberOfTickersToBeChosen, ! this.numDaysForReturnCalculation, ! this.portfolioType, ! this.benchmark); ! ! this.setFitnesses_setFitnessesActually(genManExtremeCounterTrend); ! ! } ! ! 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 Extreme Counter Trend Optimization {0}\r", DateTime.Now.ToLongDateString()+ " " +DateTime.Now.ToLongTimeString()); ! w.Write("\r\nNum days for optimization {0}\r", this.numDaysForOptimizationPeriod.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(); ! } } } --- 39,338 ---- /// 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 numDaysForOptimizationPeriod; ! private int populationSizeForGeneticOptimizer; ! private int generationNumberForGeneticOptimizer; ! private string benchmark; ! private DateTime marketDate; ! private int numDaysForReturnCalculation; ! private PortfolioType portfolioType; ! private int numDaysAfterLastOptimizationDay; ! private int numberOfSubsets; ! private Genome[] genomesToTestOutOfSample; ! private int numberOfGenomesToTest; ! ! public RunTestingOptimizationExtremeCounterTrend(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, ! string benchmark, ! DateTime marketDate, int numDaysForReturnCalculation, ! 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.numDaysForOptimizationPeriod = numDaysForOptimizationPeriod; ! this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; ! this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; ! this.benchmark = benchmark; ! this.marketDate = marketDate; ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.portfolioType = portfolioType; ! this.numDaysAfterLastOptimizationDay = numDaysAfterLastOptimizationDay; ! this.numberOfSubsets = numberOfSubsets; ! } ! ! private DataTable getSetOfTickersToBeOptimized(DateTime currentDate) ! { ! ! SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, ! currentDate); ! ! SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromTemporized = ! new SelectorByQuotationAtEachMarketDay(temporizedGroup.GetTableOfSelectedTickers(), ! false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! 600, this.benchmark); ! // filter to be used with plain stocks ! // DataTable tickersQuotedAtEachMarketDay = quotedAtEachMarketDayFromTemporized.GetTableOfSelectedTickers(); ! // SelectorByLiquidity mostLiquid = ! // new SelectorByLiquidity(tickersQuotedAtEachMarketDay, ! // false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, ! // tickersQuotedAtEachMarketDay.Rows.Count/2); ! // ! // DataTable mostLiquidTickers = mostLiquid.GetTableOfSelectedTickers(); ! // ! // SelectorByCloseToCloseVolatility lessVolatile = ! // new SelectorByCloseToCloseVolatility(mostLiquidTickers, ! // true,currentDate.AddDays(-30), currentDate, ! // Math.Min(this.numberOfEligibleTickers, mostLiquidTickers.Rows.Count/2)); ! //// return mostLiquid.GetTableOfSelectedTickers(); ! // return lessVolatile.GetTableOfSelectedTickers(); ! // ! return quotedAtEachMarketDayFromTemporized.GetTableOfSelectedTickers(); ! } ! ! private double setFitnesses_setFitnessesActually_getFitnessOutOfSample_PortfolioClose(Genome portfolioGenome, DateTime date) ! ! { ! double returnValue = 0.0; ! foreach(string tickerCode in ((GenomeMeaning)portfolioGenome.Meaning).Tickers) ! { ! double coefficient = 1.0; ! string ticker = tickerCode; ! if(ticker.StartsWith("-")) ! { ! ticker = ticker.Substring(1,ticker.Length -1); ! coefficient = -1.0; ! } ! Quotes tickerQuotes = new Quotes(ticker, date, ! date); ! returnValue += (tickerQuotes.GetFirstValidCloseToCloseRatio(date) - 1.0)*coefficient; ! } ! return returnValue/portfolioGenome.Size; ! } ! 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 endDateOutOfSample = this.marketDate.AddDays(this.numDaysAfterLastOptimizationDay); ! ! Quotes tickerQuotes = new Quotes(ticker, this.marketDate, ! endDateOutOfSample); ! double[] returns = new double[tickerQuotes.Rows.Count]; ! for(int i = 1; i<returns.Length; i++) ! { ! if(this.setFitnesses_setFitnessesActually_getFitnessOutOfSample_PortfolioClose( ! genome, (DateTime)tickerQuotes.Rows[i-1]["quDate"])>0.0) ! coefficient = -1.0 * coefficient; ! returns[i] = (tickerQuotes.GetFirstValidCloseToCloseRatio( ! (DateTime)tickerQuotes.Rows[i]["quDate"] ) - 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 genManExtremeCounterTrend = ! new GenomeManagerECT(setOfTickersToBeOptimized, ! this.marketDate.AddDays(-this.numDaysForOptimizationPeriod), ! this.marketDate, ! this.numberOfTickersToBeChosen, ! this.numDaysForReturnCalculation, ! this.portfolioType, ! this.benchmark); ! ! this.setFitnesses_setFitnessesActually(genManExtremeCounterTrend); ! ! } ! ! public void Run() ! { ! try ! { ! this.setFitnesses(); ! OptimizationTechniqueEvaluator evaluator = ! new OptimizationTechniqueEvaluator(this.fitnessesInSample, ! this.fitnessesOutOfSample); ! this.run_writeToLogFile(evaluator); ! } ! catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! } ! ! 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.ConfigurationManager.AppSettings["GenericArchive"] + ! "\\OptimizationEvaluation.txt"; ! StreamWriter w = File.AppendText(pathFile); ! w.WriteLine ("\n----------------------------------------------\r\n"); ! w.Write("\r\nNew Test for Evaluation of Extreme Counter Trend Optimization {0}\r", DateTime.Now.ToLongDateString()+ " " +DateTime.Now.ToLongTimeString()); ! w.Write("\r\nNum days for optimization {0}\r", this.numDaysForOptimizationPeriod.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: Glauco S. <gla...@us...> - 2008-08-19 17:13:45
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/SimpleOHTest In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/SimpleOHTest Modified Files: RunSimpleOHTest.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunSimpleOHTest.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/SimpleOHTest/RunSimpleOHTest.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunSimpleOHTest.cs 29 Aug 2007 09:40:11 -0000 1.2 --- RunSimpleOHTest.cs 19 Aug 2008 17:13:09 -0000 1.3 *************** *** 143,147 **** "_Short_" + this.numOfTickersForShortSelling + "_lenInDays_" + this.lengthInDaysForPerformance; ! string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; --- 143,148 ---- "_Short_" + this.numOfTickersForShortSelling + "_lenInDays_" + this.lengthInDaysForPerformance; ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:45
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading/SimplePairTrading In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/ArbitrageTesting/PairTrading/SimplePairTrading Modified Files: RunSimplePairTrading.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunSimplePairTrading.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading/SimplePairTrading/RunSimplePairTrading.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunSimplePairTrading.cs 14 May 2006 15:25:30 -0000 1.1 --- RunSimplePairTrading.cs 19 Aug 2008 17:13:09 -0000 1.2 *************** *** 113,119 **** 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"] + --- 113,121 ---- this.generationNumberForGeneticOptimizer + "PopSize" + this.populationSizeForGeneticOptimizer; ! string dirNameWhereToSaveAccounts = ! System.Configuration.ConfigurationManager.AppSettings["AccountsArchive"] + "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; // string dirNameWhereToSaveBestGenomes = System.Configuration.ConfigurationSettings.AppSettings["GenomesArchive"] + |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:45
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/ArbitrageTesting/PairTrading Modified Files: RunPairTrading.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunPairTrading.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/PairTrading/RunPairTrading.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunPairTrading.cs 14 May 2006 15:25:30 -0000 1.1 --- RunPairTrading.cs 19 Aug 2008 17:13:09 -0000 1.2 *************** *** 190,196 **** 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"] + --- 190,198 ---- this.generationNumberForGeneticOptimizer + "PopSize" + this.populationSizeForGeneticOptimizer; ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; // string dirNameWhereToSaveBestGenomes = System.Configuration.ConfigurationSettings.AppSettings["GenomesArchive"] + |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:44
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower Modified Files: RunImmediateTrendFollower.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunImmediateTrendFollower.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/TrendFollowing/ImmediateTrendFollower/RunImmediateTrendFollower.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunImmediateTrendFollower.cs 3 Aug 2006 21:14:13 -0000 1.1 --- RunImmediateTrendFollower.cs 19 Aug 2008 17:13:08 -0000 1.2 *************** *** 3,7 **** RunImmediateTrendFollower.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- RunImmediateTrendFollower.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 36,40 **** using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; --- 36,40 ---- using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; *************** *** 47,160 **** /// <summary> /// Script that implements the immediate trend follower strategy, ! /// for finding tickers that tend to ! /// earn (lose) from previous gains (losses), using efficient portfolios /// </summary> [Serializable] public class RunImmediateTrendFollower : RunEfficientPortfolio { ! private int numDaysForReturnCalculation; ! private double maxAcceptableCloseToCloseDrawdown; ! private int numDaysBetweenEachOptimization; ! public RunImmediateTrendFollower(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, ! 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, maxNumOfEligibleTickersForOptimization, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, benchmark, ! startDate, endDate, 0.0, ! portfolioType, maxRunningHours) { ! this.ScriptName = "ITF_Fitness_SR_NoWeights"; ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } ! #region auxiliary overriden methods for Run ! ! protected override void run_initializeEndOfDayTimerHandler() ! { ! this.endOfDayTimerHandler = new EndOfDayTimerHandlerITF(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 = this.scriptName + "_From_"+ this.tickerGroupID + "_" + this.numberOfEligibleTickers + ! "_DaysForOpt" + this.numDaysForOptimizationPeriod + "Tickers" + ! 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 } } --- 47,163 ---- /// <summary> /// Script that implements the immediate trend follower strategy, ! /// for finding tickers that tend to ! /// earn (lose) from previous gains (losses), using efficient portfolios /// </summary> [Serializable] public class RunImmediateTrendFollower : RunEfficientPortfolio { ! private int numDaysForReturnCalculation; ! private double maxAcceptableCloseToCloseDrawdown; ! private int numDaysBetweenEachOptimization; ! public RunImmediateTrendFollower(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, ! 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, maxNumOfEligibleTickersForOptimization, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, benchmark, ! startDate, endDate, 0.0, ! portfolioType, maxRunningHours) { ! this.ScriptName = "ITF_Fitness_SR_NoWeights"; ! this.numDaysForReturnCalculation = numDaysForReturnCalculation; ! this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; ! this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; } ! #region auxiliary overriden methods for Run ! ! protected override void run_initializeEndOfDayTimerHandler() ! { ! this.endOfDayTimerHandler = new EndOfDayTimerHandlerITF(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 = this.scriptName + "_From_"+ this.tickerGroupID + "_" + this.numberOfEligibleTickers + ! "_DaysForOpt" + this.numDaysForOptimizationPeriod + "Tickers" + ! this.numberOfTickersToBeChosen + "GenNum" + ! this.generationNumberForGeneticOptimizer + ! "PopSize" + this.populationSizeForGeneticOptimizer + ! "HalfPeriodDays" + Convert.ToString(this.numDaysForReturnCalculation) + ! Convert.ToString(this.portfolioType); ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveBestGenomes = ! System.Configuration.ConfigurationManager.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 } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:42
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators Modified Files: RunFPOscillatorCTC.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunFPOscillatorCTC.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedPeriodOscillators/RunFPOscillatorCTC.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunFPOscillatorCTC.cs 14 May 2006 15:29:22 -0000 1.1 --- RunFPOscillatorCTC.cs 19 Aug 2008 17:13:06 -0000 1.2 *************** *** 3,7 **** RunFPOscillatorCTC.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- RunFPOscillatorCTC.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 36,40 **** using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; --- 36,40 ---- using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; *************** *** 47,157 **** /// <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 } } --- 47,160 ---- /// <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.ConfigurationManager.AppSettings["ReportsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveBestGenomes = ! System.Configuration.ConfigurationManager.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 } } |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:41
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/TickerSelectionTesting Modified Files: RunEfficientPortfolio.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunEfficientPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/RunEfficientPortfolio.cs,v retrieving revision 1.21 retrieving revision 1.22 diff -C2 -d -r1.21 -r1.22 *** RunEfficientPortfolio.cs 29 Aug 2007 10:04:30 -0000 1.21 --- RunEfficientPortfolio.cs 19 Aug 2008 17:13:06 -0000 1.22 *************** *** 3,7 **** RunEfficientPortfolio.cs ! Copyright (C) 2003 Marco Milletti --- 3,7 ---- RunEfficientPortfolio.cs ! Copyright (C) 2003 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 40,44 **** using QuantProject.Business.Financial.Accounting.Commissions; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; --- 40,44 ---- using QuantProject.Business.Financial.Accounting.Commissions; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; *************** *** 52,296 **** /// </summary> [Serializable] ! public class RunEfficientPortfolio { ! protected string tickerGroupID; ! protected int numberOfEligibleTickers; ! protected int numberOfTickersToBeChosen; ! protected int numDaysForOptimizationPeriod; ! protected int generationNumberForGeneticOptimizer; ! protected int populationSizeForGeneticOptimizer; ! protected ReportTable reportTable; ! protected EndOfDayDateTime startDateTime; ! protected EndOfDayDateTime endDateTime; ! //protected int numIntervalDays;// number of days for the equity line graph protected IHistoricalQuoteProvider historicalQuoteProvider; ! //protected ProgressBarForm progressBarForm; ! protected EndOfDayTimerHandler endOfDayTimerHandler; ! protected Account account; ! protected IEndOfDayTimer endOfDayTimer; ! protected string benchmark; ! ! protected string scriptName; ! ! protected double targetReturn; ! ! protected PortfolioType portfolioType; ! ! protected DateTime startingTimeForScript; ! protected double maxRunningHours; ! //if MaxNumberOfHoursForScript has elapsed and the script ! //is still running, it will be stopped. ! ! ! public PortfolioType TypeOfPortfolio ! { ! get { return this.portfolioType; } ! } ! ! public virtual string ScriptName ! { ! get{return this.scriptName;} ! set{this.scriptName = value;} ! } ! ! public DateTime TimerLastDate ! { ! get{return this.endOfDayTimer.GetCurrentTime().DateTime ;} ! } ! public RunEfficientPortfolio(string benchmark, ! DateTime startDate, DateTime endDate, ! PortfolioType portfolioType, ! double maxRunningHours) { ! ! this.startDateTime = new EndOfDayDateTime( ! startDate, EndOfDaySpecificTime.FiveMinutesBeforeMarketClose ); ! this.endDateTime = new EndOfDayDateTime( ! endDate, EndOfDaySpecificTime.OneHourAfterMarketClose ); ! this.benchmark = benchmark; ! this.ScriptName = "EfficientGeneric"; ! this.portfolioType = portfolioType; ! this.startingTimeForScript = DateTime.Now; ! this.maxRunningHours = maxRunningHours; ! //this.numIntervalDays = 3; } ! ! public RunEfficientPortfolio(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, string benchmark, ! DateTime startDate, DateTime endDate, ! double targetReturn, ! PortfolioType portfolioType, ! double maxRunningHours) { ! //this.progressBarForm = new ProgressBarForm(); ! this.tickerGroupID = tickerGroupID; ! this.numberOfEligibleTickers = numberOfEligibleTickers; ! this.numberOfTickersToBeChosen = numberOfTickersToBeChosen; ! this.numDaysForOptimizationPeriod = numDaysForOptimizationPeriod; ! this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; ! this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; ! this.reportTable = new ReportTable( "Summary_Reports" ); ! this.startDateTime = new EndOfDayDateTime( ! startDate, EndOfDaySpecificTime.FiveMinutesBeforeMarketClose ); ! this.endDateTime = new EndOfDayDateTime( ! endDate, EndOfDaySpecificTime.OneHourAfterMarketClose ); ! this.benchmark = benchmark; ! this.ScriptName = "EfficientGeneric"; ! this.targetReturn = targetReturn; ! this.portfolioType = portfolioType; ! this.startingTimeForScript = DateTime.Now; ! this.maxRunningHours = maxRunningHours; ! //this.numIntervalDays = 3; } - - protected string getGenomeCounterInfo() - { - string returnValue = ""; - if(this.endOfDayTimerHandler.GenomeCounter != null) - returnValue = "Total generated genomes: " + - this.endOfDayTimerHandler.GenomeCounter.TotalEvaluatedGenomes.ToString() + - "; Current fitness: " + - this.endOfDayTimerHandler.GenomeCounter.BestFitness.ToString(); - return returnValue; - } ! #region Run ! ! protected virtual void run_initializeEndOfDayTimer() ! { ! //default endOfDayTimer ! this.endOfDayTimer = ! new IndexBasedEndOfDayTimer( this.startDateTime, this.endDateTime, ! 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() ! { ! //always needs specific implementation in inherited classes; ! } ! ! 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 string SaveScriptResults_CreateFileName() ! { ! return DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + ! DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + ! "From_" + this.tickerGroupID + "_" + ! + this.numberOfEligibleTickers + ! "_OptDays" + this.numDaysForOptimizationPeriod + "_Port" + ! this.numberOfTickersToBeChosen + "GenNum" + ! this.generationNumberForGeneticOptimizer + ! "PopSize" + this.populationSizeForGeneticOptimizer + ! Convert.ToString(this.portfolioType); ! } ! ! ! public virtual void SaveScriptResults() ! { ! string fileName = this.SaveScriptResults_CreateFileName(); ! 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(); ! ! } ! ! 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 ! } } --- 52,299 ---- /// </summary> [Serializable] ! public class RunEfficientPortfolio { ! protected string tickerGroupID; ! protected int numberOfEligibleTickers; ! protected int numberOfTickersToBeChosen; ! protected int numDaysForOptimizationPeriod; ! protected int generationNumberForGeneticOptimizer; ! protected int populationSizeForGeneticOptimizer; ! protected ReportTable reportTable; ! protected EndOfDayDateTime startDateTime; ! protected EndOfDayDateTime endDateTime; ! //protected int numIntervalDays;// number of days for the equity line graph protected IHistoricalQuoteProvider historicalQuoteProvider; ! //protected ProgressBarForm progressBarForm; ! protected EndOfDayTimerHandler endOfDayTimerHandler; ! protected Account account; ! protected IEndOfDayTimer endOfDayTimer; ! protected string benchmark; ! ! protected string scriptName; ! ! protected double targetReturn; ! ! protected PortfolioType portfolioType; ! ! protected DateTime startingTimeForScript; ! protected double maxRunningHours; ! //if MaxNumberOfHoursForScript has elapsed and the script ! //is still running, it will be stopped. ! ! ! public PortfolioType TypeOfPortfolio ! { ! get { return this.portfolioType; } ! } ! ! public virtual string ScriptName ! { ! get{return this.scriptName;} ! set{this.scriptName = value;} ! } ! ! public DateTime TimerLastDate ! { ! get{return this.endOfDayTimer.GetCurrentTime().DateTime ;} ! } ! public RunEfficientPortfolio(string benchmark, ! DateTime startDate, DateTime endDate, ! PortfolioType portfolioType, ! double maxRunningHours) { ! ! this.startDateTime = new EndOfDayDateTime( ! startDate, EndOfDaySpecificTime.FiveMinutesBeforeMarketClose ); ! this.endDateTime = new EndOfDayDateTime( ! endDate, EndOfDaySpecificTime.OneHourAfterMarketClose ); ! this.benchmark = benchmark; ! this.ScriptName = "EfficientGeneric"; ! this.portfolioType = portfolioType; ! this.startingTimeForScript = DateTime.Now; ! this.maxRunningHours = maxRunningHours; ! //this.numIntervalDays = 3; } ! ! public RunEfficientPortfolio(string tickerGroupID, int numberOfEligibleTickers, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, string benchmark, ! DateTime startDate, DateTime endDate, ! double targetReturn, ! PortfolioType portfolioType, ! double maxRunningHours) { ! //this.progressBarForm = new ProgressBarForm(); ! this.tickerGroupID = tickerGroupID; ! this.numberOfEligibleTickers = numberOfEligibleTickers; ! this.numberOfTickersToBeChosen = numberOfTickersToBeChosen; ! this.numDaysForOptimizationPeriod = numDaysForOptimizationPeriod; ! this.generationNumberForGeneticOptimizer = generationNumberForGeneticOptimizer; ! this.populationSizeForGeneticOptimizer = populationSizeForGeneticOptimizer; ! this.reportTable = new ReportTable( "Summary_Reports" ); ! this.startDateTime = new EndOfDayDateTime( ! startDate, EndOfDaySpecificTime.FiveMinutesBeforeMarketClose ); ! this.endDateTime = new EndOfDayDateTime( ! endDate, EndOfDaySpecificTime.OneHourAfterMarketClose ); ! this.benchmark = benchmark; ! this.ScriptName = "EfficientGeneric"; ! this.targetReturn = targetReturn; ! this.portfolioType = portfolioType; ! this.startingTimeForScript = DateTime.Now; ! this.maxRunningHours = maxRunningHours; ! //this.numIntervalDays = 3; ! } ! ! protected string getGenomeCounterInfo() ! { ! string returnValue = ""; ! if(this.endOfDayTimerHandler.GenomeCounter != null) ! returnValue = "Total generated genomes: " + ! this.endOfDayTimerHandler.GenomeCounter.TotalEvaluatedGenomes.ToString() + ! "; Current fitness: " + ! this.endOfDayTimerHandler.GenomeCounter.BestFitness.ToString(); ! return returnValue; } ! #region Run ! ! protected virtual void run_initializeEndOfDayTimer() ! { ! //default endOfDayTimer ! this.endOfDayTimer = ! new IndexBasedEndOfDayTimer( this.startDateTime, this.endDateTime, ! 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() ! { ! //always needs specific implementation in inherited classes; ! } ! ! 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 string SaveScriptResults_CreateFileName() ! { ! return DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + ! DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + ! "From_" + this.tickerGroupID + "_" + ! + this.numberOfEligibleTickers + ! "_OptDays" + this.numDaysForOptimizationPeriod + "_Port" + ! this.numberOfTickersToBeChosen + "GenNum" + ! this.generationNumberForGeneticOptimizer + ! "PopSize" + this.populationSizeForGeneticOptimizer + ! Convert.ToString(this.portfolioType); ! } ! ! ! public virtual void SaveScriptResults() ! { ! string fileName = this.SaveScriptResults_CreateFileName(); ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveBestGenomes = ! System.Configuration.ConfigurationManager.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(); ! ! } ! ! 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: Glauco S. <gla...@us...> - 2008-08-19 17:13:40
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/TestingOTCTypes/BruteForceOptimization In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/TickerSelectionTesting/TestingOTCTypes/BruteForceOptimization Modified Files: RunEfficientOTCTypesBruteForce.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunEfficientOTCTypesBruteForce.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/TestingOTCTypes/BruteForceOptimization/RunEfficientOTCTypesBruteForce.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunEfficientOTCTypesBruteForce.cs 17 Sep 2006 21:37:18 -0000 1.1 --- RunEfficientOTCTypesBruteForce.cs 19 Aug 2008 17:13:05 -0000 1.2 *************** *** 140,148 **** "OptDays" + this.numDaysForOptimizationPeriod + "Portfolio" + this.numberOfTickersToBeChosen + "BruteForce"; ! 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 + "\\"; --- 140,151 ---- "OptDays" + this.numDaysForOptimizationPeriod + "Portfolio" + this.numberOfTickersToBeChosen + "BruteForce"; ! string dirNameWhereToSaveAccounts = ! System.Configuration.ConfigurationManager.AppSettings["AccountsArchive"] + "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveBestGenomes = ! System.Configuration.ConfigurationManager.AppSettings["GenomesArchive"] + "\\" + this.ScriptName + "\\"; |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:40
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend Modified Files: RunExtremeCounterTrend.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunExtremeCounterTrend.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/ExtremeCounterTrend/RunExtremeCounterTrend.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RunExtremeCounterTrend.cs 7 Aug 2006 21:17:13 -0000 1.4 --- RunExtremeCounterTrend.cs 19 Aug 2008 17:13:06 -0000 1.5 *************** *** 123,131 **** "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 --- 123,134 ---- "HalfPeriodDays" + Convert.ToString(this.numDaysForReturnCalculation) + Convert.ToString(this.portfolioType); ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveBestGenomes = ! System.Configuration.ConfigurationManager.AppSettings["GenomesArchive"] + "\\" + this.ScriptName + "\\"; //default report with numIntervalDays = 1 |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/TestingOTCTypes In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/TickerSelectionTesting/TestingOTCTypes Modified Files: RunEfficientOTCTypes.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunEfficientOTCTypes.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/TestingOTCTypes/RunEfficientOTCTypes.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** RunEfficientOTCTypes.cs 8 Apr 2007 18:55:21 -0000 1.8 --- RunEfficientOTCTypes.cs 19 Aug 2008 17:13:05 -0000 1.9 *************** *** 150,158 **** "_PopSize" + this.populationSizeForGeneticOptimizer + Convert.ToString(this.portfolioType); ! 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 + "\\"; --- 150,161 ---- "_PopSize" + this.populationSizeForGeneticOptimizer + Convert.ToString(this.portfolioType); ! string dirNameWhereToSaveAccounts = ! System.Configuration.ConfigurationManager.AppSettings["AccountsArchive"] + "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveBestGenomes = ! System.Configuration.ConfigurationManager.AppSettings["GenomesArchive"] + "\\" + this.ScriptName + "\\"; |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_WeekEndBounce In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_WeekEndBounce Modified Files: RunDOR_WeekEndBounce.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunDOR_WeekEndBounce.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_WeekEndBounce/RunDOR_WeekEndBounce.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunDOR_WeekEndBounce.cs 29 Aug 2007 09:16:56 -0000 1.1 --- RunDOR_WeekEndBounce.cs 19 Aug 2008 17:13:04 -0000 1.2 *************** *** 151,155 **** "_forLong_" + this.numOfTickersForBuying + "_forShort_" + this.numOfTickersForShortSelling; ! string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; --- 151,156 ---- "_forLong_" + this.numOfTickersForBuying + "_forShort_" + this.numOfTickersForShortSelling; ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:38
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_OTC In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_OTC Modified Files: RunDOR_OTC.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunDOR_OTC.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_OTC/RunDOR_OTC.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** RunDOR_OTC.cs 30 Jun 2007 18:58:33 -0000 1.1 --- RunDOR_OTC.cs 19 Aug 2008 17:13:04 -0000 1.2 *************** *** 149,153 **** "_forLong_" + this.numOfTickersForBuying + "_forShort_" + this.numOfTickersForShortSelling; ! string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; --- 149,154 ---- "_forLong_" + this.numOfTickersForBuying + "_forShort_" + this.numOfTickersForShortSelling; ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:38
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO Modified Files: RunBiasedPVO.cs RunBiasedPVO_OTC.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: RunBiasedPVO.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/RunBiasedPVO.cs,v retrieving revision 1.4 retrieving revision 1.5 diff -C2 -d -r1.4 -r1.5 *** RunBiasedPVO.cs 9 Mar 2008 22:40:51 -0000 1.4 --- RunBiasedPVO.cs 19 Aug 2008 17:13:03 -0000 1.5 *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 38,42 **** using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; --- 38,42 ---- using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; *************** *** 53,57 **** /// when it is time to open new positions, /// it is not simply chosen the genome with the highest fitness ! /// (as in the PVO base), but it is chosen the genome (from a /// given set of genomes with a good fitness) that /// has the highest degree of deviation from a threshold --- 53,57 ---- /// when it is time to open new positions, /// it is not simply chosen the genome with the highest fitness ! /// (as in the PVO base), but it is chosen the genome (from a /// given set of genomes with a good fitness) that /// has the highest degree of deviation from a threshold *************** *** 60,68 **** public class RunBiasedPVO : RunPVO { ! protected double minPriceForTickersToBeChosen; ! protected double maxPriceForTickersToBeChosen; protected int numOfDifferentGenomesToEvaluateOutOfSample; ! protected int numDaysOfStayingOnTheMarket; ! protected double maxCoefficientForDegreeComputationOfCrossingThreshold; protected double numOfStdDevForThresholdsComputation; protected bool resetThresholdsBeforeCheckingOutOfSample; --- 60,68 ---- public class RunBiasedPVO : RunPVO { ! protected double minPriceForTickersToBeChosen; ! protected double maxPriceForTickersToBeChosen; protected int numOfDifferentGenomesToEvaluateOutOfSample; ! protected int numDaysOfStayingOnTheMarket; ! protected double maxCoefficientForDegreeComputationOfCrossingThreshold; protected double numOfStdDevForThresholdsComputation; protected bool resetThresholdsBeforeCheckingOutOfSample; *************** *** 70,74 **** protected bool doNotOpenReversedPositionsThatHaveJustBeenClosed; protected int numDaysForThresholdsReComputation; ! protected string pathOfFileContainingGenomes; public string PathOfFileContainingGenomes --- 70,74 ---- protected bool doNotOpenReversedPositionsThatHaveJustBeenClosed; protected int numDaysForThresholdsReComputation; ! protected string pathOfFileContainingGenomes; public string PathOfFileContainingGenomes *************** *** 78,168 **** } ! public RunBiasedPVO(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, ! double minPriceForTickersToBeChosen, ! double maxPriceForTickersToBeChosen, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, string benchmark, ! DateTime startDate, DateTime endDate, ! int numOfDifferentGenomesToEvaluateOutOfSample, ! bool resetThresholdsBeforeCheckingOutOfSample, ! int numDaysForThresholdsReComputation, ! double numOfStdDevForThresholdsComputation, ! double maxCoefficientForDegreeComputationOfCrossingThreshold, ! bool buyOnlyPositionsThatAreMovingTogether, ! bool doNotOpenReversedPositionsThatHaveJustBeenClosed, ! int numDaysForOscillatingPeriod, ! int numDaysOfStayingOnTheMarket, ! int minLevelForOversoldThreshold, ! int maxLevelForOversoldThreshold, ! int minLevelForOverboughtThreshold, ! int maxLevelForOverboughtThreshold, ! int divisorForThresholdComputation, ! bool symmetricalThresholds, ! bool overboughtMoreThanOversoldForFixedPortfolio, ! int numDaysBetweenEachOptimization, ! PortfolioType inSamplePortfolioType, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain, double maxRunningHours): ! base(tickerGroupID, maxNumOfEligibleTickersForOptimization, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, benchmark, ! startDate, endDate, ! numDaysForOscillatingPeriod, ! minLevelForOversoldThreshold, ! maxLevelForOversoldThreshold, ! minLevelForOverboughtThreshold, ! maxLevelForOverboughtThreshold, ! divisorForThresholdComputation, ! symmetricalThresholds, ! overboughtMoreThanOversoldForFixedPortfolio, ! numDaysBetweenEachOptimization, ! inSamplePortfolioType, maxAcceptableCloseToCloseDrawdown, ! minimumAcceptableGain, ! maxRunningHours) { ! this.minPriceForTickersToBeChosen = minPriceForTickersToBeChosen; ! this.maxPriceForTickersToBeChosen = maxPriceForTickersToBeChosen; this.numOfDifferentGenomesToEvaluateOutOfSample = numOfDifferentGenomesToEvaluateOutOfSample; ! this.minimumAcceptableGain = minimumAcceptableGain; ! //this.ScriptName = "PVO_Biased_WithWeightsPriceSel"; ! this.ScriptName = "PVO_Biased_NoWeightsPriceSel"; ! this.numDaysOfStayingOnTheMarket = numDaysOfStayingOnTheMarket; ! this.maxCoefficientForDegreeComputationOfCrossingThreshold = maxCoefficientForDegreeComputationOfCrossingThreshold; ! this.resetThresholdsBeforeCheckingOutOfSample = resetThresholdsBeforeCheckingOutOfSample; ! this.numDaysForThresholdsReComputation = numDaysForThresholdsReComputation; ! this.numOfStdDevForThresholdsComputation = numOfStdDevForThresholdsComputation; ! this.buyOnlyPositionsThatAreMovingTogether = buyOnlyPositionsThatAreMovingTogether; ! this.doNotOpenReversedPositionsThatHaveJustBeenClosed = doNotOpenReversedPositionsThatHaveJustBeenClosed; ! this.pathOfFileContainingGenomes = null; ! //if this field is set to null, selections of tickers (with ! //optimization), takes place; otherwise, tickers for ! //out of sample testing are chosen from a given ! //set of genomes saved to disk (representing a set of ! //a certain number of optimizations run over a given period) } ! #region auxiliary overriden methods for Run ! ! protected override void run_initializeEndOfDayTimerHandler() ! { ! this.endOfDayTimerHandler = new EndOfDayTimerHandlerBiasedPVO(this.tickerGroupID, this.numberOfEligibleTickers, ! this.minPriceForTickersToBeChosen, ! this.maxPriceForTickersToBeChosen, ! this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, this.account, this.PathOfFileContainingGenomes, ! this.generationNumberForGeneticOptimizer, ! this.populationSizeForGeneticOptimizer, this.benchmark, ! this.numOfDifferentGenomesToEvaluateOutOfSample, ! this.resetThresholdsBeforeCheckingOutOfSample, ! this.numDaysForThresholdsReComputation, ! this.numOfStdDevForThresholdsComputation, ! this.maxCoefficientForDegreeComputationOfCrossingThreshold, ! this.buyOnlyPositionsThatAreMovingTogether, ! this.doNotOpenReversedPositionsThatHaveJustBeenClosed, this.numDaysForOscillatingPeriod, this.numDaysOfStayingOnTheMarket, ! this.minLevelForOversoldThreshold, this.maxLevelForOversoldThreshold, this.minLevelForOverboughtThreshold, --- 78,168 ---- } ! public RunBiasedPVO(string tickerGroupID, int maxNumOfEligibleTickersForOptimization, ! double minPriceForTickersToBeChosen, ! double maxPriceForTickersToBeChosen, ! int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, ! int generationNumberForGeneticOptimizer, ! int populationSizeForGeneticOptimizer, string benchmark, ! DateTime startDate, DateTime endDate, ! int numOfDifferentGenomesToEvaluateOutOfSample, ! bool resetThresholdsBeforeCheckingOutOfSample, ! int numDaysForThresholdsReComputation, ! double numOfStdDevForThresholdsComputation, ! double maxCoefficientForDegreeComputationOfCrossingThreshold, ! bool buyOnlyPositionsThatAreMovingTogether, ! bool doNotOpenReversedPositionsThatHaveJustBeenClosed, ! int numDaysForOscillatingPeriod, ! int numDaysOfStayingOnTheMarket, ! int minLevelForOversoldThreshold, ! int maxLevelForOversoldThreshold, ! int minLevelForOverboughtThreshold, ! int maxLevelForOverboughtThreshold, ! int divisorForThresholdComputation, ! bool symmetricalThresholds, ! bool overboughtMoreThanOversoldForFixedPortfolio, ! int numDaysBetweenEachOptimization, ! PortfolioType inSamplePortfolioType, double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain, double maxRunningHours): ! base(tickerGroupID, maxNumOfEligibleTickersForOptimization, ! numberOfTickersToBeChosen, numDaysForOptimizationPeriod, ! generationNumberForGeneticOptimizer, ! populationSizeForGeneticOptimizer, benchmark, ! startDate, endDate, ! numDaysForOscillatingPeriod, ! minLevelForOversoldThreshold, ! maxLevelForOversoldThreshold, ! minLevelForOverboughtThreshold, ! maxLevelForOverboughtThreshold, ! divisorForThresholdComputation, ! symmetricalThresholds, ! overboughtMoreThanOversoldForFixedPortfolio, ! numDaysBetweenEachOptimization, ! inSamplePortfolioType, maxAcceptableCloseToCloseDrawdown, ! minimumAcceptableGain, ! maxRunningHours) { ! this.minPriceForTickersToBeChosen = minPriceForTickersToBeChosen; ! this.maxPriceForTickersToBeChosen = maxPriceForTickersToBeChosen; this.numOfDifferentGenomesToEvaluateOutOfSample = numOfDifferentGenomesToEvaluateOutOfSample; ! this.minimumAcceptableGain = minimumAcceptableGain; ! //this.ScriptName = "PVO_Biased_WithWeightsPriceSel"; ! this.ScriptName = "PVO_Biased_NoWeightsPriceSel"; ! this.numDaysOfStayingOnTheMarket = numDaysOfStayingOnTheMarket; ! this.maxCoefficientForDegreeComputationOfCrossingThreshold = maxCoefficientForDegreeComputationOfCrossingThreshold; ! this.resetThresholdsBeforeCheckingOutOfSample = resetThresholdsBeforeCheckingOutOfSample; ! this.numDaysForThresholdsReComputation = numDaysForThresholdsReComputation; ! this.numOfStdDevForThresholdsComputation = numOfStdDevForThresholdsComputation; ! this.buyOnlyPositionsThatAreMovingTogether = buyOnlyPositionsThatAreMovingTogether; ! this.doNotOpenReversedPositionsThatHaveJustBeenClosed = doNotOpenReversedPositionsThatHaveJustBeenClosed; ! this.pathOfFileContainingGenomes = null; ! //if this field is set to null, selections of tickers (with ! //optimization), takes place; otherwise, tickers for ! //out of sample testing are chosen from a given ! //set of genomes saved to disk (representing a set of ! //a certain number of optimizations run over a given period) } ! #region auxiliary overriden methods for Run ! ! protected override void run_initializeEndOfDayTimerHandler() ! { ! this.endOfDayTimerHandler = new EndOfDayTimerHandlerBiasedPVO(this.tickerGroupID, this.numberOfEligibleTickers, ! this.minPriceForTickersToBeChosen, ! this.maxPriceForTickersToBeChosen, ! this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, this.account, this.PathOfFileContainingGenomes, ! this.generationNumberForGeneticOptimizer, ! this.populationSizeForGeneticOptimizer, this.benchmark, ! this.numOfDifferentGenomesToEvaluateOutOfSample, ! this.resetThresholdsBeforeCheckingOutOfSample, ! this.numDaysForThresholdsReComputation, ! this.numOfStdDevForThresholdsComputation, ! this.maxCoefficientForDegreeComputationOfCrossingThreshold, ! this.buyOnlyPositionsThatAreMovingTogether, ! this.doNotOpenReversedPositionsThatHaveJustBeenClosed, this.numDaysForOscillatingPeriod, this.numDaysOfStayingOnTheMarket, ! this.minLevelForOversoldThreshold, this.maxLevelForOversoldThreshold, this.minLevelForOverboughtThreshold, *************** *** 171,184 **** this.symmetricalThresholds, this.overboughtMoreThanOversoldForFixedPortfolio, ! this.numDaysBetweenEachOptimization, ! this.portfolioType, this.maxAcceptableCloseToCloseDrawdown, this.minimumAcceptableGain); ! } ! ! protected void saveScriptResults_saveScriptFeaturesToLogFile(string nameForScriptFiles) { ! string pathFile = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + ! "\\" + this.ScriptName + "\\" + nameForScriptFiles + ".txt"; StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); --- 171,185 ---- this.symmetricalThresholds, this.overboughtMoreThanOversoldForFixedPortfolio, ! this.numDaysBetweenEachOptimization, ! this.portfolioType, this.maxAcceptableCloseToCloseDrawdown, this.minimumAcceptableGain); ! } ! ! protected void saveScriptResults_saveScriptFeaturesToLogFile(string nameForScriptFiles) { ! string pathFile = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + ! "\\" + this.ScriptName + "\\" + nameForScriptFiles + ".txt"; StreamWriter w = File.AppendText(pathFile); w.WriteLine ("\n----------------------------------------------\r\n"); *************** *** 223,273 **** // Update the underlying file. w.Flush(); ! w.Close(); } ! public override void SaveScriptResults() ! { ! string fileName = DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + ! DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + ! DateTime.Now.Second.ToString().PadLeft(2,'0') + "_" + ! this.scriptName + "GenOS_" + this.numOfDifferentGenomesToEvaluateOutOfSample + ! "_OsDays_" + numDaysForOscillatingPeriod + ! "_From_" + this.tickerGroupID + "_" + this.numberOfEligibleTickers + ! "_DaysForOpt" + this.numDaysForOptimizationPeriod + "Tick" + ! this.numberOfTickersToBeChosen + "GenN°" + ! this.generationNumberForGeneticOptimizer + ! "PopSize" + this.populationSizeForGeneticOptimizer + ! 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 + "\\"; ! ! this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); ! if( this.PathOfFileContainingGenomes == null ) ! { ! OptimizationOutput optimizationOutput = new OptimizationOutput(); ! foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) ! optimizationOutput.Add(genomeRepresentation); ! ObjectArchiver.Archive(optimizationOutput, ! dirNameWhereToSaveBestGenomes + ! fileName + ".bgn"); ! } ! this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ! AccountReport accountReport = this.account.CreateReport(fileName,1, ! this.endOfDayTimer.GetCurrentTime(), ! this.benchmark, ! new HistoricalAdjustedQuoteProvider()); ! ObjectArchiver.Archive(accountReport, ! dirNameWhereToSaveReports + ! fileName + ".qPr"); ! this.saveScriptResults_saveScriptFeaturesToLogFile(fileName); ! this.endOfDayTimer.Stop(); ! } ! ! ! #endregion } } --- 224,277 ---- // Update the underlying file. w.Flush(); ! w.Close(); } ! public override void SaveScriptResults() ! { ! string fileName = DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + ! DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + ! DateTime.Now.Second.ToString().PadLeft(2,'0') + "_" + ! this.scriptName + "GenOS_" + this.numOfDifferentGenomesToEvaluateOutOfSample + ! "_OsDays_" + numDaysForOscillatingPeriod + ! "_From_" + this.tickerGroupID + "_" + this.numberOfEligibleTickers + ! "_DaysForOpt" + this.numDaysForOptimizationPeriod + "Tick" + ! this.numberOfTickersToBeChosen + "GenN°" + ! this.generationNumberForGeneticOptimizer + ! "PopSize" + this.populationSizeForGeneticOptimizer + ! Convert.ToString(this.portfolioType); ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + ! "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveBestGenomes = ! System.Configuration.ConfigurationManager.AppSettings["GenomesArchive"] + ! "\\" + this.ScriptName + "\\"; ! ! this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveBestGenomes); ! if( this.PathOfFileContainingGenomes == null ) ! { ! OptimizationOutput optimizationOutput = new OptimizationOutput(); ! foreach(GenomeRepresentation genomeRepresentation in this.endOfDayTimerHandler.BestGenomes) ! optimizationOutput.Add(genomeRepresentation); ! ObjectArchiver.Archive(optimizationOutput, ! dirNameWhereToSaveBestGenomes + ! fileName + ".bgn"); ! } ! this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ! AccountReport accountReport = this.account.CreateReport(fileName,1, ! this.endOfDayTimer.GetCurrentTime(), ! this.benchmark, ! new HistoricalAdjustedQuoteProvider()); ! ObjectArchiver.Archive(accountReport, ! dirNameWhereToSaveReports + ! fileName + ".qPr"); ! this.saveScriptResults_saveScriptFeaturesToLogFile(fileName); ! this.endOfDayTimer.Stop(); ! } ! ! ! #endregion } } Index: RunBiasedPVO_OTC.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/BiasedPVO/RunBiasedPVO_OTC.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** RunBiasedPVO_OTC.cs 9 Mar 2008 22:40:51 -0000 1.2 --- RunBiasedPVO_OTC.cs 19 Aug 2008 17:13:03 -0000 1.3 *************** *** 184,192 **** "PopSize" + this.populationSizeForGeneticOptimizer + 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 + "\\"; --- 184,195 ---- "PopSize" + this.populationSizeForGeneticOptimizer + Convert.ToString(this.portfolioType); ! string dirNameWhereToSaveReports = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"] + "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveTransactions = ! System.Configuration.ConfigurationManager.AppSettings["TransactionsArchive"] + "\\" + this.ScriptName + "\\"; ! string dirNameWhereToSaveBestGenomes = ! System.Configuration.ConfigurationManager.AppSettings["GenomesArchive"] + "\\" + this.ScriptName + "\\"; |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:37
|
Update of /cvsroot/quantproject/QuantProject/b5_Presentation/Reporting/WindowsForm In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b5_Presentation/Reporting/WindowsForm Modified Files: Report.cs ReportTabControl.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: ReportTabControl.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b5_Presentation/Reporting/WindowsForm/ReportTabControl.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** ReportTabControl.cs 6 Feb 2008 23:16:39 -0000 1.5 --- ReportTabControl.cs 19 Aug 2008 17:13:02 -0000 1.6 *************** *** 3,7 **** ReportTabControl.cs ! Copyright (C) 2003 Glauco Siliprandi --- 3,7 ---- ReportTabControl.cs ! Copyright (C) 2003 Glauco Siliprandi *************** *** 19,23 **** 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.Runtime.Serialization; --- 19,23 ---- 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.Runtime.Serialization; *************** *** 60,64 **** /// <param name="context"></param> protected ReportTabControl( SerializationInfo info , StreamingContext context ) : ! base() { // get the set of serializable members for this class and its base classes --- 60,64 ---- /// <param name="context"></param> protected ReportTabControl( SerializationInfo info , StreamingContext context ) : ! base() { // get the set of serializable members for this class and its base classes *************** *** 68,72 **** // deserialize the fields from the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { FieldInfo fieldInfo = (FieldInfo) mi[i]; --- 68,72 ---- // deserialize the fields from the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { FieldInfo fieldInfo = (FieldInfo) mi[i]; *************** *** 76,83 **** { fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); } catch(Exception ex) ! {ex = ex;} } } --- 76,85 ---- { fieldInfo.SetValue( this , ! info.GetValue( fieldInfo.Name, fieldInfo.FieldType ) ); } catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } } } *************** *** 89,101 **** /// <param name="context"></param> void ISerializable.GetObjectData( ! SerializationInfo info, StreamingContext context) { // get the set of serializable members for this class and base classes Type thisType = this.GetType(); ! MemberInfo[] mi = FormatterServices.GetSerializableMembers( thisType , context); // serialize the fields to the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(this)); --- 91,103 ---- /// <param name="context"></param> void ISerializable.GetObjectData( ! SerializationInfo info, StreamingContext context) { // get the set of serializable members for this class and base classes Type thisType = this.GetType(); ! MemberInfo[] mi = FormatterServices.GetSerializableMembers( thisType , context); // serialize the fields to the info object ! for (Int32 i = 0 ; i < mi.Length; i++) { info.AddValue(mi[i].Name, ((FieldInfo) mi[i]).GetValue(this)); *************** *** 110,119 **** /// is to be shown</param> public ReportTabControl( AccountReport accountReport , ! bool showBenchmark ) { this.accountReport = accountReport; this.Dock = DockStyle.Fill; this.equityChart = new EquityChartTabPage( this.accountReport , ! showBenchmark ); this.Controls.Add( this.equityChart ); this.summary = new SummaryTabPage( this.accountReport ); --- 112,121 ---- /// is to be shown</param> public ReportTabControl( AccountReport accountReport , ! bool showBenchmark ) { this.accountReport = accountReport; this.Dock = DockStyle.Fill; this.equityChart = new EquityChartTabPage( this.accountReport , ! showBenchmark ); this.Controls.Add( this.equityChart ); this.summary = new SummaryTabPage( this.accountReport ); Index: Report.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b5_Presentation/Reporting/WindowsForm/Report.cs,v retrieving revision 1.19 retrieving revision 1.20 diff -C2 -d -r1.19 -r1.20 *** Report.cs 6 Mar 2008 20:23:04 -0000 1.19 --- Report.cs 19 Aug 2008 17:13:01 -0000 1.20 *************** *** 226,230 **** this.saveFileDialog.DefaultExt = "qPr"; this.saveFileDialog.InitialDirectory = ! System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"]; } else if(sender.Text.EndsWith("Account")) --- 226,230 ---- this.saveFileDialog.DefaultExt = "qPr"; this.saveFileDialog.InitialDirectory = ! System.Configuration.ConfigurationManager.AppSettings["ReportsArchive"]; } else if(sender.Text.EndsWith("Account")) *************** *** 234,238 **** this.saveFileDialog.DefaultExt = "qPa"; this.saveFileDialog.InitialDirectory = ! System.Configuration.ConfigurationSettings.AppSettings["AccountsArchive"]; } else if(sender.Text.EndsWith("Transactions")) --- 234,238 ---- this.saveFileDialog.DefaultExt = "qPa"; this.saveFileDialog.InitialDirectory = ! System.Configuration.ConfigurationManager.AppSettings["AccountsArchive"]; } else if(sender.Text.EndsWith("Transactions")) |
|
From: Glauco S. <gla...@us...> - 2008-08-19 17:13:36
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv3611/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator Modified Files: PVO_CTOMain.cs PVO_CTOStrategy.cs PVO_OTCMain.cs PVO_OTCStrategy.cs PVO_OTCStrategyLessCorrelated.cs PVOMain.cs PVOStrategy.cs RunPVO.cs Log Message: - the code has been cleaned up to avoid warnings - standard indentation has been applied Index: PVOStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/PVOStrategy.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** PVOStrategy.cs 14 Aug 2008 23:28:06 -0000 1.5 --- PVOStrategy.cs 19 Aug 2008 17:13:01 -0000 1.6 *************** *** 3,7 **** PVOStrategy.cs ! Copyright (C) 2008 Marco Milletti --- 3,7 ---- PVOStrategy.cs ! Copyright (C) 2008 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 51,108 **** { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the Portfolio Value ! /// Oscillator ! /// </summary> ! [Serializable] ! public class PVOStrategy : IEndOfDayStrategyForBacktester ! { public event NewLogItemEventHandler NewLogItem; public event NewMessageEventHandler NewMessage; //initialized by the constructor ! protected int numberOfTickersToBeChosen; ! protected int inSampleDays; ! protected int numDaysBetweenEachOptimization; ! protected IInSampleChooser inSampleChooser; ! protected IEligiblesSelector eligiblesSelector; ! protected Benchmark benchmark; ! protected HistoricalQuoteProvider historicalQuoteProvider; ! protected double maxAcceptableCloseToCloseDrawdown; ! protected double minimumAcceptableGain; ! protected int numDaysForOscillatingPeriod; ! //initialized after constructor's call ! protected int numDaysElapsedSinceLastOptimization; ! protected ReturnsManager returnsManager; protected TestingPositions[] chosenPVOPositions; //chosen in sample: these are the eligible positions for out //of sample testing protected PVOPositions pvoPositionsForOutOfSample; ! protected DateTime lastCloseDate; ! protected bool portfolioHasBeenOverbought; ! protected bool portfolioHasBeenOversold; ! protected Account account; ! public Account Account { get { return this.account; } ! set { this.account = value; } } ! protected bool stopLossConditionReached; ! protected bool takeProfitConditionReached; ! protected double currentAccountValue; ! protected double previousAccountValue; ! protected double oversoldThreshold; ! protected double overboughtThreshold; ! protected double oversoldThresholdMAX; ! protected double overboughtThresholdMAX; ! ! private string description_GetDescriptionForChooser() ! { ! if(this.inSampleChooser == null) ! return "ConstantChooser"; ! else ! return this.inSampleChooser.Description; ! } ! public string Description { --- 51,108 ---- { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the Portfolio Value ! /// Oscillator ! /// </summary> ! [Serializable] ! public class PVOStrategy : IEndOfDayStrategyForBacktester ! { public event NewLogItemEventHandler NewLogItem; public event NewMessageEventHandler NewMessage; //initialized by the constructor ! protected int numberOfTickersToBeChosen; ! protected int inSampleDays; ! protected int numDaysBetweenEachOptimization; ! protected IInSampleChooser inSampleChooser; ! protected IEligiblesSelector eligiblesSelector; ! protected Benchmark benchmark; ! protected HistoricalQuoteProvider historicalQuoteProvider; ! protected double maxAcceptableCloseToCloseDrawdown; ! protected double minimumAcceptableGain; ! protected int numDaysForOscillatingPeriod; ! //initialized after constructor's call ! protected int numDaysElapsedSinceLastOptimization; ! protected ReturnsManager returnsManager; protected TestingPositions[] chosenPVOPositions; //chosen in sample: these are the eligible positions for out //of sample testing protected PVOPositions pvoPositionsForOutOfSample; ! protected DateTime lastCloseDate; ! protected bool portfolioHasBeenOverbought; ! protected bool portfolioHasBeenOversold; ! protected Account account; ! public Account Account { get { return this.account; } ! set { this.account = value; } } ! protected bool stopLossConditionReached; ! protected bool takeProfitConditionReached; ! protected double currentAccountValue; ! protected double previousAccountValue; ! protected double oversoldThreshold; ! protected double overboughtThreshold; ! protected double oversoldThresholdMAX; ! protected double overboughtThresholdMAX; ! ! private string description_GetDescriptionForChooser() ! { ! if(this.inSampleChooser == null) ! return "ConstantChooser"; ! else ! return this.inSampleChooser.Description; ! } ! public string Description { *************** *** 128,143 **** private void pvoStrategy(IEligiblesSelector eligiblesSelector, ! int inSampleDays, ! int numDaysForOscillatingPeriod, ! int numberOfTickersToBeChosen, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! double oversoldThreshold, ! double overboughtThreshold, ! double oversoldThresholdMAX, ! double overboughtThresholdMAX, ! HistoricalQuoteProvider historicalQuoteProvider, ! double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) { this.eligiblesSelector = eligiblesSelector; --- 128,143 ---- private void pvoStrategy(IEligiblesSelector eligiblesSelector, ! int inSampleDays, ! int numDaysForOscillatingPeriod, ! int numberOfTickersToBeChosen, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! double oversoldThreshold, ! double overboughtThreshold, ! double oversoldThresholdMAX, ! double overboughtThresholdMAX, ! HistoricalQuoteProvider historicalQuoteProvider, ! double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) { this.eligiblesSelector = eligiblesSelector; *************** *** 150,154 **** this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; this.minimumAcceptableGain = minimumAcceptableGain; ! this.oversoldThreshold = oversoldThreshold; this.overboughtThreshold = overboughtThreshold; this.oversoldThresholdMAX = oversoldThresholdMAX; --- 150,154 ---- this.maxAcceptableCloseToCloseDrawdown = maxAcceptableCloseToCloseDrawdown; this.minimumAcceptableGain = minimumAcceptableGain; ! this.oversoldThreshold = oversoldThreshold; this.overboughtThreshold = overboughtThreshold; this.oversoldThresholdMAX = oversoldThresholdMAX; *************** *** 161,265 **** } ! public PVOStrategy(IEligiblesSelector eligiblesSelector, ! IInSampleChooser inSampleChooser, ! int inSampleDays, ! int numDaysForOscillatingPeriod, ! int numberOfTickersToBeChosen, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! double oversoldThreshold, ! double overboughtThreshold, ! double oversoldThresholdMAX, ! double overboughtThresholdMAX, ! HistoricalQuoteProvider historicalQuoteProvider, ! double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) ! ! { this.pvoStrategy(eligiblesSelector, inSampleDays , numDaysForOscillatingPeriod , ! numberOfTickersToBeChosen , benchmark , numDaysBetweenEachOptimization , ! oversoldThreshold, overboughtThreshold, ! oversoldThresholdMAX, overboughtThresholdMAX, ! historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain ); this.inSampleChooser = inSampleChooser; ! } ! public PVOStrategy(IEligiblesSelector eligiblesSelector, ! IInSampleChooser inSampleChooser, ! int inSampleDays, ! int numDaysForOscillatingPeriod, ! int numberOfTickersToBeChosen, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! double oversoldThreshold, ! double overboughtThreshold, ! HistoricalQuoteProvider historicalQuoteProvider, ! double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) ! { this.pvoStrategy(eligiblesSelector, inSampleDays , numDaysForOscillatingPeriod , ! numberOfTickersToBeChosen , benchmark , numDaysBetweenEachOptimization , ! oversoldThreshold, overboughtThreshold, ! double.MaxValue, double.MaxValue, ! historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain ); this.inSampleChooser = inSampleChooser; } public PVOStrategy(IEligiblesSelector eligiblesSelector, ! TestingPositions[] chosenPVOPositions, ! int inSampleDays, ! int numDaysForOscillatingPeriod, ! int numberOfTickersToBeChosen, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! double oversoldThreshold, ! double overboughtThreshold, ! double oversoldThresholdMAX, ! double overboughtThresholdMAX, ! HistoricalQuoteProvider historicalQuoteProvider, ! double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) ! { this.pvoStrategy(eligiblesSelector, inSampleDays , numDaysForOscillatingPeriod , ! numberOfTickersToBeChosen , benchmark , numDaysBetweenEachOptimization , ! oversoldThreshold, overboughtThreshold, ! oversoldThresholdMAX, overboughtThresholdMAX, ! historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain ); this.chosenPVOPositions = chosenPVOPositions; } public PVOStrategy(IEligiblesSelector eligiblesSelector, ! TestingPositions[] chosenPVOPositions, ! int inSampleDays, ! int numDaysForOscillatingPeriod, ! int numberOfTickersToBeChosen, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! double oversoldThreshold, ! double overboughtThreshold, ! HistoricalQuoteProvider historicalQuoteProvider, ! double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) ! { this.pvoStrategy(eligiblesSelector, inSampleDays , numDaysForOscillatingPeriod , ! numberOfTickersToBeChosen , benchmark , numDaysBetweenEachOptimization , ! oversoldThreshold, overboughtThreshold, ! double.MaxValue , double.MaxValue , ! historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain ); this.chosenPVOPositions = chosenPVOPositions; } ! public virtual void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } public void FiveMinutesBeforeMarketCloseEventHandler( --- 161,265 ---- } ! public PVOStrategy(IEligiblesSelector eligiblesSelector, ! IInSampleChooser inSampleChooser, ! int inSampleDays, ! int numDaysForOscillatingPeriod, ! int numberOfTickersToBeChosen, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! double oversoldThreshold, ! double overboughtThreshold, ! double oversoldThresholdMAX, ! double overboughtThresholdMAX, ! HistoricalQuoteProvider historicalQuoteProvider, ! double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) ! ! { this.pvoStrategy(eligiblesSelector, inSampleDays , numDaysForOscillatingPeriod , ! numberOfTickersToBeChosen , benchmark , numDaysBetweenEachOptimization , ! oversoldThreshold, overboughtThreshold, ! oversoldThresholdMAX, overboughtThresholdMAX, ! historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain ); this.inSampleChooser = inSampleChooser; ! } ! public PVOStrategy(IEligiblesSelector eligiblesSelector, ! IInSampleChooser inSampleChooser, ! int inSampleDays, ! int numDaysForOscillatingPeriod, ! int numberOfTickersToBeChosen, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! double oversoldThreshold, ! double overboughtThreshold, ! HistoricalQuoteProvider historicalQuoteProvider, ! double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) ! { this.pvoStrategy(eligiblesSelector, inSampleDays , numDaysForOscillatingPeriod , ! numberOfTickersToBeChosen , benchmark , numDaysBetweenEachOptimization , ! oversoldThreshold, overboughtThreshold, ! double.MaxValue, double.MaxValue, ! historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain ); this.inSampleChooser = inSampleChooser; } public PVOStrategy(IEligiblesSelector eligiblesSelector, ! TestingPositions[] chosenPVOPositions, ! int inSampleDays, ! int numDaysForOscillatingPeriod, ! int numberOfTickersToBeChosen, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! double oversoldThreshold, ! double overboughtThreshold, ! double oversoldThresholdMAX, ! double overboughtThresholdMAX, ! HistoricalQuoteProvider historicalQuoteProvider, ! double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) ! { this.pvoStrategy(eligiblesSelector, inSampleDays , numDaysForOscillatingPeriod , ! numberOfTickersToBeChosen , benchmark , numDaysBetweenEachOptimization , ! oversoldThreshold, overboughtThreshold, ! oversoldThresholdMAX, overboughtThresholdMAX, ! historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain ); this.chosenPVOPositions = chosenPVOPositions; } public PVOStrategy(IEligiblesSelector eligiblesSelector, ! TestingPositions[] chosenPVOPositions, ! int inSampleDays, ! int numDaysForOscillatingPeriod, ! int numberOfTickersToBeChosen, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! double oversoldThreshold, ! double overboughtThreshold, ! HistoricalQuoteProvider historicalQuoteProvider, ! double maxAcceptableCloseToCloseDrawdown, ! double minimumAcceptableGain) ! { this.pvoStrategy(eligiblesSelector, inSampleDays , numDaysForOscillatingPeriod , ! numberOfTickersToBeChosen , benchmark , numDaysBetweenEachOptimization , ! oversoldThreshold, overboughtThreshold, ! double.MaxValue , double.MaxValue , ! historicalQuoteProvider , maxAcceptableCloseToCloseDrawdown , ! minimumAcceptableGain ); this.chosenPVOPositions = chosenPVOPositions; } ! public virtual void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! ; ! } public void FiveMinutesBeforeMarketCloseEventHandler( *************** *** 273,464 **** } ! #region MarketCloseEventHandler ! //forOutOfSampleTesting protected virtual EndOfDayDateTime getBeginOfOscillatingPeriod(IndexBasedEndOfDayTimer timer) { return new EndOfDayDateTime( (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition-this.numDaysForOscillatingPeriod]["quDate"], ! EndOfDaySpecificTime.MarketClose ); } ! private void marketCloseEventHandler_reverseIfNeeded_reverse(PVOPositionsStatus currentStatus) ! { ! if(currentStatus == PVOPositionsStatus.Overbought) ! { ! this.portfolioHasBeenOversold = false; ! this.portfolioHasBeenOverbought = true; ! } ! else if(currentStatus == PVOPositionsStatus.Oversold) ! { ! this.portfolioHasBeenOversold = true; ! this.portfolioHasBeenOverbought = false; ! } ! AccountManager.ReversePositions(this.account); ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! private void marketCloseEventHandler_reverseIfNeeded(IndexBasedEndOfDayTimer timer) ! { ! EndOfDayDateTime today = timer.GetCurrentTime(); EndOfDayDateTime beginOfOscillatingPeriod = this.getBeginOfOscillatingPeriod(timer); ! PVOPositionsStatus pvoPositionsStatus = ! this.pvoPositionsForOutOfSample.GetStatus(beginOfOscillatingPeriod, today , this.benchmark.Ticker, this.historicalQuoteProvider, double.MaxValue, double.MaxValue); ! if(pvoPositionsStatus == PVOPositionsStatus.Overbought && ! this.portfolioHasBeenOversold) ! //open positions derive from an overSold period but now ! //the overbought threshold has been reached ! this.marketCloseEventHandler_reverseIfNeeded_reverse(pvoPositionsStatus); ! ! if(pvoPositionsStatus == PVOPositionsStatus.Oversold && ! this.portfolioHasBeenOverbought) ! //open positions derive from an overBought period but now ! //the overSold threshold has been reached ! this.marketCloseEventHandler_reverseIfNeeded_reverse(pvoPositionsStatus); ! } ! private PVOPositionsStatus marketCloseEventHandler_openPositions_getStatus(IndexBasedEndOfDayTimer timer) ! { ! EndOfDayDateTime today = timer.GetCurrentTime(); ! EndOfDayDateTime beginOfOscillatingPeriod = ! this.getBeginOfOscillatingPeriod(timer); ! PVOPositionsStatus currentStatus = ! PVOPositionsStatus.InTheMiddle; ! for(int i = 0; i<this.chosenPVOPositions.Length; i++) ! { ! if(this.chosenPVOPositions[i] != null) ! currentStatus = ! ((PVOPositions)this.chosenPVOPositions[i]).GetStatus(beginOfOscillatingPeriod, today, ! this.benchmark.Ticker, this.historicalQuoteProvider, ! double.MaxValue, double.MaxValue); ! if(currentStatus == PVOPositionsStatus.Oversold || ! currentStatus == PVOPositionsStatus.Overbought ) ! { this.pvoPositionsForOutOfSample = (PVOPositions)this.chosenPVOPositions[i]; i = this.chosenPVOPositions.Length;//exit from for } ! } ! return currentStatus; ! } ! ! protected void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) ! { ! PVOPositionsStatus pvoPositionsStatus = PVOPositionsStatus.InTheMiddle; ! if(timer.CurrentDateArrayPosition >= this.numDaysForOscillatingPeriod) ! pvoPositionsStatus = ! this.marketCloseEventHandler_openPositions_getStatus(timer); switch (pvoPositionsStatus){ ! case PVOPositionsStatus.Overbought: ! { ! #region manage Overbought case ! this.pvoPositionsForOutOfSample.WeightedPositions.Reverse(); ! try{ ! AccountManager.OpenPositions( this.pvoPositionsForOutOfSample.WeightedPositions, ! this.account ); ! this.portfolioHasBeenOverbought = true; ! this.portfolioHasBeenOversold = false; ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! catch(Exception ex){ ! ex = ex; ! } ! finally{ ! this.pvoPositionsForOutOfSample.WeightedPositions.Reverse(); ! } ! #endregion ! break; ! } ! case PVOPositionsStatus.Oversold: ! { ! #region manage Oversold case ! AccountManager.OpenPositions( this.pvoPositionsForOutOfSample.WeightedPositions, ! this.account ); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = true; ! this.previousAccountValue = this.account.GetMarketValue(); ! #endregion ! break; ! } ! case PVOPositionsStatus.InTheMiddle://that is ! { //pvoPositionsForOutOfSample has not been set ! ! this.previousAccountValue = this.account.GetMarketValue(); ! break; ! } default: ! { ! //it should never been reached ! this.previousAccountValue = this.account.GetMarketValue(); ! break; ! } ! } ! } ! ! protected virtual void marketCloseEventHandler_closePositionsIfNeeded() ! { ! if(this.stopLossConditionReached || ! this.takeProfitConditionReached || ! this.numDaysElapsedSinceLastOptimization + 1 == this.numDaysBetweenEachOptimization ) ! { ! AccountManager.ClosePositions(this.account); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = false; ! } ! } ! ! protected virtual void marketCloseEventHandler_updateStopLossAndTakeProfitConditions() ! { ! //this.previousAccountValue has been set at opening positions ! this.stopLossConditionReached = false; ! this.takeProfitConditionReached = false; ! this.currentAccountValue = this.account.GetMarketValue(); ! double portfolioGainOrLoss = (this.currentAccountValue - this.previousAccountValue) ! /this.previousAccountValue; ! ! if(!double.IsInfinity(portfolioGainOrLoss) && ! portfolioGainOrLoss <= -this.maxAcceptableCloseToCloseDrawdown ) ! { ! this.stopLossConditionReached = true; ! this.takeProfitConditionReached = false; ! } ! else if (!double.IsInfinity(portfolioGainOrLoss) && ! portfolioGainOrLoss >= this.minimumAcceptableGain ) ! ! { ! this.stopLossConditionReached = false; ! this.takeProfitConditionReached = true; ! } ! } ! ! public virtual void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! try{ ! this.marketCloseEventHandler_updateStopLossAndTakeProfitConditions(); ! //this.marketCloseEventHandler_closePositionsIfNeeded(); ! if( this.chosenPVOPositions != null ) ! //PVOPositions have been chosen by the chooser ! { ! if(this.account.Portfolio.Count == 0) ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); ! //positions are opened only if thresholds are reached ! else//there are some opened positions ! this.marketCloseEventHandler_closePositionsIfNeeded(); ! //this.marketCloseEventHandler_reverseIfNeeded((IndexBasedEndOfDayTimer)sender); ! } ! } ! catch(TickerNotExchangedException ex) ! {ex=ex;} ! } ! #endregion ! ! #region OneHourAfterMarketCloseEventHandler ! protected virtual void updateReturnsManager(EndOfDayDateTime firstEndOfDayDateTime, ! EndOfDayDateTime lastEndOfDayDateTime) { ! this.returnsManager = new ReturnsManager(new CloseToCloseIntervals(firstEndOfDayDateTime, lastEndOfDayDateTime, ! this.benchmark.Ticker, this.numDaysForOscillatingPeriod), ! this.historicalQuoteProvider); } --- 273,468 ---- } ! #region MarketCloseEventHandler ! //forOutOfSampleTesting protected virtual EndOfDayDateTime getBeginOfOscillatingPeriod(IndexBasedEndOfDayTimer timer) { return new EndOfDayDateTime( (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition-this.numDaysForOscillatingPeriod]["quDate"], ! EndOfDaySpecificTime.MarketClose ); } ! private void marketCloseEventHandler_reverseIfNeeded_reverse(PVOPositionsStatus currentStatus) ! { ! if(currentStatus == PVOPositionsStatus.Overbought) ! { ! this.portfolioHasBeenOversold = false; ! this.portfolioHasBeenOverbought = true; ! } ! else if(currentStatus == PVOPositionsStatus.Oversold) ! { ! this.portfolioHasBeenOversold = true; ! this.portfolioHasBeenOverbought = false; ! } ! AccountManager.ReversePositions(this.account); ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! private void marketCloseEventHandler_reverseIfNeeded(IndexBasedEndOfDayTimer timer) ! { ! EndOfDayDateTime today = timer.GetCurrentTime(); EndOfDayDateTime beginOfOscillatingPeriod = this.getBeginOfOscillatingPeriod(timer); ! PVOPositionsStatus pvoPositionsStatus = ! this.pvoPositionsForOutOfSample.GetStatus(beginOfOscillatingPeriod, today , this.benchmark.Ticker, this.historicalQuoteProvider, double.MaxValue, double.MaxValue); ! if(pvoPositionsStatus == PVOPositionsStatus.Overbought && ! this.portfolioHasBeenOversold) ! //open positions derive from an overSold period but now ! //the overbought threshold has been reached ! this.marketCloseEventHandler_reverseIfNeeded_reverse(pvoPositionsStatus); ! ! if(pvoPositionsStatus == PVOPositionsStatus.Oversold && ! this.portfolioHasBeenOverbought) ! //open positions derive from an overBought period but now ! //the overSold threshold has been reached ! this.marketCloseEventHandler_reverseIfNeeded_reverse(pvoPositionsStatus); ! } ! private PVOPositionsStatus marketCloseEventHandler_openPositions_getStatus(IndexBasedEndOfDayTimer timer) ! { ! EndOfDayDateTime today = timer.GetCurrentTime(); ! EndOfDayDateTime beginOfOscillatingPeriod = ! this.getBeginOfOscillatingPeriod(timer); ! PVOPositionsStatus currentStatus = ! PVOPositionsStatus.InTheMiddle; ! for(int i = 0; i<this.chosenPVOPositions.Length; i++) ! { ! if(this.chosenPVOPositions[i] != null) ! currentStatus = ! ((PVOPositions)this.chosenPVOPositions[i]).GetStatus(beginOfOscillatingPeriod, today, ! this.benchmark.Ticker, this.historicalQuoteProvider, ! double.MaxValue, double.MaxValue); ! if(currentStatus == PVOPositionsStatus.Oversold || ! currentStatus == PVOPositionsStatus.Overbought ) ! { this.pvoPositionsForOutOfSample = (PVOPositions)this.chosenPVOPositions[i]; i = this.chosenPVOPositions.Length;//exit from for } ! } ! return currentStatus; ! } ! ! protected void marketCloseEventHandler_openPositions(IndexBasedEndOfDayTimer timer) ! { ! PVOPositionsStatus pvoPositionsStatus = PVOPositionsStatus.InTheMiddle; ! if(timer.CurrentDateArrayPosition >= this.numDaysForOscillatingPeriod) ! pvoPositionsStatus = ! this.marketCloseEventHandler_openPositions_getStatus(timer); switch (pvoPositionsStatus){ ! case PVOPositionsStatus.Overbought: ! { ! #region manage Overbought case ! this.pvoPositionsForOutOfSample.WeightedPositions.Reverse(); ! try{ ! AccountManager.OpenPositions( this.pvoPositionsForOutOfSample.WeightedPositions, ! this.account ); ! this.portfolioHasBeenOverbought = true; ! this.portfolioHasBeenOversold = false; ! this.previousAccountValue = this.account.GetMarketValue(); ! } ! catch(Exception ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! ! finally{ ! this.pvoPositionsForOutOfSample.WeightedPositions.Reverse(); ! } ! #endregion ! break; ! } ! case PVOPositionsStatus.Oversold: ! { ! #region manage Oversold case ! AccountManager.OpenPositions( this.pvoPositionsForOutOfSample.WeightedPositions, ! this.account ); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = true; ! this.previousAccountValue = this.account.GetMarketValue(); ! #endregion ! break; ! } ! case PVOPositionsStatus.InTheMiddle://that is ! { //pvoPositionsForOutOfSample has not been set ! ! this.previousAccountValue = this.account.GetMarketValue(); ! break; ! } default: ! { ! //it should never been reached ! this.previousAccountValue = this.account.GetMarketValue(); ! break; ! } ! } ! } ! ! protected virtual void marketCloseEventHandler_closePositionsIfNeeded() ! { ! if(this.stopLossConditionReached || ! this.takeProfitConditionReached || ! this.numDaysElapsedSinceLastOptimization + 1 == this.numDaysBetweenEachOptimization ) ! { ! AccountManager.ClosePositions(this.account); ! this.portfolioHasBeenOverbought = false; ! this.portfolioHasBeenOversold = false; ! } ! } ! ! protected virtual void marketCloseEventHandler_updateStopLossAndTakeProfitConditions() ! { ! //this.previousAccountValue has been set at opening positions ! this.stopLossConditionReached = false; ! this.takeProfitConditionReached = false; ! this.currentAccountValue = this.account.GetMarketValue(); ! double portfolioGainOrLoss = (this.currentAccountValue - this.previousAccountValue) ! /this.previousAccountValue; ! ! if(!double.IsInfinity(portfolioGainOrLoss) && ! portfolioGainOrLoss <= -this.maxAcceptableCloseToCloseDrawdown ) ! { ! this.stopLossConditionReached = true; ! this.takeProfitConditionReached = false; ! } ! else if (!double.IsInfinity(portfolioGainOrLoss) && ! portfolioGainOrLoss >= this.minimumAcceptableGain ) ! ! { ! this.stopLossConditionReached = false; ! this.takeProfitConditionReached = true; ! } ! } ! ! public virtual void MarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! try{ ! this.marketCloseEventHandler_updateStopLossAndTakeProfitConditions(); ! //this.marketCloseEventHandler_closePositionsIfNeeded(); ! if( this.chosenPVOPositions != null ) ! //PVOPositions have been chosen by the chooser ! { ! if(this.account.Portfolio.Count == 0) ! this.marketCloseEventHandler_openPositions((IndexBasedEndOfDayTimer)sender); ! //positions are opened only if thresholds are reached ! else//there are some opened positions ! this.marketCloseEventHandler_closePositionsIfNeeded(); ! //this.marketCloseEventHandler_reverseIfNeeded((IndexBasedEndOfDayTimer)sender); ! } ! } ! catch(TickerNotExchangedException ex) ! { ! string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; ! } ! } ! #endregion ! ! #region OneHourAfterMarketCloseEventHandler ! protected virtual void updateReturnsManager(EndOfDayDateTime firstEndOfDayDateTime, ! EndOfDayDateTime lastEndOfDayDateTime) { ! this.returnsManager = new ReturnsManager(new CloseToCloseIntervals(firstEndOfDayDateTime, lastEndOfDayDateTime, ! this.benchmark.Ticker, this.numDaysForOscillatingPeriod), ! this.historicalQuoteProvider); } *************** *** 471,491 **** logItem.NumberOfEligibleTickers = eligibleTickers.Count; ! logItem.FitnessOfFirst = this.chosenPVOPositions[0].FitnessInSample; ! logItem.FitnessOfLast = this.chosenPVOPositions[this.chosenPVOPositions.Length - 1].FitnessInSample; ! logItem.GenerationOfFirst = ((IGeneticallyOptimizable)this.chosenPVOPositions[0]).Generation; ! logItem.GenerationOfLast = ((IGeneticallyOptimizable)this.chosenPVOPositions[this.chosenPVOPositions.Length - 1]).Generation; ! logItem.ThresholdsOfFirst = ((PVOPositions)this.chosenPVOPositions[0]).OversoldThreshold.ToString() + ";" + ((PVOPositions)this.chosenPVOPositions[0]).OverboughtThreshold.ToString(); ! logItem.ThresholdsOfLast = ((PVOPositions)this.chosenPVOPositions[this.chosenPVOPositions.Length - 1]).OversoldThreshold.ToString() + ";" + ((PVOPositions)this.chosenPVOPositions[this.chosenPVOPositions.Length - 1]).OverboughtThreshold.ToString(); ! logItem.TickersOfFirst = this.chosenPVOPositions[0].HashCodeForTickerComposition; ! logItem.TickersOfLast = this.chosenPVOPositions[this.chosenPVOPositions.Length - 1].HashCodeForTickerComposition; return logItem; --- 475,495 ---- logItem.NumberOfEligibleTickers = eligibleTickers.Count; ! logItem.FitnessOfFirst = this.chosenPVOPositions[0].FitnessInSample; ! logItem.FitnessOfLast = this.chosenPVOPositions[this.chosenPVOPositions.Length - 1].FitnessInSample; ! logItem.GenerationOfFirst = ((IGeneticallyOptimizable)this.chosenPVOPositions[0]).Generation; ! logItem.GenerationOfLast = ((IGeneticallyOptimizable)this.chosenPVOPositions[this.chosenPVOPositions.Length - 1]).Generation; ! logItem.ThresholdsOfFirst = ((PVOPositions)this.chosenPVOPositions[0]).OversoldThreshold.ToString() + ";" + ((PVOPositions)this.chosenPVOPositions[0]).OverboughtThreshold.ToString(); ! logItem.ThresholdsOfLast = ((PVOPositions)this.chosenPVOPositions[this.chosenPVOPositions.Length - 1]).OversoldThreshold.ToString() + ";" + ((PVOPositions)this.chosenPVOPositions[this.chosenPVOPositions.Length - 1]).OverboughtThreshold.ToString(); ! logItem.TickersOfFirst = this.chosenPVOPositions[0].HashCodeForTickerComposition; ! logItem.TickersOfLast = this.chosenPVOPositions[this.chosenPVOPositions.Length - 1].HashCodeForTickerComposition; return logItem; *************** *** 524,536 **** } ! protected virtual void updateTestingPositions(DateTime currentDate) ! { EndOfDayHistory endOfDayHistory = this.benchmark.GetEndOfDayHistory( ! new EndOfDayDateTime(currentDate.AddDays(-this.inSampleDays), ! EndOfDaySpecificTime.MarketClose), ! new EndOfDayDateTime(currentDate, ! EndOfDaySpecificTime.MarketClose)); ! EligibleTickers eligibles = this.eligiblesSelector.GetEligibleTickers(endOfDayHistory); this.updateReturnsManager(endOfDayHistory.FirstEndOfDayDateTime, --- 528,540 ---- } ! protected virtual void updateTestingPositions(DateTime currentDate) ! { EndOfDayHistory endOfDayHistory = this.benchmark.GetEndOfDayHistory( ! new EndOfDayDateTime(currentDate.AddDays(-this.inSampleDays), ! EndOfDaySpecificTime.MarketClose), ! new EndOfDayDateTime(currentDate, ! EndOfDaySpecificTime.MarketClose)); ! EligibleTickers eligibles = this.eligiblesSelector.GetEligibleTickers(endOfDayHistory); this.updateReturnsManager(endOfDayHistory.FirstEndOfDayDateTime, *************** *** 540,566 **** this.updateTestingPositions_updateThresholds(); this.logOptimizationInfo(eligibles); ! } ! ! /// <summary> ! /// Handles a "One hour after market close" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public virtual void OneHourAfterMarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! this.numDaysElapsedSinceLastOptimization++; ! if((this.numDaysElapsedSinceLastOptimization == ! this.numDaysBetweenEachOptimization)) ! //num days without optimization has elapsed ! { ! this.updateTestingPositions(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime); ! //sets tickers to be chosen next Market Close event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! ! } #endregion ! } } --- 544,570 ---- this.updateTestingPositions_updateThresholds(); this.logOptimizationInfo(eligibles); ! } ! ! /// <summary> ! /// Handles a "One hour after market close" event. ! /// </summary> ! /// <param name="sender"></param> ! /// <param name="eventArgs"></param> ! public virtual void OneHourAfterMarketCloseEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { ! this.lastCloseDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; ! this.numDaysElapsedSinceLastOptimization++; ! if((this.numDaysElapsedSinceLastOptimization == ! this.numDaysBetweenEachOptimization)) ! //num days without optimization has elapsed ! { ! this.updateTestingPositions(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime); ! //sets tickers to be chosen next Market Close event ! this.numDaysElapsedSinceLastOptimization = 0; ! } ! ! } #endregion ! } } Index: PVO_OTCMain.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/PVO_OTCMain.cs,v retrieving revision 1.6 retrieving revision 1.7 diff -C2 -d -r1.6 -r1.7 *** PVO_OTCMain.cs 14 Aug 2008 23:28:06 -0000 1.6 --- PVO_OTCMain.cs 19 Aug 2008 17:12:59 -0000 1.7 *************** *** 208,212 **** { string pathForTheMainFolderWhereScriptsResultsAreToBeSaved = ! System.Configuration.ConfigurationSettings.AppSettings["LogArchive"]; return pathForTheMainFolderWhereScriptsResultsAreToBeSaved; } --- 208,212 ---- { string pathForTheMainFolderWhereScriptsResultsAreToBeSaved = ! System.Configuration.ConfigurationManager.AppSettings["LogArchive"]; return pathForTheMainFolderWhereScriptsResultsAreToBeSaved; } Index: PVO_OTCStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TechnicalAnalysisTesting/Oscillators/FixedLevelOscillators/PortfolioValueOscillator/PVO_OTCStrategy.cs,v retrieving revision 1.5 retrieving revision 1.6 diff -C2 -d -r1.5 -r1.6 *** PVO_OTCStrategy.cs 14 Aug 2008 23:28:06 -0000 1.5 --- PVO_OTCStrategy.cs 19 Aug 2008 17:13:00 -0000 1.6 *************** *** 3,7 **** PVO_OTCStrategy.cs ! Copyright (C) 2008 Marco Milletti --- 3,7 ---- PVO_OTCStrategy.cs ! Copyright (C) 2008 Marco Milletti *************** *** 19,23 **** 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; --- 19,23 ---- 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; *************** *** 52,104 **** { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the Portfolio Value ! /// Oscillator ! /// </summary> ! [Serializable] ! public class PVO_OTCStrategy : IEndOfDayStrategyForBacktester ! { public event NewLogItemEventHandler NewLogItem; public event NewMessageEventHandler NewMessage; //initialized by the constructor ! protected int inSampleDays; ! protected int numDaysBetweenEachOptimization; ! protected IInSampleChooser inSampleChooser; ! protected IEligiblesSelector eligiblesSelector; ! protected Benchmark benchmark; ! protected HistoricalQuoteProvider historicalQuoteProvider; ! protected double oversoldThreshold; ! protected double overboughtThreshold; ! protected double oversoldThresholdMAX; ! protected double overboughtThresholdMAX; ! //initialized after constructor's call ! protected int numDaysElapsedSinceLastOptimization; ! protected ReturnsManager returnsManager; protected TestingPositions[] chosenPVOPositions; //chosen in sample: these are the eligible positions for out //of sample testing protected PVOPositions pvoPositionsForOutOfSample; ! protected DateTime lastCloseDate; protected DateTime lastOptimizationDateTime; ! protected Account account; ! public Account Account { ! get { return this.account; } ! set { this.account = value; } } ! private int numOfClosingsToCrossBeforeExit; ! private int numOfClosingsWithOpenPositions; ! private int minimumNumberOfEligiblesForValidOptimization; ! private bool optimalPositionsHaveBeenUpdated; ! ! private string description_GetDescriptionForChooser() ! { ! if(this.inSampleChooser == null) ! return "ConstantChooser"; ! else ! return this.inSampleChooser.Description; ! } ! public string Description { --- 52,104 ---- { /// <summary> ! /// Implements MarketOpenEventHandler and MarketCloseEventHandler ! /// These handlers contain the core strategy for the Portfolio Value ! /// Oscillator ! /// </summary> ! [Serializable] ! public class PVO_OTCStrategy : IEndOfDayStrategyForBacktester ! { public event NewLogItemEventHandler NewLogItem; public event NewMessageEventHandler NewMessage; //initialized by the constructor ! protected int inSampleDays; ! protected int numDaysBetweenEachOptimization; ! protected IInSampleChooser inSampleChooser; ! protected IEligiblesSelector eligiblesSelector; ! protected Benchmark benchmark; ! protected HistoricalQuoteProvider historicalQuoteProvider; ! protected double oversoldThreshold; ! protected double overboughtThreshold; ! protected double oversoldThresholdMAX; ! protected double overboughtThresholdMAX; ! //initialized after constructor's call ! protected int numDaysElapsedSinceLastOptimization; ! protected ReturnsManager returnsManager; protected TestingPositions[] chosenPVOPositions; //chosen in sample: these are the eligible positions for out //of sample testing protected PVOPositions pvoPositionsForOutOfSample; ! protected DateTime lastCloseDate; protected DateTime lastOptimizationDateTime; ! protected Account account; ! public Account Account { ! get { return this.account; } ! set { this.account = value; } } ! private int numOfClosingsToCrossBeforeExit; ! private int numOfClosingsWithOpenPositions; ! private int minimumNumberOfEligiblesForValidOptimization; ! private bool optimalPositionsHaveBeenUpdated; ! ! private string description_GetDescriptionForChooser() ! { ! if(this.inSampleChooser == null) ! return "ConstantChooser"; ! else ! return this.inSampleChooser.Description; ! } ! public string Description { *************** *** 127,140 **** private void pvo_otcStrategy(IEligiblesSelector eligiblesSelector, ! int minimumNumberOfEligiblesForValidOptimization, ! int inSampleDays, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! int numOfClosingsToCrossBeforeExit, ! double oversoldThreshold, ! double overboughtThreshold, ! double oversoldThresholdMAX, ! double overboughtThresholdMAX, ! HistoricalQuoteProvider historicalQuoteProvider) { this.numOfClosingsWithOpenPositions = 0; --- 127,140 ---- private void pvo_otcStrategy(IEligiblesSelector eligiblesSelector, ! int minimumNumberOfEligiblesForValidOptimization, ! int inSampleDays, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! int numOfClosingsToCrossBeforeExit, ! double oversoldThreshold, ! double overboughtThreshold, ! double oversoldThresholdMAX, ! double overboughtThresholdMAX, ! HistoricalQuoteProvider historicalQuoteProvider) { this.numOfClosingsWithOpenPositions = 0; *************** *** 154,238 **** } ! public PVO_OTCStrategy(IEligiblesSelector eligiblesSelector, ! int minimumNumberOfEligiblesForValidOptimization, ! IInSampleChooser inSampleChooser, ! int inSampleDays, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! int numOfClosingsToCrossBeforeExit, ! double oversoldThreshold, ! double overboughtThreshold, ! double oversoldThresholdMAX, ! double overboughtThresholdMAX, ! HistoricalQuoteProvider historicalQuoteProvider) ! ! { ! this.pvo_otcStrategy(eligiblesSelector, minimumNumberOfEligiblesForValidOptimization, ! inSampleDays , benchmark , numDaysBetweenEachOptimization , ! numOfClosingsToCrossBeforeExit, oversoldThreshold, overboughtThreshold, ! oversoldThresholdMAX, overboughtThresholdMAX, ! historicalQuoteProvider); this.inSampleChooser = inSampleChooser; ! } ! public PVO_OTCStrategy(IEligiblesSelector eligiblesSelector, ! int minimumNumberOfEligiblesForValidOptimization, ! IInSampleChooser inSampleChooser, ! int inSampleDays, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! int numOfClosingsToCrossBeforeExit, ! double oversoldThreshold, ! double overboughtThreshold, ! HistoricalQuoteProvider historicalQuoteProvider) ! ! { this.pvo_otcStrategy(eligiblesSelector, minimumNumberOfEligiblesForValidOptimization, ! inSampleDays , benchmark , numDaysBetweenEachOptimization , ! numOfClosingsToCrossBeforeExit, oversoldThreshold, overboughtThreshold, ! double.MaxValue, double.MaxValue, ! historicalQuoteProvider); this.inSampleChooser = inSampleChooser; ! } public PVO_OTCStrategy(IEligiblesSelector eligiblesSelector, ! int minimumNumberOfEligiblesForValidOptimization, ! TestingPositions[] chosenPVOPositions, ! int inSampleDays, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! int numOfClosingsToCrossBeforeExit, ! double oversoldThreshold, ! double overboughtThreshold, ! double oversoldThresholdMAX, ! double overboughtThresholdMAX, ! HistoricalQuoteProvider historicalQuoteProvider) ! { this.pvo_otcStrategy(eligiblesSelector, minimumNumberOfEligiblesForValidOptimization, ! inSampleDays , benchmark , numDaysBetweenEachOptimization , ! numOfClosingsToCrossBeforeExit, ! oversoldThreshold, overboughtThreshold, ! oversoldThresholdMAX, overboughtThresholdMAX, ! historicalQuoteProvider); this.chosenPVOPositions = chosenPVOPositions; } public PVO_OTCStrategy(IEligiblesSelector eligiblesSelector, ! int minimumNumberOfEligiblesForValidOptimization, ! TestingPositions[] chosenPVOPositions, ! int inSampleDays, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! int numOfClosingsToCrossBeforeExit, ! double oversoldThreshold, ! double overboughtThreshold, ! HistoricalQuoteProvider historicalQuoteProvider) ! { this.pvo_otcStrategy(eligiblesSelector, minimumNumberOfEligiblesForValidOptimization, ! inSampleDays , benchmark , numDaysBetweenEachOptimization , ! numOfClosingsToCrossBeforeExit, ! oversoldThreshold, overboughtThreshold, ! double.MaxValue, double.MaxValue, ! historicalQuoteProvider); this.chosenPVOPositions = chosenPVOPositions; } --- 154,238 ---- } ! public PVO_OTCStrategy(IEligiblesSelector eligiblesSelector, ! int minimumNumberOfEligiblesForValidOptimization, ! IInSampleChooser inSampleChooser, ! int inSampleDays, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! int numOfClosingsToCrossBeforeExit, ! double oversoldThreshold, ! double overboughtThreshold, ! double oversoldThresholdMAX, ! double overboughtThresholdMAX, ! HistoricalQuoteProvider historicalQuoteProvider) ! ! { ! this.pvo_otcStrategy(eligiblesSelector, minimumNumberOfEligiblesForValidOptimization, ! inSampleDays , benchmark , numDaysBetweenEachOptimization , ! numOfClosingsToCrossBeforeExit, oversoldThreshold, overboughtThreshold, ! oversoldThresholdMAX, overboughtThresholdMAX, ! historicalQuoteProvider); this.inSampleChooser = inSampleChooser; ! } ! public PVO_OTCStrategy(IEligiblesSelector eligiblesSelector, ! int minimumNumberOfEligiblesForValidOptimization, ! IInSampleChooser inSampleChooser, ! int inSampleDays, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! int numOfClosingsToCrossBeforeExit, ! double oversoldThreshold, ! double overboughtThreshold, ! HistoricalQuoteProvider historicalQuoteProvider) ! ! { this.pvo_otcStrategy(eligiblesSelector, minimumNumberOfEligiblesForValidOptimization, ! inSampleDays , benchmark , numDaysBetweenEachOptimization , ! numOfClosingsToCrossBeforeExit, oversoldThreshold, overboughtThreshold, ! double.MaxValue, double.MaxValue, ! historicalQuoteProvider); this.inSampleChooser = inSampleChooser; ! } public PVO_OTCStrategy(IEligiblesSelector eligiblesSelector, ! int minimumNumberOfEligiblesForValidOptimization, ! TestingPositions[] chosenPVOPositions, ! int inSampleDays, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! int numOfClosingsToCrossBeforeExit, ! double oversoldThreshold, ! double overboughtThreshold, ! double oversoldThresholdMAX, ! double overboughtThresholdMAX, ! HistoricalQuoteProvider historicalQuoteProvider) ! { this.pvo_otcStrategy(eligiblesSelector, minimumNumberOfEligiblesForValidOptimization, ! inSampleDays , benchmark , numDaysBetweenEachOptimization , ! numOfClosingsToCrossBeforeExit, ! oversoldThreshold, overboughtThreshold, ! oversoldThresholdMAX, overboughtThresholdMAX, ! historicalQuoteProvider); this.chosenPVOPositions = chosenPVOPositions; } public PVO_OTCStrategy(IEligiblesSelector eligiblesSelector, ! int minimumNumberOfEligiblesForValidOptimization, ! TestingPositions[] chosenPVOPositions, ! int inSampleDays, ! Benchmark benchmark, ! int numDaysBetweenEachOptimization, ! int numOfClosingsToCrossBeforeExit, ! double oversoldThreshold, ! double overboughtThreshold, ! HistoricalQuoteProvider historicalQuoteProvider) ! { this.pvo_otcStrategy(eligiblesSelector, minimumNumberOfEligiblesForValidOptimization, ! inSampleDays , benchmark , numDaysBetweenEachOptimization , ! numOfClosingsToCrossBeforeExit, ! oversoldThreshold, overboughtThreshold, ! double.MaxValue, double.MaxValue, ! historicalQuoteProvider); this.chosenPVOPositions = chosenPVOPositions; } *************** *** 244,273 **** { return new EndOfDayDateTime( (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition-1]["quDate"], ! EndOfDaySpecificTime.MarketClose ); } private PVOPositionsStatus marketOpenEventHandler_openPositions_getStatus(IndexBasedEndOfDayTimer timer) ! { ! EndOfDayDateTime today = timer.GetCurrentTime(); ! EndOfDayDateTime beginOfOscillatingPeriod = ! this.getBeginOfOscillatingPeriod(timer); ! PVOPositionsStatus currentStatus = ! PVOPositionsStatus.InTheMiddle; ! for(int i = 0; i<this.chosenPVOPositions.Length; i++) ! { ! if(this.chosenPVOPositions[i] != null) ! currentStatus = ! ((PVOPositions)this.chosenPVOPositions[i]).GetStatus(beginOfOscillatingPeriod, today, ! this.benchmark.Ticker, this.historicalQuoteProvider, ! this.oversoldThresholdMAX, this.overboughtThresholdMAX); ! if(currentStatus == PVOPositionsStatus.Oversold || ! currentStatus == PVOPositionsStatus.Overbought ) ! { this.pvoPositionsForOutOfSample = (PVOPositions)this.chosenPVOPositions[i]; i = this.chosenPVOPositions.Length;//exit from for } ! } ! return currentStatus; ! } protected void marketOpenEventHandler_openPositions(IndexBasedEndOfDayTimer timer) --- 244,273 ---- { return new EndOfDayDateTime( (DateTime)timer.IndexQuotes.Rows[timer.CurrentDateArrayPosition-1]["quDate"], ! EndOfDaySpecificTime.MarketClose ); } private PVOPositionsStatus marketOpenEventHandler_openPositions_getStatus(IndexBasedEndOfDayTimer timer) ! { ! EndOfDayDateTime today = timer.GetCurrentTime(); ! EndOfDayDateTime beginOfOscillatingPeriod = ! this.getBeginOfOscillatingPeriod(timer); ! PVOPositionsStatus currentStatus = ! PVOPositionsStatus.InTheMiddle; ! for(int i = 0; i<this.chosenPVOPositions.Length; i++) ! { ! if(this.chosenPVOPositions[i] != null) ! currentStatus = ! ((PVOPositions)this.chosenPVOPositions[i]).GetStatus(beginOfOscillatingPeriod, today, ! this.benchmark.Ticker, this.historicalQuoteProvider, ! this.oversoldThresholdMAX, this.overboughtThresholdMAX); ! if(currentStatus == PVOPositionsStatus.Oversold || ! currentStatus == PVOPositionsStatus.Overbought ) ! { this.pvoPositionsForOutOfSample = (PVOPositions)this.chosenPVOPositions[i]; i = this.chosenPVOPositions.Length;//exit from for } ! } ! return currentStatus; ! } protected void marketOpenEventHandler_openPositions(IndexBasedEndOfDayTimer timer) *************** *** 275,329 **** PVOPositionsStatus pvoPositionsStatus = PVOPositionsStatus.InTheMiddle; if(timer.CurrentDateArrayPosition >= 1) ! pvoPositionsStatus = this.marketOpenEventHandler_openPositions_getStatus(timer); switch (pvoPositionsStatus) { case PVOPositionsStatus.Overbought: - { - #region manage Overbought case - this.pvoPositionsForOutOfSample.WeightedPositions.Reverse(); - try - { - AccountManager.OpenPositions( this.pvoPositionsForOutOfSample.WeightedPositions, - this.account ); - } - catch(Exception ex) - { - ex = ex; - } - finally { this.pvoPositionsForOutOfSample.WeightedPositions.Reverse(); } - #endregion - break; - } case PVOPositionsStatus.Oversold: ! { ! AccountManager.OpenPositions( this.pvoPositionsForOutOfSample.WeightedPositions, ! this.account ); ! break; ! } case PVOPositionsStatus.InTheMiddle://that is ! { //pvoPositionsForOutOfSample has not been set ! ! break; ! } default: ! { ! //it should never been reached ! break; ! } } } ! public virtual void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { if ( this.account.Portfolio.Count == 0 && ! this.chosenPVOPositions != null && ! this.optimalPositionsHaveBeenUpdated == true) ! //portfolio is empty and optimization has ! //been already successfully launched { try{ --- 275,329 ---- PVOPositionsStatus pvoPositionsStatus = PVOPositionsStatus.InTheMiddle; if(timer.CurrentDateArrayPosition >= 1) ! pvoPositionsStatus = this.marketOpenEventHandler_openPositions_getStatus(timer); switch (pvoPositionsStatus) { case PVOPositionsStatus.Overbought: { + #region manage Overbought case this.pvoPositionsForOutOfSample.WeightedPositions.Reverse(); + try + { + AccountManager.OpenPositions( this.pvoPositionsForOutOfSample.WeightedPositions, + this.account ); + } + catch(Exception ex) + { + string forBreakpoint = ex.Message; forBreakpoint = forBreakpoint + ""; + } + finally + { + this.pvoPositionsForOutOfSample.WeightedPositions.Reverse(); + } + #endregion + break; } case PVOPositionsStatus.Oversold: ! { ! AccountManager.OpenPositions( this.pvoPositionsForOutOfSample.WeightedPositions, ! this.account ); ! break; ! } case PVOPositionsStatus.InTheMiddle://that is ! { //pvoPositionsForOutOfSample has not been set ! ! break; ! } default: ! { ! //it should never been reached ! break; ! } } } ! public virtual void MarketOpenEventHandler( ! Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) ! { if ( this.account.Portfolio.Count == 0 && ! this.chosenPVOPositions != null && ! this.optimalPositionsHaveBeenUpdated == true) ! //portfolio is empty and optimization has ! //been already successfully launched { try{ *************** *** 331,337 **** ... [truncated message content] |