quantproject-developers Mailing List for QuantProject (Page 73)
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...> - 2007-07-13 10:02:05
|
Update of /cvsroot/quantproject/QuantProject/b3_Data In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv17546/b3_Data Modified Files: b3_Data.csproj Log Message: Automatic changes applied by VSNet Index: b3_Data.csproj =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b3_Data/b3_Data.csproj,v retrieving revision 1.47 retrieving revision 1.48 diff -C2 -d -r1.47 -r1.48 *** b3_Data.csproj 11 Jun 2007 17:54:02 -0000 1.47 --- b3_Data.csproj 13 Jul 2007 10:01:56 -0000 1.48 *************** *** 121,129 **** /> <Reference - Name = "b1_ADT" - Project = "{B8A01161-3698-4591-B1EF-90F5FC7D8DBA}" - Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" - /> - <Reference Name = "Microsoft.Office.Core" Guid = "{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}" --- 121,124 ---- *************** *** 133,136 **** --- 128,136 ---- WrapperTool = "primary" /> + <Reference + Name = "b1_ADT" + Project = "{B8A01161-3698-4591-B1EF-90F5FC7D8DBA}" + Package = "{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}" + /> </References> </Build> |
|
From: Glauco S. <gla...@us...> - 2007-07-13 10:00:54
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv16488/b1_ADT Modified Files: b1_ADT.csproj Log Message: - Collections\FloatArrayManager.cs has been added - Collections\Set.cs has been added Index: b1_ADT.csproj =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/b1_ADT.csproj,v retrieving revision 1.24 retrieving revision 1.25 diff -C2 -d -r1.24 -r1.25 *** b1_ADT.csproj 8 Sep 2006 15:23:36 -0000 1.24 --- b1_ADT.csproj 13 Jul 2007 10:00:42 -0000 1.25 *************** *** 158,161 **** --- 158,166 ---- /> <File + RelPath = "Collections\FloatArrayManager.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "Collections\QPHashtable.cs" SubType = "Code" *************** *** 163,166 **** --- 168,176 ---- /> <File + RelPath = "Collections\Set.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "FileManaging\ObjectArchiver.cs" SubType = "Code" |
|
From: Glauco S. <gla...@us...> - 2007-07-13 09:59:39
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT/Collections In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv15527/b1_ADT/Collections Added Files: Set.cs Log Message: A mathematical set --- NEW FILE: Set.cs --- /* QuantProject - Quantitative Finance Library Set.cs Copyright (C) 2006 Glauco Siliprandi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; namespace QuantProject.ADT.Collections { /// <summary> /// A mathematical set /// </summary> public class Set { // TO DO: it should implement ICollection private Hashtable elements; public Set() { this.elements = new Hashtable(); } /// <summary> /// Adds a new /// </summary> /// <param name="obj"></param> public void Add( object element ) { if ( !this.Contains( element ) ) this.elements.Add( element , null ); } /// <summary> /// Checks if element belongs to this set /// </summary> /// <param name="element"></param> /// <returns></returns> public bool Contains( object element ) { return this.elements.ContainsKey( element ); } } } |
|
From: Glauco S. <gla...@us...> - 2007-07-13 09:59:11
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT/Collections In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv15375/b1_ADT/Collections Added Files: FloatArrayManager.cs Log Message: This class provides functions to manage array of floats --- NEW FILE: FloatArrayManager.cs --- /* QuantProject - Quantitative Finance Library FloatArrayManager.cs Copyright (C) 2006 Glauco Siliprandi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; namespace QuantProject.ADT.Collections { /// <summary> /// This class provides functions to manage array of floats /// </summary> public class FloatArrayManager { public FloatArrayManager() { // // TODO: Add constructor logic here // } #region GetRatios private static float getRatio( float[] values , int i ) { return ( values[ i + 1 ] / values[ i ] ); } /// <summary> /// If values contains n elements (V0, V1, ... Vn-1), /// GetRatios returns n-1 elements (E0, E1, ... En-2) where /// Ei = Vi+1 / Vi, for all i=0,1,...n-2 /// </summary> /// <param name="values"></param> /// <returns></returns> public static float[] GetRatios( float[] values ) { float[] ratios = new float[ values.Length - 1 ]; for ( int i=0 ; i < values.Length ; i++ ) ratios[ i ] = getRatio( values , i ); return ratios; } #endregion } } |
|
From: Glauco S. <gla...@us...> - 2007-07-13 09:49:44
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/returnsManagement In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv2138 Modified Files: CloseToCloseReturnsManager.cs Log Message: The previous log message was wrong: this class is used to keep and provide, in an efficient way, array of close to close returns (to be used by in sample optimizations) Index: CloseToCloseReturnsManager.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/returnsManagement/CloseToCloseReturnsManager.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** CloseToCloseReturnsManager.cs 13 Jul 2007 09:46:54 -0000 1.1 --- CloseToCloseReturnsManager.cs 13 Jul 2007 09:49:36 -0000 1.2 *************** *** 29,34 **** { /// <summary> ! /// This abstract class is used to keep and provide, in an efficient ! /// way, array of returs (to be used by in sample optimizations) /// </summary> public class CloseToCloseReturnsManager : ReturnsManager --- 29,34 ---- { /// <summary> ! /// This class is used to keep and provide, in an efficient way, array ! /// of close to close returns (to be used by in sample optimizations) /// </summary> public class CloseToCloseReturnsManager : ReturnsManager |
|
From: Glauco S. <gla...@us...> - 2007-07-13 09:47:52
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/returnsManagement In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv31495 Added Files: ReturnsManager.cs Log Message: This abstract class is used to keep and provide, in an efficient way, array of returns (to be used by in sample optimizations) --- NEW FILE: ReturnsManager.cs --- /* QuantProject - Quantitative Finance Library ReturnsManager.cs Copyright (C) 2007 Glauco Siliprandi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using QuantProject.ADT.Collections; using QuantProject.ADT.Histories; using QuantProject.ADT.Statistics; using QuantProject.Data.DataTables; namespace QuantProject.Business.Strategies.ReturnsManagement { /// <summary> /// This abstract class is used to keep and provide, in an efficient /// way, array of returns (to be used by in sample optimizations) /// </summary> public abstract class ReturnsManager { protected History timeLineForQuotes; // if we have n market days for quotes, // we will then have n-1 returns private Set tickersMissingQuotes; private Hashtable tickersReturns; private Hashtable tickersReturnsStandardDeviations; /// <summary> /// Dates when quotes are computed. If TimeLine contains /// n elements, then returns are n-1 elements /// </summary> public History TimeLine { get { return this.timeLineForQuotes; } } protected DateTime firstDateTime { get { return (DateTime)this.timeLineForQuotes[ 0 ]; } } protected DateTime lastDateTime { get { int lastIndex = this.timeLineForQuotes.Count - 1; return (DateTime)this.timeLineForQuotes[ lastIndex ]; } } /// <summary> /// Abstract class used to store and efficiently provide arrays of /// returns for several tickers, on dates within a given interval /// when a given benchmark is quoted too. /// If the ticker lacks some quote, all ticker's quotes are /// discarded /// </summary> /// <param name="firstDate">first quote date</param> /// <param name="lastDate">last quote date</param> /// <param name="benchmark">returns are computed only for /// dates when the benchmark is quoted; if n quotes are given /// for the benchmark, each array of returns will have exactly /// n-1 elements</param> public ReturnsManager( DateTime firstDate , DateTime lastDate , string benchmark ) { // TO DO: let WFLagEligibleTickers use this class also!!! this.timeLineForQuotes = this.getMarketDaysForQuotes( firstDate , lastDate , benchmark ); this.commonInitialization(); } public ReturnsManager( History timeLine ) { // TO DO: let WFLagEligibleTickers use this class also!!! this.timeLineForQuotes = timeLineForQuotes; this.commonInitialization(); } private void commonInitialization() { this.tickersMissingQuotes = new Set(); this.tickersReturns = new Hashtable(); this.tickersReturnsStandardDeviations = new Hashtable(); } private History getMarketDaysForQuotes( DateTime firstDate , DateTime lastDate , string benchmark ) { return Quotes.GetMarketDays( benchmark , firstDate , lastDate ); } private bool isAValidIndexForAReturn( int index ) { return ( ( index >= 0 ) && ( index <= this.TimeLine.Count - 2 ) ); } #region GetReturns private bool areReturnsAlreadySet( string ticker ) { return this.tickersReturns.ContainsKey( ticker ); } protected abstract History getQuotes( string ticker ); #region setReturns private bool areMarketDaysForQuotesAllCovered( History returns ) { bool areAllCovered = true; foreach ( DateTime dateTime in this.timeLineForQuotes ) if ( !returns.ContainsKey( dateTime ) ) areAllCovered = false; return areAllCovered; } private float selectReturnOnValidDateTime( History returns , int i ) { DateTime currentDateTimeForReturn = (DateTime)this.timeLineForQuotes.GetByIndex( i ); return (float)returns[ currentDateTimeForReturn ]; } private float[] selectReturnsOnValidDateTimes( History returns ) { // TO DO: this method is n log n, it could be implemented to // be have a linear complexity!!! float[] returnsOnValidDateTimes = new float[ this.timeLineForQuotes.Count ]; for ( int i = 0 ; i < this.timeLineForQuotes.Count ; i++ ) returnsOnValidDateTimes[ i ] = this.selectReturnOnValidDateTime( returns , i ); return returnsOnValidDateTimes; } private void setReturnsActually( string ticker , History returns ) { float[] arrayOfReturns = this.selectReturnsOnValidDateTimes( returns ); this.tickersReturns.Add( ticker , arrayOfReturns ); } private void setReturns( string ticker , History quotes ) { if ( this.areMarketDaysForQuotesAllCovered( quotes ) ) this.setReturnsActually( ticker , quotes ); else this.tickersMissingQuotes.Add( ticker ); } private void setReturns( string ticker ) { History quotes = this.getQuotes( ticker ); this.setReturns( ticker , quotes ); } #endregion setReturns private float[] getAlreadySetReturns( string ticker ) { return (float[])this.tickersReturns[ ticker ]; } public float[] GetReturns( string ticker ) { if ( !this.areReturnsAlreadySet( ticker ) ) // returns for this tickerhave not been set yet this.setReturns( ticker ); return this.getAlreadySetReturns( ticker ); } #endregion GetReturns #region GetReturns /// <summary> /// Gives out the returnIndex_th return for the given ticker /// </summary> /// <param name="ticker"></param> /// <param name="returnIndex"></param> /// <returns></returns> private void getReturnCheckParameters( string ticker , int returnIndex ) { this.GetReturns( ticker ); //enforces returns calculation for the ticker if ( this.tickersMissingQuotes.Contains( ticker ) ) throw new Exception( "The ticker '" + ticker + "' has missing " + "quotes with respect to the timeLine!" ); if ( !this.isAValidIndexForAReturn( returnIndex ) ) throw new Exception( "returnIndex is too large for the time line" ); } private float getReturnActually( string ticker , int returnIndex ) { float[] tickerReturns = this.GetReturns( ticker ); return tickerReturns[ returnIndex ]; } public float GetReturn( string ticker , int returnIndex ) { this.getReturnCheckParameters( ticker , returnIndex ); return this.getReturnActually( ticker , returnIndex ); } #endregion GetReturn #region GetReturnsStandardDeviation private bool isReturnsStandardDeviationAlreadySet( string ticker ) { return this.tickersReturns.ContainsKey( ticker ); } private void setReturnsStandardDeviation( string ticker , float[] tickerReturns ) { this.tickersReturnsStandardDeviations.Add( ticker , BasicFunctions.GetStdDev( tickerReturns ) ); } private void setReturnsStandardDeviation( string ticker ) { float[] tickerReturns = this.GetReturns( ticker ); this.setReturnsStandardDeviation( ticker , tickerReturns ); } private float getReturnsStandardDeviation( string ticker ) { return (float)this.tickersReturnsStandardDeviations[ ticker ]; } /// <summary> /// Returns the standard deviation of ticker returns (and stores /// it for future fast response) /// </summary> /// <param name="ticker"></param> /// <returns></returns> public float GetReturnsStandardDeviation( string ticker ) { if ( !this.isReturnsStandardDeviationAlreadySet( ticker ) ) this.setReturnsStandardDeviation( ticker ); return this.getReturnsStandardDeviation( ticker ); } #endregion //GetReturnsStandardDeviation } } |
|
From: Glauco S. <gla...@us...> - 2007-07-13 09:47:01
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/returnsManagement In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv30233 Added Files: CloseToCloseReturnsManager.cs Log Message: This abstract class is used to keep and provide, in an efficient way, array of returns (to be used by in sample optimizations) --- NEW FILE: CloseToCloseReturnsManager.cs --- /* QuantProject - Quantitative Finance Library CloseToCloseReturnsManager.cs Copyright (C) 2007 Glauco Siliprandi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using QuantProject.ADT.Histories; using QuantProject.Data.DataTables; namespace QuantProject.Business.Strategies.ReturnsManagement { /// <summary> /// This abstract class is used to keep and provide, in an efficient /// way, array of returs (to be used by in sample optimizations) /// </summary> public class CloseToCloseReturnsManager : ReturnsManager { public CloseToCloseReturnsManager( DateTime firstDate , DateTime lastDate , string benchmark ) : base( firstDate , lastDate , benchmark ) { } public CloseToCloseReturnsManager( History timeLine ) : base( timeLine ) { } protected override History getQuotes( string ticker ) { return Quotes.GetAdjustedCloseHistory( ticker , this.firstDateTime , this.lastDateTime ); } } } |
|
From: Glauco S. <gla...@us...> - 2007-07-13 09:45:59
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/returnsManagement In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv29124/returnsManagement Log Message: Directory /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/returnsManagement added to the repository |
|
From: Marco M. <mi...@us...> - 2007-06-30 18:58:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_OTC In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv19514 Added Files: EndOfDayTimerHandlerDOR_OTC.cs RunDOR_OTC.cs Log Message: Added the Double Over Reaction _ Open To Close (DOR_OTC) strategy. --- NEW FILE: RunDOR_OTC.cs --- /* QuantProject - Quantitative Finance Library RunDOR_OTC.cs Copyright (C) 2007 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.IO; using QuantProject.ADT.FileManaging; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Presentation.Reporting.WindowsForm; namespace QuantProject.Scripts.ArbitrageTesting.OverReactionHypothesis.DoubleOverReaction_OTC { /// <summary> /// Script that implements the Double OverReaction Open To Close strategy: /// at each open, l long positions and s short positions will be open, /// buying and shorting, accordingly, the l tickers among the /// b best that more moves down (at open) and the s tickers among the w worst /// that more moves up (at open). /// For chosing the b best and w worst tickers just the /// previous close to close ratio is considered. /// The fundamental of the strategy should be the fact (to be verified ...) /// that overreactions may be followed by opposite overreactions. /// At each close, open positions are closed. /// </summary> [Serializable] public class RunDOR_OTC { private string scriptName; private string tickerGroupID; private string benchmark; private int numberOfEligibleTickers; private int numOfBestTickers; private int numOfWorstTickers; private int numOfTickersForBuying; private int numOfTickersForShortSelling; private DateTime startDate; private DateTime endDate; private double maxRunningHours; private DateTime startingTimeForScript; private Account account; private IHistoricalQuoteProvider historicalQuoteProvider; private IEndOfDayTimer endOfDayTimer; public RunDOR_OTC(string tickerGroupID, string benchmark, int numberOfEligibleTickers, int numOfBestTickers, int numOfWorstTickers, int numOfTickersForBuying, int numOfTickersForShortSelling, DateTime startDate, DateTime endDate, double maxRunningHours) { this.tickerGroupID = tickerGroupID; this.benchmark = benchmark; this.numberOfEligibleTickers = numberOfEligibleTickers; this.numOfBestTickers = numOfBestTickers; this.numOfWorstTickers = numOfWorstTickers; this.numOfTickersForBuying = numOfTickersForBuying; this.numOfTickersForShortSelling = numOfTickersForShortSelling; this.startDate = startDate; this.endDate = endDate; this.maxRunningHours = maxRunningHours; this.scriptName = "DoubleOverReaction_OTC"; this.historicalQuoteProvider = new HistoricalRawQuoteProvider(); this.endOfDayTimer = new IndexBasedEndOfDayTimer( new EndOfDayDateTime( this.startDate , EndOfDaySpecificTime.MarketOpen ) , this.benchmark ); } public void Run() { this.startingTimeForScript = DateTime.Now; this.account = new Account( "DoubleOverReaction_OTC" , this.endOfDayTimer , new HistoricalEndOfDayDataStreamer( this.endOfDayTimer , this.historicalQuoteProvider ) , new HistoricalEndOfDayOrderExecutor( this.endOfDayTimer , this.historicalQuoteProvider ) ); EndOfDayTimerHandlerDOR_OTC endOfDayTimerHandler = new EndOfDayTimerHandlerDOR_OTC(this.tickerGroupID, this.numberOfEligibleTickers, this.numOfBestTickers, this.numOfWorstTickers, this.numOfTickersForBuying, this.numOfTickersForShortSelling, this.account, this.benchmark); this.endOfDayTimer.MarketOpen += new MarketOpenEventHandler( endOfDayTimerHandler.MarketOpenEventHandler ); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( endOfDayTimerHandler.MarketCloseEventHandler ); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); this.endOfDayTimer.OneHourAfterMarketClose += new OneHourAfterMarketCloseEventHandler( endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler ); this.endOfDayTimer.Start(); } private void checkDateForReport(Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs) { if(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime>=this.endDate || 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(); } private void checkDateForReport_createDirIfNotPresent(string dirPath) { if(!Directory.Exists(dirPath)) Directory.CreateDirectory(dirPath); } public void SaveScriptResults() { TimeSpan span; span = DateTime.Now.Subtract(this.startingTimeForScript); int secondsElapsed = span.Hours * 3600 + span.Minutes * 60 + span.Seconds; string fileName = "SecondsElapsed_" + secondsElapsed.ToString() + "_" + DateTime.Now.Hour.ToString().PadLeft(2,'0') + "_" + DateTime.Now.Minute.ToString().PadLeft(2,'0') + "_" + this.scriptName + "_From_" + this.tickerGroupID + "_elig_" + this.numberOfEligibleTickers + "_best_" + this.numOfBestTickers + "_worst_" + this.numOfWorstTickers + "_forLong_" + this.numOfTickersForBuying + "_forShort_" + this.numOfTickersForShortSelling; string dirNameWhereToSaveReports = System.Configuration.ConfigurationSettings.AppSettings["ReportsArchive"] + "\\" + this.scriptName + "\\"; //default report with numIntervalDays = 1 AccountReport accountReport = this.account.CreateReport(fileName,1, this.endOfDayTimer.GetCurrentTime(), this.benchmark, new HistoricalRawQuoteProvider() ); // new HistoricalAdjustedQuoteProvider()); this.checkDateForReport_createDirIfNotPresent(dirNameWhereToSaveReports); ObjectArchiver.Archive(accountReport, dirNameWhereToSaveReports + fileName + ".qPr"); this.endOfDayTimer.Stop(); } } } --- NEW FILE: EndOfDayTimerHandlerDOR_OTC.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerDOR_OTC.cs Copyright (C) 2007 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.ADT; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.Strategies; using QuantProject.Data; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; namespace QuantProject.Scripts.ArbitrageTesting.OverReactionHypothesis.DoubleOverReaction_OTC { /// <summary> /// Implements MarketOpenEventHandler and MarketCloseEventHandler /// These handlers contain the core strategy for /// the Double OverReaction Open To Close Test, /// based on the OverReaction Hypothesis /// </summary> [Serializable] public class EndOfDayTimerHandlerDOR_OTC { private string tickerGroupID; private int numberOfEligibleTickers; private string benchmark; private Account account; private int numOfWorstTickers; private int numOfBestTickers; private int numOfTickersForBuying; private int numOfTickersForShortSelling; private string[] bestTickers; private string[] worstTickers; private string[] chosenTickers; private string[] lastOrderedTickers; private ArrayList orders; private bool thereAreEnoughBestTickers; private bool thereAreEnoughWorstTickers; public EndOfDayTimerHandlerDOR_OTC(string tickerGroupID, int numberOfEligibleTickers, int numOfBestTickers, int numOfWorstTickers, int numOfTickersForBuying, int numOfTickersForShortSelling, Account account, string benchmark) { this.tickerGroupID = tickerGroupID; this.numberOfEligibleTickers = numberOfEligibleTickers; this.account = account; this.benchmark = benchmark; this.numOfBestTickers = numOfBestTickers; this.bestTickers = new string[this.numOfBestTickers]; this.numOfWorstTickers = numOfWorstTickers; this.worstTickers = new string[this.numOfWorstTickers]; this.numOfTickersForBuying = numOfTickersForBuying; this.numOfTickersForShortSelling = numOfTickersForShortSelling; this.chosenTickers = new string[this.numOfTickersForBuying + this.numOfTickersForShortSelling]; this.lastOrderedTickers = new string[this.chosenTickers.Length]; this.orders = new ArrayList(); } #region MarketOpenEventHandler private void addOrderForTicker(string[] tickers, int tickerPosition ) { string ticker = SignedTicker.GetTicker(tickers[tickerPosition]); double cashForSinglePosition = this.account.CashAmount / this.chosenTickers.Length; long quantity = Convert.ToInt64( Math.Floor( cashForSinglePosition / this.account.DataStreamer.GetCurrentBid( ticker ) ) ); Order order = new Order( SignedTicker.GetMarketOrderType(tickers[tickerPosition]), new Instrument( ticker ) , quantity ); this.orders.Add(order); } private void addChosenTickersToOrderList(string[] tickers) { for( int i = 0; i<tickers.Length; i++) { if(tickers[i] != null) { this.addOrderForTicker( tickers, i ); this.lastOrderedTickers[i] = SignedTicker.GetTicker(tickers[i]); } } } private void openPositions(string[] tickers) { this.addChosenTickersToOrderList(tickers); //execute orders actually foreach(object item in this.orders) this.account.AddOrder((Order)item); } private double setChosenTickers_getGainOrLossFromPreviousClose(string signedTicker) { IndexBasedEndOfDayTimer currentTimer = (IndexBasedEndOfDayTimer)this.account.EndOfDayTimer; ExtendedDateTime nowAtOpen = new ExtendedDateTime(currentTimer.GetCurrentTime().DateTime, BarComponent.Open); ExtendedDateTime previousClose = new ExtendedDateTime(currentTimer.GetPreviousDateTime(), BarComponent.Close); double currentValueAtOpen = HistoricalDataProvider.GetAdjustedMarketValue(SignedTicker.GetTicker(signedTicker), nowAtOpen); double previousValueAtClose = HistoricalDataProvider.GetAdjustedMarketValue(SignedTicker.GetTicker(signedTicker), previousClose); return (currentValueAtOpen - previousValueAtClose) / previousValueAtClose; } private void setChosenTickers_addTickersForShorting() { DataTable worstTickersOrderedByGainAtOpen = new DataTable(); worstTickersOrderedByGainAtOpen.Columns.Add("ticker", Type.GetType("System.String")); worstTickersOrderedByGainAtOpen.Columns.Add("gainAtOpen", Type.GetType("System.Double")); object[] values = new object[2]; for (int i = 0; i<this.worstTickers.Length; i++) { values[0] = this.worstTickers[i]; values[1] = this.setChosenTickers_getGainOrLossFromPreviousClose(this.worstTickers[i]); worstTickersOrderedByGainAtOpen.Rows.Add(values); } DataRow[] orderedRows = new DataRow[this.bestTickers.Length]; orderedRows = worstTickersOrderedByGainAtOpen.Select("", "gainAtOpen DESC"); for(int i = 0;i<this.numOfTickersForShortSelling; i++) if( (double)orderedRows[i]["gainAtOpen"] > 0.0 ) //at open, current ticker is gaining this.chosenTickers[this.numOfTickersForBuying + i] = "-" + (string)orderedRows[i]["ticker"]; } private void setChosenTickers_addTickersForBuying() { DataTable bestTickersOrderedByLossAtOpen = new DataTable(); bestTickersOrderedByLossAtOpen.Columns.Add("ticker", Type.GetType("System.String")); bestTickersOrderedByLossAtOpen.Columns.Add("lossAtOpen", Type.GetType("System.Double")); object[] values = new object[2]; for (int i = 0; i<this.bestTickers.Length; i++) { values[0] = this.bestTickers[i]; values[1] = - this.setChosenTickers_getGainOrLossFromPreviousClose(this.bestTickers[i]); bestTickersOrderedByLossAtOpen.Rows.Add(values); } DataRow[] orderedRows = new DataRow[this.bestTickers.Length]; orderedRows = bestTickersOrderedByLossAtOpen.Select("", "lossAtOpen DESC"); for( int i = 0; i<this.numOfTickersForBuying; i++) if( (double)orderedRows[i]["lossAtOpen"] > 0.0 ) //at open, current ticker is losing this.chosenTickers[i] = (string)orderedRows[i]["ticker"]; } private void setChosenTickersBothForLongAndShort() { if( this.thereAreEnoughBestTickers && this.thereAreEnoughWorstTickers ) { try { this.setChosenTickers_addTickersForBuying(); this.setChosenTickers_addTickersForShorting(); } catch(Exception ex) {ex = ex;} } } /// <summary> /// Handles a "Market Open" event. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> public void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { if(this.orders.Count == 0 && this.account.Transactions.Count == 0) this.account.AddCash(30000); this.setChosenTickersBothForLongAndShort(); bool allTickersHasBeenChosenForLongAndShort = true; for( int i = 0; i<this.chosenTickers.Length; i++) { if(this.chosenTickers[i] == null) allTickersHasBeenChosenForLongAndShort = false; } if(allTickersHasBeenChosenForLongAndShort) this.openPositions(this.chosenTickers); } #endregion #region MarketCloseEventHandler private void closePosition( string ticker ) { this.account.ClosePosition( ticker ); } private void closePositions() { if(this.lastOrderedTickers != null) foreach( string ticker in this.lastOrderedTickers ) for( int i = 0; i<this.account.Portfolio.Keys.Count; i++ ) if( this.account.Portfolio[ticker]!=null ) closePosition( ticker ); } public void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { this.closePositions(); } #endregion #region OneHourAfterMarketCloseEventHandler private void oneHourAfterMarketCloseEventHandler_clear() { this.orders.Clear(); this.thereAreEnoughBestTickers = false; this.thereAreEnoughWorstTickers = false; for(int i = 0; i<this.chosenTickers.Length;i++) this.chosenTickers[i] = null; } /// <summary> /// Handles a "One hour after market close" event. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> public void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { this.oneHourAfterMarketCloseEventHandler_clear(); DateTime currentDate = endOfDayTimingEventArgs.EndOfDayDateTime.DateTime; SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); //remark from here for DEBUG SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromGroup = new SelectorByQuotationAtEachMarketDay(tickersFromGroup, false, currentDate.AddDays(-30), currentDate, tickersFromGroup.Rows.Count, this.benchmark); SelectorByAverageRawOpenPrice byPrice = new SelectorByAverageRawOpenPrice( quotedAtEachMarketDayFromGroup.GetTableOfSelectedTickers(), false, currentDate.AddDays(-10), currentDate, tickersFromGroup.Rows.Count, 25 ); SelectorByLiquidity mostLiquidSelector = new SelectorByLiquidity(byPrice.GetTableOfSelectedTickers(), false,currentDate.AddDays(-30), currentDate, this.numberOfEligibleTickers); SelectorByOpenToCloseVolatility lessVolatile = new SelectorByOpenToCloseVolatility(mostLiquidSelector.GetTableOfSelectedTickers(), true,currentDate.AddDays(-30), currentDate, this.numberOfEligibleTickers/2); SelectorByAverageCloseToClosePerformance bestTickersFromLessVolatile = new SelectorByAverageCloseToClosePerformance(lessVolatile.GetTableOfSelectedTickers(), false,currentDate,currentDate,this.bestTickers.Length); SelectorByAverageCloseToClosePerformance worstTickersFromLessVolatile = new SelectorByAverageCloseToClosePerformance(lessVolatile.GetTableOfSelectedTickers(), true,currentDate,currentDate,this.worstTickers.Length); DataTable tableOfBestTickers = bestTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfBestTickers.Rows.Count >= this.bestTickers.Length) { this.thereAreEnoughBestTickers = true; for(int i = 0;i<this.bestTickers.Length;i++) { if( (double)tableOfBestTickers.Rows[i]["AverageCloseToClosePerformance"] > 1.0 ) this.bestTickers[i] = (string)tableOfBestTickers.Rows[i][0]; else this.thereAreEnoughBestTickers = false; } } DataTable tableOfWorstTickers = worstTickersFromLessVolatile.GetTableOfSelectedTickers(); if(tableOfWorstTickers.Rows.Count >= this.worstTickers.Length) { this.thereAreEnoughWorstTickers = true; for(int i = 0;i<this.worstTickers.Length;i++) { if( (double)tableOfWorstTickers.Rows[i]["AverageCloseToClosePerformance"] < 1.0 ) this.worstTickers[i] = (string)tableOfWorstTickers.Rows[i][0]; else this.thereAreEnoughWorstTickers = false; } } // //for DEBUG // //remark from here for real running // SelectorByLiquidity mostLiquidSelector = // new SelectorByLiquidity(tickersFromGroup, // false,currentDate.AddDays(-30), currentDate, // this.numberOfEligibleTickers); // // SelectorByAverageCloseToClosePerformance bestTickersFromMostLiquid = // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), // false,currentDate,currentDate,this.bestTickers.Length); // // SelectorByAverageCloseToClosePerformance worstTickersFromMostLiquid = // new SelectorByAverageCloseToClosePerformance(mostLiquidSelector.GetTableOfSelectedTickers(), // true,currentDate,currentDate,this.worstTickers.Length); // // DataTable tableOfBestTickers = bestTickersFromMostLiquid.GetTableOfSelectedTickers(); // for(int i = 0;i<this.bestTickers.Length;i++) // if(tableOfBestTickers.Rows[i][0] != null) // this.bestTickers[i] = (string)tableOfBestTickers.Rows[i][0]; // // DataTable tableOfWorstTickers = worstTickersFromMostLiquid.GetTableOfSelectedTickers(); // for(int i = 0;i<this.worstTickers.Length;i++) // if(tableOfWorstTickers.Rows[i][0] != null) // this.worstTickers[i] = (string)tableOfWorstTickers.Rows[i][0]; } #endregion } } |
|
From: Marco M. <mi...@us...> - 2007-06-30 18:55:29
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_OTC In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv18103/DoubleOverReaction_OTC Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/ArbitrageTesting/OverReactionHypothesis/DoubleOverReaction_OTC added to the repository |
|
From: Marco M. <mi...@us...> - 2007-06-30 18:52:57
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv16641/b7_Scripts/TickerSelectionTesting Added Files: EndOfDayTimerHandlerCTO_WorstAtDay.cs RunEfficientCTO_WorstAtDayPortfolio.cs Log Message: Added the CTO_WorstAtDay strategy (a variation of the CloseToOpen strategy). This strategy consists of selecting the tickers at close, among a given number of the best tickers found by the optimizer, that have lost the most the current market day (a reversal in trend is expected the following night). --- NEW FILE: RunEfficientCTO_WorstAtDayPortfolio.cs --- /* QuantProject - Quantitative Finance Library RunEfficientCTOPorfolio_WorstAtDay.cs Copyright (C) 2003 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using System.Data; using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.ADT.FileManaging; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Scripting; using QuantProject.Business.Strategies; using QuantProject.Business.Testing; using QuantProject.Business.Timing; using QuantProject.Business.Financial.Accounting.Commissions; using QuantProject.Business.Financial.Accounting.Slippage; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; namespace QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios { /// <summary> /// Script to buy at open and sell at close /// the efficient close to open daily portfolio /// </summary> [Serializable] public class RunEfficientCTOPortfolio_WorstAtDay : RunEfficientPortfolio { protected int numDaysBetweenEachOptimization; protected int numOfGenomesForOTCScanning; public RunEfficientCTOPortfolio_WorstAtDay(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, double targetReturn, PortfolioType portfolioType, double maxRunningHours, int numDaysBetweenEachOptimization, int numOfGenomesForOTCScanning): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, startDate, endDate, targetReturn, portfolioType, maxRunningHours) { this.ScriptName = "CTOWorstAtDay_NoCoeff_SharpeOTCCTO"; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.numOfGenomesForOTCScanning = numOfGenomesForOTCScanning; } // delete remark delimitations for having ib commission // and a fixed percentage calculation of slippage protected override void run_initializeAccount() { this.account = new Account(this.ScriptName, this.endOfDayTimer , new HistoricalEndOfDayDataStreamer(this.endOfDayTimer , this.historicalQuoteProvider ) , new HistoricalEndOfDayOrderExecutor(this.endOfDayTimer , this.historicalQuoteProvider)); //, new FixedPercentageSlippageManager(this.historicalQuoteProvider, // this.endOfDayTimer,0.08)), //new IBCommissionManager()); } protected override void run_initializeEndOfDayTimerHandler() { this.endOfDayTimerHandler = new EndOfDayTimerHandlerCTO_WorstAtDay(this.tickerGroupID, this.numberOfEligibleTickers, this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, this.account, this.generationNumberForGeneticOptimizer, this.populationSizeForGeneticOptimizer, this.benchmark, this.targetReturn, this.portfolioType, this.numDaysBetweenEachOptimization, this.numOfGenomesForOTCScanning); } protected override void run_initializeHistoricalQuoteProvider() { this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); } protected override void run_addEventHandlers() { this.endOfDayTimer.MarketOpen += new MarketOpenEventHandler( this.endOfDayTimerHandler.MarketOpenEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.endOfDayTimerHandler.MarketCloseEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); this.endOfDayTimer.OneHourAfterMarketClose += new OneHourAfterMarketCloseEventHandler( this.endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler ); } //necessary far calling RunEfficientPortfolio.Run() //in classes that inherit from this class public override void Run() { base.Run(); } } } --- NEW FILE: EndOfDayTimerHandlerCTO_WorstAtDay.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerCTO_WorstAtDay.cs Copyright (C) 2007 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.ADT; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Timing; using QuantProject.Business.Strategies; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.ADT.Optimizing.Genetic; namespace QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios { /// <summary> /// Implements MarketOpenEventHandler, /// MarketCloseEventHandler, /// OneHourAfterMarketCloseEventHandler /// These handlers contain the core strategy /// for the efficient close to open worst by day portfolio! /// </summary> [Serializable] public class EndOfDayTimerHandlerCTO_WorstAtDay : EndOfDayTimerHandler { protected int numDaysBetweenEachOptimization; private int numDaysElapsedSinceLastOptimization; protected int seedForRandomGenerator; protected GeneticOptimizer currentGO; protected int numOfGenomesForOTCScanning; public EndOfDayTimerHandlerCTO_WorstAtDay(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, double targetReturn, PortfolioType portfolioType, int numDaysBetweenEachOptimization, int numOfGenomesForOTCScanning): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, targetReturn, portfolioType) { this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.numDaysElapsedSinceLastOptimization = 0; this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; this.numOfGenomesForOTCScanning = numOfGenomesForOTCScanning; } /// <summary> /// Handles a "Market Open" event. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> public override void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { this.closePositions(); } private void marketCloseEventHandler_chooseTheWorstOTCGenome() { int populationSize = this.currentGO.PopulationSize; int indexOfWorstCombination = populationSize - 1; double lossOfCurrentCombination; double lossOfCurrentWorstCombination = 0.0; double fitnessOfPreviousCombination = 0.0; IndexBasedEndOfDayTimer currentTimer = (IndexBasedEndOfDayTimer)this.account.EndOfDayTimer; DateTime today = currentTimer.GetCurrentTime().DateTime; int numOfGenomesScanned = 0; for(int i = 0; numOfGenomesScanned < this.numOfGenomesForOTCScanning; i++) { if( i == 0 || ( ((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Fitness < fitnessOfPreviousCombination ) ) //it is the best genome or the current genome is different from - and //so it has to be strictly less of - the previous scanned genome { fitnessOfPreviousCombination = ((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Fitness; try{ //retrieves loss at day for the CurrentCombination lossOfCurrentCombination = - SignedTicker.GetOpenToClosePortfolioReturn( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Meaning).Tickers, ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Meaning).TickersPortfolioWeights, today);//- because fitness in GenomeOTCCTO is just the reversal of what needed numOfGenomesScanned++; if(lossOfCurrentCombination < lossOfCurrentWorstCombination) { indexOfWorstCombination = populationSize - i - 1; lossOfCurrentWorstCombination = lossOfCurrentCombination; } } catch(Exception ex){ //if retrieving of loss of current combination fails ex = ex; } } } this.chosenTickers = ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[indexOfWorstCombination]).Meaning).Tickers; SignedTicker.ChangeSignOfEachTicker(this.chosenTickers);//it is used a fitness that is //the reversal of qwhat needed this.chosenTickersPortfolioWeights = ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[indexOfWorstCombination]).Meaning).TickersPortfolioWeights; } public override void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { if(this.orders.Count == 0 && this.account.Transactions.Count == 0) this.account.AddCash(30000); if(this.currentGO != null) //so a list of genomes is available this.marketCloseEventHandler_chooseTheWorstOTCGenome(); this.openPositions(this.chosenTickers); } #region OneHourAfterMarketCloseEventHandler protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); SelectorByLiquidity mostLiquid = new SelectorByLiquidity(tickersFromGroup, false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfEligibleTickers); SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromMostLiquid = new SelectorByQuotationAtEachMarketDay(mostLiquid.GetTableOfSelectedTickers(), false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfEligibleTickers, this.benchmark); SelectorByAverageRawOpenPrice byPrice = new SelectorByAverageRawOpenPrice(quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(), false,currentDate.AddDays(-30), currentDate, this.numberOfEligibleTickers, 30); return byPrice.GetTableOfSelectedTickers(); } protected virtual void setTickers(DateTime currentDate, bool setGenomeCounter) { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); if(setOfTickersToBeOptimized.Rows.Count > this.chosenTickers.Length*2) //the optimization process is possible only if the initial set of tickers is //as large as the number of tickers to be chosen { IGenomeManager genManEfficientCTOPortfolio = new GenomeManagerForEfficientOTCCTOPortfolio(setOfTickersToBeOptimized, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, this.targetReturn, this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientCTOPortfolio, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer, this.seedForRandomGenerator); if(setGenomeCounter) this.genomeCounter = new GenomeCounter(GO); GO.MutationRate = 0.25; GO.CrossoverRate = 0.95; GO.Run(false); this.addGenomeToBestGenomes(GO.BestGenome,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, setOfTickersToBeOptimized.Rows.Count); this.chosenTickers = ((GenomeMeaning)GO.BestGenome.Meaning).Tickers; this.chosenTickersPortfolioWeights = ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights; this.currentGO = GO; } //else it will be buyed again the previous optimized portfolio //that's it the actual chosenTickers member } protected void oneHourAfterMarketCloseEventHandler_updatePrices() { //min price for minimizing commission amount //according to IB Broker's commission scheme this.minPriceForMinimumCommission = this.account.CashAmount/(this.numberOfTickersToBeChosen*100); this.maxPriceForMinimumCommission = this.maxPriceForMinimumCommission; //just to avoid warning message } /// <summary> /// Handles a "One hour after market close" event. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> public override void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { this.seedForRandomGenerator++; this.orders.Clear(); //this.oneHourAfterMarketCloseEventHandler_updatePrices(); if(this.numDaysElapsedSinceLastOptimization == this.numDaysBetweenEachOptimization - 1) { this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); //sets tickers to be chosen next Market Close event this.numDaysElapsedSinceLastOptimization = 0; } else { this.numDaysElapsedSinceLastOptimization++; } } #endregion } } |
|
From: Marco M. <mi...@us...> - 2007-06-30 18:50:43
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv15710/b7_Scripts/TickerSelectionTesting Added Files: EndOfDayTimerHandlerOTC_WorstAtNight.cs RunEfficientOTC_WorstAtNightPortfolio.cs Log Message: Added the OTC_WorstAtNight strategy (a variation of the OpenToClose strategy). This strategy consists of selecting the tickers, among a given number of the best tickers found by the optimizer, that have lost the most the previous night. --- NEW FILE: RunEfficientOTC_WorstAtNightPortfolio.cs --- /* QuantProject - Quantitative Finance Library RunEfficientOTCPortfolio_WorstAtNight.cs Copyright (C) 2003 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using System.Data; using QuantProject.ADT; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.ADT.FileManaging; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Accounting.Reporting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Scripting; using QuantProject.Business.Strategies; using QuantProject.Business.Testing; using QuantProject.Business.Timing; using QuantProject.Business.Financial.Accounting.Commissions; using QuantProject.Business.Financial.Accounting.Slippage; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; using QuantProject.Presentation.Reporting.WindowsForm; namespace QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios { /// <summary> /// Script to buy at open and sell at close /// the efficient open to close daily portfolio /// </summary> [Serializable] public class RunEfficientOTCPortfolio_WorstAtNight : RunEfficientPortfolio { protected int numDaysBetweenEachOptimization; protected int numOfGenomesForCTOScanning; public RunEfficientOTCPortfolio_WorstAtNight(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, DateTime startDate, DateTime endDate, double targetReturn, PortfolioType portfolioType, double maxRunningHours, int numDaysBetweenEachOptimization, int numOfGenomesForCTOScanning): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, startDate, endDate, targetReturn, portfolioType, maxRunningHours) { //this.ScriptName = "OpenCloseScriptsSharpeRatioWithCoeff"; //this.ScriptName = "OpenCloseScriptsSharpeRatio"; this.ScriptName = "OTC_WorstAtNight_SharpeRatioNoCoeff"; //this.ScriptName = "OpenCloseScripts"; this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.numOfGenomesForCTOScanning = numOfGenomesForCTOScanning; } // delete remark delimitations for having ib commission // and a fixed percentage calculation of slippage protected override void run_initializeAccount() { this.account = new Account(this.ScriptName, this.endOfDayTimer , new HistoricalEndOfDayDataStreamer(this.endOfDayTimer , this.historicalQuoteProvider ) , new HistoricalEndOfDayOrderExecutor(this.endOfDayTimer , this.historicalQuoteProvider)//, // new FixedPercentageSlippageManager(this.historicalQuoteProvider, // this.endOfDayTimer,0.08)), ); //new IBCommissionManager()); } protected override void run_initializeEndOfDayTimerHandler() { this.endOfDayTimerHandler = new EndOfDayTimerHandlerOTC_WorstAtNight(this.tickerGroupID, this.numberOfEligibleTickers, this.numberOfTickersToBeChosen, this.numDaysForOptimizationPeriod, this.account, this.generationNumberForGeneticOptimizer, this.populationSizeForGeneticOptimizer, this.benchmark, this.targetReturn, this.portfolioType, this.numDaysBetweenEachOptimization, this.numOfGenomesForCTOScanning); } protected override void run_initializeHistoricalQuoteProvider() { this.historicalQuoteProvider = new HistoricalRawQuoteProvider(); //this.historicalQuoteProvider = new HistoricalAdjustedQuoteProvider(); } protected override void run_addEventHandlers() { this.endOfDayTimer.MarketOpen += new MarketOpenEventHandler( this.endOfDayTimerHandler.MarketOpenEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.endOfDayTimerHandler.MarketCloseEventHandler); this.endOfDayTimer.MarketClose += new MarketCloseEventHandler( this.checkDateForReport); this.endOfDayTimer.OneHourAfterMarketClose += new OneHourAfterMarketCloseEventHandler( this.endOfDayTimerHandler.OneHourAfterMarketCloseEventHandler ); } public override 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 + "_GenomesScanned" + this.numOfGenomesForCTOScanning; } //necessary far calling RunEfficientPortfolio.Run() //in classes that inherit from this class public override void Run() { base.Run(); } } } --- NEW FILE: EndOfDayTimerHandlerOTC_WorstAtNight.cs --- /* QuantProject - Quantitative Finance Library EndOfDayTimerHandlerOTC_WorstAtNight.cs Copyright (C) 2003 Marco Milletti This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Data; using System.Collections; using QuantProject.ADT; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Financial.Instruments; using QuantProject.Business.Financial.Ordering; using QuantProject.Business.Strategies; using QuantProject.Business.Timing; using QuantProject.Data.DataProviders; using QuantProject.Data.Selectors; using QuantProject.ADT.Optimizing.Genetic; namespace QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios { /// <summary> /// Implements MarketOpenEventHandler, /// TwoMinutesBeforeMarketCloseEventHandler and OneHourAfterMarketCloseEventHandler /// These handlers contain the core strategy for the efficient close to open portfolio! /// </summary> [Serializable] public class EndOfDayTimerHandlerOTC_WorstAtNight : EndOfDayTimerHandler { protected int numDaysBetweenEachOptimization; private int numDaysElapsedSinceLastOptimization; protected int seedForRandomGenerator; protected GeneticOptimizer currentGO; protected int numOfGenomesForCTOScanning; public EndOfDayTimerHandlerOTC_WorstAtNight(string tickerGroupID, int numberOfEligibleTickers, int numberOfTickersToBeChosen, int numDaysForOptimizationPeriod, Account account, int generationNumberForGeneticOptimizer, int populationSizeForGeneticOptimizer, string benchmark, double targetReturn, PortfolioType portfolioType, int numDaysBetweenEachOptimization, int numOfGenomesForCTOScanning): base(tickerGroupID, numberOfEligibleTickers, numberOfTickersToBeChosen, numDaysForOptimizationPeriod, account, generationNumberForGeneticOptimizer, populationSizeForGeneticOptimizer, benchmark, targetReturn, portfolioType) { this.numDaysBetweenEachOptimization = numDaysBetweenEachOptimization; this.numDaysElapsedSinceLastOptimization = 0; this.seedForRandomGenerator = ConstantsProvider.SeedForRandomGenerator; this.numOfGenomesForCTOScanning = numOfGenomesForCTOScanning; } private void marketOpenEventHandler_chooseTheWorstCTOGenome() { int populationSize = this.currentGO.PopulationSize; int indexOfWorstCombination = populationSize - 1; double lossOfCurrentCombination; double lossOfCurrentWorstCombination = 0.0; double fitnessOfPreviousCombination = 0.0; IndexBasedEndOfDayTimer currentTimer = (IndexBasedEndOfDayTimer)this.account.EndOfDayTimer; DateTime today = currentTimer.GetCurrentTime().DateTime; DateTime lastMarketDay = currentTimer.GetPreviousDateTime(); int numOfGenomesScanned = 0; for(int i = 0; numOfGenomesScanned < this.numOfGenomesForCTOScanning; i++) { if( i == 0 || ( ((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Fitness < fitnessOfPreviousCombination ) ) //it is the best genome or the current genome is different from - and //so it has to be strictly less of - the previous scanned genome { fitnessOfPreviousCombination = ((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Fitness; try{ //tries to retrieve loss at night for the CurrentCombination lossOfCurrentCombination = SignedTicker.GetLastNightPortfolioReturn( ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Meaning).Tickers, ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[populationSize - i - 1]).Meaning).TickersPortfolioWeights, lastMarketDay, today); numOfGenomesScanned++; if(lossOfCurrentCombination < lossOfCurrentWorstCombination) { indexOfWorstCombination = populationSize - i - 1; lossOfCurrentWorstCombination = lossOfCurrentCombination; } } catch(Exception ex){ //retrieve of loss of current combination fails ex = ex; } } } this.chosenTickers = ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[indexOfWorstCombination]).Meaning).Tickers; this.chosenTickersPortfolioWeights = ((GenomeMeaning)((Genome)this.currentGO.CurrentGeneration[indexOfWorstCombination]).Meaning).TickersPortfolioWeights; } /// <summary> /// Handles a "Market Open" event. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> public override void MarketOpenEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { if(this.orders.Count == 0 && this.account.Transactions.Count == 0) this.account.AddCash(30000); if(this.currentGO != null) //so a list of genomes is available this.marketOpenEventHandler_chooseTheWorstCTOGenome(); this.openPositions(this.chosenTickers); } public override void MarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { this.closePositions(); } #region OneHourAfterMarketCloseEventHandler protected DataTable getSetOfTickersToBeOptimized(DateTime currentDate) { SelectorByGroup temporizedGroup = new SelectorByGroup(this.tickerGroupID, currentDate); DataTable tickersFromGroup = temporizedGroup.GetTableOfSelectedTickers(); SelectorByLiquidity mostLiquid = new SelectorByLiquidity(tickersFromGroup, false,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfEligibleTickers); SelectorByQuotationAtEachMarketDay quotedAtEachMarketDayFromMostLiquid = new SelectorByQuotationAtEachMarketDay(mostLiquid.GetTableOfSelectedTickers(), false, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfEligibleTickers, this.benchmark); SelectorByAverageRawOpenPrice byPrice = new SelectorByAverageRawOpenPrice(quotedAtEachMarketDayFromMostLiquid.GetTableOfSelectedTickers(), false,currentDate.AddDays(-30), currentDate, this.numberOfEligibleTickers, 28); DataTable tickersByPrice = byPrice.GetTableOfSelectedTickers(); SelectorByOpenCloseCorrelationToBenchmark tickersLessCorrelatedToBenchmark = new SelectorByOpenCloseCorrelationToBenchmark(tickersByPrice, "^GSPC",true, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, tickersByPrice.Rows.Count/2); return tickersLessCorrelatedToBenchmark.GetTableOfSelectedTickers(); } protected virtual void setTickers(DateTime currentDate, bool setGenomeCounter) { DataTable setOfTickersToBeOptimized = this.getSetOfTickersToBeOptimized(currentDate); if(setOfTickersToBeOptimized.Rows.Count > this.chosenTickers.Length*2) //the optimization process is possible only if the initial set of tickers is //as large as the number of tickers to be chosen { IGenomeManager genManEfficientOTCPortfolio = // new GenomeManagerForEfficientOTCPortfolio(setOfTickersToBeOptimized, // currentDate.AddDays(-this.numDaysForOptimizationPeriod), // currentDate, // this.numberOfTickersToBeChosen, // this.targetReturn, // this.portfolioType); new GenomeManagerForEfficientOTCCTOPortfolio(setOfTickersToBeOptimized, currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, this.numberOfTickersToBeChosen, this.targetReturn, this.portfolioType); GeneticOptimizer GO = new GeneticOptimizer(genManEfficientOTCPortfolio, this.populationSizeForGeneticOptimizer, this.generationNumberForGeneticOptimizer, this.seedForRandomGenerator); if(setGenomeCounter) this.genomeCounter = new GenomeCounter(GO); GO.MutationRate = 0.25; GO.CrossoverRate = 0.95; GO.Run(false); this.addGenomeToBestGenomes(GO.BestGenome,currentDate.AddDays(-this.numDaysForOptimizationPeriod), currentDate, setOfTickersToBeOptimized.Rows.Count); this.chosenTickers = ((GenomeMeaning)GO.BestGenome.Meaning).Tickers; this.chosenTickersPortfolioWeights = ((GenomeMeaning)GO.BestGenome.Meaning).TickersPortfolioWeights; this.currentGO = GO; } //else it will be buyed again the previous optimized portfolio //that's it the actual chosenTickers member } protected void oneHourAfterMarketCloseEventHandler_updatePrices() { //min price for minimizing commission amount //according to IB Broker's commission scheme this.minPriceForMinimumCommission = this.account.CashAmount/(this.numberOfTickersToBeChosen*100); this.maxPriceForMinimumCommission = this.maxPriceForMinimumCommission; //just to avoid warning message } /// <summary> /// Handles a "One hour after market close" event. /// </summary> /// <param name="sender"></param> /// <param name="eventArgs"></param> public override void OneHourAfterMarketCloseEventHandler( Object sender , EndOfDayTimingEventArgs endOfDayTimingEventArgs ) { this.seedForRandomGenerator++; this.orders.Clear(); //this.oneHourAfterMarketCloseEventHandler_updatePrices(); if(this.numDaysElapsedSinceLastOptimization == this.numDaysBetweenEachOptimization - 1) { this.setTickers(endOfDayTimingEventArgs.EndOfDayDateTime.DateTime, false); //sets tickers to be chosen next Market Open event this.numDaysElapsedSinceLastOptimization = 0; } else { this.numDaysElapsedSinceLastOptimization++; } } #endregion } } |
|
From: Marco M. <mi...@us...> - 2007-06-29 15:18:27
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv26958 Modified Files: Genome.cs Log Message: Fixed bug in Genome's Fitness property. Index: Genome.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic/Genome.cs,v retrieving revision 1.17 retrieving revision 1.18 diff -C2 -d -r1.17 -r1.18 *** Genome.cs 20 Jun 2007 14:56:59 -0000 1.17 --- Genome.cs 29 Jun 2007 15:18:21 -0000 1.18 *************** *** 61,64 **** --- 61,71 ---- } + private void setFitnessValue(double fitnessValue) + { + this.fitness = fitnessValue; + this.hasFitnessBeenAssigned = true; + } + + public double Fitness { *************** *** 70,78 **** if ( ! this.hasFitnessBeenAssigned ) // the genome's fitness has not been assigned yet ! { ! this.fitness = this.genomeManager.GetFitnessValue(this); ! this.hasFitnessBeenAssigned = true; ! } ! return this.fitness; } } --- 77,83 ---- if ( ! this.hasFitnessBeenAssigned ) // the genome's fitness has not been assigned yet ! this.setFitnessValue(this.genomeManager.GetFitnessValue(this)); ! ! return this.fitness; } } *************** *** 166,170 **** Genome returnValue = new Genome(this.genomeManager, this.geneticOptimizer); returnValue.CopyValuesInGenes(this.genes); ! returnValue.fitness = this.fitness; returnValue.meaning = this.meaning; returnValue.generation = this.Generation; --- 171,175 ---- Genome returnValue = new Genome(this.genomeManager, this.geneticOptimizer); returnValue.CopyValuesInGenes(this.genes); ! returnValue.setFitnessValue(this.fitness); returnValue.meaning = this.meaning; returnValue.generation = this.Generation; |
|
From: Glauco S. <gla...@us...> - 2007-06-24 21:37:04
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv29788/b7_Scripts/WalkForwardTesting/WalkForwardLag Modified Files: WFLagMain.cs Log Message: The signed ticker for the second portfolio position has been fixed (short now). Index: WFLagMain.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WFLagMain.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** WFLagMain.cs 11 Jun 2007 17:53:29 -0000 1.8 --- WFLagMain.cs 24 Jun 2007 21:36:59 -0000 1.9 *************** *** 139,147 **** IWFLagWeightedPositionsChooser wFLagWeightedPositionsChooser = new WFLagBruteForceFixedPortfolioWeightedPositionsChooser( ! 4 , new string[]{ "IWM" , "SPY" } , 100 , "EWQ" , new QuantProject.Business.Strategies.EquityEvaluation.WinningPeriods() ); wFLagWeightedPositionsChooser = new WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio( ! 4 , new string[]{ "IWM" , "SPY" } , 100 , "EWQ" , new QuantProject.Business.Strategies.EquityEvaluation.WinningPeriods() , 1000 , 15 ); --- 139,147 ---- IWFLagWeightedPositionsChooser wFLagWeightedPositionsChooser = new WFLagBruteForceFixedPortfolioWeightedPositionsChooser( ! 4 , new string[]{ "IWM" , "-SPY" } , 100 , "EWQ" , new QuantProject.Business.Strategies.EquityEvaluation.WinningPeriods() ); wFLagWeightedPositionsChooser = new WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio( ! 4 , new string[]{ "IWM" , "-SPY" } , 100 , "EWQ" , new QuantProject.Business.Strategies.EquityEvaluation.WinningPeriods() , 1000 , 15 ); |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers/WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv28914/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers/WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio Modified Files: WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio.cs Log Message: The Decode method has been virtually completely rewritten. It is next to the final version now. Index: WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers/WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio/WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio.cs 13 Jun 2007 21:31:41 -0000 1.1 --- WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio.cs 24 Jun 2007 21:34:55 -0000 1.2 *************** *** 44,52 **** { private int numberOfDrivingPositions; ! private int numberOfTickersInPortfolio; ! private int numberOfEligibleTickersForDrivingWeightedPositions; protected DataTable eligibleTickersForDrivingWeightedPositions; protected DataTable eligibleTickersForPortfolioWeightedPositions; ! private DateTime firstOptimizationDate; private DateTime lastOptimizationDate; --- 44,52 ---- { private int numberOfDrivingPositions; ! private string[] portfolioSignedTickers; ! // private int numberOfEligibleTickersForDrivingWeightedPositions; protected DataTable eligibleTickersForDrivingWeightedPositions; protected DataTable eligibleTickersForPortfolioWeightedPositions; ! private DateTime firstOptimizationDateForDrivingPositions; private DateTime lastOptimizationDate; *************** *** 57,60 **** --- 57,63 ---- private IEquityEvaluator equityEvaluator; + private WFLagMeaningForUndecodableGenomes wFLagMeaningForUndecodableGenomes; + private string[] tickersForPortfolioPositions; + public int GenomeSize *************** *** 62,82 **** get { ! return ( this.numberOfDrivingPositions + this.numberOfTickersInPortfolio ); } } - // public int MinValueForGenes - // { - // get { return -this.numberOfEligibleTickersForDrivingWeightedPositions; } - // } - // public int MaxValueForGenes - // { - // get { return this.numberOfEligibleTickersForDrivingWeightedPositions - 1; } - // } - // public GeneticOptimizer CurrentGeneticOptimizer - // { - // get{ return this.currentGeneticOptimizer; } - // set{ this.currentGeneticOptimizer = value; } - // } /// <summary> --- 65,72 ---- get { ! return ( this.numberOfDrivingPositions ); } } /// <summary> *************** *** 96,105 **** /// <param name="numberOfTickersInPortfolio"></param> public WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio( DataTable eligibleTickersForDrivingWeightedPositions , ! DataTable eligibleTickersForPortfolioWeightedPositions , ! DateTime firstOptimizationDate , DateTime lastOptimizationDate , - int numberOfDrivingPositions , - int numberOfTickersInPortfolio , IEquityEvaluator equityEvaluator , int seedForRandomGenerator ) --- 86,94 ---- /// <param name="numberOfTickersInPortfolio"></param> public WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio( + int numberOfDrivingPositions , DataTable eligibleTickersForDrivingWeightedPositions , ! string[] portfolioSignedTickers , ! DateTime firstOptimizationDateForDrivingPositions , DateTime lastOptimizationDate , IEquityEvaluator equityEvaluator , int seedForRandomGenerator ) *************** *** 107,118 **** { this.numberOfDrivingPositions = numberOfDrivingPositions; ! this.numberOfTickersInPortfolio = numberOfTickersInPortfolio; ! this.numberOfEligibleTickersForDrivingWeightedPositions = ! eligibleTickersForDrivingWeightedPositions.Rows.Count; this.eligibleTickersForDrivingWeightedPositions = eligibleTickersForDrivingWeightedPositions; ! this.eligibleTickersForPortfolioWeightedPositions = ! eligibleTickersForPortfolioWeightedPositions; ! this.firstOptimizationDate = firstOptimizationDate; this.lastOptimizationDate = lastOptimizationDate; --- 96,108 ---- { this.numberOfDrivingPositions = numberOfDrivingPositions; ! // this.numberOfEligibleTickersForDrivingWeightedPositions = ! // eligibleTickersForDrivingWeightedPositions.Rows.Count; this.eligibleTickersForDrivingWeightedPositions = eligibleTickersForDrivingWeightedPositions; ! // this.eligibleTickersForPortfolioWeightedPositions = ! // eligibleTickersForPortfolioWeightedPositions; ! this.portfolioSignedTickers = portfolioSignedTickers; ! this.firstOptimizationDateForDrivingPositions = ! firstOptimizationDateForDrivingPositions; this.lastOptimizationDate = lastOptimizationDate; *************** *** 130,144 **** this.wFLagCandidates = new WFLagCandidates( this.eligibleTickersForDrivingWeightedPositions , ! this.firstOptimizationDate , this.lastOptimizationDate ); } public int GetMinValueForGenes( int genePosition ) { int minValueForGene = ! -this.numberOfEligibleTickersForDrivingWeightedPositions; return minValueForGene; } public int GetMaxValueForGenes( int genePosition ) { ! return this.numberOfEligibleTickersForDrivingWeightedPositions - 1; } --- 120,137 ---- this.wFLagCandidates = new WFLagCandidates( this.eligibleTickersForDrivingWeightedPositions , ! this.firstOptimizationDateForDrivingPositions , this.lastOptimizationDate ); ! ! this.wFLagMeaningForUndecodableGenomes = ! new WFLagMeaningForUndecodableGenomes(); } public int GetMinValueForGenes( int genePosition ) { int minValueForGene = ! -this.eligibleTickersForDrivingWeightedPositions.Rows.Count; return minValueForGene; } public int GetMaxValueForGenes( int genePosition ) { ! return this.eligibleTickersForDrivingWeightedPositions.Rows.Count - 1; } *************** *** 252,271 **** { double fitnessValue; ! WFLagWeightedPositions wFLagWeightedPositions = ! ( WFLagWeightedPositions )this.Decode( genome ); ! int genomeLength = genome.Genes().Length; ! int decodedWeightedPositions = ! wFLagWeightedPositions.DrivingWeightedPositions.Count + ! wFLagWeightedPositions.PortfolioWeightedPositions.Count; ! if ( decodedWeightedPositions < genomeLength ) ! // genome contains a duplicate gene either for ! // driving positions or for portfolio positions ! //fitnessValue = double.MinValue; ! fitnessValue = -0.2; ! else // all driving positions genes are distinct and // all portfolio positions genes are distinct ! fitnessValue = ! this.GetFitnessValue( wFLagWeightedPositions ); return fitnessValue; } --- 245,263 ---- { double fitnessValue; ! object genomeMeaning = this.Decode( genome ); ! if ( genomeMeaning is WFLagWeightedPositions ) ! { // all driving positions genes are distinct and // all portfolio positions genes are distinct ! WFLagWeightedPositions wFLagWeightedPositions = ! (WFLagWeightedPositions)genomeMeaning; ! fitnessValue = this.GetFitnessValue( wFLagWeightedPositions ); ! } ! else ! { ! // genome contains a duplicate gene either for ! // driving positions or for portfolio positions ! fitnessValue = -0.4; ! } return fitnessValue; } *************** *** 289,311 **** } #region Decode ! private int getWeight( Genome genome , int genePosition ) { ! int geneValue = 1; ! if ( genome.GetGeneValue( genePosition ) < 0 ) ! // the position is short ! geneValue = -1; ! return geneValue; } ! private int[] getWeightRelatedGeneValuesForDrivingPositions( Genome genome ) { ! int[] weightRelatedGeneValuesForDrivingPositions = ! new int[ this.numberOfDrivingPositions ]; ! for ( int genePosition = 0 ; ! genePosition < this.numberOfDrivingPositions ; genePosition++ ) ! weightRelatedGeneValuesForDrivingPositions[ genePosition ] = ! this.getWeight( genome , genePosition ); ! return weightRelatedGeneValuesForDrivingPositions; } private int getTickerIndex( Genome genome , int genePosition ) { --- 281,392 ---- } #region Decode ! private void getGenes_checkParameters( Genome genome , int firstGenePosition , ! int numberOfGenes ) { ! if ( firstGenePosition < 0 ) ! throw new Exception( "firstGenePosition is less than zero!" ); ! if ( firstGenePosition >= genome.Size ) ! throw new Exception( "firstGenePosition is >= than genome.Size!" ); ! if ( numberOfGenes <0 ) ! throw new Exception( "firstGenePosition is less than zero!" ); ! if ( firstGenePosition + numberOfGenes > genome.Size ) ! throw new Exception( "firstGenePosition + numberOfGenes is >= genome.Size !!" ); } ! private int[] getGenes( Genome genome , int firstGenePosition , int numberOfGenes ) ! { ! getGenes_checkParameters( genome , firstGenePosition , numberOfGenes ); ! int[] genes = new int[ numberOfGenes ]; ! for ( int i = 0 ; i < numberOfGenes ; i++ ) ! { ! int genePosition = firstGenePosition + i; ! genes[ i ] = this.getTickerIndex( genome , genePosition ); ! } ! return genes; ! } ! private int[] getTickerRelatedGeneValuesForDrivingPositions( Genome genome ) { ! return this.getGenes( genome , 0 , this.numberOfDrivingPositions ); } + // private int[] getTickerRelatedGeneValuesForPortfolioPositions( + // Genome genome ) + // { + // return this.getGenes( genome , this.numberOfDrivingPositions , + // this.numberOfPortfolioPositions ); + // } + private void decodeTicker_checkParameters( int geneValue , DataTable eligibleTickers ) + { + if ( geneValue >= eligibleTickers.Rows.Count ) + throw new Exception( "geneValue is too (positive) large for eligibleTickers !!" ); + if ( geneValue < -eligibleTickers.Rows.Count ) + throw new Exception( "geneValue is too (negative) large for eligibleTickers !!" ); + } + private string decodeTicker( int geneValue , DataTable eligibleTickers ) + { + string ticker; + decodeTicker_checkParameters( geneValue , eligibleTickers ); + if ( geneValue >= 0 ) + // long ticker + ticker = ( string )eligibleTickers.Rows[ geneValue ][ 0 ]; + else + // short ticker + ticker = ( string )eligibleTickers.Rows[ -(geneValue+1) ][ 0 ]; + return ticker; + } + private string[] decodeTickers( int[] tickerRelatedGeneValues , + DataTable eligibleTickers ) + { + string[] tickers = new string[ tickerRelatedGeneValues.Length ]; + for( int i = 0 ; i < tickerRelatedGeneValues.Length ; i++ ) + { + int currentGeneValue = tickerRelatedGeneValues[ i ]; + tickers[ i ] = decodeTicker( currentGeneValue , eligibleTickers ); + + tickers[ i ] = + ( string )eligibleTickers.Rows[ currentGeneValue ][ 0 ]; + } + return tickers; + } + private string[] getTickersForDrivingPositions( Genome genome ) + { + int[] geneValues = this.getTickerRelatedGeneValuesForDrivingPositions( genome ); + return this.decodeTickers( geneValues , this.eligibleTickersForDrivingWeightedPositions ); + } + #region getTickersForPortfolioPositions + + private void setTickerForPortfolioPositions( int i ) + { + string signedTicker = this.portfolioSignedTickers[ i ]; + this.tickersForPortfolioPositions[ i ] = SignedTicker.GetTicker( signedTicker ); + } + private void setTickersForPortfolioPositions() + { + this.tickersForPortfolioPositions = new string[ this.portfolioSignedTickers.Length ]; + for( int i=0 ; i < portfolioSignedTickers.Length ; i++ ) + this.setTickerForPortfolioPositions( i ); + } + private string[] getTickersForPortfolioPositions() + { + if ( this.tickersForPortfolioPositions == null ) + this.setTickersForPortfolioPositions(); + return this.tickersForPortfolioPositions; + } + #endregion //getTickersForPortfolioPositions + private bool isDecodable( Genome genome ) + { + return + ( WeightedPositions.AreValidTickers( this.getTickersForDrivingPositions( genome ) ) ); + } + // private int[] getWeightRelatedGeneValuesForDrivingPositions( + // Genome genome ) + // { + // int[] weightRelatedGeneValuesForDrivingPositions = + // new int[ this.numberOfDrivingPositions ]; + // for ( int genePosition = 0 ; + // genePosition < this.numberOfDrivingPositions ; genePosition++ ) + // weightRelatedGeneValuesForDrivingPositions[ genePosition ] = + // this.getWeight( genome , genePosition ); + // return weightRelatedGeneValuesForDrivingPositions; + // } private int getTickerIndex( Genome genome , int genePosition ) { *************** *** 316,362 **** return tickerIndex; } ! private int[] getTickerRelatedGeneValuesForDrivingPositions( ! Genome genome ) { ! int[] tickerRelatedGeneValuesForDrivingPositions = ! new int[ this.numberOfDrivingPositions ]; ! for ( int genePosition = 0 ; ! genePosition < this.numberOfDrivingPositions ; genePosition++ ) ! tickerRelatedGeneValuesForDrivingPositions[ genePosition ] = ! this.getTickerIndex( genome , genePosition ); ! return tickerRelatedGeneValuesForDrivingPositions; } ! private int[] getWeightRelatedGeneValuesForPortfolioPositions( ! Genome genome ) { ! int[] weightRelatedGeneValuesForPortfolioPositions = ! new int[ this.numberOfTickersInPortfolio ]; ! int firstPositionForPortfolioRelatedGenomes = ! this.numberOfDrivingPositions; ! for ( int i = 0 ; i < this.numberOfTickersInPortfolio ; i++ ) { ! int genePosition = ! firstPositionForPortfolioRelatedGenomes + i; ! weightRelatedGeneValuesForPortfolioPositions[ i ] = ! this.getWeight( genome , genePosition ); } ! return weightRelatedGeneValuesForPortfolioPositions; } ! private int[] getTickerRelatedGeneValuesForPortfolioPositions( ! Genome genome ) { ! int[] tickerRelatedGeneValuesForPortfolioPositions = ! new int[ this.numberOfTickersInPortfolio ]; ! int firstPositionForPortfolioRelatedGenomes = ! this.numberOfDrivingPositions; ! for ( int i = 0 ; i < this.numberOfTickersInPortfolio ; i++ ) ! { ! int genePosition = ! firstPositionForPortfolioRelatedGenomes + i; ! tickerRelatedGeneValuesForPortfolioPositions[ i ] = ! this.getTickerIndex( genome , genePosition ); ! } ! return tickerRelatedGeneValuesForPortfolioPositions; } #region decodeWeightedPositions #region getNormalizedWeightValues --- 397,427 ---- return tickerIndex; } ! private double getWeight( Genome genome , int genePosition ) { ! double weight = 1; ! if ( genome.GetGeneValue( genePosition ) < 0 ) ! // the position is short ! weight = -1; ! return weight; } ! private double[] getWeights( Genome genome , int firstGenePosition , int numberOfGenes ) { ! double[] weights = new double[ numberOfGenes ]; ! for ( int i = 0 ; i < numberOfGenes ; i++ ) { ! int genePosition = firstGenePosition + i; ! weights[ i ] = this.getWeight( genome , genePosition ); } ! return weights; } ! private double[] getWeightsForDrivingPositions( Genome genome ) { ! return this.getWeights( genome , 0 , this.numberOfDrivingPositions ); } + // private double[] getWeightsForPortfolioPositions( Genome genome ) + // { + // return this.getWeights( genome , this.numberOfDrivingPositions , + // this.numberOfPortfolioPositions ); + // } #region decodeWeightedPositions #region getNormalizedWeightValues *************** *** 407,441 **** return BasicFunctions.MultiplyBy( nonNormalizedWeightValues , normalizingFactor ); } ! private double[] getNormalizedWeightValues( double[] nonNormalizedWeightValues ) ! { ! double normalizingFactor = this.getNormalizingFactor( nonNormalizedWeightValues ); ! return getNormalizedWeightValues( nonNormalizedWeightValues , normalizingFactor ); ! } ! private double[] getNormalizedWeightValues( int[] weightRelatedGeneValues ) { ! double[] nonNormalizedWeightValues = ! this.getNonNormalizedWeightValues( weightRelatedGeneValues ); ! return this.getNormalizedWeightValues( nonNormalizedWeightValues ); } #endregion ! private string[] decodeTickers( int[] tickerRelatedGeneValues , ! DataTable eligibleTickers ) ! { ! string[] tickers = new string[ tickerRelatedGeneValues.Length ]; ! for( int i = 0 ; i < tickerRelatedGeneValues.Length ; i++ ) ! { ! int currentGeneValue = tickerRelatedGeneValues[ i ]; ! tickers[ i ] = ! ( string )eligibleTickers.Rows[ currentGeneValue ][ 0 ]; ! } ! return tickers; ! } ! private WeightedPositions decodeWeightedPositions( int[] weightRelatedGeneValues , ! int[] tickerRelatedGeneValues , DataTable eligibleTickers ) { ! double[] normalizedWeightValues = this.getNormalizedWeightValues( weightRelatedGeneValues ); ! string[] tickers = this.decodeTickers( tickerRelatedGeneValues , eligibleTickers ); WeightedPositions weightedPositions = new WeightedPositions( ! normalizedWeightValues , tickers ); return weightedPositions; } --- 472,493 ---- return BasicFunctions.MultiplyBy( nonNormalizedWeightValues , normalizingFactor ); } ! private double[] getNormalizedWeights( double[] nonNormalizedWeights ) { ! double normalizingFactor = this.getNormalizingFactor( nonNormalizedWeights ); ! return getNormalizedWeightValues( nonNormalizedWeights , normalizingFactor ); } + // private double[] getNormalizedWeightValues( int[] weightRelatedGeneValues ) + // { + // double[] nonNormalizedWeightValues = + // this.getNonNormalizedWeightValues( weightRelatedGeneValues ); + // return this.getNormalizedWeightValues( nonNormalizedWeightValues ); + // } #endregion ! private WeightedPositions decodeWeightedPositions( double[] weights , ! string[] tickers , DataTable eligibleTickers ) { ! double[] normalizedWeights = this.getNormalizedWeights( weights ); WeightedPositions weightedPositions = new WeightedPositions( ! normalizedWeights , tickers ); return weightedPositions; } *************** *** 444,483 **** Genome genome ) { ! int[] weightRelatedGeneValuesForDrivingPositions = ! this.getWeightRelatedGeneValuesForDrivingPositions( genome ); ! int[] tickerRelatedGeneValuesForDrivingPositions = ! this.getTickerRelatedGeneValuesForDrivingPositions( genome ); return decodeWeightedPositions( ! weightRelatedGeneValuesForDrivingPositions , ! tickerRelatedGeneValuesForDrivingPositions , this.eligibleTickersForDrivingWeightedPositions ); ! // ! // double weight = this.decodeDrivingWeight( genome , geneIndex ); ! // string ticker = this.decodeDrivingTicker( genome , geneIndex ); ! // WeightedPosition weightedPosition = new WeightedPosition( ! // weight , ticker ); ! // wFLagWeightedPositions.DrivingWeightedPositions.AddWeightedPosition( ! // weightedPosition ); } private WeightedPositions decodePortfolioWeightedPositions( Genome genome ) { ! int[] weightRelatedGeneValuesForPortfolioPositions = ! this.getWeightRelatedGeneValuesForPortfolioPositions( genome ); ! int[] tickerRelatedGeneValuesForPortfolioPositions = ! this.getTickerRelatedGeneValuesForPortfolioPositions( genome ); return decodeWeightedPositions( ! weightRelatedGeneValuesForPortfolioPositions , ! tickerRelatedGeneValuesForPortfolioPositions , this.eligibleTickersForPortfolioWeightedPositions ); - // - // double weight = this.decodeDrivingWeight( genome , geneIndex ); - // string ticker = this.decodeDrivingTicker( genome , geneIndex ); - // WeightedPosition weightedPosition = new WeightedPosition( - // weight , ticker ); - // wFLagWeightedPositions.DrivingWeightedPositions.AddWeightedPosition( - // weightedPosition ); } ! public virtual object Decode(Genome genome) { WeightedPositions drivingWeightedPositions = --- 496,524 ---- Genome genome ) { ! double[] weightsForDrivingPositions = this.getWeightsForDrivingPositions( genome ); ! string[] tickersForDrivingPositions = this.getTickersForDrivingPositions( genome ); return decodeWeightedPositions( ! weightsForDrivingPositions , ! tickersForDrivingPositions , this.eligibleTickersForDrivingWeightedPositions ); ! } ! private double[] getNormalizedWeightsForPortfolioPositions() ! { ! return WeightedPositions.GetBalancedWeights( this.portfolioSignedTickers , ! this.firstOptimizationDateForDrivingPositions.AddDays( 1 ) , ! this.lastOptimizationDate ); } private WeightedPositions decodePortfolioWeightedPositions( Genome genome ) { ! string[] tickersForPortfolioPositions = this.getTickersForPortfolioPositions(); ! double[] portfolioPositionsWeights = ! this.getNormalizedWeightsForPortfolioPositions(); return decodeWeightedPositions( ! portfolioPositionsWeights , ! tickersForPortfolioPositions , this.eligibleTickersForPortfolioWeightedPositions ); } ! private WFLagWeightedPositions dedcodeDecodableGenome( Genome genome ) { WeightedPositions drivingWeightedPositions = *************** *** 488,512 **** new WFLagWeightedPositions( drivingWeightedPositions , portfolioWeightedPositions ); - - // int[] drivingGeneValues = this.getDrivingGeneValues( genome ); - // for ( int geneIndex = 0 ; geneIndex < this.numberOfDrivingPositions * 2 ; - // geneIndex += 2 ) - // this.decode_addDrivingPosition( genome , geneIndex , wFLagWeightedPositions ); - // for ( int geneIndex = this.numberOfDrivingPositions * 2 ; - // geneIndex < - // ( this.numberOfDrivingPositions + this.numberOfTickersInPortfolio ) * 2 ; - // geneIndex += 2 ) - // this.decode_addPortfolioPosition( genome , geneIndex , wFLagSignedTickers ); - // string[] arrayOfTickers = new string[genome.Genes().Length]; - // int indexOfTicker; - // for(int index = 0; index < genome.Genes().Length; index++) - // { - // indexOfTicker = (int)genome.Genes().GetValue(index); - // arrayOfTickers[index] = - // this.decode_getSignedTickerForGeneValue(indexOfTicker); - // } return wFLagWeightedPositions; } ! #endregion #region GetNewGeneValue public int GetNewGeneValue( Genome genome , int genePosition ) --- 529,555 ---- new WFLagWeightedPositions( drivingWeightedPositions , portfolioWeightedPositions ); return wFLagWeightedPositions; } ! /// <summary> ! /// A positive genome value means a long position. A negative genome value means a ! /// short position. ! /// The gene positive value n means the same ticker as the value -(n+1). ! /// Thus, if there are p (>0) eligible tickers, genome values should range from -p to p-1 ! /// </summary> ! /// <param name="genome"></param> ! /// <returns></returns> ! public virtual object Decode(Genome genome) ! { ! object meaning; ! if ( this.isDecodable( genome ) ) ! // genome can be decoded to a WFLagWeightedPositions object ! meaning = this.dedcodeDecodableGenome( genome ); ! else ! // genome cannot be decoded to a WFLagWeightedPositions object ! meaning = this.wFLagMeaningForUndecodableGenomes; ! return meaning; ! ! } ! #endregion //Decode #region GetNewGeneValue public int GetNewGeneValue( Genome genome , int genePosition ) |
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers/WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv28011/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers/WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio Modified Files: WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio.cs Log Message: Several private members have been cleaned up, in order to reflect the constructor parameters Index: WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers/WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio/WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio.cs 13 Jun 2007 21:29:01 -0000 1.2 --- WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio.cs 24 Jun 2007 21:32:45 -0000 1.3 *************** *** 42,46 **** protected int numberOfDrivingPositions; ! protected int numberOfPortfolioPositions; protected int inSampleDays; protected string benchmark; --- 42,46 ---- protected int numberOfDrivingPositions; ! private string[] portfolioSignedTickers; protected int inSampleDays; protected string benchmark; *************** *** 52,56 **** // first in sample quote date for driving positions ! protected DateTime firstInSampleDrivingDate; // last in sample quote date for equity evaluation protected DateTime lastInSampleOptimizationDate; --- 52,56 ---- // first in sample quote date for driving positions ! protected DateTime firstInSampleDateForDrivingPositions; // last in sample quote date for equity evaluation protected DateTime lastInSampleOptimizationDate; *************** *** 68,72 **** get { ! return this.numberOfPortfolioPositions; } } --- 68,72 ---- get { ! return this.portfolioSignedTickers.Length; } } *************** *** 106,110 **** public WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio( int numberOfDrivingPositions , ! string[] portfolioPositionTickers , int inSampleDays , string benchmark , --- 106,110 ---- public WFLagGeneticFixedPortfolioWithNormalDrivingAndPortfolio( int numberOfDrivingPositions , ! string[] portfolioSignedTickers , int inSampleDays , string benchmark , *************** *** 115,119 **** { this.numberOfDrivingPositions = numberOfDrivingPositions; ! this.numberOfPortfolioPositions = portfolioPositionTickers.Length; this.inSampleDays = inSampleDays; this.benchmark = benchmark; --- 115,119 ---- { this.numberOfDrivingPositions = numberOfDrivingPositions; ! this.portfolioSignedTickers = portfolioSignedTickers; this.inSampleDays = inSampleDays; this.benchmark = benchmark; *************** *** 154,158 **** EndOfDayDateTime now ) { ! this.firstInSampleDrivingDate = now.DateTime.AddDays( -( this.NumberDaysForInSampleOptimization - 1 ) ); --- 154,158 ---- EndOfDayDateTime now ) { ! this.firstInSampleDateForDrivingPositions = now.DateTime.AddDays( -( this.NumberDaysForInSampleOptimization - 1 ) ); *************** *** 163,172 **** genomeManager = new WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio( eligibleTickersForDrivingPositions.EligibleTickers , ! eligibleTickersForDrivingPositions.EligibleTickers , ! this.firstInSampleDrivingDate , this.lastInSampleOptimizationDate , - this.numberOfDrivingPositions , - this.numberOfPortfolioPositions , this.equityEvaluator , QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator ); --- 163,171 ---- genomeManager = new WFLagGenomeManagerForFixedPortfolioWithNormalDrivingAndPortfolio( + this.numberOfDrivingPositions , eligibleTickersForDrivingPositions.EligibleTickers , ! this.portfolioSignedTickers , ! this.firstInSampleDateForDrivingPositions , this.lastInSampleOptimizationDate , this.equityEvaluator , QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator ); |
|
From: Glauco S. <gla...@us...> - 2007-06-24 21:31:17
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv27069/b7_Scripts/WalkForwardTesting/WalkForwardLag Modified Files: WeightedPositions.cs Log Message: The public static method GetBalancedWeights has been added: it returns weights balanced with respect to the close to close volatility, in the given period (the most volatile ticker is given the lighter weight) Index: WeightedPositions.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositions.cs,v retrieving revision 1.3 retrieving revision 1.4 diff -C2 -d -r1.3 -r1.4 *** WeightedPositions.cs 8 Oct 2006 16:13:54 -0000 1.3 --- WeightedPositions.cs 24 Jun 2007 21:31:05 -0000 1.4 *************** *** 24,31 **** --- 24,33 ---- using System.Collections; + using QuantProject.ADT.Statistics; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Strategies; using QuantProject.Business.Timing; + using QuantProject.Data.DataTables; namespace QuantProject.Scripts.WalkForwardTesting.WalkForwardLag *************** *** 312,315 **** --- 314,389 ---- } #endregion + #region GetBalancedWeights + private static float[][] getTickerCloseToCloseReturnsForSignedTickers( + string[] signedTickers , DateTime firstDate , DateTime lastDate ) + { + float[][] tickerReturns = new float[ signedTickers.Length ][]; + for ( int i = 0 ; i < signedTickers.Length ; i++ ) + { + string ticker = SignedTicker.GetTicker( signedTickers[ i ] ); + tickerReturns[ i ] = Quotes.GetArrayOfCloseToCloseRatios( + ticker , ref firstDate , lastDate , 1 ); + } + return tickerReturns; + } + private static double getStandardDeviation( float[] returnsForTicker ) + { + return BasicFunctions.GetStdDev( returnsForTicker ); + } + private static double[] getStandardDeviations( float[][] returnsForTickers ) + { + double[] standardDeviations = new double[ returnsForTickers.Length ]; + for ( int i = 0 ; i < standardDeviations.Length ; i++ ) + standardDeviations[ i ] = getStandardDeviation( returnsForTickers[ i ] ); + return standardDeviations; + } + private static double[] getStandardDeviations( string[] signedTickers , + DateTime firstDate , DateTime lastDate ) + { + float[][] returnsForTickers = getTickerCloseToCloseReturnsForSignedTickers( + signedTickers , firstDate , lastDate ); + return getStandardDeviations( returnsForTickers ); + } + private static double getNonNormalizedWeightsButBalancedForVolatility( + double[] standardDeviations , double maxStandardDeviation , int i ) + { + return maxStandardDeviation / standardDeviations[ i ]; + } + private static double[] getNonNormalizedWeightsButBalancedForVolatility( + double[] standardDeviations , double maxStandardDeviation ) + { + double[] nonNormalizedWeightsButBalancedForVolatility = + new double[ standardDeviations.Length ]; + for ( int i = 0 ; i < standardDeviations.Length ; i++ ) + nonNormalizedWeightsButBalancedForVolatility[ i ] = + getNonNormalizedWeightsButBalancedForVolatility( + standardDeviations , maxStandardDeviation , i ); + return nonNormalizedWeightsButBalancedForVolatility; + } + private static double[] getNonNormalizedWeightsButBalancedForVolatility( + double[] standardDeviations ) + { + double maxStandardDeviation = BasicFunctions.GetMax( standardDeviations ); + return getNonNormalizedWeightsButBalancedForVolatility( + standardDeviations , maxStandardDeviation ); + } + /// <summary> + /// Returns weights balanced with respect to the close to close volatility, + /// in the given period + /// (the most volatile ticker is given the lighter weight) + /// </summary> + /// <param name="signedTickers"></param> + /// <returns></returns> + public static double[] GetBalancedWeights( + string[] signedTickers , DateTime firstDate , DateTime lastDate ) + { + double[] standardDeviations = getStandardDeviations( signedTickers , firstDate , lastDate ); + double[] nonNormalizedButBalancedWeights = + getNonNormalizedWeightsButBalancedForVolatility( standardDeviations ); + double[] normalizedBalancedWeights = + GetNormalizedWeights( nonNormalizedButBalancedWeights ); + return normalizedBalancedWeights; + } + #endregion //GetBalancedWeights } } |
|
From: Glauco S. <gla...@us...> - 2007-06-24 21:29:05
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv25723/b4_Business/a2_Strategies Modified Files: SignedTicker.cs Log Message: GetCloseToCloseReturnsForUnsignedTicker has been added, but it is commented out (because already available in Quotes), so no real change Index: SignedTicker.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/SignedTicker.cs,v retrieving revision 1.7 retrieving revision 1.8 diff -C2 -d -r1.7 -r1.8 *** SignedTicker.cs 27 Feb 2007 22:57:20 -0000 1.7 --- SignedTicker.cs 24 Jun 2007 21:29:00 -0000 1.8 *************** *** 122,125 **** --- 122,156 ---- } + // #region GetCloseToCloseReturnsForUnsignedTicker + // /// <summary> + // /// Returns the (adjusted) close to close returns for the given unsigned ticker, + // /// starting from the firstQuoteDate and ending with the lastQuoteDate + // /// </summary> + // /// <param name="ticker"></param> + // /// <param name="firstQuoteDate"></param> + // /// <param name="lastQuoteDate"></param> + // /// <returns></returns> + // public static double GetCloseToCloseReturnsForUnsignedTicker( + // string ticker , DateTime firstQuoteDate , DateTime lastQuoteDate ) + // { + //// Quotes tickerQuotes = + //// new Quotes( ticker , firstQuoteDate , lastQuoteDate ); + //// float[] tickerAdjustedCloses = + //// QuantProject.Data.ExtendedDataTable.GetArrayOfFloatFromColumn( + //// tickerQuotes , "quAdjustedClose"); + // float[] tickerAdjustedCloses = + // Quotes.GetArrayOfCloseToCloseRatios( ticker , firstQuoteDate , lastQuoteDate , 1 ); + // float[] closeToCloseTickerReturns = + // new float[ tickerAdjustedCloses.Length - 1 ]; + // int i = 0; //index for ratesOfReturns array + // for( int idx = 0 ; idx < tickerAdjustedCloses.Length - 1 ; idx++ ) + // { + // closeToCloseTickerReturns[ i ] = + // tickerAdjustedCloses[ idx + 1 ] / tickerAdjustedCloses[ idx ] - 1; + // i++; + // } + // return closeToCloseTickerReturns; + // } + // #endregion //GetCloseToCloseReturnsForUnsignedTicker #region getCloseToClosePortfolioReturn_setReturns |
|
From: Glauco S. <gla...@us...> - 2007-06-24 21:27:19
|
Update of /cvsroot/quantproject/QuantProject/b91_QuantProject In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv25231/b91_QuantProject Modified Files: Main.cs Log Message: A global try catch statement has been removed Index: Main.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b91_QuantProject/Main.cs,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** Main.cs 6 Dec 2006 16:10:40 -0000 1.16 --- Main.cs 24 Jun 2007 21:27:16 -0000 1.17 *************** *** 33,36 **** --- 33,37 ---- using QuantProject.Scripts.SimpleTesting; using QuantProject.Scripts.WalkForwardTesting.WalkForwardOneRank; + using QuantProject.Scripts.WalkForwardTesting.WalkForwardLag; using QuantProject.Scripts.CallingReportsForRunScripts; using QuantProject.Presentation.Reporting.WindowsForm; *************** *** 372,377 **** static void Main() { ! try ! { //new RunMSFTsimpleTest().Run(); // new RunMSFTsimpleTest_2().Run(); --- 373,378 ---- static void Main() { ! // try ! // { //new RunMSFTsimpleTest().Run(); // new RunMSFTsimpleTest_2().Run(); *************** *** 404,413 **** //new RunWalkForwardOneRank().Run(); ! } ! catch ( Exception ex ) ! { ! // QuantProject.Principale.Principale.runEfficientPortfolio.SaveScriptResults(); ! writeExceptionToLogFile(ex); ! } } static private void writeExceptionToLogFile(Exception ex) --- 405,414 ---- //new RunWalkForwardOneRank().Run(); ! // } ! // catch ( Exception ex ) ! // { ! //// QuantProject.Principale.Principale.runEfficientPortfolio.SaveScriptResults(); ! // writeExceptionToLogFile(ex); ! // } } static private void writeExceptionToLogFile(Exception ex) *************** *** 456,462 **** // try // {//call here your scripts ! //new RunWalkForwardOneRank().Run(); ! new RunOneRank().Run(); //new RunEfficientCTCPorfolio("Test",400,5,90,10,10000, // "^SPX", --- 457,464 ---- // try // {//call here your scripts ! //new RunWalkForwardOneRank().Run(); ! new WFLagMain().ShowDialog(); ! // new RunOneRank().Run(); //new RunEfficientCTCPorfolio("Test",400,5,90,10,10000, // "^SPX", |
|
From: Glauco S. <gla...@us...> - 2007-06-24 21:25:59
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT/Statistics In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv24333/b1_ADT/Statistics Modified Files: BasicFunctions.cs Log Message: static public double GetMax( ICollection data ) has been added (it returns the max value of the given data collection) Index: BasicFunctions.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/Statistics/BasicFunctions.cs,v retrieving revision 1.8 retrieving revision 1.9 diff -C2 -d -r1.8 -r1.9 *** BasicFunctions.cs 30 Jul 2006 14:16:31 -0000 1.8 --- BasicFunctions.cs 24 Jun 2007 21:25:54 -0000 1.9 *************** *** 59,62 **** --- 59,89 ---- return sum; } + /// <summary> + /// Returns the max value of the given data + /// </summary> + /// <param name="data">each data item must be convertible to a double</param> + /// <returns></returns> + static public double GetMax( ICollection data ) + { + if ( data.Count < 1 ) + throw new Exception( "The data collection does not contain " + + "any value!" ); + double max = Double.MinValue; + foreach( object obj in data ) + { + double valueToBeCompared; + try + { + valueToBeCompared = Convert.ToDouble( obj ); + } + catch + { + throw new Exception( "The data collection contains " + + "a data that cannot be converted to double!" ); + } + max = Math.Max( max , valueToBeCompared ); + } + return max; + } static public double GetSum( ICollection data ) { |
|
From: Glauco S. <gla...@us...> - 2007-06-24 21:21:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv22161/b7_Scripts Modified Files: b7_Scripts.csproj Log Message: WalkForwardTesting\WalkForwardLag\WFLagMeaningForUndecodableGenomes.cs has been added WalkForwardTesting\WalkForwardLag\WeightedPositionsChoosers\WFLagGeneticWithEqualWeights\WFLagGeneticWithEqualWeights.cs has been added Index: b7_Scripts.csproj =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/b7_Scripts.csproj,v retrieving revision 1.73 retrieving revision 1.74 diff -C2 -d -r1.73 -r1.74 *** b7_Scripts.csproj 13 Jun 2007 21:32:11 -0000 1.73 --- b7_Scripts.csproj 24 Jun 2007 21:21:33 -0000 1.74 *************** *** 774,777 **** --- 774,782 ---- /> <File + RelPath = "WalkForwardTesting\WalkForwardLag\WFLagMeaningForUndecodableGenomes.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "WalkForwardTesting\WalkForwardLag\WFLagNewChosenPositionsEventArgs.cs" SubType = "Code" *************** *** 814,817 **** --- 819,827 ---- /> <File + RelPath = "WalkForwardTesting\WalkForwardLag\WeightedPositionsChoosers\WFLagGeneticWithEqualWeights\WFLagGeneticWithEqualWeights.cs" + SubType = "Code" + BuildAction = "Compile" + /> + <File RelPath = "WalkForwardTesting\WalkForwardLag\WFLagBruteForceOptimizableItemManager\WFLagBruteForceOptimizableParametersManager.cs" SubType = "Code" |
|
From: Glauco S. <gla...@us...> - 2007-06-24 21:20:15
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv21204 Added Files: WFLagMeaningForUndecodableGenomes.cs Log Message: Object used to assign a dummy meaning to those genomes that cannot be decoded to a WFLagWeightedPositions (usually for duplicated tickers) --- NEW FILE: WFLagMeaningForUndecodableGenomes.cs --- /* QuantProject - Quantitative Finance Library WFLagMeaningForUndecodableGenomes.cs Copyright (C) 2003 Glauco Siliprandi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; namespace QuantProject.Scripts.WalkForwardTesting.WalkForwardLag { /// <summary> /// Object used to assign a dummy meaning to those genomes that /// cannot be decoded to a WFLagWeightedPositions /// (usually for duplicated tickers) /// </summary> public class WFLagMeaningForUndecodableGenomes { public WFLagMeaningForUndecodableGenomes() { // // TODO: Add constructor logic here // } } } |
|
From: Glauco S. <gla...@us...> - 2007-06-24 21:11:51
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers/WFLagGeneticWithEqualWeights In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv14915 Added Files: WFLagGeneticWithEqualWeights.cs Log Message: This class implements IGenomeManager, in order to find the best driving position group and the best portfolio position group with respect to the lag strategy. It uses equal weights both within the driving positions and within the portfolio positions. --- NEW FILE: WFLagGeneticWithEqualWeights.cs --- /* QuantProject - Quantitative Finance Library WFLagGeneticWithEqualWeights.cs Copyright (C) 2003 Glauco Siliprandi This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ using System; using System.Collections; using System.Data; using QuantProject.ADT.Optimizing.Genetic; using QuantProject.ADT.Statistics; using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.EquityEvaluation; namespace QuantProject.Scripts.WalkForwardTesting.WalkForwardLag { /// <summary> /// This class implements IGenomeManager, in order to find the /// best driving position group and the best /// portfolio position group with respect to the lag strategy. /// It uses equal weights both within the driving positions and within the /// portfolio positions. /// </summary> public class WFLagGeneticWithEqualWeights : IGenomeManager { private int numberOfDrivingPositions; private int numberOfPortfolioPositions; private int numberOfEligibleTickersForDrivingWeightedPositions; protected DataTable eligibleTickersForDrivingWeightedPositions; protected DataTable eligibleTickersForPortfolioWeightedPositions; private DateTime firstOptimizationDate; private DateTime lastOptimizationDate; private double minimumPositionWeight; protected WFLagCandidates wFLagCandidates; private IEquityEvaluator equityEvaluator; private WFLagMeaningForUndecodableGenomes wFLagMeaningForUndecodableGenomes; public int GenomeSize { get { return ( this.numberOfDrivingPositions + this.numberOfPortfolioPositions ); } } /// <summary> /// This class implements IGenomeManager, in order to find the /// best driving position group and the best /// portfolio position group with respect to the lag strategy. /// Weighted positions are used for both the driving positions /// and the portfolio positions /// </summary> /// <param name="eligibleTickersForDrivingWeightedPositions">weighted positions /// for driving positions will be chosen among these tickers</param> /// <param name="eligibleTickersForPortfolioWeightedPositions">weighted positions /// for portfolio positions will be chosen among these tickers</param> /// <param name="firstOptimizationDate"></param> /// <param name="lastQuoteDate"></param> /// <param name="numberOfDrivingPositions"></param> /// <param name="numberOfTickersInPortfolio"></param> public WFLagGeneticWithEqualWeights( DataTable eligibleTickersForDrivingWeightedPositions , DataTable eligibleTickersForPortfolioWeightedPositions , DateTime firstOptimizationDate , DateTime lastOptimizationDate , int numberOfDrivingPositions , int numberOfPortfolioPositions , IEquityEvaluator equityEvaluator , int seedForRandomGenerator ) { this.numberOfDrivingPositions = numberOfDrivingPositions; this.numberOfPortfolioPositions = numberOfPortfolioPositions; this.numberOfEligibleTickersForDrivingWeightedPositions = eligibleTickersForDrivingWeightedPositions.Rows.Count; this.eligibleTickersForDrivingWeightedPositions = eligibleTickersForDrivingWeightedPositions; this.eligibleTickersForPortfolioWeightedPositions = eligibleTickersForPortfolioWeightedPositions; this.firstOptimizationDate = firstOptimizationDate; this.lastOptimizationDate = lastOptimizationDate; this.minimumPositionWeight = 0.2; // TO DO this value should become a constructor parameter this.equityEvaluator = equityEvaluator; // GenomeManagement.SetRandomGenerator( // QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator // + this.firstOptimizationDate.DayOfYear ); // GenomeManagement.SetRandomGenerator( // 11 ); GenomeManagement.SetRandomGenerator( seedForRandomGenerator ); this.wFLagCandidates = new WFLagCandidates( this.eligibleTickersForDrivingWeightedPositions , this.firstOptimizationDate , this.lastOptimizationDate ); this.wFLagMeaningForUndecodableGenomes = new WFLagMeaningForUndecodableGenomes(); } public int GetMinValueForGenes( int genePosition ) { int minValueForGene = -this.numberOfEligibleTickersForDrivingWeightedPositions; return minValueForGene; } public int GetMaxValueForGenes( int genePosition ) { return this.numberOfEligibleTickersForDrivingWeightedPositions - 1; } #region GetFitnessValue private string[] getTickers( WeightedPositions weightedPositions ) { string[] tickers = new string[ weightedPositions.Count ]; for ( int i = 0 ; i < weightedPositions.Count ; i++ ) { WeightedPosition weightedPosition = weightedPositions.GetWeightedPosition( i ); tickers[ i ] = weightedPosition.Ticker; } return tickers; } private float[] getMultipliers( WeightedPositions weightedPositions ) { float[] multipliers = new float[ weightedPositions.Count ]; for ( int i = 0 ; i < weightedPositions.Count ; i++ ) { WeightedPosition weightedPosition = weightedPositions.GetWeightedPosition( i ); multipliers[ i ] = Convert.ToSingle( weightedPosition.Weight ); } return multipliers; } private double[] getFitnessValue_getLinearCombinationReturns( WeightedPositions weightedPositions ) { // ArrayList enumeratedweightedPositions = // this.getEnumeratedWeightedPositions( weightedPositions ); int numberOfWeightedPositions = weightedPositions.Count; string[] tickers = this.getTickers( weightedPositions ); float[] multipliers = this.getMultipliers( weightedPositions ); // arrays of close to close returns, one for each signed ticker float[][] tickersReturns = this.wFLagCandidates.GetTickersReturns( tickers ); double[] linearCombinationReturns = new double[ tickersReturns[ 0 ].Length ]; for( int i = 0; i < linearCombinationReturns.Length ; i++ ) // computes linearCombinationReturns[ i ] { linearCombinationReturns[ i ] = 0; for ( int j=0 ; j < weightedPositions.Count ; j++ ) { double weightedPositionReturn = tickersReturns[ j ][ i ] * multipliers[ j ]; linearCombinationReturns[ i ] += weightedPositionReturn; } } return linearCombinationReturns; } private double[] getFitnessValue_getStrategyReturn( double[] drivingPositionsReturns , double[] portfolioPositionsReturns ) { // strategyReturns contains one element less than drivingPositionsReturns, // because there is no strategy for the very first period (at least // one day signal is needed) double[] strategyReturns = new double[ portfolioPositionsReturns.Length - 1 ]; for ( int i = 0 ; i < portfolioPositionsReturns.Length - 1 ; i++ ) if ( drivingPositionsReturns[ i ] < 0 ) // the current linear combination of tickers, at period i // has a negative return // go short tomorrow strategyReturns[ i ] = -portfolioPositionsReturns[ i + 1 ]; else // the current linear combination of tickers, at period i // has a positive return // go long tomorrow strategyReturns[ i ] = portfolioPositionsReturns[ i + 1 ]; return strategyReturns; } private double getFitnessValue( double[] strategyReturns ) { // double fitnessValue = // AdvancedFunctions.GetSharpeRatio( // strategyReturns ); // double fitnessValue = // AdvancedFunctions.GetExpectancyScore( // strategyReturns ); double fitnessValue = this.equityEvaluator.GetReturnsEvaluation( strategyReturns ); // double fitnessValue = // this.getFitnessValue_withGoodFinal( strategyReturns ); // double fitnessValue = // BasicFunctions.GetSimpleAverage( strategyReturns ) / // ( Math.Pow( BasicFunctions.GetStdDev( strategyReturns ) , 1.3 ) ); return fitnessValue; } public double GetFitnessValue( WFLagWeightedPositions wFLagWeightedPositions ) { double[] drivingPositionsReturns = this.getFitnessValue_getLinearCombinationReturns( wFLagWeightedPositions.DrivingWeightedPositions ); double[] portfolioPositionsReturns = this.getFitnessValue_getLinearCombinationReturns( wFLagWeightedPositions.PortfolioWeightedPositions ); double[] strategyReturns = this.getFitnessValue_getStrategyReturn( drivingPositionsReturns , portfolioPositionsReturns ); double fitnessValue = this.getFitnessValue( strategyReturns ); return fitnessValue; } public double GetFitnessValue( Genome genome ) { double fitnessValue; WFLagWeightedPositions wFLagWeightedPositions = ( WFLagWeightedPositions )this.Decode( genome ); int genomeLength = genome.Genes().Length; int decodedWeightedPositions = wFLagWeightedPositions.DrivingWeightedPositions.Count + wFLagWeightedPositions.PortfolioWeightedPositions.Count; if ( decodedWeightedPositions < genomeLength ) // genome contains a duplicate gene either for // driving positions or for portfolio positions //fitnessValue = double.MinValue; fitnessValue = -0.2; else // all driving positions genes are distinct and // all portfolio positions genes are distinct fitnessValue = this.GetFitnessValue( wFLagWeightedPositions ); return fitnessValue; } #endregion public Genome[] GetChilds( Genome parent1 , Genome parent2 ) { return GenomeManagement.AlternateFixedCrossover(parent1, parent2); } public void Mutate( Genome genome ) { // int newValueForGene = GenomeManagement.RandomGenerator.Next( // genome.MinValueForGenes , // genome.MaxValueForGenes + 1 ); int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next( genome.Size ); int newValueForGene = this.GetNewGeneValue( genome , genePositionToBeMutated ); GenomeManagement.MutateOneGene( genome , genePositionToBeMutated , newValueForGene ); } #region Decode private void getGenes_checkParameters( Genome genome , int firstGenePosition , int numberOfGenes ) { if ( firstGenePosition < 0 ) throw new Exception( "firstGenePosition is less than zero!" ); if ( firstGenePosition >= genome.Size ) throw new Exception( "firstGenePosition is >= than genome.Size!" ); if ( numberOfGenes <0 ) throw new Exception( "firstGenePosition is less than zero!" ); if ( firstGenePosition + numberOfGenes >= genome.Size ) throw new Exception( "firstGenePosition + numberOfGenes is >= genome.Size !!" ); } private int[] getGenes( Genome genome , int firstGenePosition , int numberOfGenes ) { getGenes_checkParameters( genome , firstGenePosition , numberOfGenes ); int[] genes = new int[ numberOfGenes ]; for ( int i = 0 ; i < this.numberOfPortfolioPositions ; i++ ) { int genePosition = firstGenePosition + i; genes[ i ] = this.getTickerIndex( genome , genePosition ); } return genes; } private int[] getTickerRelatedGeneValuesForDrivingPositions( Genome genome ) { return this.getGenes( genome , 0 , this.numberOfDrivingPositions ); } private int[] getTickerRelatedGeneValuesForPortfolioPositions( Genome genome ) { return this.getGenes( genome , this.numberOfDrivingPositions , this.numberOfPortfolioPositions ); } private void decodeTicker_checkParameters( int geneValue , DataTable eligibleTickers ) { if ( geneValue >= eligibleTickers.Rows.Count ) throw new Exception( "geneValue is too (positive) large for eligibleTickers !!" ); if ( geneValue < -eligibleTickers.Rows.Count ) throw new Exception( "geneValue is too (negative) large for eligibleTickers !!" ); } private string decodeTicker( int geneValue , DataTable eligibleTickers ) { string ticker; decodeTicker_checkParameters( geneValue , eligibleTickers ); if ( geneValue >= 0 ) // long ticker ticker = ( string )eligibleTickers.Rows[ geneValue ][ 0 ]; else // short ticker ticker = ( string )eligibleTickers.Rows[ -(geneValue+1) ][ 0 ]; return ticker; } private string[] decodeTickers( int[] tickerRelatedGeneValues , DataTable eligibleTickers ) { string[] tickers = new string[ tickerRelatedGeneValues.Length ]; for( int i = 0 ; i < tickerRelatedGeneValues.Length ; i++ ) { int currentGeneValue = tickerRelatedGeneValues[ i ]; tickers[ i ] = decodeTicker( currentGeneValue , eligibleTickers ); tickers[ i ] = ( string )eligibleTickers.Rows[ currentGeneValue ][ 0 ]; } return tickers; } private string[] getTickersForDrivingPositions( Genome genome ) { int[] geneValues = this.getTickerRelatedGeneValuesForDrivingPositions( genome ); return this.decodeTickers( geneValues , this.eligibleTickersForDrivingWeightedPositions ); } private string[] getTickersForPortfolioPositions( Genome genome ) { int[] geneValues = this.getTickerRelatedGeneValuesForPortfolioPositions( genome ); return this.decodeTickers( geneValues , this.eligibleTickersForPortfolioWeightedPositions ); } private bool isDecodable( Genome genome ) { return ( WeightedPositions.AreValidTickers( this.getTickersForDrivingPositions( genome ) ) ) && ( WeightedPositions.AreValidTickers( this.getTickersForPortfolioPositions( genome ) ) ); } // private int[] getWeightRelatedGeneValuesForDrivingPositions( // Genome genome ) // { // int[] weightRelatedGeneValuesForDrivingPositions = // new int[ this.numberOfDrivingPositions ]; // for ( int genePosition = 0 ; // genePosition < this.numberOfDrivingPositions ; genePosition++ ) // weightRelatedGeneValuesForDrivingPositions[ genePosition ] = // this.getWeight( genome , genePosition ); // return weightRelatedGeneValuesForDrivingPositions; // } private int getTickerIndex( Genome genome , int genePosition ) { int tickerIndex = genome.GetGeneValue( genePosition ); if ( tickerIndex < 0 ) // the position is short tickerIndex += -this.GetMinValueForGenes( genePosition ); return tickerIndex; } private double getWeight( Genome genome , int genePosition ) { double weight = 1; if ( genome.GetGeneValue( genePosition ) < 0 ) // the position is short weight = -1; return weight; } private double[] getWeights( Genome genome , int firstGenePosition , int numberOfGenes ) { double[] weights = new double[ numberOfGenes ]; for ( int i = 0 ; i < numberOfGenes ; i++ ) { int genePosition = firstGenePosition + i; weights[ i ] = this.getWeight( genome , genePosition ); } return weights; } private double[] getWeightsForDrivingPositions( Genome genome ) { return this.getWeights( genome , 0 , this.numberOfDrivingPositions ); } private double[] getWeightsForPortfolioPositions( Genome genome ) { return this.getWeights( genome , this.numberOfDrivingPositions , this.numberOfPortfolioPositions ); } #region decodeWeightedPositions #region getNormalizedWeightValues private double getAdditionalWeight( int weightRelatedGeneValue ) { double midrangeValue = ( this.GetMinValueForGenes( 0 ) + this.GetMaxValueForGenes( 0 ) ) / 2; double singleWeightFreeRange = 1 - this.minimumPositionWeight; double scaleRange = Convert.ToDouble( this.GetMinValueForGenes( 0 ) - this.GetMaxValueForGenes( 0 ) ); double nonScaledAdditionalWeight = Convert.ToDouble( weightRelatedGeneValue ) - midrangeValue; double scaledAdditionalWeight = nonScaledAdditionalWeight * singleWeightFreeRange / scaleRange; return scaledAdditionalWeight; } private double getNonNormalizedWeightValue( int weightRelatedGeneValue ) { double additionalWeight = this.getAdditionalWeight( weightRelatedGeneValue ); double nonNormalizedWeightValue = 0; if ( additionalWeight >= 0 ) // the gene value represents a long position nonNormalizedWeightValue = this.minimumPositionWeight + additionalWeight; else // additionalWeight < 0 , i.e. the gene value represents a short position nonNormalizedWeightValue = -this.minimumPositionWeight + additionalWeight; return nonNormalizedWeightValue; } private double[] getNonNormalizedWeightValues( int[] weightRelatedGeneValues ) { double[] nonNormalizedWeightValues = new double[ weightRelatedGeneValues.Length ]; for ( int i = 0 ; i < weightRelatedGeneValues.Length ; i++ ) nonNormalizedWeightValues[ i ] = this.getNonNormalizedWeightValue( weightRelatedGeneValues[ i ] ); return nonNormalizedWeightValues; } private double getNormalizingFactor( double[] nonNormalizedWeightValues ) { // the absolute value for each nonNormalizedWeightValue is between // this.minimumPositionWeight and 1 double totalForNonNormalizedWeightValues = BasicFunctions.SumOfAbs( nonNormalizedWeightValues ); double normalizingFactor = 1 / totalForNonNormalizedWeightValues; return normalizingFactor; } private double[] getNormalizedWeightValues( double[] nonNormalizedWeightValues , double normalizingFactor ) { return BasicFunctions.MultiplyBy( nonNormalizedWeightValues , normalizingFactor ); } private double[] getNormalizedWeights( double[] nonNormalizedWeights ) { double normalizingFactor = this.getNormalizingFactor( nonNormalizedWeights ); return getNormalizedWeightValues( nonNormalizedWeights , normalizingFactor ); } // private double[] getNormalizedWeightValues( int[] weightRelatedGeneValues ) // { // double[] nonNormalizedWeightValues = // this.getNonNormalizedWeightValues( weightRelatedGeneValues ); // return this.getNormalizedWeightValues( nonNormalizedWeightValues ); // } #endregion private WeightedPositions decodeWeightedPositions( double[] weights , string[] tickers , DataTable eligibleTickers ) { double[] normalizedWeights = this.getNormalizedWeights( weights ); WeightedPositions weightedPositions = new WeightedPositions( normalizedWeights , tickers ); return weightedPositions; } #endregion private WeightedPositions decodeDrivingWeightedPositions( Genome genome ) { double[] weightsForDrivingPositions = this.getWeightsForDrivingPositions( genome ); string[] tickersForDrivingPositions = this.getTickersForDrivingPositions( genome ); return decodeWeightedPositions( weightsForDrivingPositions , tickersForDrivingPositions , this.eligibleTickersForDrivingWeightedPositions ); } private WeightedPositions decodePortfolioWeightedPositions( Genome genome ) { double[] portfolioPositionsWeights = this.getWeightsForPortfolioPositions( genome ); string[] tickersForPortfolioPositions = this.getTickersForPortfolioPositions( genome ); return decodeWeightedPositions( portfolioPositionsWeights , tickersForPortfolioPositions , this.eligibleTickersForPortfolioWeightedPositions ); } private WFLagWeightedPositions dedcodeDecodableGenome( Genome genome ) { WeightedPositions drivingWeightedPositions = this.decodeDrivingWeightedPositions( genome ); WeightedPositions portfolioWeightedPositions = this.decodePortfolioWeightedPositions( genome ); WFLagWeightedPositions wFLagWeightedPositions = new WFLagWeightedPositions( drivingWeightedPositions , portfolioWeightedPositions ); return wFLagWeightedPositions; } /// <summary> /// A positive genome value means a long position. A negative genome value means a /// short position. /// The gene positive value n means the same ticker as the value -(n+1). /// Thus, if there are p (>0) eligible tickers, genome values should range from -p to p-1 /// </summary> /// <param name="genome"></param> /// <returns></returns> public virtual object Decode(Genome genome) { object meaning; if ( this.isDecodable( genome ) ) // genome can be decoded to a WFLagWeightedPositions object meaning = this.dedcodeDecodableGenome( genome ); else // genome cannot be decoded to a WFLagWeightedPositions object meaning = this.wFLagMeaningForUndecodableGenomes; return meaning; } #endregion //Decode #region GetNewGeneValue public int GetNewGeneValue( Genome genome , int genePosition ) { int minGeneValue = this.GetMinValueForGenes( genePosition ); int maxGeneValue = this.GetMaxValueForGenes( genePosition ); int returnValue = GenomeManagement.RandomGenerator.Next( minGeneValue , maxGeneValue + 1); return returnValue; } #endregion } } |
|
From: Glauco S. <gla...@us...> - 2007-06-24 21:10:41
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers/WFLagGeneticWithEqualWeights In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv13979/WFLagGeneticWithEqualWeights Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/WalkForwardLag/WeightedPositionsChoosers/WFLagGeneticWithEqualWeights added to the repository |
|
From: Marco M. <mi...@us...> - 2007-06-20 14:57:08
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic In directory sc8-pr-cvs16.sourceforge.net:/tmp/cvs-serv9810 Modified Files: Genome.cs Log Message: Fixed bug in get method for the Fitness property Deleted set method in Fitness property. Index: Genome.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/Optimizing/Genetic/Genome.cs,v retrieving revision 1.16 retrieving revision 1.17 diff -C2 -d -r1.16 -r1.17 *** Genome.cs 19 Jun 2007 19:18:38 -0000 1.16 --- Genome.cs 20 Jun 2007 14:56:59 -0000 1.17 *************** *** 70,80 **** if ( ! this.hasFitnessBeenAssigned ) // the genome's fitness has not been assigned yet this.fitness = this.genomeManager.GetFitnessValue(this); ! return this.fitness; ! } ! set ! { ! this.fitness = value; ! this.hasFitnessBeenAssigned = true; } } --- 70,78 ---- if ( ! this.hasFitnessBeenAssigned ) // the genome's fitness has not been assigned yet + { this.fitness = this.genomeManager.GetFitnessValue(this); ! this.hasFitnessBeenAssigned = true; ! } ! return this.fitness; } } *************** *** 86,96 **** if ( this.meaning == null ) // the genome's meaning has not been assigned yet ! this.meaning = this.genomeManager.Decode( this ); return this.meaning; } - set - { - this.meaning = value; - } } --- 84,90 ---- if ( this.meaning == null ) // the genome's meaning has not been assigned yet ! this.meaning = this.genomeManager.Decode( this ); return this.meaning; } } *************** *** 172,177 **** Genome returnValue = new Genome(this.genomeManager, this.geneticOptimizer); returnValue.CopyValuesInGenes(this.genes); ! returnValue.Fitness = this.Fitness; ! returnValue.Meaning = this.Meaning; returnValue.generation = this.Generation; returnValue.hasBeenCloned = true; --- 166,171 ---- Genome returnValue = new Genome(this.genomeManager, this.geneticOptimizer); returnValue.CopyValuesInGenes(this.genes); ! returnValue.fitness = this.fitness; ! returnValue.meaning = this.meaning; returnValue.generation = this.Generation; returnValue.hasBeenCloned = true; |