quantproject-developers Mailing List for QuantProject (Page 2)
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...> - 2011-09-22 19:42:26
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/WalkForwardTesting/LinearRegression/EntryStrategies
In directory vz-cvs-3.sog:/tmp/cvs-serv20376
Added Files:
EntryStrategyBasedOnForecastedReturnInBothDirections.cs
Log Message:
Enumerates the given testing positions, until the forecasted return is either larger than a given threshold or smaller than a negative threashold: in the former case, the straight weighted positions are returned; in the latter case, the opposite of the weighted positions are returned
--- NEW FILE: EntryStrategyBasedOnForecastedReturnInBothDirections.cs ---
/*
QuantProject - Quantitative Finance Library
EntryStrategyBasedOnForecastedReturnInBothDirections.cs
Copyright (C) 2011
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.Business.DataProviders;
using QuantProject.Business.Strategies;
using QuantProject.Business.Strategies.ReturnsManagement.Time;
namespace QuantProject.Scripts.WalkForwardTesting.LinearRegression
{
/// <summary>
/// Enumerates the given testing positions, until the forecasted return is either
/// larger than a given threshold or smaller than a negative threashold: in the
/// former case, the straight weighted positions are returned; in the latter case,
/// the opposite of the weighted positions are returned
/// </summary>
[Serializable]
public class EntryStrategyBasedOnForecastedReturnInBothDirections :
EntryStrategyBasedOnForecastedReturn
{
public EntryStrategyBasedOnForecastedReturnInBothDirections(
double minAverageExpectedReturn ,
ILinearRegressionFitnessEvaluator fitnessEvaluator ,
IReturnIntervalSelectorForSignaling returnIntervalSelectorForSignaling ,
HistoricalMarketValueProvider historicalMarketValueProvider ) :
base( minAverageExpectedReturn , fitnessEvaluator ,
returnIntervalSelectorForSignaling , historicalMarketValueProvider )
{
}
protected override WeightedPositions tryThisCandidate(
LinearRegressionTestingPositions candidate, double expectedReturn )
{
WeightedPositions weightedPositionsToBeOpened = null;
if ( expectedReturn >= this.minAverageExpectedReturn )
weightedPositionsToBeOpened = candidate.WeightedPositions;
if ( expectedReturn < -this.minAverageExpectedReturn )
weightedPositionsToBeOpened = candidate.WeightedPositions.Opposite;
return weightedPositionsToBeOpened;
}
}
}
|
|
From: Marco M. <mi...@us...> - 2011-08-27 14:06:18
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a4_Fundamentals In directory vz-cvs-3.sog:/tmp/cvs-serv13805 Removed Files: IFairValueProvider.cs Log Message: Removed old file (not even included in the project) --- IFairValueProvider.cs DELETED --- |
|
From: Marco M. <mi...@us...> - 2011-08-24 21:52:05
|
Update of /cvsroot/quantproject/QuantProject/b4_Business
In directory vz-cvs-3.sog:/tmp/cvs-serv10092/b4_Business
Modified Files:
Business_SD.csproj
Log Message:
Updated project file
Index: Business_SD.csproj
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b4_Business/Business_SD.csproj,v
retrieving revision 1.44
retrieving revision 1.45
diff -C2 -d -r1.44 -r1.45
*** Business_SD.csproj 21 Aug 2011 14:07:45 -0000 1.44
--- Business_SD.csproj 24 Aug 2011 21:52:03 -0000 1.45
***************
*** 98,101 ****
--- 98,102 ----
<Compile Include="a1_Financial\a4_Fundamentals\RatioProviders\IGrowthRateProvider.cs" />
<Compile Include="a1_Financial\a4_Fundamentals\RatioProviders\IRatioProvider_PE.cs" />
+ <Compile Include="a1_Financial\a4_Fundamentals\RatioProviders\LastAvailableBookValueGrowthRateProvider.cs" />
<Compile Include="a1_Financial\a4_Fundamentals\RatioProviders\LastAvailableGrowthRateProvider.cs" />
<Compile Include="a1_Financial\a4_Fundamentals\RatioProviders\LastAvailablePEProvider.cs" />
|
|
From: Marco M. <mi...@us...> - 2011-08-24 21:51:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider
In directory vz-cvs-3.sog:/tmp/cvs-serv10076/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider
Modified Files:
DrivenByFVProviderMain.cs
Log Message:
Updated main script file
Index: DrivenByFVProviderMain.cs
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/DrivenByFVProviderMain.cs,v
retrieving revision 1.3
retrieving revision 1.4
diff -C2 -d -r1.3 -r1.4
*** DrivenByFVProviderMain.cs 21 Aug 2011 14:21:05 -0000 1.3
--- DrivenByFVProviderMain.cs 24 Aug 2011 21:51:37 -0000 1.4
***************
*** 92,96 ****
// this.tickersGroupId = "STOCKMI";
this.temporizedGroup = true;
! this.numDaysForPortfolioVolatilityAnalysis = 90;
this.maxNumberOfEligiblesToBeChosen = 500;
// int numOfTopRowsToDelete = 500;
--- 92,96 ----
// this.tickersGroupId = "STOCKMI";
this.temporizedGroup = true;
! this.numDaysForPortfolioVolatilityAnalysis = 180;
this.maxNumberOfEligiblesToBeChosen = 500;
// int numOfTopRowsToDelete = 500;
***************
*** 141,146 ****
// new LastAvailableGrowthRateProvider(numDaysForFundamentalDataAvailability);
FundamentalDataProvider[] fundamentalDataProviders =
! new FundamentalDataProvider[1]{
new BookValueProvider(numDaysForFundamentalDataAvailability)
};
--- 141,149 ----
// new LastAvailableGrowthRateProvider(numDaysForFundamentalDataAvailability);
FundamentalDataProvider[] fundamentalDataProviders =
! new FundamentalDataProvider[2]{
new BookValueProvider(numDaysForFundamentalDataAvailability)
+ ,
+ new LastAvailablePEProvider(this.historicalMarketValueProviderForInSample,
+ numDaysForFundamentalDataAvailability)
};
|
|
From: Marco M. <mi...@us...> - 2011-08-24 21:51:04
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a4_Fundamentals/RatioProviders In directory vz-cvs-3.sog:/tmp/cvs-serv10025/b4_Business/a1_Financial/a4_Fundamentals/RatioProviders Modified Files: LastAvailablePEProvider.cs Log Message: Modified the way P/E is computed when earnings are near to 0 Index: LastAvailablePEProvider.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a4_Fundamentals/RatioProviders/LastAvailablePEProvider.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** LastAvailablePEProvider.cs 21 Aug 2011 13:05:31 -0000 1.2 --- LastAvailablePEProvider.cs 24 Aug 2011 21:51:02 -0000 1.3 *************** *** 71,74 **** --- 71,79 ---- returnValue = priceAtDate / earningsPerShareAtDate; + if(returnValue > 1000.0) + //if earnings is zero or near to zero ... + returnValue = 1000.0; + else if(returnValue < -1000.0) + returnValue = -1000.0; return returnValue; |
|
From: Marco M. <mi...@us...> - 2011-08-24 21:48:18
|
Update of /cvsroot/quantproject/QuantProject/b1_ADT
In directory vz-cvs-3.sog:/tmp/cvs-serv9867/b1_ADT
Modified Files:
ExtendedDataTable.cs
Log Message:
Fixed minor bug
Index: ExtendedDataTable.cs
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b1_ADT/ExtendedDataTable.cs,v
retrieving revision 1.14
retrieving revision 1.15
diff -C2 -d -r1.14 -r1.15
*** ExtendedDataTable.cs 21 Aug 2011 09:57:33 -0000 1.14
--- ExtendedDataTable.cs 24 Aug 2011 21:48:15 -0000 1.15
***************
*** 305,318 ****
{
int numRows = table.Rows.Count;
! string[] arrayOfString = new string[numRows];
int index = 0;
try
{
! for(; index!= numRows; index++)
{
if(index == 0)
arrayOfString[index] = getArrayOfStringFromRows_getColumnNames(table);
else
! arrayOfString[index] = getArrayOfStringFromRows_getRowValues(table, index);
}
}
--- 305,318 ----
{
int numRows = table.Rows.Count;
! string[] arrayOfString = new string[numRows + 1];
int index = 0;
try
{
! for(; index < arrayOfString.Length; index++)
{
if(index == 0)
arrayOfString[index] = getArrayOfStringFromRows_getColumnNames(table);
else
! arrayOfString[index] = getArrayOfStringFromRows_getRowValues(table, index - 1);
}
}
***************
*** 320,324 ****
{
MessageBox.Show(ex.ToString());
! index = numRows;
}
return arrayOfString;
--- 320,324 ----
{
MessageBox.Show(ex.ToString());
! index = arrayOfString.Length;
}
return arrayOfString;
|
|
From: Marco M. <mi...@us...> - 2011-08-24 21:47:44
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a1_Financial/a4_Fundamentals/RatioProviders
In directory vz-cvs-3.sog:/tmp/cvs-serv9848/b4_Business/a1_Financial/a4_Fundamentals/RatioProviders
Added Files:
LastAvailableBookValueGrowthRateProvider.cs
Log Message:
Added LastAvailableBookValueGrowthRateProvider: an alternative way of measuring growth through book value
--- NEW FILE: LastAvailableBookValueGrowthRateProvider.cs ---
/*
QuantProject - Quantitative Finance Library
LastAvailableBookValueGrowthRateProvider.cs
Copyright (C) 2011
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 QuantProject.ADT;
using QuantProject.DataAccess.Tables;
using QuantProject.Business.DataProviders;
using QuantProject.Business.Financial.Fundamentals;
using QuantProject.Business.Financial.Fundamentals.RatioProviders;
namespace QuantProject.Business.Financial.Fundamentals.RatioProviders
{
/// <summary>
/// Class implementing IGrowthRateProvider Interface
/// It provides the last available growth rate of the book value
/// </summary>
[Serializable]
public class LastAvailableBookValueGrowthRateProvider :
FundamentalDataProvider,
IGrowthRateProvider
{
public LastAvailableBookValueGrowthRateProvider( int daysForAvailabilityOfData ) :
base( daysForAvailabilityOfData )
{
}
public double GetGrowthRate( string ticker , DateTime atDate )
{
double returnValue;
double lastBookValue;
double previousBookValue;
DateTime limitDateForEndingPeriodDate =
atDate.AddDays(- this.daysForAvailabilityOfData);
DataTable tableOfBookValues =
FinancialValues.GetLastFinancialValuesForTicker(
ticker, FinancialValueType.BookValuePerShare, 12, limitDateForEndingPeriodDate);
string[] tableForDebugging =
ExtendedDataTable.GetArrayOfStringFromRows(tableOfBookValues);
int numOfRows = tableOfBookValues.Rows.Count;
previousBookValue = (double)tableOfBookValues.Rows[numOfRows - 2]["fvValue"];
lastBookValue = (double)tableOfBookValues.Rows[numOfRows - 1]["fvValue"];
returnValue = (lastBookValue - previousBookValue)/previousBookValue;
return returnValue;
}
public override double GetValue( string ticker , DateTime atDate )
{
return this.GetGrowthRate(ticker, atDate);
}
}
}
|
|
From: Marco M. <mi...@us...> - 2011-08-21 14:30:23
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts
In directory vz-cvs-3.sog:/tmp/cvs-serv21952
Modified Files:
Scripts_SD.csproj
Log Message:
Updated Script project file
Index: Scripts_SD.csproj
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/Scripts_SD.csproj,v
retrieving revision 1.47
retrieving revision 1.48
diff -C2 -d -r1.47 -r1.48
*** Scripts_SD.csproj 3 Aug 2011 22:27:02 -0000 1.47
--- Scripts_SD.csproj 21 Aug 2011 14:30:21 -0000 1.48
***************
*** 51,54 ****
--- 51,55 ----
<Compile Include="General\BasicScriptForBacktesting.cs" />
<Compile Include="General\Logging\AnalyzableLogItem.cs" />
+ <Compile Include="General\Logging\BuyAndHoldTesterForTestingPositions.cs" />
<Compile Include="General\Logging\LogArchiver.cs" />
<Compile Include="General\Logging\LogViewer.cs" />
***************
*** 112,115 ****
--- 113,117 ----
<Compile Include="TechnicalAnalysisTesting\Oscillators\FixedLevelOscillators\PortfolioValueOscillator\WeightedPVO\WeightedBalancedPVO\GenomeManagerWeightedBalancedPVO.cs" />
<Compile Include="TechnicalAnalysisTesting\Oscillators\FixedLevelOscillators\PortfolioValueOscillator\WeightedPVO\WeightedBalancedPVO\RunWeightedBalancedPVO.cs" />
+ <Compile Include="TickerSelectionTesting\DrivenByFundamentals\DrivenByFairValueProvider\Decoding\DecoderForFVProviderStrategy.cs" />
<Compile Include="TickerSelectionTesting\DrivenByFundamentals\DrivenByFairValueProvider\DrivenByFVProviderLogItem.cs" />
<Compile Include="TickerSelectionTesting\DrivenByFundamentals\DrivenByFairValueProvider\DrivenByFVProviderMain.cs" />
***************
*** 117,125 ****
--- 119,132 ----
<Compile Include="TickerSelectionTesting\DrivenByFundamentals\DrivenByFairValueProvider\InSampleChoosers\Genetic\DrivenByFVProviderInSampleChooser.cs" />
<Compile Include="TickerSelectionTesting\DrivenByFundamentals\DrivenByFairValueProvider\InSampleChoosers\Genetic\GenomeManagerForDrivenByFVProvider.cs" />
+ <Compile Include="TickerSelectionTesting\DrivenByFundamentals\DrivenByFairValueProvider\InSampleChoosers\SelectTopBottomEligiblesWithSignInSampleChooser.cs" />
<Compile Include="TickerSelectionTesting\DrivenBySharpeRatio\DrivenBySharpeRatioLogItem.cs" />
<Compile Include="TickerSelectionTesting\DrivenBySharpeRatio\DrivenBySharpeRatioMain.cs" />
<Compile Include="TickerSelectionTesting\DrivenBySharpeRatio\DrivenBySharpeRatioStrategy.cs" />
+ <Compile Include="TickerSelectionTesting\DrivenBySharpeRatio\InSampleChoosers\BruteForce\DrivenBySharpeRatioBruteForceChooser.cs" />
+ <Compile Include="TickerSelectionTesting\DrivenBySharpeRatio\InSampleChoosers\BruteForce\DrivenBySharpeROptimizableParametersManager.cs" />
<Compile Include="TickerSelectionTesting\DrivenBySharpeRatio\InSampleChoosers\Genetic\DrivenBySharpeRatioInSampleChooser.cs" />
+ <Compile Include="TickerSelectionTesting\DrivenBySharpeRatio\InSampleChoosers\Genetic\DrivenBySharpeRatioInSampleChooserWithWeights.cs" />
<Compile Include="TickerSelectionTesting\DrivenBySharpeRatio\InSampleChoosers\Genetic\GenomeManagerForDrivenBySharpeRatio.cs" />
+ <Compile Include="TickerSelectionTesting\DrivenBySharpeRatio\InSampleChoosers\Genetic\GenomeManagerForDrivenBySharpeRatioWithWeights.cs" />
<Compile Include="TickerSelectionTesting\EndOfDayTimerHandlerCTC.cs" />
<Compile Include="TickerSelectionTesting\EndOfDayTimerHandlerCTO.cs" />
***************
*** 374,381 ****
--- 381,390 ----
<Folder Include="TickerSelectionTesting\DrivenByFundamentals" />
<Folder Include="TickerSelectionTesting\DrivenByFundamentals\DrivenByFairValueProvider" />
+ <Folder Include="TickerSelectionTesting\DrivenByFundamentals\DrivenByFairValueProvider\Decoding" />
<Folder Include="TickerSelectionTesting\DrivenByFundamentals\DrivenByFairValueProvider\InSampleChoosers" />
<Folder Include="TickerSelectionTesting\DrivenByFundamentals\DrivenByFairValueProvider\InSampleChoosers\Genetic" />
<Folder Include="TickerSelectionTesting\DrivenBySharpeRatio" />
<Folder Include="TickerSelectionTesting\DrivenBySharpeRatio\InSampleChoosers" />
+ <Folder Include="TickerSelectionTesting\DrivenBySharpeRatio\InSampleChoosers\BruteForce" />
<Folder Include="TickerSelectionTesting\DrivenBySharpeRatio\InSampleChoosers\Genetic" />
<Folder Include="TickerSelectionTesting\OTC" />
|
|
From: Marco M. <mi...@us...> - 2011-08-21 14:29:49
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/InSampleChoosers
In directory vz-cvs-3.sog:/tmp/cvs-serv21921/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/InSampleChoosers
Added Files:
SelectTopBottomEligiblesWithSignInSampleChooser.cs
Log Message:
Added SelectTopBottomEligiblesWithSignInSampleChooser, for the driven by fair value provider strategy
--- NEW FILE: SelectTopBottomEligiblesWithSignInSampleChooser.cs ---
/*
QuantProject - Quantitative Finance Library
SelectTopBottomEligiblesWithSignInSampleChooser.cs
Copyright (C) 2011
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 QuantProject.ADT;
using QuantProject.ADT.Messaging;
using QuantProject.Business.DataProviders;
using QuantProject.Business.Strategies;
using QuantProject.Business.Strategies.Eligibles;
using QuantProject.Business.Strategies.InSample;
using QuantProject.Business.Strategies.OutOfSample;
using QuantProject.Business.Strategies.ReturnsManagement;
using QuantProject.Business.Timing;
namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider.InSampleChoosers
{
/// <summary>
/// Select TestingPositions half from top eligible tickers,
/// and half from bottom eligibles, without doing anything but
/// distinguishing between tickers which have to
/// be sell-shorted (from bottom) or bought (from top) according to a
/// strategy based on a fundamental fair value
/// provider
/// </summary>
[Serializable]
public class SelectTopBottomEligiblesWithSignInSampleChooser : IInSampleChooser
{
public event NewMessageEventHandler NewMessage;
public event NewProgressEventHandler NewProgress;
protected int maxNumOfTestingPositionsToBeReturned;
protected int numOfTickersInEachTestingPosition;
protected HistoricalMarketValueProvider historicalMarketValueProvider;
protected Timer timer;
public string Description
{
get{ return "TopBottomEligiblesInSampleChooser"; }
}
public SelectTopBottomEligiblesWithSignInSampleChooser(int numOfTickersInEachTestingPosition,
int maxNumOfTestingPositionsToBeReturned,
HistoricalMarketValueProvider historicalMarketValueProvider,
Timer timer)
{
if(numOfTickersInEachTestingPosition %2 != 0 )
throw new Exception("numOfTickersInEachTestingPositions must be even!");
this.numOfTickersInEachTestingPosition =
numOfTickersInEachTestingPosition;
this.maxNumOfTestingPositionsToBeReturned =
maxNumOfTestingPositionsToBeReturned;
this.historicalMarketValueProvider = historicalMarketValueProvider;
this.timer = timer;
}
protected string[] analyzeInSample_getTestingPositionsArray_getAlternatedTickers_getTop(EligibleTickers eligibleTickers)
{
string[] returnValue = new string[eligibleTickers.Count];
int idx = 0;
DataTable tableOfEligibleTickers = eligibleTickers.SourceDataTable;
double relativeDiffBetweenFairAndMarket;
for( int i = 0; i < returnValue.Length; i++ )
{
relativeDiffBetweenFairAndMarket =
(double)tableOfEligibleTickers.Rows[i]["RelativeDifferenceBetweenFairAndMarketPrice"];
if(relativeDiffBetweenFairAndMarket >= 0)
{
returnValue[idx] = eligibleTickers.Tickers[i];
idx++;
}
}
return returnValue;
}
protected string[] analyzeInSample_getTestingPositionsArray_getAlternatedTickers_getBottom(EligibleTickers eligibleTickers)
{
string[] returnValue = new string[eligibleTickers.Count];
int idxBottom = 0;
DataTable tableOfEligibleTickers = eligibleTickers.SourceDataTable;
int lastIdxOfEligibles = eligibleTickers.Count - 1;
double relativeDiffBetweenFairAndMarket;
for( int i = 0; i < returnValue.Length; i++ )
{
relativeDiffBetweenFairAndMarket =
(double)tableOfEligibleTickers.Rows[lastIdxOfEligibles - i]["RelativeDifferenceBetweenFairAndMarketPrice"];
if(relativeDiffBetweenFairAndMarket < 0)
{
returnValue[idxBottom] = "-" + eligibleTickers.Tickers[lastIdxOfEligibles - i];
idxBottom++;
}
}
return returnValue;
}
protected string[] analyzeInSample_getTestingPositionsArray_getAlternatedTickers(EligibleTickers eligibleTickers)
{
string[] returnValue = new string[eligibleTickers.Count];
string[] topTickers = new string[eligibleTickers.Count];
string[] bottomTickers = new string[eligibleTickers.Count];
//creare due liste: top e bottom da cui recuperare i ticker
topTickers =
analyzeInSample_getTestingPositionsArray_getAlternatedTickers_getTop(eligibleTickers);
bottomTickers =
analyzeInSample_getTestingPositionsArray_getAlternatedTickers_getBottom(eligibleTickers);
int idxTop = 0;
int idxBottom = 0;
for(int i = 0; i < returnValue.Length; i++)
{
if(i%2 == 0)
//at even position, a top ticker ( a bottom if top is null )
{
if(topTickers[idxTop] != null)
{
returnValue[i] = topTickers[idxTop];
idxTop++;
}
else if(bottomTickers[idxBottom] != null)
{
returnValue[i] = bottomTickers[idxBottom];
idxBottom++;
}
}
else
//at odd, a bottom ( a top, if bottom is null )
{
if(bottomTickers[idxBottom] != null)
{
returnValue[i] = bottomTickers[idxBottom];
idxBottom++;
}
else if (topTickers[idxTop] != null)
{
returnValue[i] = topTickers[idxTop];
idxTop++;
}
}
}
return returnValue;
}
#region analyzeInSample_getTestingPositionsArray_getTheoreticalProfit
private double analyzeInSample_getTestingPositionsArray_getTheoreticalProfit_getFairPrice(WeightedPosition position,
EligibleTickers eligibleTickers)
{
double returnValue;
object[] keys = new object[1];
keys[0] = position.Ticker;
DataRow foundRow =
eligibleTickers.SourceDataTable.Rows.Find(keys);
returnValue = (double)foundRow["FairPrice"];
return returnValue;
}
private double analyzeInSample_getTestingPositionsArray_getTheoreticalProfit_getBuyPrice(WeightedPosition position,
EligibleTickers eligibleTickers)
{
double returnValue;
returnValue =
this.historicalMarketValueProvider.GetMarketValue(position.Ticker,
this.timer.GetCurrentDateTime() );
return returnValue;
}
protected double analyzeInSample_getTestingPositionsArray_getTheoreticalProfit(WeightedPositions weightedPositions,
EligibleTickers eligibleTickers)
{
double returnValue = 0.0;
double marketPriceOfCurrentPosition;
double fairPriceOfCurrentPosition;
double weightOfCurrentPosition;
try{
foreach( WeightedPosition position in weightedPositions )
{
marketPriceOfCurrentPosition = this.analyzeInSample_getTestingPositionsArray_getTheoreticalProfit_getBuyPrice(position, eligibleTickers);
fairPriceOfCurrentPosition = this.analyzeInSample_getTestingPositionsArray_getTheoreticalProfit_getFairPrice(position, eligibleTickers);
weightOfCurrentPosition = position.Weight;
returnValue +=
weightOfCurrentPosition*(fairPriceOfCurrentPosition-marketPriceOfCurrentPosition)/
marketPriceOfCurrentPosition;
}
}
catch(Exception ex)
{
string s = ex.ToString();
}
return returnValue;
}
#endregion analyzeInSample_getTestingPositionsArray_getTheoreticalProfit
protected GeneticallyOptimizableTestingPositions[] analyzeInSample_getTestingPositionsArray(EligibleTickers eligibleTickers)
{
if( eligibleTickers.Count <
(this.maxNumOfTestingPositionsToBeReturned *
this.numOfTickersInEachTestingPosition) )
throw new Exception("Not enough eligibles !");
GeneticallyOptimizableTestingPositions[] returnValue =
new GeneticallyOptimizableTestingPositions[ this.maxNumOfTestingPositionsToBeReturned ];
int idxEligible = 0;
string[] signedTickers = new string[numOfTickersInEachTestingPosition];
string[] eligibleTickersAlternatedTopAndBottom =
analyzeInSample_getTestingPositionsArray_getAlternatedTickers(eligibleTickers);
WeightedPositions chosenWeightedPositions;
for ( int i = 0; i < returnValue.Length ; i++)
{
for ( int j = 0;
idxEligible < eligibleTickersAlternatedTopAndBottom.Length && j < numOfTickersInEachTestingPosition;
j++ )
{
signedTickers[j] = eligibleTickersAlternatedTopAndBottom[idxEligible + j];
}
chosenWeightedPositions = new WeightedPositions(new SignedTickers(signedTickers));
returnValue[i] =
new GeneticallyOptimizableTestingPositions(chosenWeightedPositions);
returnValue[i].FitnessInSample =
this.analyzeInSample_getTestingPositionsArray_getTheoreticalProfit(chosenWeightedPositions, eligibleTickers);
idxEligible = idxEligible + numOfTickersInEachTestingPosition;
}
return returnValue;
}
public object AnalyzeInSample( EligibleTickers eligibleTickers ,
ReturnsManager returnsManager )
{
if ( this.NewMessage != null )
this.NewMessage( this , new NewMessageEventArgs( "New" ) );
if ( this.NewProgress != null )
this.NewProgress( this , new NewProgressEventArgs( 1 , 1 ) );
GeneticallyOptimizableTestingPositions[] returnValue =
this.analyzeInSample_getTestingPositionsArray(eligibleTickers);
return returnValue;
}
}
}
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/InSampleChoosers/Genetic
In directory vz-cvs-3.sog:/tmp/cvs-serv21838/InSampleChoosers/Genetic
Added Files:
DrivenBySharpeRatioInSampleChooserWithWeights.cs
GenomeManagerForDrivenBySharpeRatioWithWeights.cs
Log Message:
Added script files for the driven by SharpeRatio strategy
--- NEW FILE: DrivenBySharpeRatioInSampleChooserWithWeights.cs ---
/*
QuantProject - Quantitative Finance Library
DrivenBySharpeRatioInSampleChooserWithWeights.cs
Copyright (C) 2011
Marco Milletti
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
using System;
using QuantProject.ADT.Optimizing.Genetic;
using QuantProject.Business.Strategies;
using QuantProject.Business.DataProviders;
using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation;
using QuantProject.Business.Strategies.Optimizing.Decoding;
using QuantProject.Business.Strategies.Eligibles;
using QuantProject.Business.Strategies.InSample;
using QuantProject.Business.Strategies.ReturnsManagement;
using QuantProject.Business.Strategies.OutOfSample;
using QuantProject.Business.Strategies.Optimizing.GenomeManagers;
using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios;
namespace QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio.InSampleChoosers.Genetic
{
/// <summary>
/// In sample genetic analyzer for the
/// Driven by Sharpe Ratio strategy using weights
/// </summary>
[Serializable]
public class DrivenBySharpeRatioInSampleChooserWithWeights : GeneticChooser
{
protected GenomeManagerType genomeManagerType;
protected bool keepOnRunningUntilConvergenceHasReached;
protected double minConvergenceRate;
public DrivenBySharpeRatioInSampleChooserWithWeights(
int numberOfPortfolioPositions , int numberOfBestTestingPositionsToBeReturned ,
Benchmark benchmark ,
IDecoderForTestingPositions decoderForTestingPositions ,
GenomeManagerType genomeManagerType ,
IFitnessEvaluator fitnessEvaluator ,
HistoricalMarketValueProvider historicalMarketValueProvider ,
double crossoverRate , double mutationRate , double elitismRate ,
int populationSizeForGeneticOptimizer ,
int generationNumberForGeneticOptimizer ,
int seedForRandomGenerator,
bool keepOnRunningUntilConvergenceHasReached,
double minConvergenceRate)
:
base(numberOfPortfolioPositions, numberOfBestTestingPositionsToBeReturned,
benchmark , decoderForTestingPositions ,
fitnessEvaluator , historicalMarketValueProvider ,
crossoverRate , mutationRate , elitismRate ,
populationSizeForGeneticOptimizer ,
generationNumberForGeneticOptimizer ,
seedForRandomGenerator )
{
this.genomeManagerType = genomeManagerType;
this.keepOnRunningUntilConvergenceHasReached =
keepOnRunningUntilConvergenceHasReached;
this.minConvergenceRate = minConvergenceRate;
}
protected override string getHashCodeForGenome(QuantProject.ADT.Optimizing.Genetic.Genome genome)
{
string returnValue = ((TestingPositions)genome.Meaning).HashCodeForTickerComposition;
return returnValue;
}
public override IGenomeManager GetGenomeManager(EligibleTickers eligibleTickers ,
ReturnsManager returnsManager)
{
return new GenomeManagerForDrivenBySharpeRatioWithWeights(eligibleTickers, this.numberOfPortfolioPositions,
this.decoderForTestingPositions, this.fitnessEvaluator,
this.genomeManagerType , returnsManager,
this.seedForRandomGeneratorForTheGeneticOptimizer);
}
}
}
--- NEW FILE: GenomeManagerForDrivenBySharpeRatioWithWeights.cs ---
/*
QuantProject - Quantitative Finance Library
GenomeManagerForDrivenBySharpeRatioWithWeights.cs
Copyright (C) 2011
Marco Milletti
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
using System;
using System.Data;
using System.Collections;
using QuantProject.ADT;
using QuantProject.ADT.Statistics;
using QuantProject.ADT.Optimizing.Genetic;
using QuantProject.Data;
using QuantProject.Data.DataTables;
using QuantProject.Business.DataProviders;
using QuantProject.Business.Timing;
using QuantProject.Business.Strategies;
using QuantProject.Business.Strategies.ReturnsManagement;
using QuantProject.Business.Strategies.ReturnsManagement.Time;
using QuantProject.Business.Strategies.TickersRelationships;
using QuantProject.Business.Strategies.Eligibles;
using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation;
using QuantProject.Business.Strategies.Optimizing.Decoding;
using QuantProject.Business.Strategies.Optimizing.GenomeManagers;
using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios;
namespace QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio.InSampleChoosers.Genetic
{
/// <summary>
/// Implements a simple GenomeManager for finding
/// the portfolio with the highest Sharpe Ratio
/// </summary>
[Serializable]
public class GenomeManagerForDrivenBySharpeRatioWithWeights : GenomeManagerForDrivenBySharpeRatio
{
public GenomeManagerForDrivenBySharpeRatioWithWeights(EligibleTickers eligibleTickers,
int numberOfTickersInPortfolio,
IDecoderForTestingPositions decoderForTestingPositions,
IFitnessEvaluator fitnessEvaluator,
GenomeManagerType genomeManagerType,
ReturnsManager returnsManager,
int seedForRandomGenerator)
:
base(eligibleTickers,
numberOfTickersInPortfolio,
decoderForTestingPositions,
fitnessEvaluator,
genomeManagerType,
returnsManager,
seedForRandomGenerator)
{
this.genomeSize = 2 * this.genomeSize;
}
public override int GetMinValueForGenes(int genePosition)
{
int returnValue = this.minValueForGenes;
//default value for genes mapping tickers
if(genePosition %2 == 0)
//the gene maps weights
returnValue = 10;
return returnValue;
}
public override int GetMaxValueForGenes(int genePosition)
{
int returnValue = this.maxValueForGenes;
//default value for genes mapping tickers
if(genePosition %2 == 0)
//the gene maps weights
returnValue = 100;
return returnValue;
}
public override Genome[] GetChilds(Genome parent1, Genome parent2)
{
return GenomeManagement.OnePointCrossover(parent1, parent2);
}
public override int GetNewGeneValue(Genome genome, int genePosition)
{
//The optimization has to be run only on weights, for this genome manager
//The number of tickers in eligibles is equal to the
//number of genes dedicated to tickers
int returnValue;
if( genePosition %2 == 0 )
//gene position is even, so it contains a weight
returnValue = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePosition),
genome.GetMaxValueForGenes(genePosition)+1);
else
//gene position is odd, so it contains a ticker code
//which is fixed in this implementation
returnValue = (genePosition - 1) / 2;
return returnValue;
}
public override void Mutate(Genome genome)
{
// in this implementation only one gene, corresponding to
// a weight, has to be mutated
int genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size);
int newValueForGene;
while( genePositionToBeMutated %2 != 0 )
//the genePosition doesn't point to a weight
{
genePositionToBeMutated = GenomeManagement.RandomGenerator.Next(genome.Size);
}
newValueForGene = GenomeManagement.RandomGenerator.Next(genome.GetMinValueForGenes(genePositionToBeMutated),
genome.GetMaxValueForGenes(genePositionToBeMutated) + 1);
GenomeManagement.MutateOneGene(genome, genePositionToBeMutated, newValueForGene);
}
}
}
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/InSampleChoosers/BruteForce
In directory vz-cvs-3.sog:/tmp/cvs-serv21790/InSampleChoosers/BruteForce
Added Files:
DrivenBySharpeRatioBruteForceChooser.cs
DrivenBySharpeROptimizableParametersManager.cs
Log Message:
Added script files for BruteForce optimization
--- NEW FILE: DrivenBySharpeRatioBruteForceChooser.cs ---
/*
QuantProject - Quantitative Finance Library
DrivenBySharpeRatioBruteForceChooser.cs
Copyright (C) 2011
Marco Milletti
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
using System;
using QuantProject.ADT.Optimizing.Genetic;
using QuantProject.ADT.Optimizing.BruteForce;
using QuantProject.Business.Strategies;
using QuantProject.Business.DataProviders;
using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation;
using QuantProject.Business.Strategies.Optimizing.Decoding;
using QuantProject.Business.Strategies.Eligibles;
using QuantProject.Business.Strategies.InSample;
using QuantProject.Business.Strategies.ReturnsManagement;
using QuantProject.Business.Strategies.OutOfSample;
using QuantProject.Business.Strategies.Optimizing.GenomeManagers;
using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios;
namespace QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio.InSampleChoosers.BruteForce
{
/// <summary>
/// brute force IInSampleChooser with End Of Day data for the strategy
/// driven by SharpeRatio
/// </summary>
[Serializable]
public class DrivenBySharpeRatioBruteForceChooser : BruteForceChooser
{
private int numberOfPortfolioPositions;
private PortfolioType portfolioType;
public DrivenBySharpeRatioBruteForceChooser( PortfolioType portfolioType,
int numberOfPortfolioPositions , int numberOfBestTestingPositionsToBeReturned ,
Benchmark benchmark ,
IDecoderForTestingPositions decoderForTestingPositions ,
IFitnessEvaluator fitnessEvaluator ,
HistoricalMarketValueProvider historicalMarketValueProvider) :
base (
numberOfBestTestingPositionsToBeReturned ,
decoderForTestingPositions ,
fitnessEvaluator )
{
this.portfolioType = portfolioType;
this.numberOfPortfolioPositions = numberOfPortfolioPositions;
}
protected override IBruteForceOptimizableParametersManager
getBruteForceOptimizableParametersManager(
EligibleTickers eligibleTickers ,
ReturnsManager returnsManager )
{
IBruteForceOptimizableParametersManager parametersManager;
parametersManager = new DrivenBySharpeROptimizableParametersManager(
eligibleTickers ,
this.numberOfPortfolioPositions ,
this.decoderForTestingPositions ,
this.fitnessEvaluator ,
returnsManager );
return parametersManager;
}
}
}
--- NEW FILE: DrivenBySharpeROptimizableParametersManager.cs ---
/*
QuantProject - Quantitative Finance Library
DrivenBySharpeROptimizableParametersManager.cs
Copyright (C) 2011
Marco Milletti
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
using System;
using QuantProject.ADT.Optimizing.BruteForce;
using QuantProject.ADT.Statistics.Combinatorial;
using QuantProject.Business.Strategies.Eligibles;
using QuantProject.Business.Strategies.Optimizing.BruteForce;
using QuantProject.Business.Strategies.Optimizing.Decoding;
using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation;
using QuantProject.Business.Strategies.OutOfSample;
using QuantProject.Business.Strategies.ReturnsManagement;
using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios;
namespace QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio.InSampleChoosers.BruteForce
{
/// <summary>
/// BruteForceOptimizableParametersManager to be used by the
/// driven by sharpe ratio strategy.
/// </summary>
[Serializable]
public class DrivenBySharpeROptimizableParametersManager :
CombinationBasedBruteForceOptimizableParametersManager
{
private EligibleTickers eligibleTickers;
private int numberOfPositions;
private IDecoderForTestingPositions decoderForTestingPositions;
private IFitnessEvaluator fitnessEvaluator;
private ReturnsManager returnsManager;
public DrivenBySharpeROptimizableParametersManager(
EligibleTickers eligibleTickers ,
int numberOfPositions ,
IDecoderForTestingPositions decoderForTestingPositions ,
IFitnessEvaluator fitnessEvaluator ,
ReturnsManager returnsManager ) :
base( new Combination(
0 , eligibleTickers.Count - 1 ,
numberOfPositions ) )
{
this.eligibleTickers = eligibleTickers;
this.numberOfPositions = numberOfPositions;
this.decoderForTestingPositions = decoderForTestingPositions;
this.fitnessEvaluator = fitnessEvaluator;
this.returnsManager = returnsManager;
}
public override object Decode( BruteForceOptimizableParameters
bruteForceOptimizableParameters )
{
return this.decoderForTestingPositions.Decode(
bruteForceOptimizableParameters.GetValues() ,
this.eligibleTickers ,
this.returnsManager );
}
public override double GetFitnessValue(
BruteForceOptimizableParameters bruteForceOptimizableParameters )
{
object meaning = this.Decode(
bruteForceOptimizableParameters );
double fitnessValue =
this.fitnessEvaluator.GetFitnessValue( meaning , this.returnsManager );
return fitnessValue;
}
#region AreEquivalentAsTopBestParameters
private void areEquivalentAsTopBestParameters_checkParameters(
BruteForceOptimizableParameters bruteForceOptimizableParameters1 ,
BruteForceOptimizableParameters bruteForceOptimizableParameters2 )
{
if ( !(bruteForceOptimizableParameters1.Meaning is TestingPositions) )
throw new Exception( "The first parameter is expected " +
"to represent a TestingPositions!" );
if ( !(bruteForceOptimizableParameters2.Meaning is TestingPositions) )
throw new Exception( "The second parameter is expected " +
"to represent a TestingPositions!" );
}
public override bool AreEquivalentAsTopBestParameters(
BruteForceOptimizableParameters bruteForceOptimizableParameters1 ,
BruteForceOptimizableParameters bruteForceOptimizableParameters2 )
{
this.areEquivalentAsTopBestParameters_checkParameters(
bruteForceOptimizableParameters1 , bruteForceOptimizableParameters2 );
bool areEquivalentAsTopBestParameters =
((TestingPositions)bruteForceOptimizableParameters1.Meaning ).HashCode ==
((TestingPositions)bruteForceOptimizableParameters2.Meaning ).HashCode;
return areEquivalentAsTopBestParameters;
}
#endregion AreEquivalentAsTopBestParameters
}
}
|
|
From: Marco M. <mi...@us...> - 2011-08-21 14:24:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/InSampleChoosers/BruteForce In directory vz-cvs-3.sog:/tmp/cvs-serv21741/BruteForce Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/InSampleChoosers/BruteForce added to the repository |
|
From: Marco M. <mi...@us...> - 2011-08-21 14:23:23
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/InSampleChoosers/Genetic
In directory vz-cvs-3.sog:/tmp/cvs-serv21699/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/InSampleChoosers/Genetic
Modified Files:
GenomeManagerForDrivenByFVProvider.cs
Log Message:
Updated script files
Index: GenomeManagerForDrivenByFVProvider.cs
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/InSampleChoosers/Genetic/GenomeManagerForDrivenByFVProvider.cs,v
retrieving revision 1.1
retrieving revision 1.2
diff -C2 -d -r1.1 -r1.2
*** GenomeManagerForDrivenByFVProvider.cs 17 Jan 2011 23:02:37 -0000 1.1
--- GenomeManagerForDrivenByFVProvider.cs 21 Aug 2011 14:23:21 -0000 1.2
***************
*** 89,92 ****
--- 89,97 ----
this.mixPastReturnsEvaluationWithFundamentalEvaluation =
mixPastReturnsEvaluationWithFundamentalEvaluation;
+ //the range is the same as if it was OnlyLong:
+ //the sign of tickers depend on the fair value level
+ //with respect to the market price
+ this.minValueForGenes = 0;
+ this.maxValueForGenes = this.eligibleTickers.Count - 1;
}
***************
*** 96,102 ****
{
double returnValue;
! returnValue =
! this.historicalMarketValueProvider.GetMarketValue(position.Ticker,
! this.timer.GetCurrentDateTime() );
return returnValue;
}
--- 101,110 ----
{
double returnValue;
! object[] keys = new object[1];
! keys[0] = position.Ticker;
! DataRow foundRow =
! this.eligibleTickers.SourceDataTable.Rows.Find(keys);
! returnValue = (double)foundRow["AverageMarketPrice"];
!
return returnValue;
}
|
|
From: Marco M. <mi...@us...> - 2011-08-21 14:22:34
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/InSampleChoosers/Genetic
In directory vz-cvs-3.sog:/tmp/cvs-serv21649/TickerSelectionTesting/DrivenBySharpeRatio/InSampleChoosers/Genetic
Modified Files:
DrivenBySharpeRatioInSampleChooser.cs
Log Message:
Updated script files
Index: DrivenBySharpeRatioInSampleChooser.cs
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/InSampleChoosers/Genetic/DrivenBySharpeRatioInSampleChooser.cs,v
retrieving revision 1.1
retrieving revision 1.2
diff -C2 -d -r1.1 -r1.2
*** DrivenBySharpeRatioInSampleChooser.cs 16 Jan 2011 19:37:32 -0000 1.1
--- DrivenBySharpeRatioInSampleChooser.cs 21 Aug 2011 14:22:32 -0000 1.2
***************
*** 46,49 ****
--- 46,51 ----
{
protected GenomeManagerType genomeManagerType;
+ protected bool keepOnRunningUntilConvergenceHasReached;
+ protected double minConvergenceRate;
public DrivenBySharpeRatioInSampleChooser(
***************
*** 57,61 ****
int populationSizeForGeneticOptimizer ,
int generationNumberForGeneticOptimizer ,
! int seedForRandomGenerator)
:
base(numberOfPortfolioPositions, numberOfBestTestingPositionsToBeReturned,
--- 59,65 ----
int populationSizeForGeneticOptimizer ,
int generationNumberForGeneticOptimizer ,
! int seedForRandomGenerator,
! bool keepOnRunningUntilConvergenceHasReached,
! double minConvergenceRate)
:
base(numberOfPortfolioPositions, numberOfBestTestingPositionsToBeReturned,
***************
*** 68,73 ****
{
this.genomeManagerType = genomeManagerType;
}
!
protected override string getHashCodeForGenome(QuantProject.ADT.Optimizing.Genetic.Genome genome)
{
--- 72,80 ----
{
this.genomeManagerType = genomeManagerType;
+ this.keepOnRunningUntilConvergenceHasReached =
+ keepOnRunningUntilConvergenceHasReached;
+ this.minConvergenceRate = minConvergenceRate;
}
!
protected override string getHashCodeForGenome(QuantProject.ADT.Optimizing.Genetic.Genome genome)
{
***************
*** 84,87 ****
--- 91,110 ----
this.seedForRandomGeneratorForTheGeneticOptimizer);
}
+
+ // public DrivenBySharpeRatioInSampleChooser GetCopy(int numOfPortfolioPositions , int numOfBestTestingPositionsToBeReturned ,
+ // IDecoderForTestingPositions decoder, int populationSizeForGO,
+ // int generationNumberForGO)
+ // {
+ // DrivenBySharpeRatioInSampleChooser returnValue =
+ // new DrivenBySharpeRatioInSampleChooser(numOfPortfolioPositions,
+ // numOfBestTestingPositionsToBeReturned, this.benchmark,
+ // decoder, this.genomeManagerType, fitnessEvaluator,
+ // this.historicalMarketValueProvider, this.crossoverRate, this.mutationRate,
+ // this.elitismRate, populationSizeForGO, generationNumberForGO,
+ // this.seedForRandomGeneratorForTheGeneticOptimizer, this.keepOnRunningUntilConvergenceHasReached,
+ // this.minConvergenceRate);
+ //
+ // return returnValue;
+ // }
}
}
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio
In directory vz-cvs-3.sog:/tmp/cvs-serv21636/TickerSelectionTesting/DrivenBySharpeRatio
Modified Files:
DrivenBySharpeRatioLogItem.cs DrivenBySharpeRatioMain.cs
DrivenBySharpeRatioStrategy.cs
Log Message:
Updated script files
Index: DrivenBySharpeRatioStrategy.cs
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/DrivenBySharpeRatioStrategy.cs,v
retrieving revision 1.1
retrieving revision 1.2
diff -C2 -d -r1.1 -r1.2
*** DrivenBySharpeRatioStrategy.cs 16 Jan 2011 19:37:08 -0000 1.1
--- DrivenBySharpeRatioStrategy.cs 21 Aug 2011 14:22:07 -0000 1.2
***************
*** 47,50 ****
--- 47,52 ----
using QuantProject.Business.Strategies.Eligibles;
using QuantProject.Business.Strategies.Optimizing.Decoding;
+ using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation;
+ using QuantProject.Business.Strategies.Optimizing.GenomeManagers;
using QuantProject.Data;
using QuantProject.Data.DataProviders;
***************
*** 52,59 ****
using QuantProject.Data.DataTables;
using QuantProject.ADT.Optimizing.Genetic;
! using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.InSampleChoosers;
! using QuantProject.Scripts.TickerSelectionTesting.OTC;
using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios;
- using QuantProject.Scripts.WalkForwardTesting.LinearCombination;
namespace QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio
--- 54,59 ----
using QuantProject.Data.DataTables;
using QuantProject.ADT.Optimizing.Genetic;
! using QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio.InSampleChoosers.Genetic;
using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios;
namespace QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio
***************
*** 103,106 ****
--- 103,111 ----
protected double stopLoss;
protected double takeProfit;
+ protected string hedgingTicker;
+ protected double hedgingTickerWeight;
+ protected int popSizeForGeneticHedgingOptimization;
+ protected int genNumForGeneticHedgingOptimization;
+ protected IFitnessEvaluator fitnessEvaluatorForGeneticHedgingOptimization;
private string description_GetDescriptionForChooser()
***************
*** 155,164 ****
int minNumOfEligiblesForValidOptimization, IInSampleChooser inSampleChooser ,
int inSamplePeriodLengthInDays ,
! Benchmark benchmark , int numDaysBetweenEachOptimization ,
HistoricalMarketValueProvider historicalMarketValueProviderForInSample ,
HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample ,
PortfolioType portfolioType, double stopLoss,
double takeProfit)
{
this.drivenBySharpeRatioStrategy_commonInitialization(eligiblesSelector ,
minNumOfEligiblesForValidOptimization, inSampleChooser ,
--- 160,177 ----
int minNumOfEligiblesForValidOptimization, IInSampleChooser inSampleChooser ,
int inSamplePeriodLengthInDays ,
! Benchmark benchmark , string hedgingTicker , double hedgingTickerWeight,
! int numDaysBetweenEachOptimization ,
HistoricalMarketValueProvider historicalMarketValueProviderForInSample ,
HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample ,
+ int popSizeForGeneticHedgingOptimization, int genNumForGeneticHedgingOptimization,
+ IFitnessEvaluator fitnessEvaluatorForGeneticHedgingOptimization,
PortfolioType portfolioType, double stopLoss,
double takeProfit)
{
+ this.hedgingTicker = hedgingTicker;
+ this.hedgingTickerWeight = hedgingTickerWeight;
+ this.popSizeForGeneticHedgingOptimization = popSizeForGeneticHedgingOptimization;
+ this.genNumForGeneticHedgingOptimization = genNumForGeneticHedgingOptimization;
+ this.fitnessEvaluatorForGeneticHedgingOptimization = fitnessEvaluatorForGeneticHedgingOptimization;
this.drivenBySharpeRatioStrategy_commonInitialization(eligiblesSelector ,
minNumOfEligiblesForValidOptimization, inSampleChooser ,
***************
*** 215,223 ****
{
DateTime currentDateTime = this.now();
! if( allTickersAreExchanged( currentDateTime, AccountManager.GetTickersInOpenedPositions(this.account) ) )
! {
! AccountManager.ClosePositions( this.account );
! this.lastEntryTime = new DateTime(1900,1,1);
! }
}
#endregion newDateTimeEventHandler_closePositions
--- 228,236 ----
{
DateTime currentDateTime = this.now();
! // if( allTickersAreExchanged( currentDateTime, AccountManager.GetTickersInOpenedPositions(this.account) ) )
! // {
! AccountManager.ClosePositions( this.account );
! this.lastEntryTime = new DateTime(1900,1,1);
! // }
}
#endregion newDateTimeEventHandler_closePositions
***************
*** 321,325 ****
#region UpdateTestingPositions
!
protected void updateTestingPositions(DateTime currentDateTime)
{
--- 334,408 ----
#region UpdateTestingPositions
!
! #region updateTestingPositions_getPositionsHedgedOrNot
! protected EligibleTickers updateTestingPositions_getPositionsHedgedOrNot_getHedgedPositions_getEligibles(TestingPositions[] positionsToHedge)
! {
! EligibleTickers returnValue;
! ICollection<string> tickersNotHedged = new List<string>();
! foreach(WeightedPosition weightedPosition in positionsToHedge[0].WeightedPositions)
! tickersNotHedged.Add(weightedPosition.Ticker);
! returnValue = new EligibleTickers(tickersNotHedged);
! returnValue.AddAdditionalTicker(this.hedgingTicker);
!
! return returnValue;
! }
! protected IInSampleChooser updateTestingPositions_getPositionsHedgedOrNot_getChooserForHedgedPositions(int numOfPositionsToHedge)
! {
! IInSampleChooser returnValue;
! IDecoderForTestingPositions decoderWithWeights =
! new BasicDecoderForTestingPositionsWithWeights();
! returnValue =
! new DrivenBySharpeRatioInSampleChooserWithWeights(numOfPositionsToHedge + 1, 10 ,
! this.benchmark, decoderWithWeights, GenomeManagerType.OnlyLong, this.fitnessEvaluatorForGeneticHedgingOptimization,
! this.historicalMarketValueProviderForInSample, 0.90, 0.10, 0.001,
! this.popSizeForGeneticHedgingOptimization,
! this.genNumForGeneticHedgingOptimization, 30, false, 0.9);
!
! return returnValue;
! }
! private void updateTestingPositions_getPositionsHedgedOrNot_getHedgedPositions_setWeights(TestingPositions[] returnValue)
! {
! int numOfPositions = returnValue[0].WeightedPositions.Count;
! for(int i = 0; i < numOfPositions; i++)
! {
! if( returnValue[0].WeightedPositions[i].Ticker == this.hedgingTicker )
! returnValue[0].WeightedPositions[i].Weight = this.hedgingTickerWeight;
! else
! returnValue[0].WeightedPositions[i].Weight =
! (1.0-this.hedgingTickerWeight)/(numOfPositions - 1);
! }
! }
!
! protected TestingPositions[] updateTestingPositions_getPositionsHedgedOrNot_getHedgedPositions()
! {
! TestingPositions[] returnValue;
! TestingPositions[] positionsNotHedged =
! (TestingPositions[])inSampleChooser.AnalyzeInSample(this.currentEligibles, this.returnsManager);
! EligibleTickers chosenTickersWithHedgingTicker =
! this.updateTestingPositions_getPositionsHedgedOrNot_getHedgedPositions_getEligibles(positionsNotHedged);
! //set new insample chooser, with a decoder with weights
! IInSampleChooser chooserForHedgedPositions =
! this.updateTestingPositions_getPositionsHedgedOrNot_getChooserForHedgedPositions(positionsNotHedged[0].WeightedPositions.Count);
! returnValue =
! (TestingPositions[])chooserForHedgedPositions.AnalyzeInSample(chosenTickersWithHedgingTicker, this.returnsManager);
! //hedgingTickerWeight is directly determined
! // the other positions are given their weight consequently
! if(this.hedgingTickerWeight != 0.0)
! this.updateTestingPositions_getPositionsHedgedOrNot_getHedgedPositions_setWeights(returnValue);
! return returnValue;
! }
!
! protected TestingPositions[] updateTestingPositions_getPositionsHedgedOrNot()
! {
! TestingPositions[] returnValue;
! if(this.hedgingTicker == null)
! returnValue = (TestingPositions[])inSampleChooser.AnalyzeInSample(this.currentEligibles, this.returnsManager);
! else
! returnValue = this.updateTestingPositions_getPositionsHedgedOrNot_getHedgedPositions();
!
! return returnValue;
! }
! #endregion updateTestingPositions_getPositionsHedgedOrNot
!
protected void updateTestingPositions(DateTime currentDateTime)
{
***************
*** 342,346 ****
this.inSampleChooser != null ) )
{
! this.chosenPositions = (TestingPositions[])inSampleChooser.AnalyzeInSample(this.currentEligibles, this.returnsManager);
this.logOptimizationInfo(this.currentEligibles);
}
--- 425,429 ----
this.inSampleChooser != null ) )
{
! this.chosenPositions = this.updateTestingPositions_getPositionsHedgedOrNot();
this.logOptimizationInfo(this.currentEligibles);
}
***************
*** 395,399 ****
DrivenBySharpeRatioLogItem logItem =
new DrivenBySharpeRatioLogItem( this.now(),
! this.inSamplePeriodLengthInDays);
logItem.BestPositionsInSample =
this.chosenPositions;
--- 478,484 ----
DrivenBySharpeRatioLogItem logItem =
new DrivenBySharpeRatioLogItem( this.now(),
! this.inSamplePeriodLengthInDays,
! this.benchmark,
! this.historicalMarketValueProviderForInSample);
logItem.BestPositionsInSample =
this.chosenPositions;
Index: DrivenBySharpeRatioMain.cs
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/DrivenBySharpeRatioMain.cs,v
retrieving revision 1.1
retrieving revision 1.2
diff -C2 -d -r1.1 -r1.2
*** DrivenBySharpeRatioMain.cs 16 Jan 2011 19:37:08 -0000 1.1
--- DrivenBySharpeRatioMain.cs 21 Aug 2011 14:22:07 -0000 1.2
***************
*** 31,34 ****
--- 31,35 ----
using QuantProject.ADT.Timing;
using QuantProject.Business.DataProviders;
+ using QuantProject.Business.DataProviders.VirtualQuotesProviding;
//using QuantProject.Data.DataProviders.Bars.Caching;
using QuantProject.Business.Strategies;
***************
*** 53,56 ****
--- 54,58 ----
using QuantProject.Scripts.General.Strategies.Optimizing.FitnessEvaluation;
using QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio.InSampleChoosers.Genetic;
+ using QuantProject.Scripts.TickerSelectionTesting.DrivenBySharpeRatio.InSampleChoosers.BruteForce;
using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios;
//using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers.Genetic;
***************
*** 75,78 ****
--- 77,81 ----
private DateTime firstDateTime;
private DateTime lastDateTime;
+ private int numDaysBetweenEachOptimization;
private HistoricalMarketValueProvider historicalMarketValueProviderForInSample;
private HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample;
***************
*** 80,99 ****
private Timer timerForBackTester;
private GenomeManagerType genomeManagerType;
#region main
public DrivenBySharpeRatioMain()
{
! this.numberOfPortfolioPositions = 4;
! this.benchmark = new Benchmark( "^MIBTEL" );
! // this.benchmark = new Benchmark( "^GSPC" );
! this.portfolioType = PortfolioType.OnlyLong;//filter for out of sample
! this.genomeManagerType = GenomeManagerType.OnlyLong;//filter for the genetic chooser
// this.benchmark = new Benchmark( "ENI.MI" );
! this.firstDateTime = new DateTime( 2001 , 1 , 1 );
! this.lastDateTime = new DateTime( 2005 , 12 , 31 );
this.historicalMarketValueProviderForInSample =
// new HistoricalRawQuoteProvider();
new HistoricalAdjustedQuoteProvider();
this.historicalMarketValueProviderForOutOfSample =
this.historicalMarketValueProviderForInSample;
--- 83,120 ----
private Timer timerForBackTester;
private GenomeManagerType genomeManagerType;
+ private string hedgingTicker;
#region main
public DrivenBySharpeRatioMain()
{
! this.numberOfPortfolioPositions = 6;
! // this.benchmark = new Benchmark( "FTSEMIB.MI" );
! this.benchmark = new Benchmark( "^GSPC" );
! // this.hedgingTicker = "SH(FTSEMIB)";
! this.hedgingTicker = null;
! this.portfolioType = PortfolioType.ShortAndLong;//filter for out of sample
! this.genomeManagerType = GenomeManagerType.ShortAndLong;//filter for the genetic chooser
// this.benchmark = new Benchmark( "ENI.MI" );
! this.firstDateTime = new DateTime( 2003 , 1 , 1 );
! this.lastDateTime = new DateTime( 2009 , 12 , 31 );
! this.numDaysBetweenEachOptimization = 180;
+ HistoricalAdjustedQuoteProvider historicalAdjustedQuoteProvider =
+ new HistoricalAdjustedQuoteProvider();
+ List<DerivedVirtualTicker> virtualTickerList =
+ new List<DerivedVirtualTicker>();
+ DerivedVirtualTicker virtualTicker1 =
+ new DerivedVirtualTicker(this.hedgingTicker, this.benchmark.Ticker, 100);
+ virtualTickerList.Add(virtualTicker1);
+ ShortVirtualQuoteProvider shortVirtualQuoteProvider =
+ // new ShortVirtualQuoteProvider(virtualTickerList, historicalAdjustedQuoteProvider,
+ // 2 * this.numDaysBetweenEachOptimization);
+ new ShortVirtualQuoteProvider(virtualTickerList, historicalAdjustedQuoteProvider,
+ new DateTime(2003,6,1,16,0,0) );
this.historicalMarketValueProviderForInSample =
// new HistoricalRawQuoteProvider();
new HistoricalAdjustedQuoteProvider();
+ // new VirtualAndHistoricalAdjustedQuoteProvider(shortVirtualQuoteProvider);
+
this.historicalMarketValueProviderForOutOfSample =
this.historicalMarketValueProviderForInSample;
***************
*** 117,134 ****
protected override IEligiblesSelector getEligiblesSelector()
{
! this.maxNumberOfEligiblesToBeChosen = 200;
! // string tickersGroupId = "ticUSFin";
// string tickersGroupId = "USFunds";
// string tickersGroupId = "SP500";
! string tickersGroupId = "STOCKMI";
bool temporizedGroup = false;//Attenzione!
IEligiblesSelector eligiblesSelector =
// new ByGroup( tickersGroupId , temporizedGroup);
! new ByLiquidity ( tickersGroupId , temporizedGroup ,
! maxNumberOfEligiblesToBeChosen);
! // eligiblesSelector =
// new DummyEligibleSelector();
//
--- 138,199 ----
protected override IEligiblesSelector getEligiblesSelector()
{
! this.maxNumberOfEligiblesToBeChosen = 1000;
! string tickersGroupId = "ticUSFin";
// string tickersGroupId = "USFunds";
// string tickersGroupId = "SP500";
! // string tickersGroupId = "BLUECHIX";
! // string tickersGroupId = "ETFMI";
bool temporizedGroup = false;//Attenzione!
+ // by most discounted prices parameters
+ int numDaysForFundamentalDataAvailability = 60;
+ // int numDaysForFundamentalAnalysis = 365;
+ // double optimalDebtEquityRatioLevel = 0.1;
+ // int maxNumOfGrowthRatesToTakeIntoAccount = 4;
+ IGrowthRateProvider growthProvider =
+ // new AverageAndDebtAdjustedGrowthRateProvider(numDaysForFundamentalDataAvailability,
+ // maxNumOfGrowthRatesToTakeIntoAccount,
+ // optimalDebtEquityRatioLevel);
+ new LastAvailableGrowthRateProvider(numDaysForFundamentalDataAvailability);
+
+ IRatioProvider_PE PEProvider =
+ new LastAvailablePEProvider(this.historicalMarketValueProviderForInSample,
+ numDaysForFundamentalDataAvailability);
+ double fairPEGRatioLevel = 1.0;
+ IFairValueProvider fairValueProvider =
+ new PEGRatioFairValueProvider(fairPEGRatioLevel,PEProvider,
+ growthProvider,this.historicalMarketValueProviderForInSample);
+ // double minimumIncome = 1000000;
+ // int numOfMinIncomeInARow = 2;
+ // double minimumRelativeDifferenceBetweenFairAndAverageMarketPrice = 0.05;
+ // int numDaysForAveragePriceComputation = 90;
+
+ //end of by most discounted prices parameters
IEligiblesSelector eligiblesSelector =
// new ByGroup( tickersGroupId , temporizedGroup);
! // new ByLiquidity ( tickersGroupId , temporizedGroup ,
! // maxNumberOfEligiblesToBeChosen);
!
! new ByPriceMostLiquidAlwaysQuoted(tickersGroupId,
! temporizedGroup, maxNumberOfEligiblesToBeChosen,
! 6, 1.0, 5000.0);
!
! // new ByPriceLiquidityLowestPEQuotedAtAGivenPercentage(
! // tickersGroupId , temporizedGroup ,
! // maxNumberOfEligiblesToBeChosen ,
! // maxNumberOfEligiblesToBeChosen * 2,
! // numDaysForAveragePriceComputation,
! // 1, 1000, 10, 50, 0.9);
! // new ByMostDiscountedPrices( fairValueProvider ,
! // tickersGroupId , temporizedGroup ,
! // maxNumberOfEligiblesToBeChosen , numDaysForFundamentalAnalysis,
! // numDaysForFundamentalDataAvailability,
! // minimumIncome, numOfMinIncomeInARow,
! // minimumRelativeDifferenceBetweenFairAndAverageMarketPrice,
! // numDaysForAveragePriceComputation);
!
! // eligiblesSelector =
// new DummyEligibleSelector();
//
***************
*** 140,152 ****
protected override IInSampleChooser getInSampleChooser()
{
! int numberOfBestTestingPositionsToBeReturned = 5;
// parameters for the genetic optimizer
! double crossoverRate = 0.85;
! double mutationRate = 0.02;
! double elitismRate = 0.001;
! int populationSizeForGeneticOptimizer = 25000;
! int generationNumberForGeneticOptimizer = 25;
int seedForRandomGenerator =
QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator;
BuyAndHoldFitnessEvaluator fitnessEvaluator =
--- 205,219 ----
protected override IInSampleChooser getInSampleChooser()
{
! int numberOfBestTestingPositionsToBeReturned = 10;
// parameters for the genetic optimizer
! double crossoverRate = 0.99;
! double mutationRate = 0.1;
! double elitismRate = 0.0;
! int populationSizeForGeneticOptimizer = 20000;
! int generationNumberForGeneticOptimizer = 35;
int seedForRandomGenerator =
QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator;
+ bool keepOnRunningUntilConvergence = false;
+ double minConvergenceRate = 0.50;
BuyAndHoldFitnessEvaluator fitnessEvaluator =
***************
*** 163,167 ****
crossoverRate, mutationRate, elitismRate ,
populationSizeForGeneticOptimizer, generationNumberForGeneticOptimizer,
! seedForRandomGenerator);
return inSampleChooser;
--- 230,239 ----
crossoverRate, mutationRate, elitismRate ,
populationSizeForGeneticOptimizer, generationNumberForGeneticOptimizer,
! seedForRandomGenerator, keepOnRunningUntilConvergence,
! minConvergenceRate);
! // new DrivenBySharpeRatioBruteForceChooser(PortfolioType.OnlyLong,
! // this.numberOfPortfolioPositions, numberOfBestTestingPositionsToBeReturned,
! // this.benchmark, basicGenOptDecoder, fitnessEvaluator,
! // this.historicalMarketValueProviderForInSample);
return inSampleChooser;
***************
*** 172,177 ****
protected override IStrategyForBacktester getStrategyForBacktester()
{
! int numDaysBetweenEachOptimization = 60;
! int minNumOfEligiblesForValidOptimization = 15;
IStrategyForBacktester strategyForBacktester
--- 244,255 ----
protected override IStrategyForBacktester getStrategyForBacktester()
{
! // ConstantsProvider.AmountOfVariableWeightToBeAssignedToTickers = 0.5;
! int minNumOfEligiblesForValidOptimization = 10;
! int popSizeForGeneticHedgingOptimization = 10;
! int genNumForGeneticHedgingOptimization = 1;
! double weightForHedgingTicker = 0.40; //set 0.0 if you want
! //this weight be set by the genetic optimizer
! IFitnessEvaluator fitnessEvaluatorForGeneticHedgingOptimization =
! new BuyAndHoldFitnessEvaluator( new SharpeRatio() );
IStrategyForBacktester strategyForBacktester
***************
*** 179,185 ****
minNumOfEligiblesForValidOptimization, inSampleChooser ,
numDaysForInSample ,
! benchmark , numDaysBetweenEachOptimization ,
historicalMarketValueProviderForInSample ,
historicalMarketValueProviderForOutOfSample ,
this.portfolioType, this.stopLoss,
this.takeProfit);
--- 257,266 ----
minNumOfEligiblesForValidOptimization, inSampleChooser ,
numDaysForInSample ,
! benchmark , this.hedgingTicker, weightForHedgingTicker, numDaysBetweenEachOptimization ,
historicalMarketValueProviderForInSample ,
historicalMarketValueProviderForOutOfSample ,
+ popSizeForGeneticHedgingOptimization,
+ genNumForGeneticHedgingOptimization,
+ fitnessEvaluatorForGeneticHedgingOptimization,
this.portfolioType, this.stopLoss,
this.takeProfit);
Index: DrivenBySharpeRatioLogItem.cs
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenBySharpeRatio/DrivenBySharpeRatioLogItem.cs,v
retrieving revision 1.1
retrieving revision 1.2
diff -C2 -d -r1.1 -r1.2
*** DrivenBySharpeRatioLogItem.cs 16 Jan 2011 19:37:08 -0000 1.1
--- DrivenBySharpeRatioLogItem.cs 21 Aug 2011 14:22:07 -0000 1.2
***************
*** 52,57 ****
public class DrivenBySharpeRatioLogItem : LogItem
{
! protected DummyTesterForTestingPositions[]
! dummyTestersForBestTestingPositionsInSample;
protected TestingPositions[] bestPositionsInSample;
protected int numberOfEligibleTickers;
--- 52,57 ----
public class DrivenBySharpeRatioLogItem : LogItem
{
! protected BuyAndHoldTesterForTestingPositions[]
! buyAndHoldTestersForBestTestingPositionsInSample;
protected TestingPositions[] bestPositionsInSample;
protected int numberOfEligibleTickers;
***************
*** 60,63 ****
--- 60,65 ----
protected string tickers;
protected int inSamplePeriodLengthInDays;
+ protected Benchmark benchmark;
+ protected HistoricalMarketValueProvider historicalMarketValueProvider;
public TestingPositions[] BestPositionsInSample
***************
*** 108,112 ****
}
public DrivenBySharpeRatioLogItem(DateTime dateTime,
! int inSamplePeriodLengthInDays)
: base( dateTime )
{
--- 110,116 ----
}
public DrivenBySharpeRatioLogItem(DateTime dateTime,
! int inSamplePeriodLengthInDays,
! Benchmark benchmark,
! HistoricalMarketValueProvider historicalMarketValueProvider)
: base( dateTime )
{
***************
*** 114,129 ****
this.numberOfEligibleTickers = int.MinValue;
this.fitness = double.MinValue;
}
! #region runStrategyClickEventHandler
! protected virtual void runStrategyClickEventHandler(object sender, System.EventArgs e)
{
! // ;
! //general
DateTime firstDateTime = this.SimulatedCreationDateTime.AddDays(-this.inSamplePeriodLengthInDays);
DateTime lastDateTime = this.SimulatedCreationDateTime;
double maxRunningHours = 1;
- Benchmark benchmark = new Benchmark( "^GSPC" );
int numberOfPortfolioPositions = this.bestPositionsInSample[0].WeightedPositions.Count;
//cash and portfolio type
--- 118,218 ----
this.numberOfEligibleTickers = int.MinValue;
this.fitness = double.MinValue;
+ this.benchmark = benchmark;
+ this.historicalMarketValueProvider = historicalMarketValueProvider;
}
! #region runStrategyClickEventHandlerOnlyInSample
! protected virtual void runStrategyClickEventHandlerOnlyInSample(object sender, System.EventArgs e)
{
! DateTime firstDateTime = this.SimulatedCreationDateTime.AddDays(-this.inSamplePeriodLengthInDays);
! DateTime lastDateTime = this.SimulatedCreationDateTime;
! double maxRunningHours = 1;
! int numberOfPortfolioPositions = this.bestPositionsInSample[0].WeightedPositions.Count;
! //cash and portfolio type
! double cashToStart = 10000;
! HistoricalMarketValueProvider historicalQuoteProviderForBackTester,
! historicalQuoteProviderForInSampleChooser,
! historicalQuoteProviderForStrategy;
! historicalQuoteProviderForBackTester = this.historicalMarketValueProvider;
! historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester;
! historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser;
! //strategyParameters
! TestingPositions[] positionsToTest = this.BestPositionsInSample;
! DrivenBySharpeRatioStrategy strategy =
! new DrivenBySharpeRatioStrategy(positionsToTest,
! this.inSamplePeriodLengthInDays, this.benchmark,
! historicalQuoteProviderForBackTester,
! PortfolioType.OnlyLong);
!
! QuantProject.Business.Timing.Timer timer =
! new IndexBasedEndOfDayTimer( firstDateTime,
! lastDateTime,
! this.benchmark.Ticker);
!
! EndOfDayStrategyBackTester endOfDayStrategyBackTester =
! new EndOfDayStrategyBackTester(
! "BuyAndHold" , timer , strategy,
! historicalQuoteProviderForBackTester ,
! new SimpleAccountProvider(), firstDateTime ,
! lastDateTime ,
! this.benchmark , cashToStart , maxRunningHours );
!
! endOfDayStrategyBackTester.Run();
! BackTesterReportViewer.ShowReport( lastDateTime ,
! endOfDayStrategyBackTester );
! }
! #endregion runStrategyClickEventHandlerOnlyInSample
!
! #region runStrategyClickEventHandlerOnlyOutOfSample
! protected virtual void runStrategyClickEventHandlerOnlyOutOfSample(object sender, System.EventArgs e)
! {
! DateTime firstDateTime = this.SimulatedCreationDateTime;
! DateTime lastDateTime = this.SimulatedCreationDateTime.AddDays(this.inSamplePeriodLengthInDays);
! double maxRunningHours = 1;
! int numberOfPortfolioPositions = this.bestPositionsInSample[0].WeightedPositions.Count;
! //cash and portfolio type
! double cashToStart = 10000;
! HistoricalMarketValueProvider historicalQuoteProviderForBackTester,
! historicalQuoteProviderForInSampleChooser,
! historicalQuoteProviderForStrategy;
! historicalQuoteProviderForBackTester = this.historicalMarketValueProvider;
! historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester;
! historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser;
! //strategyParameters
! TestingPositions[] positionsToTest = this.BestPositionsInSample;
!
! DrivenBySharpeRatioStrategy strategy =
! new DrivenBySharpeRatioStrategy(positionsToTest,
! this.inSamplePeriodLengthInDays, this.benchmark,
! historicalQuoteProviderForBackTester,
! PortfolioType.OnlyLong);
!
! QuantProject.Business.Timing.Timer timer =
! new IndexBasedEndOfDayTimer( firstDateTime,
! lastDateTime,
! this.benchmark.Ticker);
!
! EndOfDayStrategyBackTester endOfDayStrategyBackTester =
! new EndOfDayStrategyBackTester(
! "BuyAndHold" , timer , strategy,
! historicalQuoteProviderForBackTester ,
! new SimpleAccountProvider(), firstDateTime ,
! lastDateTime ,
! this.benchmark , cashToStart , maxRunningHours );
!
! endOfDayStrategyBackTester.Run();
! BackTesterReportViewer.ShowReport( lastDateTime ,
! endOfDayStrategyBackTester );
!
! }
! #endregion runStrategyClickEventHandlerOnlyOutOfSample
!
! #region runStrategyClickEventHandlerInAndOutOfSample
! protected virtual void runStrategyClickEventHandlerInAndOutOfSample(object sender, System.EventArgs e)
! {
DateTime firstDateTime = this.SimulatedCreationDateTime.AddDays(-this.inSamplePeriodLengthInDays);
DateTime lastDateTime = this.SimulatedCreationDateTime;
double maxRunningHours = 1;
int numberOfPortfolioPositions = this.bestPositionsInSample[0].WeightedPositions.Count;
//cash and portfolio type
***************
*** 132,136 ****
historicalQuoteProviderForInSampleChooser,
historicalQuoteProviderForStrategy;
! historicalQuoteProviderForBackTester = new HistoricalAdjustedQuoteProvider();
historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester;
historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser;
--- 221,225 ----
historicalQuoteProviderForInSampleChooser,
historicalQuoteProviderForStrategy;
! historicalQuoteProviderForBackTester = this.historicalMarketValueProvider;
historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester;
historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser;
***************
*** 140,144 ****
DrivenBySharpeRatioStrategy strategy =
new DrivenBySharpeRatioStrategy(positionsToTest,
! this.inSamplePeriodLengthInDays, benchmark,
historicalQuoteProviderForBackTester,
PortfolioType.OnlyLong);
--- 229,233 ----
DrivenBySharpeRatioStrategy strategy =
new DrivenBySharpeRatioStrategy(positionsToTest,
! this.inSamplePeriodLengthInDays, this.benchmark,
historicalQuoteProviderForBackTester,
PortfolioType.OnlyLong);
***************
*** 147,151 ****
new IndexBasedEndOfDayTimer( firstDateTime,
lastDateTime.AddDays(this.inSamplePeriodLengthInDays),
! benchmark.Ticker);
EndOfDayStrategyBackTester endOfDayStrategyBackTester =
--- 236,240 ----
new IndexBasedEndOfDayTimer( firstDateTime,
lastDateTime.AddDays(this.inSamplePeriodLengthInDays),
! this.benchmark.Ticker);
EndOfDayStrategyBackTester endOfDayStrategyBackTester =
***************
*** 155,159 ****
new SimpleAccountProvider(), firstDateTime ,
lastDateTime.AddDays(this.inSamplePeriodLengthInDays) ,
! benchmark , cashToStart , maxRunningHours );
endOfDayStrategyBackTester.Run();
--- 244,248 ----
new SimpleAccountProvider(), firstDateTime ,
lastDateTime.AddDays(this.inSamplePeriodLengthInDays) ,
! this.benchmark , cashToStart , maxRunningHours );
endOfDayStrategyBackTester.Run();
***************
*** 162,185 ****
}
! #endregion runStrategyClickEventHandler
! private void showTestingPositionsClickEventHandler_setDummyTesters_setTester(
int currentIndex ,
TestingPositions testingPositions ,
DateTime simulatedCreationDateTime )
{
! this.dummyTestersForBestTestingPositionsInSample[ currentIndex ] =
! new DummyTesterForTestingPositions(
! testingPositions ,
this.inSamplePeriodLengthInDays ,
simulatedCreationDateTime );
}
! private void showTestingPositionsClickEventHandler_setDummyTesters()
{
! this.dummyTestersForBestTestingPositionsInSample =
! new DummyTesterForTestingPositions[this.BestPositionsInSample.Length];
! for ( int i = 0 ; i < BestPositionsInSample.Length; i++ )
! this.showTestingPositionsClickEventHandler_setDummyTesters_setTester(
i ,
BestPositionsInSample[ i ] ,
--- 251,276 ----
}
! #endregion runStrategyClickEventHandlerInAndOutOfSample
! private void showTestingPositionsClickEventHandler_setTesters_setTester(
int currentIndex ,
TestingPositions testingPositions ,
DateTime simulatedCreationDateTime )
{
! this.buyAndHoldTestersForBestTestingPositionsInSample[ currentIndex ] =
! new BuyAndHoldTesterForTestingPositions(this.historicalMarketValueProvider,
! this.benchmark, testingPositions ,
this.inSamplePeriodLengthInDays ,
simulatedCreationDateTime );
}
! private void showTestingPositionsClickEventHandler_setTesters()
{
! this.buyAndHoldTestersForBestTestingPositionsInSample =
! new BuyAndHoldTesterForTestingPositions[this.BestPositionsInSample.Length];
! for ( int i = 0 ;
! i < BestPositionsInSample.Length && this.BestPositionsInSample[ i ] != null;
! i++ )
! this.showTestingPositionsClickEventHandler_setTesters_setTester(
i ,
BestPositionsInSample[ i ] ,
***************
*** 189,196 ****
protected virtual void showTestingPositionsClickEventHandler(object sender, System.EventArgs e)
{
! this.showTestingPositionsClickEventHandler_setDummyTesters();
QuantProject.Presentation.ExecutablesListViewer executablesListViewer =
new ExecutablesListViewer(
! this.dummyTestersForBestTestingPositionsInSample );
executablesListViewer.Show();
}
--- 280,287 ----
protected virtual void showTestingPositionsClickEventHandler(object sender, System.EventArgs e)
{
! this.showTestingPositionsClickEventHandler_setTesters();
QuantProject.Presentation.ExecutablesListViewer executablesListViewer =
new ExecutablesListViewer(
! this.buyAndHoldTestersForBestTestingPositionsInSample );
executablesListViewer.Show();
}
***************
*** 198,207 ****
protected virtual void createAndShowContextMenu()
{
! MenuItem[] menuItems = new MenuItem[2];
! menuItems[0] = new MenuItem("Run Strategy");
! menuItems[1] = new MenuItem("Show TestingPositions");
menuItems[0].Click +=
! new System.EventHandler(this.runStrategyClickEventHandler);
menuItems[1].Click +=
new System.EventHandler(this.showTestingPositionsClickEventHandler);
ContextMenu contextMenu = new ContextMenu(menuItems);
--- 289,304 ----
protected virtual void createAndShowContextMenu()
{
! MenuItem[] menuItems = new MenuItem[4];
! menuItems[0] = new MenuItem("Run Strategy In Sample And Out of S.");
! menuItems[1] = new MenuItem("Run Strategy Only In Sample");
! menuItems[2] = new MenuItem("Run Strategy Only Out of S.");
! menuItems[3] = new MenuItem("Show TestingPositions");
menuItems[0].Click +=
! new System.EventHandler(this.runStrategyClickEventHandlerInAndOutOfSample);
menuItems[1].Click +=
+ new System.EventHandler(this.runStrategyClickEventHandlerOnlyInSample);
+ menuItems[2].Click +=
+ new System.EventHandler(this.runStrategyClickEventHandlerOnlyOutOfSample);
+ menuItems[3].Click +=
new System.EventHandler(this.showTestingPositionsClickEventHandler);
ContextMenu contextMenu = new ContextMenu(menuItems);
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider In directory vz-cvs-3.sog:/tmp/cvs-serv21606/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider Modified Files: DrivenByFVProviderLogItem.cs DrivenByFVProviderMain.cs DrivenByFVProviderStrategy.cs Log Message: Updated script files Index: DrivenByFVProviderStrategy.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/DrivenByFVProviderStrategy.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** DrivenByFVProviderStrategy.cs 16 Jan 2011 19:35:50 -0000 1.1 --- DrivenByFVProviderStrategy.cs 21 Aug 2011 14:21:05 -0000 1.2 *************** *** 22,59 **** using System; using System.Data; - using System.Collections; - using System.Collections.Generic; using System.IO; - using QuantProject.ADT; - using QuantProject.ADT.Statistics; using QuantProject.ADT.Histories; using QuantProject.ADT.Messaging; ! using QuantProject.ADT.Timing; using QuantProject.Business.Financial.Accounting; - using QuantProject.Business.Financial.Instruments; - using QuantProject.Business.Financial.Ordering; - using QuantProject.Business.Timing; using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.InSample; - using QuantProject.Business.Strategies.InSample.InSampleFitnessDistributionEstimation; - using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.Logging; using QuantProject.Business.Strategies.ReturnsManagement; - //using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors using QuantProject.Business.Strategies.ReturnsManagement.Time; ! using QuantProject.Business.DataProviders; ! using QuantProject.Business.Strategies.TickersRelationships; ! using QuantProject.Business.Strategies.Eligibles; ! using QuantProject.Business.Strategies.Optimizing.Decoding; ! using QuantProject.Data; ! using QuantProject.Data.DataProviders; ! using QuantProject.Data.Selectors; ! using QuantProject.Data.DataTables; ! using QuantProject.ADT.Optimizing.Genetic; ! using QuantProject.Scripts.TechnicalAnalysisTesting.Oscillators.FixedLevelOscillators.PortfolioValueOscillator.InSampleChoosers; ! using QuantProject.Scripts.TickerSelectionTesting.OTC; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; - using QuantProject.Scripts.WalkForwardTesting.LinearCombination; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider --- 22,40 ---- using System; using System.Data; using System.IO; using QuantProject.ADT.Histories; using QuantProject.ADT.Messaging; ! using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting; using QuantProject.Business.Strategies; + using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.InSample; using QuantProject.Business.Strategies.Logging; + using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.ReturnsManagement; using QuantProject.Business.Strategies.ReturnsManagement.Time; ! using QuantProject.Business.Timing; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider *************** *** 68,73 **** public event NewLogItemEventHandler NewLogItem; public event NewMessageEventHandler NewMessage; ! ! protected int numDaysForFundamentalAnalysis; protected int inSamplePeriodLengthInDays; protected int numDaysBetweenEachOptimization; --- 49,56 ---- public event NewLogItemEventHandler NewLogItem; public event NewMessageEventHandler NewMessage; ! ! protected int numDaysForFundamentalDataAvailability; ! // protected int numDaysForFundamentalAnalysis; ! protected int numOfMaximumConsecutiveDaysWithSomeMissingQuotes; protected int inSamplePeriodLengthInDays; protected int numDaysBetweenEachOptimization; *************** *** 83,86 **** --- 66,70 ---- protected ReturnsManager returnsManager; protected TestingPositions[] chosenPositions; + protected TestingPositions positionsToOpen; //chosen in sample by the chooser or passed //directly by the user using a form: *************** *** 111,114 **** --- 95,100 ---- //the portfolio is sold, no matter what the current value //of percentageOfTheoreticalProfit is + protected string hedgingTicker; + protected double hedgingTickerWeight = 0.0; private string description_GetDescriptionForChooser() *************** *** 140,154 **** public DrivenByFVProviderStrategy(IEligiblesSelector eligiblesSelector , int minNumOfEligiblesForValidOptimization, IInSampleChooser inSampleChooser , ! int numDaysForFundamentalAnalysis , int numDaysForPortfolioVolatilityAnalysis , Benchmark benchmark , int numDaysBetweenEachOptimization , HistoricalMarketValueProvider historicalMarketValueProviderForInSample , HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample , PortfolioType portfolioType, double stopLoss, double percentageOfTheoreticalProfit, ! double takeProfitLevelInAnyCase) { this.eligiblesSelector = eligiblesSelector; this.minimumNumberOfEligiblesForValidOptimization = minNumOfEligiblesForValidOptimization; this.inSampleChooser = inSampleChooser; ! this.numDaysForFundamentalAnalysis = numDaysForFundamentalAnalysis; this.inSamplePeriodLengthInDays = numDaysForPortfolioVolatilityAnalysis; this.benchmark = benchmark; --- 126,142 ---- public DrivenByFVProviderStrategy(IEligiblesSelector eligiblesSelector , int minNumOfEligiblesForValidOptimization, IInSampleChooser inSampleChooser , ! int numDaysForFundamentalDataAvailability, int numDaysForPortfolioVolatilityAnalysis , Benchmark benchmark , int numDaysBetweenEachOptimization , HistoricalMarketValueProvider historicalMarketValueProviderForInSample , HistoricalMarketValueProvider historicalMarketValueProviderForOutOfSample , PortfolioType portfolioType, double stopLoss, double percentageOfTheoreticalProfit, ! double takeProfitLevelInAnyCase, ! string hedgingTicker, double hedgingTickerWeight) { this.eligiblesSelector = eligiblesSelector; this.minimumNumberOfEligiblesForValidOptimization = minNumOfEligiblesForValidOptimization; this.inSampleChooser = inSampleChooser; ! this.numDaysForFundamentalDataAvailability = numDaysForFundamentalDataAvailability; ! // this.numDaysForFundamentalAnalysis = numDaysForFundamentalAnalysis; this.inSamplePeriodLengthInDays = numDaysForPortfolioVolatilityAnalysis; this.benchmark = benchmark; *************** *** 160,163 **** --- 148,193 ---- this.percentageOfTheoreticalProfit = percentageOfTheoreticalProfit; this.takeProfitLevelInAnyCase = takeProfitLevelInAnyCase; + this.numOfMaximumConsecutiveDaysWithSomeMissingQuotes = 10; + this.hedgingTicker = hedgingTicker; + this.hedgingTickerWeight = hedgingTickerWeight; + } + + private bool someTickersHaveNotBeenTradedForTooManyDays(DateTime dateTime, + string[] tickers) + { + bool returnValue = false; + DateTime firstDateToCheck = + dateTime.AddDays(-this.numOfMaximumConsecutiveDaysWithSomeMissingQuotes); + DateTime currentDateToCheck; + double currentQuote; + for( int i = 0; i < tickers.Length; i++ ) + { + if(returnValue == true) + return returnValue; + else + returnValue = true; + for(int idxDay = 0; + idxDay < this.numOfMaximumConsecutiveDaysWithSomeMissingQuotes; + idxDay++) + { + currentDateToCheck = firstDateToCheck.AddDays(idxDay); + currentQuote = double.MinValue; + try{ + currentQuote = + QuantProject.DataAccess.Tables.Quotes.GetAdjustedClose( tickers[i], currentDateToCheck ); + } + catch(Exception ex){ + string forBreakpoint = ex.Message; + forBreakpoint = forBreakpoint + ""; + } + if( currentQuote != double.MinValue ) + { + returnValue = false; + idxDay = this.numOfMaximumConsecutiveDaysWithSomeMissingQuotes; + } + } + } + + return returnValue; } *************** *** 184,187 **** --- 214,244 ---- } + private bool allTickersHaveAtLeastOneQuoteInTheLastPeriod(DateTime lastPeriodDay, + int periodLengthInDays, + string[] tickers) + { + bool returnValue = true; + int currentNumberOfQuotes; + DateTime firstPeriodDay = lastPeriodDay.AddDays(-periodLengthInDays); + try{ + for( int i = 0; i < tickers.Length; i++ ) + { + currentNumberOfQuotes = + QuantProject.DataAccess.Tables.Quotes.GetNumberOfDaysWithQuotes(tickers[i], firstPeriodDay, lastPeriodDay); + if( currentNumberOfQuotes == 0 ) + { + returnValue = false; + i = tickers.Length; //exit from for + } + } + } + catch(Exception ex){ + string forBreakpoint = ex.Message; + forBreakpoint = forBreakpoint + ""; + returnValue = false; + } + return returnValue; + } + #region newDateTimeEventHandler_closePositions *************** *** 189,193 **** { DateTime currentDateTime = this.now(); ! if( allTickersAreExchanged( currentDateTime, AccountManager.GetTickersInOpenedPositions(this.account) ) ) { AccountManager.ClosePositions( this.account ); --- 246,250 ---- { DateTime currentDateTime = this.now(); ! if( allTickersHaveAtLeastOneQuoteInTheLastPeriod( currentDateTime, 180, AccountManager.GetTickersInOpenedPositions(this.account) ) ) { AccountManager.ClosePositions( this.account ); *************** *** 198,212 **** #region newDateTimeEventHandler_openPositions ! private void newDateTimeEventHandler_openPositions() { ! if( this.chosenPositions != null && ! this.allTickersAreExchanged( this.now(), this.chosenPositions[0].WeightedPositions.SignedTickers.Tickers) ! ) { try { ! AccountManager.OpenPositions( this.chosenPositions[0].WeightedPositions, ! this.account ); this.lastEntryTime = this.now(); this.previousAccountValue = this.account.GetMarketValue(); --- 255,325 ---- #region newDateTimeEventHandler_openPositions ! ! private WeightedPositions newDateTimeEventHandler_openPositions_getPositions() ! { ! WeightedPositions returnValue = ! new WeightedPositions(this.positionsToOpen.WeightedPositions.SignedTickers); ! returnValue.Clear(); ! for(int i = 0; ! i < this.positionsToOpen.WeightedPositions.Count; ! i++) ! { ! if(this.portfolioType == PortfolioType.ShortAndLong) ! returnValue.Add(this.positionsToOpen.WeightedPositions[i]); ! else if( this.positionsToOpen.WeightedPositions[i].IsLong && ! this.portfolioType == PortfolioType.OnlyLong ) ! returnValue.Add(this.positionsToOpen.WeightedPositions[i]); ! else if( this.positionsToOpen.WeightedPositions[i].IsShort && ! this.portfolioType == PortfolioType.OnlyShort ) ! returnValue.Add(this.positionsToOpen.WeightedPositions[i]); ! } ! return returnValue; ! } ! ! private TestingPositions newDateTimeEventHandler_openPositions_setPositionsToOpen_addHedging(int currentIdxOfTestingPosition) ! { ! TestingPositions returnValue = this.chosenPositions[currentIdxOfTestingPosition].Copy(); ! returnValue.AddWeightedPosition(new WeightedPosition( ! this.hedgingTickerWeight, this.hedgingTicker)); ! ! return returnValue; ! } ! ! private void newDateTimeEventHandler_openPositions_setPositionsToOpen() ! { ! if( this.chosenPositions != null ) ! { ! //the first positions with all tickers exchanged are set ! for(int i = 0; i < this.chosenPositions.Length; i++) ! { ! if(this.allTickersAreExchanged( this.now(), this.chosenPositions[i].WeightedPositions.SignedTickers.Tickers)) ! { ! if( this.hedgingTicker != null && ! this.historicalMarketValueProviderForOutOfSample.WasExchanged( this.hedgingTicker, this.now() ) ) ! { ! this.positionsToOpen = ! this.newDateTimeEventHandler_openPositions_setPositionsToOpen_addHedging( i ); ! i = this.chosenPositions.Length; ! } ! else // no hedging ticker provided or hedging ticker not exchanged ! { ! this.positionsToOpen = this.chosenPositions[i]; ! i = this.chosenPositions.Length; ! } ! } ! } ! } ! } ! private void newDateTimeEventHandler_openPositions() { ! this.newDateTimeEventHandler_openPositions_setPositionsToOpen(); ! if( this.positionsToOpen != null ) { try { ! WeightedPositions weightedPositionsToOpen = ! this.newDateTimeEventHandler_openPositions_getPositions(); ! AccountManager.OpenPositions( weightedPositionsToOpen, this.account ); this.lastEntryTime = this.now(); this.previousAccountValue = this.account.GetMarketValue(); *************** *** 256,271 **** Object sender , DateTime dateTime ) { ! this.newDateTimeEventHandler_updateStopLossAndTakeProfitConditions(); ! bool timeToProfitOrToStopLoss = this.takeProfitConditionReached || ! this.stopLossConditionReached; ! ! if( this.account.Portfolio.Count == 0 ) ! this.newDateTimeEventHandler_openPositions(); ! if( (this.account.Portfolio.Count > 0 && timeToProfitOrToStopLoss) || ! this.optimalTestingPositionsAreToBeUpdated() ) ! this.newDateTimeEventHandler_closePositions(); ! ! this.newDateTimeEventHandler_updateTestingPositions( dateTime ); } --- 369,389 ---- Object sender , DateTime dateTime ) { ! if(HistoricalEndOfDayTimer.IsMarketClose( dateTime ) || ! HistoricalEndOfDayTimer.IsMarketOpen( dateTime ) ) ! { ! this.newDateTimeEventHandler_updateStopLossAndTakeProfitConditions(); ! bool timeToProfitOrToStopLoss = this.takeProfitConditionReached || ! this.stopLossConditionReached; ! ! if( this.account.Portfolio.Count == 0 ) ! this.newDateTimeEventHandler_openPositions(); ! ! if( (this.account.Portfolio.Count > 0 && timeToProfitOrToStopLoss) || ! this.optimalTestingPositionsAreToBeUpdated() || ! this.someTickersHaveNotBeenTradedForTooManyDays(this.now(), AccountManager.GetTickersInOpenedPositions(this.account) ) ) ! this.newDateTimeEventHandler_closePositions(); ! this.newDateTimeEventHandler_updateTestingPositions( dateTime ); ! } } *************** *** 280,284 **** w.WriteLine ("\n----------------------------------------------\r\n"); w.Write("\r\nPositions for PositionsForDrivenByFVProviderStrategy on date: {0}\r", today.ToLongDateString() ); - w.Write("\r\nNum days for fundamental analysis {0}\r", this.numDaysForFundamentalAnalysis.ToString()); w.Write("\r\nNum days for portofolio analysis for volatility {0}\r", this.inSamplePeriodLengthInDays.ToString()); w.Write("\r\nEligibles: {0}\r", eligibles.Count.ToString() ); --- 398,401 ---- *************** *** 335,346 **** protected void updateTestingPositions(DateTime currentDateTime) { ! History historyForEligiblesSelector = ! this.benchmark.GetEndOfDayHistory( ! HistoricalEndOfDayTimer.GetMarketClose( ! currentDateTime.AddDays( -this.numDaysForFundamentalAnalysis ) ) , ! HistoricalEndOfDayTimer.GetMarketClose( ! currentDateTime.AddDays(-1) ) ); ! History historyForReturnsManager = this.benchmark.GetEndOfDayHistory( HistoricalEndOfDayTimer.GetMarketClose( --- 452,463 ---- protected void updateTestingPositions(DateTime currentDateTime) { ! // History historyForEligiblesSelector = ! // this.benchmark.GetEndOfDayHistory( ! // HistoricalEndOfDayTimer.GetMarketClose( ! // currentDateTime.AddDays( -this.numDaysForFundamentalAnalysis ) ) , ! // HistoricalEndOfDayTimer.GetMarketClose( ! // currentDateTime.AddDays(-1) ) ); ! History history = this.benchmark.GetEndOfDayHistory( HistoricalEndOfDayTimer.GetMarketClose( *************** *** 350,357 **** this.currentEligibles = ! this.eligiblesSelector.GetEligibleTickers(historyForEligiblesSelector); ! this.updateReturnsManager(historyForReturnsManager.FirstDateTime, ! historyForReturnsManager.LastDateTime); if( ( this.eligiblesSelector is DummyEligibleSelector && --- 467,474 ---- this.currentEligibles = ! this.eligiblesSelector.GetEligibleTickers(history); ! this.updateReturnsManager(history.FirstDateTime, ! history.LastDateTime); if( ( this.eligiblesSelector is DummyEligibleSelector && *************** *** 384,388 **** DateTime dateTime ) { ! if ( this.optimalTestingPositionsAreToBeUpdated() ) { this.chosenPositions = null; --- 501,506 ---- DateTime dateTime ) { ! if ( this.account.Portfolio.Count == 0 || ! this.optimalTestingPositionsAreToBeUpdated() ) { this.chosenPositions = null; *************** *** 416,421 **** { DrivenByFVProviderLogItem logItem = ! new DrivenByFVProviderLogItem( this.now(), this.numDaysForFundamentalAnalysis, ! this.inSamplePeriodLengthInDays); logItem.BestPositionsInSample = this.chosenPositions; --- 534,541 ---- { DrivenByFVProviderLogItem logItem = ! new DrivenByFVProviderLogItem( this.now(), ! this.inSamplePeriodLengthInDays, ! this.historicalMarketValueProviderForInSample, ! this.benchmark); logItem.BestPositionsInSample = this.chosenPositions; Index: DrivenByFVProviderMain.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/DrivenByFVProviderMain.cs,v retrieving revision 1.2 retrieving revision 1.3 diff -C2 -d -r1.2 -r1.3 *** DrivenByFVProviderMain.cs 17 Jan 2011 23:03:51 -0000 1.2 --- DrivenByFVProviderMain.cs 21 Aug 2011 14:21:05 -0000 1.3 *************** *** 22,59 **** using System; - using System.Collections; - using System.Collections.Generic; using System.IO; - - using QuantProject.ADT; - using QuantProject.ADT.Statistics.Combinatorial; - using QuantProject.ADT.FileManaging; using QuantProject.ADT.Timing; using QuantProject.Business.DataProviders; - //using QuantProject.Data.DataProviders.Bars.Caching; - using QuantProject.Business.Strategies; using QuantProject.Business.Financial.Accounting.AccountProviding; using QuantProject.Business.Financial.Fundamentals.FairValueProviders; using QuantProject.Business.Financial.Fundamentals.RatioProviders; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.EquityEvaluation; using QuantProject.Business.Strategies.InSample; - using QuantProject.Business.Strategies.Logging; using QuantProject.Business.Strategies.Optimizing.Decoding; - using QuantProject.Business.Strategies.Optimizing.GenomeManagers; using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation; ! using QuantProject.Business.Strategies.ReturnsManagement; ! using QuantProject.Business.Strategies.ReturnsManagement.Time; ! using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors; using QuantProject.Business.Timing; ! using QuantProject.Presentation; using QuantProject.Scripts.General; - using QuantProject.Scripts.General.Logging; - using QuantProject.Scripts.General.Reporting; - using QuantProject.Scripts.General.Strategies.Optimizing.FitnessEvaluation; using QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider.InSampleChoosers.Genetic; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; ! //using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers.Genetic; ! //using QuantProject.Scripts.TickerSelectionTesting.OTC.InSampleChoosers.BruteForce; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider --- 22,46 ---- using System; using System.IO; using QuantProject.ADT.Timing; using QuantProject.Business.DataProviders; using QuantProject.Business.Financial.Accounting.AccountProviding; + using QuantProject.Business.Financial.Fundamentals; using QuantProject.Business.Financial.Fundamentals.FairValueProviders; + using QuantProject.Business.Financial.Fundamentals.FairValueProviders.LinearRegression; using QuantProject.Business.Financial.Fundamentals.RatioProviders; + using QuantProject.Business.Strategies; using QuantProject.Business.Strategies.Eligibles; using QuantProject.Business.Strategies.EquityEvaluation; using QuantProject.Business.Strategies.InSample; using QuantProject.Business.Strategies.Optimizing.Decoding; using QuantProject.Business.Strategies.Optimizing.FitnessEvaluation; ! using QuantProject.Business.Strategies.Optimizing.GenomeManagers; using QuantProject.Business.Timing; ! using QuantProject.Data.Selectors; using QuantProject.Scripts.General; using QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider.InSampleChoosers.Genetic; using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; ! using QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider.InSampleChoosers; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider *************** *** 64,67 **** --- 51,55 ---- /// be done /// </summary> + [Serializable] public class DrivenByFVProviderMain : BasicScriptForBacktesting { *************** *** 73,79 **** private int maxNumberOfEligiblesToBeChosen; private IFairValueProvider fairValueProvider; - private int numDaysForFundamentalAnalysis; private int numDaysForPortfolioVolatilityAnalysis; private int numDaysForFundamentalDataAvailability; private Benchmark benchmark; private DateTime firstDateTime; --- 61,67 ---- private int maxNumberOfEligiblesToBeChosen; private IFairValueProvider fairValueProvider; private int numDaysForPortfolioVolatilityAnalysis; private int numDaysForFundamentalDataAvailability; + private string tickersGroupId; private Benchmark benchmark; private DateTime firstDateTime; *************** *** 83,98 **** private HistoricalMarketValueProvider historicalMarketValueProviderForTheBackTester; private Timer timerForBackTester; ! private GenomeManagerType genomeManagerType; #region main public DrivenByFVProviderMain() { ! this.numberOfPortfolioPositions = 4; this.benchmark = new Benchmark( "^GSPC" ); ! this.portfolioType = PortfolioType.OnlyLong;//filter for out of sample ! this.genomeManagerType = GenomeManagerType.OnlyLong;//filter for the genetic chooser // this.benchmark = new Benchmark( "ENI.MI" ); ! this.firstDateTime = new DateTime( 2002 , 4 , 1 ); ! this.lastDateTime = new DateTime( 2009 , 3, 31 ); this.historicalMarketValueProviderForInSample = --- 71,125 ---- private HistoricalMarketValueProvider historicalMarketValueProviderForTheBackTester; private Timer timerForBackTester; ! // private GenomeManagerType genomeManagerType; ! private ITickerSelectorByDate tickerSelectorByDate; ! private bool temporizedGroup; ! // private int numDayForAveragePriceComputation; ! private string hedgingTicker; ! private double hedgingTickerWeight; #region main public DrivenByFVProviderMain() { ! this.numberOfPortfolioPositions = 6; ! this.hedgingTicker = "SH"; ! // this.hedgingTicker ="MYY"; ! // this.hedgingTicker = null; ! this.hedgingTickerWeight = 0.5; this.benchmark = new Benchmark( "^GSPC" ); ! // this.benchmark = new Benchmark( "FTSEMIB.MI" ); ! this.tickersGroupId = "SP500"; ! // this.tickersGroupId = "ticUSFin"; ! // this.tickersGroupId = "STOCKMI"; ! this.temporizedGroup = true; ! this.numDaysForPortfolioVolatilityAnalysis = 90; ! this.maxNumberOfEligiblesToBeChosen = 500; ! // int numOfTopRowsToDelete = 500; ! // this.numDayForAveragePriceComputation = 10; ! // double minPriceForTickersToBeSelected = 0.5; ! // string benchmarkForCorrelation = "C"; //citigroup ! int numOfDaysForCorrelation = this.numDaysForPortfolioVolatilityAnalysis; ! this.tickerSelectorByDate = ! // new SelectorByGroupLiquidityAndPrice(this.tickersGroupId, temporizedGroup, ! // false, this.numDaysForPortfolioVolatilityAnalysis, ! // this.maxNumberOfEligiblesToBeChosen, ! // numOfTopRowsToDelete, ! // numDayForAveragePriceComputation, ! // minPriceForTickersToBeSelected); ! new SelectorByGroup(this.tickersGroupId, temporizedGroup); ! // new SelectorByCloseToCloseCorrelationToBenchmark( ! // new SelectorByGroupLiquidityAndPrice(this.tickersGroupId, temporizedGroup, ! // false, numOfDaysForCorrelation, ! // 3000, numDayForAveragePriceComputation, ! // minPriceForTickersToBeSelected), ! // new SelectorByGroup(this.tickersGroupId, temporizedGroup), ! // numOfDaysForCorrelation, ! // benchmarkForCorrelation, false, ! // this.maxNumberOfEligiblesToBeChosen, false); ! ! this.portfolioType = PortfolioType.ShortAndLong;//filter for out of sample ! // this.genomeManagerType = GenomeManagerType.ShortAndLong;//filter for the genetic chooser // this.benchmark = new Benchmark( "ENI.MI" ); ! this.firstDateTime = new DateTime( 2003 , 1 , 1 ); ! this.lastDateTime = new DateTime( 2009 , 12, 31 ); this.historicalMarketValueProviderForInSample = *************** *** 105,126 **** //ricordarsi di togliere - mettere //commento nel gestore evento tempo ! this.numDaysForFundamentalDataAvailability = 30; // double optimalDebtEquityRatioLevel = 0.1; // int maxNumOfGrowthRatesToTakeIntoAccount = 4; ! IGrowthRateProvider growthProvider = // new AverageAndDebtAdjustedGrowthRateProvider(numDaysForFundamentalDataAvailability, // maxNumOfGrowthRatesToTakeIntoAccount, // optimalDebtEquityRatioLevel); ! new LastAvailableGrowthRateProvider(numDaysForFundamentalDataAvailability); ! IRatioProvider_PE PEProvider = ! new LastAvailablePEProvider(this.historicalMarketValueProviderForInSample, ! numDaysForFundamentalDataAvailability); ! double fairPEGRatioLevel = 1.0; this.fairValueProvider = ! new PEGRatioFairValueProvider(fairPEGRatioLevel,PEProvider, ! growthProvider,this.historicalMarketValueProviderForInSample); ! this.numDaysForFundamentalAnalysis = 365; ! this.numDaysForPortfolioVolatilityAnalysis = 90; this.timerForBackTester = --- 132,165 ---- //ricordarsi di togliere - mettere //commento nel gestore evento tempo ! this.numDaysForFundamentalDataAvailability = 60; // double optimalDebtEquityRatioLevel = 0.1; // int maxNumOfGrowthRatesToTakeIntoAccount = 4; ! // IGrowthRateProvider growthProvider = // new AverageAndDebtAdjustedGrowthRateProvider(numDaysForFundamentalDataAvailability, // maxNumOfGrowthRatesToTakeIntoAccount, // optimalDebtEquityRatioLevel); ! // new LastAvailableGrowthRateProvider(numDaysForFundamentalDataAvailability); ! FundamentalDataProvider[] fundamentalDataProviders = ! new FundamentalDataProvider[1]{ ! new BookValueProvider(numDaysForFundamentalDataAvailability) ! }; ! ! ILinearRegressionValuesProvider linearRegressionValuesProvider = ! new BasicLinearRegressionValuesProvider(this.tickerSelectorByDate, ! fundamentalDataProviders, ! new DayOfMonth(12, 31) ); ! IIndipendentValuesProvider indipendentValuesProvider = ! new BasicIndipendentValuesProvider(fundamentalDataProviders); ! // IRatioProvider_PE PEProvider = ! // new LastAvailablePEProvider(this.historicalMarketValueProviderForInSample, ! // numDaysForFundamentalDataAvailability); ! // double fairPEGRatioLevel = 1.0; this.fairValueProvider = ! // new PEGRatioFairValueProvider(fairPEGRatioLevel,PEProvider, ! // growthProvider,this.historicalMarketValueProviderForInSample); ! new LinearRegressionFairValueProvider(linearRegressionValuesProvider, ! indipendentValuesProvider); ! // this.genomeManagerType = GenomeManagerType.ShortAndLong; this.timerForBackTester = *************** *** 141,166 **** protected override IEligiblesSelector getEligiblesSelector() { ! this.maxNumberOfEligiblesToBeChosen = 800; ! string tickersGroupId = "ticUSFin"; ! // string tickersGroupId = "SP500"; ! // string tickersGroupId = "STOCKMI"; ! ! bool temporizedGroup = true;//Attenzione! ! double minimumIncome = 10000000.0;//10 mln ! int numOfMinIncomeInARow = 4; ! double minimumRelativeDifferenceBetweenFairAndAverageMarketPrice = 0.05; ! int numDaysForAveragePriceComputation = 10; IEligiblesSelector eligiblesSelector = ! new ByMostDiscountedPrices( this.fairValueProvider , ! tickersGroupId , temporizedGroup , ! maxNumberOfEligiblesToBeChosen , this.numDaysForFundamentalAnalysis, ! this.numDaysForFundamentalDataAvailability, ! minimumIncome, numOfMinIncomeInARow, ! minimumRelativeDifferenceBetweenFairAndAverageMarketPrice, ! numDaysForAveragePriceComputation); ! // new ByLiquidity ( tickersGroupId , temporizedGroup , ! // maxNumberOfEligiblesToBeChosen ); ! // eligiblesSelector = --- 180,202 ---- protected override IEligiblesSelector getEligiblesSelector() { ! // double minimumIncome = 10000000.0;//10 mln ! // int numOfMinIncomeInARow = 3; ! // double minimumRelativeDifferenceBetweenFairAndAverageMarketPrice = 0.01; ! int numDaysForAveragePriceComputation = 5; ! int firstPercentileOfMostDiscountedToExclude = 0; ! int firstPercentileOfMostExpensiveToExclude = 100; ! //the strategy is only long: over-valued tickers are discarded IEligiblesSelector eligiblesSelector = ! new ByRelativeDifferenceBetweenPriceAndFairValue( this.fairValueProvider, ! this.tickerSelectorByDate , ! maxNumberOfEligiblesToBeChosen , ! firstPercentileOfMostDiscountedToExclude , ! firstPercentileOfMostExpensiveToExclude , ! numDaysForAveragePriceComputation ); ! ! // new ByPriceMostLiquidAlwaysQuoted(tickersGroupId, ! // temporizedGroup, maxNumberOfEligiblesToBeChosen, ! // numDaysForAveragePriceComputation, 1.0, 5000.0); // eligiblesSelector = *************** *** 174,210 **** protected override IInSampleChooser getInSampleChooser() { ! int numberOfBestTestingPositionsToBeReturned = 1; // parameters for the genetic optimizer ! double crossoverRate = 0.85; ! double mutationRate = 0.02; ! double elitismRate = 0.001; ! int populationSizeForGeneticOptimizer = 40000; ! int generationNumberForGeneticOptimizer = 50; ! int seedForRandomGenerator = ! QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator; ! BuyAndHoldFitnessEvaluator fitnessEvaluator = // new BuyAndHoldFitnessEvaluator( new Variance() ); ! new BuyAndHoldFitnessEvaluator( new SharpeRatio() ); ! bool mixPastReturnsEvaluationWithFundamentalEvaluation = ! false; ! BasicDecoderForGeneticallyOptimizableTestingPositions basicGenOptDecoder = ! new BasicDecoderForGeneticallyOptimizableTestingPositions(); IInSampleChooser inSampleChooser = ! new DrivenByFVProviderInSampleChooser(this.numberOfPortfolioPositions, ! numberOfBestTestingPositionsToBeReturned, ! benchmark, basicGenOptDecoder, this.genomeManagerType , ! fitnessEvaluator , mixPastReturnsEvaluationWithFundamentalEvaluation, ! historicalMarketValueProviderForInSample, this.timerForBackTester, ! crossoverRate, mutationRate, elitismRate , ! populationSizeForGeneticOptimizer, generationNumberForGeneticOptimizer, ! seedForRandomGenerator); - // new SelectTopEligiblesInSampleChooser( this.numberOfPortfolioPositions, - // numberOfBestTestingPositionsToBeReturned); return inSampleChooser; --- 210,248 ---- protected override IInSampleChooser getInSampleChooser() { ! int numberOfBestTestingPositionsToBeReturned = 5; // parameters for the genetic optimizer ! // double crossoverRate = 0.85; ! // double mutationRate = 0.02; ! // double elitismRate = 0.001; ! // int populationSizeForGeneticOptimizer = 1000; ! // int generationNumberForGeneticOptimizer = 10; ! // int seedForRandomGenerator = ! // QuantProject.ADT.ConstantsProvider.SeedForRandomGenerator; ! // BuyAndHoldFitnessEvaluator fitnessEvaluator = // new BuyAndHoldFitnessEvaluator( new Variance() ); ! // new BuyAndHoldFitnessEvaluator( new SharpeRatio() ); ! // bool mixPastReturnsEvaluationWithFundamentalEvaluation = true; ! BasicDecoderForGeneticallyOptimizableTestingPositions decoderForFVProvider = ! new DecoderForFVProviderStrategy(); IInSampleChooser inSampleChooser = ! // new DrivenByFVProviderInSampleChooser(this.numberOfPortfolioPositions, ! // numberOfBestTestingPositionsToBeReturned, ! // benchmark, decoderForFVProvider, this.genomeManagerType , ! // fitnessEvaluator , mixPastReturnsEvaluationWithFundamentalEvaluation, ! // historicalMarketValueProviderForInSample, this.timerForBackTester, ! // crossoverRate, mutationRate, elitismRate , ! // populationSizeForGeneticOptimizer, generationNumberForGeneticOptimizer, ! // seedForRandomGenerator); ! ! new SelectTopBottomEligiblesWithSignInSampleChooser( this.numberOfPortfolioPositions, ! numberOfBestTestingPositionsToBeReturned, ! this.historicalMarketValueProviderForInSample, ! this.timerForBackTester); return inSampleChooser; *************** *** 215,230 **** protected override IStrategyForBacktester getStrategyForBacktester() { ! int numDaysBetweenEachOptimization = 60; ! int minNumOfEligiblesForValidOptimization = 10; IStrategyForBacktester strategyForBacktester = new DrivenByFVProviderStrategy(eligiblesSelector , minNumOfEligiblesForValidOptimization, inSampleChooser , ! numDaysForFundamentalAnalysis , numDaysForPortfolioVolatilityAnalysis , benchmark , numDaysBetweenEachOptimization , historicalMarketValueProviderForInSample , historicalMarketValueProviderForOutOfSample , this.portfolioType, this.stopLoss, this.percentageOfTheoreticalProfitForExit, ! this.takeProfitLevelInAnyCase); return strategyForBacktester; --- 253,268 ---- protected override IStrategyForBacktester getStrategyForBacktester() { ! int numDaysBetweenEachOptimization = 180; ! int minNumOfEligiblesForValidOptimization = 20; IStrategyForBacktester strategyForBacktester = new DrivenByFVProviderStrategy(eligiblesSelector , minNumOfEligiblesForValidOptimization, inSampleChooser , ! this.numDaysForFundamentalDataAvailability, numDaysForPortfolioVolatilityAnalysis , benchmark , numDaysBetweenEachOptimization , historicalMarketValueProviderForInSample , historicalMarketValueProviderForOutOfSample , this.portfolioType, this.stopLoss, this.percentageOfTheoreticalProfitForExit, ! this.takeProfitLevelInAnyCase, this.hedgingTicker, this.hedgingTickerWeight); return strategyForBacktester; Index: DrivenByFVProviderLogItem.cs =================================================================== RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/DrivenByFVProviderLogItem.cs,v retrieving revision 1.1 retrieving revision 1.2 diff -C2 -d -r1.1 -r1.2 *** DrivenByFVProviderLogItem.cs 16 Jan 2011 19:35:50 -0000 1.1 --- DrivenByFVProviderLogItem.cs 21 Aug 2011 14:21:05 -0000 1.2 *************** *** 22,46 **** using System; - using System.Collections.Generic; using System.Windows.Forms; ! using QuantProject.ADT; using QuantProject.ADT.Timing; using QuantProject.Data.DataProviders.Bars.Caching; - using QuantProject.Business.DataProviders; using QuantProject.Business.Strategies; using QuantProject.Business.Financial.Accounting.AccountProviding; using QuantProject.Business.Strategies.Eligibles; ! using QuantProject.Business.Strategies.InSample; ! using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Strategies.Logging; ! using QuantProject.Business.Strategies.ReturnsManagement.Time; ! using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors; ! using QuantProject.Scripts.TickerSelectionTesting.OTC.OTC_Intraday; using QuantProject.Business.Timing; using QuantProject.Presentation; ! using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; ! using QuantProject.Scripts.General.Reporting; using QuantProject.Scripts.General.Logging; namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider --- 22,51 ---- using System; using System.Windows.Forms; ! using System.Collections.Generic; using QuantProject.ADT; using QuantProject.ADT.Timing; using QuantProject.Data.DataProviders.Bars.Caching; using QuantProject.Business.Strategies; using QuantProject.Business.Financial.Accounting.AccountProviding; using QuantProject.Business.Strategies.Eligibles; ! using QuantProject.Business.DataProviders; using QuantProject.Business.Strategies.Logging; ! using QuantProject.Business.Strategies.OutOfSample; using QuantProject.Business.Timing; using QuantProject.Presentation; ! using QuantProject.Scripts.General; using QuantProject.Scripts.General.Logging; + using QuantProject.Scripts.General.Reporting; + // + // + //using QuantProject.Business.Strategies.InSample; + //using QuantProject.Business.Strategies.Logging; + //using QuantProject.Business.Strategies.ReturnsManagement.Time; + //using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors; + // + //using QuantProject.Presentation; + //using QuantProject.Scripts.TickerSelectionTesting.EfficientPortfolios; + // namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider *************** *** 52,63 **** public class DrivenByFVProviderLogItem : LogItem { ! protected DummyTesterForTestingPositions[] ! dummyTestersForBestTestingPositionsInSample; protected TestingPositions[] bestPositionsInSample; protected int numberOfEligibleTickers; protected double fitness; protected int generation; protected string tickers; - protected int numberOfDaysForFundamentalAnalysis; protected int numberOfDaysForVolatilityAnalysis; --- 57,69 ---- public class DrivenByFVProviderLogItem : LogItem { ! protected BuyAndHoldTesterForTestingPositions[] ! buyAndHoldTestersForBestTestingPositionsInSample; protected TestingPositions[] bestPositionsInSample; + protected HistoricalMarketValueProvider historicalMarketValueProvider; + protected Benchmark benchmark; protected int numberOfEligibleTickers; protected double fitness; protected int generation; protected string tickers; protected int numberOfDaysForVolatilityAnalysis; *************** *** 109,123 **** } public DrivenByFVProviderLogItem(DateTime dateTime, ! int numberOfDaysForFundamentalAnalysis, ! int numberOfDaysForVolatilityAnalysis) : base( dateTime ) { - this.numberOfDaysForFundamentalAnalysis = numberOfDaysForFundamentalAnalysis; this.numberOfDaysForVolatilityAnalysis = numberOfDaysForVolatilityAnalysis; this.numberOfEligibleTickers = int.MinValue; this.fitness = double.MinValue; } ! #region runStrategyClickEventHandler protected virtual void runStrategyClickEventHandler(object sender, System.EventArgs e) { --- 115,131 ---- } public DrivenByFVProviderLogItem(DateTime dateTime, ! int numberOfDaysForVolatilityAnalysis, ! HistoricalMarketValueProvider historicalMarketValueProvider, ! Benchmark benchmark) : base( dateTime ) { this.numberOfDaysForVolatilityAnalysis = numberOfDaysForVolatilityAnalysis; + this.benchmark = benchmark; + this.historicalMarketValueProvider = historicalMarketValueProvider; this.numberOfEligibleTickers = int.MinValue; this.fitness = double.MinValue; } ! #region runStrategyClickEventHandler OLD protected virtual void runStrategyClickEventHandler(object sender, System.EventArgs e) { *************** *** 186,196 **** #endregion runStrategyClickEventHandler ! private void showTestingPositionsClickEventHandler_setDummyTesters_setTester( int currentIndex , TestingPositions testingPositions , DateTime simulatedCreationDateTime ) { ! this.dummyTestersForBestTestingPositionsInSample[ currentIndex ] = ! new DummyTesterForTestingPositions( testingPositions , this.numberOfDaysForVolatilityAnalysis , --- 194,323 ---- #endregion runStrategyClickEventHandler ! #region runStrategyClickEventHandlerInAndOutOfSample ! protected virtual void runStrategyClickEventHandlerInAndOutOfSample(object sender, System.EventArgs e) ! { ! DateTime firstDateTime = this.SimulatedCreationDateTime.AddDays(-this.numberOfDaysForVolatilityAnalysis); ! DateTime lastDateTime = this.SimulatedCreationDateTime; ! double maxRunningHours = 1; ! int numberOfPortfolioPositions = this.bestPositionsInSample[0].WeightedPositions.Count; ! //cash and portfolio type ! double cashToStart = 10000; ! HistoricalMarketValueProvider historicalQuoteProviderForBackTester, ! historicalQuoteProviderForInSampleChooser, ! historicalQuoteProviderForStrategy; ! historicalQuoteProviderForBackTester = this.historicalMarketValueProvider; ! historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester; ! historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser; ! //strategyParameters ! TestingPositions positionsToTest = this.BestPositionsInSample[0]; ! ! BuyAndHoldStrategy strategy = new BuyAndHoldStrategy(positionsToTest); ! ! QuantProject.Business.Timing.Timer timer = ! new IndexBasedEndOfDayTimer( firstDateTime, ! lastDateTime.AddDays(this.numberOfDaysForVolatilityAnalysis), ! this.benchmark.Ticker); ! ! EndOfDayStrategyBackTester endOfDayStrategyBackTester = ! new EndOfDayStrategyBackTester( ! "BuyAndHold" , timer , strategy, ! historicalQuoteProviderForBackTester , ! new SimpleAccountProvider(), firstDateTime , ! lastDateTime.AddDays(this.numberOfDaysForVolatilityAnalysis) , ! this.benchmark , cashToStart , maxRunningHours ); ! ! endOfDayStrategyBackTester.Run(); ! BackTesterReportViewer.ShowReport( lastDateTime.AddDays(this.numberOfDaysForVolatilityAnalysis) , ! endOfDayStrategyBackTester ); ! ! } ! #endregion runStrategyClickEventHandlerInAndOutOfSample ! ! #region runStrategyClickEventHandlerOnlyInSample ! protected virtual void runStrategyClickEventHandlerOnlyInSample(object sender, System.EventArgs e) ! { ! DateTime firstDateTime = this.SimulatedCreationDateTime.AddDays(-this.numberOfDaysForVolatilityAnalysis); ! DateTime lastDateTime = this.SimulatedCreationDateTime; ! double maxRunningHours = 1; ! int numberOfPortfolioPositions = this.bestPositionsInSample[0].WeightedPositions.Count; ! //cash and portfolio type ! double cashToStart = 10000; ! HistoricalMarketValueProvider historicalQuoteProviderForBackTester, ! historicalQuoteProviderForInSampleChooser, ! historicalQuoteProviderForStrategy; ! historicalQuoteProviderForBackTester = this.historicalMarketValueProvider; ! historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester; ! historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser; ! //strategyParameters ! TestingPositions positionsToTest = this.BestPositionsInSample[0]; ! ! BuyAndHoldStrategy strategy = new BuyAndHoldStrategy(positionsToTest); ! QuantProject.Business.Timing.Timer timer = ! new IndexBasedEndOfDayTimer( firstDateTime, ! lastDateTime, ! this.benchmark.Ticker); ! ! EndOfDayStrategyBackTester endOfDayStrategyBackTester = ! new EndOfDayStrategyBackTester( ! "BuyAndHold" , timer , strategy, ! historicalQuoteProviderForBackTester , ! new SimpleAccountProvider(), firstDateTime , ! lastDateTime , ! this.benchmark , cashToStart , maxRunningHours ); ! ! endOfDayStrategyBackTester.Run(); ! BackTesterReportViewer.ShowReport( lastDateTime , ! endOfDayStrategyBackTester ); ! } ! #endregion runStrategyClickEventHandlerOnlyInSample ! ! #region runStrategyClickEventHandlerOnlyOutOfSample ! protected virtual void runStrategyClickEventHandlerOnlyOutOfSample(object sender, System.EventArgs e) ! { ! DateTime firstDateTime = this.SimulatedCreationDateTime; ! DateTime lastDateTime = this.SimulatedCreationDateTime.AddDays(this.numberOfDaysForVolatilityAnalysis); ! double maxRunningHours = 1; ! int numberOfPortfolioPositions = this.bestPositionsInSample[0].WeightedPositions.Count; ! //cash and portfolio type ! double cashToStart = 10000; ! HistoricalMarketValueProvider historicalQuoteProviderForBackTester, ! historicalQuoteProviderForInSampleChooser, ! historicalQuoteProviderForStrategy; ! historicalQuoteProviderForBackTester = this.historicalMarketValueProvider; ! historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester; ! historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser; ! //strategyParameters ! TestingPositions positionsToTest = this.BestPositionsInSample[0]; ! ! BuyAndHoldStrategy strategy = new BuyAndHoldStrategy(positionsToTest); ! ! QuantProject.Business.Timing.Timer timer = ! new IndexBasedEndOfDayTimer( firstDateTime, ! lastDateTime, ! this.benchmark.Ticker); ! ! EndOfDayStrategyBackTester endOfDayStrategyBackTester = ! new EndOfDayStrategyBackTester( ! "BuyAndHold" , timer , strategy, ! historicalQuoteProviderForBackTester , ! new SimpleAccountProvider(), firstDateTime , ! lastDateTime , ! this.benchmark , cashToStart , maxRunningHours ); ! ! endOfDayStrategyBackTester.Run(); ! BackTesterReportViewer.ShowReport( lastDateTime , ! endOfDayStrategyBackTester ); ! ! } ! #endregion runStrategyClickEventHandlerOnlyOutOfSample ! ! private void showTestingPositionsClickEventHandler_setTesters_setTester( int currentIndex , TestingPositions testingPositions , DateTime simulatedCreationDateTime ) { ! this.buyAndHoldTestersForBestTestingPositionsInSample[ currentIndex ] = ! new BuyAndHoldTesterForTestingPositions(this.historicalMarketValueProvider, ! this.benchmark, testingPositions , this.numberOfDaysForVolatilityAnalysis , *************** *** 198,207 **** } ! private void showTestingPositionsClickEventHandler_setDummyTesters() { ! this.dummyTestersForBestTestingPositionsInSample = ! new DummyTesterForTestingPositions[this.BestPositionsInSample.Length]; for ( int i = 0 ; i < BestPositionsInSample.Length; i++ ) ! this.showTestingPositionsClickEventHandler_setDummyTesters_setTester( i , BestPositionsInSample[ i ] , --- 325,334 ---- } ! private void showTestingPositionsClickEventHandler_setTesters() { ! this.buyAndHoldTestersForBestTestingPositionsInSample = ! new BuyAndHoldTesterForTestingPositions[this.BestPositionsInSample.Length]; for ( int i = 0 ; i < BestPositionsInSample.Length; i++ ) ! this.showTestingPositionsClickEventHandler_setTesters_setTester( i , BestPositionsInSample[ i ] , *************** *** 211,229 **** protected virtual void showTestingPositionsClickEventHandler(object sender, System.EventArgs e) { ! this.showTestingPositionsClickEventHandler_setDummyTesters(); QuantProject.Presentation.ExecutablesListViewer executablesListViewer = new ExecutablesListViewer( ! this.dummyTestersForBestTestingPositionsInSample ); executablesListViewer.Show(); } protected virtual void createAndShowContextMenu() { ! MenuItem[] menuItems = new MenuItem[2]; ! menuItems[0] = new MenuItem("Run Strategy"); ! menuItems[1] = new MenuItem("Show TestingPositions"); menuItems[0].Click += ! new System.EventHandler(this.runStrategyClickEventHandler); menuItems[1].Click += new System.EventHandler(this.showTestingPositionsClickEventHandler); ContextMenu contextMenu = new ContextMenu(menuItems); --- 338,375 ---- protected virtual void showTestingPositionsClickEventHandler(object sender, System.EventArgs e) { ! this.showTestingPositionsClickEventHandler_setTesters(); QuantProject.Presentation.ExecutablesListViewer executablesListViewer = new ExecutablesListViewer( ! this.buyAndHoldTestersForBestTestingPositionsInSample ); executablesListViewer.Show(); } + //OLD protected virtual void createAndShowContextMenu() + // { + // MenuItem[] menuItems = new MenuItem[2]; + // menuItems[0] = new MenuItem("Run Strategy"); + // menuItems[1] = new MenuItem("Show TestingPositions"); + // menuItems[0].Click += + // new System.EventHandler(this.runStrategyClickEventHandler); + // menuItems[1].Click += + // new System.EventHandler(this.showTestingPositionsClickEventHandler); + // ContextMenu contextMenu = new ContextMenu(menuItems); + // contextMenu.Show(Form.ActiveForm, Form.MousePosition); + // } + protected virtual void createAndShowContextMenu() { ! MenuItem[] menuItems = new MenuItem[4]; ! menuItems[0] = new MenuItem("Run Strategy In Sample And Out of S."); ! menuItems[1] = new MenuItem("Run Strategy Only In Sample"); ! menuItems[2] = new MenuItem("Run Strategy Only Out of S."); ! menuItems[3] = new MenuItem("Show TestingPositions"); menuItems[0].Click += ! new System.EventHandler(this.runStrategyClickEventHandlerInAndOutOfSample); menuItems[1].Click += + new System.EventHandler(this.runStrategyClickEventHandlerOnlyInSample); + menuItems[2].Click += + new System.EventHandler(this.runStrategyClickEventHandlerOnlyOutOfSample); + menuItems[3].Click += new System.EventHandler(this.showTestingPositionsClickEventHandler); ContextMenu contextMenu = new ContextMenu(menuItems); |
|
From: Marco M. <mi...@us...> - 2011-08-21 14:20:23
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider
In directory vz-cvs-3.sog:/tmp/cvs-serv21585/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider
Modified Files:
DrivenByFVProviderPositions.cs
Log Message:
Updated
Index: DrivenByFVProviderPositions.cs
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/DrivenByFVProviderPositions.cs,v
retrieving revision 1.1
retrieving revision 1.2
diff -C2 -d -r1.1 -r1.2
*** DrivenByFVProviderPositions.cs 16 Jan 2011 19:35:50 -0000 1.1
--- DrivenByFVProviderPositions.cs 21 Aug 2011 14:20:20 -0000 1.2
***************
*** 3,7 ****
DrivenByFVProviderPositions.cs
! Copyright (C) 2010
Marco Milletti
--- 3,7 ----
DrivenByFVProviderPositions.cs
! Copyright (C) 2011
Marco Milletti
***************
*** 41,47 ****
private int generation;
private double[] buyPricesForWeightedPositions;
-
-
-
//explicit interface implementation
//the property can be used only by a interface
--- 41,44 ----
***************
*** 52,56 ****
set{this.generation = value;}
}
!
public DrivenByFVProviderPositions Copy()
{
--- 49,53 ----
set{this.generation = value;}
}
!
public DrivenByFVProviderPositions Copy()
{
|
|
From: Marco M. <mi...@us...> - 2011-08-21 14:17:36
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/Decoding
In directory vz-cvs-3.sog:/tmp/cvs-serv20465
Added Files:
DecoderForFVProviderStrategy.cs
Log Message:
Added DecoderForFVProviderStrategy
--- NEW FILE: DecoderForFVProviderStrategy.cs ---
/*
QuantProject - Quantitative Finance Library
DecoderForFVProviderStrategy.cs
Copyright (C) 2011
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 QuantProject.Business.Financial.Accounting;
using QuantProject.Business.Strategies;
using QuantProject.Business.Strategies.Optimizing.Decoding;
namespace QuantProject.Scripts.TickerSelectionTesting.DrivenByFundamentals.DrivenByFairValueProvider
{
/// <summary>
/// Decodes optimization candidates to a GeneticallyOptimizableTestingPositions
/// </summary>
[Serializable]
public class DecoderForFVProviderStrategy : BasicDecoderForGeneticallyOptimizableTestingPositions
{
public DecoderForFVProviderStrategy() : base()
{
}
private void decodeSignedTickers_checkParameters( int geneValue )
{
if ( geneValue >= this.eligibleTickers.Count ||
geneValue < 0 )
throw new Exception( "geneValue has to be greater than 0 and less than the number of eligibles !" );
}
private PositionType decodeSignedTickers_getPositionType( int geneValue )
{
PositionType returnValue = PositionType.Long;
object[] keys = new object[1];
keys[0] = this.eligibleTickers.Tickers[ geneValue ];
DataRow foundRow =
this.eligibleTickers.SourceDataTable.Rows.Find(keys);
double relativeDifferenceBetweenFairValueAndMarketPrice =
(double)foundRow["RelativeDifferenceBetweenFairAndMarketPrice"];
if( relativeDifferenceBetweenFairValueAndMarketPrice < 0.0 )
returnValue = PositionType.Short;
return returnValue;
}
protected override SignedTicker decodeSignedTickers( int i )
{
int signedTickerCode = this.tickerRelatedGeneValues[ i ];
decodeSignedTickers_checkParameters( signedTickerCode );
string ticker = this.eligibleTickers[ signedTickerCode ];
PositionType positionType = this.decodeSignedTickers_getPositionType ( signedTickerCode );
SignedTicker signedTicker = new SignedTicker( ticker , positionType );
return signedTicker;
}
protected override string getDescription()
{
return "Dcdr_ForFairValueProvider";
}
}
}
|
|
From: Marco M. <mi...@us...> - 2011-08-21 14:14:39
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/Decoding In directory vz-cvs-3.sog:/tmp/cvs-serv20359/Decoding Log Message: Directory /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/DrivenByFundamentals/DrivenByFairValueProvider/Decoding added to the repository |
|
From: Marco M. <mi...@us...> - 2011-08-21 14:13:49
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts
In directory vz-cvs-3.sog:/tmp/cvs-serv20333
Modified Files:
SimpleScriptsContainer.cs
Log Message:
Updated script files
Index: SimpleScriptsContainer.cs
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/SimpleScriptsContainer.cs,v
retrieving revision 1.2
retrieving revision 1.3
diff -C2 -d -r1.2 -r1.3
*** SimpleScriptsContainer.cs 5 Feb 2009 22:17:08 -0000 1.2
--- SimpleScriptsContainer.cs 21 Aug 2011 14:13:47 -0000 1.3
***************
*** 41,54 ****
public static void Execute()
{
! QuantProject.Data.Selectors.ByLinearIndipendence.SelectorByMaxLinearIndipendence selector =
! new QuantProject.Data.Selectors.ByLinearIndipendence.SelectorByMaxLinearIndipendence(
! "SP500",new DateTime(2004,1,1),new DateTime(2004,5,31),5,3,2000,"^GSPC");
!
! DataTable indipendentTickers = selector.GetTableOfSelectedTickers();
! SelectorByCloseToCloseCorrelationToBenchmark selector2 =
! new SelectorByCloseToCloseCorrelationToBenchmark("SP500",(string)indipendentTickers.Rows[0][0],
! false,new DateTime(2004,1,1),new DateTime(2004,5,31),
! 20,false);
! DataTable correlatedTickers = selector2.GetTableOfSelectedTickers();
}
#endregion Execute
--- 41,54 ----
public static void Execute()
{
! // QuantProject.Data.Selectors.ByLinearIndipendence.SelectorByMaxLinearIndipendence selector =
! // new QuantProject.Data.Selectors.ByLinearIndipendence.SelectorByMaxLinearIndipendence(
! // "SP500",new DateTime(2004,1,1),new DateTime(2004,5,31),5,3,2000,"^GSPC");
! //
! // DataTable indipendentTickers = selector.GetTableOfSelectedTickers();
! // SelectorByCloseToCloseCorrelationToBenchmark selector2 =
! // new SelectorByCloseToCloseCorrelationToBenchmark("SP500",(string)indipendentTickers.Rows[0][0],
! // false,new DateTime(2004,1,1),new DateTime(2004,5,31),
! // 20,false);
! // DataTable correlatedTickers = selector2.GetTableOfSelectedTickers();
}
#endregion Execute
|
|
From: Marco M. <mi...@us...> - 2011-08-21 14:12:59
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC
In directory vz-cvs-3.sog:/tmp/cvs-serv20272/TickerSelectionTesting/OTC
Modified Files:
OTCPositions.cs
Log Message:
Updated script files
Index: OTCPositions.cs
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b7_Scripts/TickerSelectionTesting/OTC/OTCPositions.cs,v
retrieving revision 1.1
retrieving revision 1.2
diff -C2 -d -r1.1 -r1.2
*** OTCPositions.cs 31 Aug 2009 20:40:30 -0000 1.1
--- OTCPositions.cs 21 Aug 2011 14:12:57 -0000 1.2
***************
*** 50,54 ****
}
! public OTCPositions Copy()
{
return new OTCPositions( this.WeightedPositions,
--- 50,54 ----
}
! public new OTCPositions Copy()
{
return new OTCPositions( this.WeightedPositions,
|
|
From: Marco M. <mi...@us...> - 2011-08-21 14:11:36
|
Update of /cvsroot/quantproject/QuantProject/b7_Scripts/General/Logging
In directory vz-cvs-3.sog:/tmp/cvs-serv20216/Logging
Added Files:
BuyAndHoldTesterForTestingPositions.cs
Log Message:
Added BuyAndHoldTesterForTestingPositions
--- NEW FILE: BuyAndHoldTesterForTestingPositions.cs ---
/*
QuantProject - Quantitative Finance Library
BuyAndHoldTesterForTestingPositions.cs
Copyright (C) 2011
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.Windows.Forms;
using QuantProject.Business.DataProviders;
using QuantProject.Business.Financial.Accounting.AccountProviding;
using QuantProject.Business.Scripting;
using QuantProject.Business.Strategies;
using QuantProject.Business.Strategies.OutOfSample;
using QuantProject.Business.Strategies.ReturnsManagement.Time.IntervalsSelectors;
using QuantProject.Business.Timing;
using QuantProject.Scripts.General.Reporting;
namespace QuantProject.Scripts.General.Logging
{
[Serializable]
/// <summary>
/// It runs a simple buy and hold test on the given TestingPositions object
/// </summary>
public class BuyAndHoldTesterForTestingPositions : IExecutable
{
private HistoricalMarketValueProvider historicalMarketValueProvider;
private Benchmark benchmark;
private TestingPositions testingPositions;
private int numberOfInSampleDays;
private DateTime simulatedCreationDateTime;
/// <summary>
/// Generation when the TestingPositions object has been created
/// (if genetically optimized)
/// </summary>
public int Generation
{
get
{
int generation = -1;
if( this.testingPositions is IGeneticallyOptimizable )
generation =
((IGeneticallyOptimizable)this.testingPositions).Generation;
return generation;
}
}
public double FitnessInSample
{
get { return this.testingPositions.FitnessInSample; }
}
public string ShortDescription
{
get { return this.testingPositions.WeightedPositions.Description; }
}
public BuyAndHoldTesterForTestingPositions( HistoricalMarketValueProvider historicalMarketValueProvider,
Benchmark benchmark,
TestingPositions testingPositions ,
int numberOfInSampleDays ,
DateTime simulatedCreationDateTime )
{
this.historicalMarketValueProvider = historicalMarketValueProvider;
this.benchmark = benchmark;
this.testingPositions = testingPositions;
this.numberOfInSampleDays = numberOfInSampleDays;
this.simulatedCreationDateTime =
simulatedCreationDateTime;
}
#region runStrategyClickEventHandlerInAndOutOfSample
protected virtual void runStrategyClickEventHandlerInAndOutOfSample(object sender, System.EventArgs e)
{
DateTime firstDateTime = this.simulatedCreationDateTime.AddDays(-this.numberOfInSampleDays);
DateTime lastDateTime = this.simulatedCreationDateTime;
double maxRunningHours = 1;
int numberOfPortfolioPositions = this.testingPositions.WeightedPositions.Count;
//cash and portfolio type
double cashToStart = 10000;
HistoricalMarketValueProvider historicalQuoteProviderForBackTester,
historicalQuoteProviderForInSampleChooser,
historicalQuoteProviderForStrategy;
historicalQuoteProviderForBackTester = this.historicalMarketValueProvider;
historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester;
historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser;
BuyAndHoldStrategy strategy =
new BuyAndHoldStrategy(this.testingPositions);
QuantProject.Business.Timing.Timer timer =
new IndexBasedEndOfDayTimer( firstDateTime,
lastDateTime.AddDays(this.numberOfInSampleDays),
this.benchmark.Ticker);
EndOfDayStrategyBackTester endOfDayStrategyBackTester =
new EndOfDayStrategyBackTester(
"BuyAndHold" , timer , strategy,
historicalQuoteProviderForBackTester ,
new SimpleAccountProvider(), firstDateTime ,
lastDateTime.AddDays(this.numberOfInSampleDays) ,
this.benchmark , cashToStart , maxRunningHours );
endOfDayStrategyBackTester.Run();
BackTesterReportViewer.ShowReport( lastDateTime.AddDays(this.numberOfInSampleDays) ,
endOfDayStrategyBackTester );
}
#endregion runStrategyClickEventHandlerInAndOutOfSample
#region runStrategyClickEventHandlerOnlyInSample
protected virtual void runStrategyClickEventHandlerOnlyInSample(object sender, System.EventArgs e)
{
DateTime firstDateTime = this.simulatedCreationDateTime.AddDays(-this.numberOfInSampleDays);
DateTime lastDateTime = this.simulatedCreationDateTime;
double maxRunningHours = 1;
int numberOfPortfolioPositions = this.testingPositions.WeightedPositions.Count;
//cash and portfolio type
double cashToStart = 10000;
HistoricalMarketValueProvider historicalQuoteProviderForBackTester,
historicalQuoteProviderForInSampleChooser,
historicalQuoteProviderForStrategy;
historicalQuoteProviderForBackTester = this.historicalMarketValueProvider;
historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester;
historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser;
BuyAndHoldStrategy strategy =
new BuyAndHoldStrategy(this.testingPositions);
QuantProject.Business.Timing.Timer timer =
new IndexBasedEndOfDayTimer( firstDateTime,
lastDateTime,
this.benchmark.Ticker);
EndOfDayStrategyBackTester endOfDayStrategyBackTester =
new EndOfDayStrategyBackTester(
"BuyAndHold" , timer , strategy,
historicalQuoteProviderForBackTester ,
new SimpleAccountProvider(), firstDateTime ,
lastDateTime ,
this.benchmark , cashToStart , maxRunningHours );
endOfDayStrategyBackTester.Run();
BackTesterReportViewer.ShowReport( lastDateTime ,
endOfDayStrategyBackTester );
}
#endregion runStrategyClickEventHandlerOnlyInSample
#region runStrategyClickEventHandlerOnlyOutOfSample
protected virtual void runStrategyClickEventHandlerOnlyOutOfSample(object sender, System.EventArgs e)
{
DateTime firstDateTime = this.simulatedCreationDateTime;
DateTime lastDateTime = this.simulatedCreationDateTime.AddDays(this.numberOfInSampleDays);
double maxRunningHours = 1;
int numberOfPortfolioPositions = this.testingPositions.WeightedPositions.Count;
//cash and portfolio type
double cashToStart = 10000;
HistoricalMarketValueProvider historicalQuoteProviderForBackTester,
historicalQuoteProviderForInSampleChooser,
historicalQuoteProviderForStrategy;
historicalQuoteProviderForBackTester = this.historicalMarketValueProvider;
historicalQuoteProviderForInSampleChooser = historicalQuoteProviderForBackTester;
historicalQuoteProviderForStrategy = historicalQuoteProviderForInSampleChooser;
BuyAndHoldStrategy strategy =
new BuyAndHoldStrategy(this.testingPositions);
QuantProject.Business.Timing.Timer timer =
new IndexBasedEndOfDayTimer( firstDateTime,
lastDateTime,
this.benchmark.Ticker);
EndOfDayStrategyBackTester endOfDayStrategyBackTester =
new EndOfDayStrategyBackTester(
"BuyAndHold" , timer , strategy,
historicalQuoteProviderForBackTester ,
new SimpleAccountProvider(), firstDateTime ,
lastDateTime ,
this.benchmark , cashToStart , maxRunningHours );
endOfDayStrategyBackTester.Run();
BackTesterReportViewer.ShowReport( lastDateTime ,
endOfDayStrategyBackTester );
}
#endregion runStrategyClickEventHandlerOnlyOutOfSample
protected virtual void createAndShowContextMenu()
{
MenuItem[] menuItems = new MenuItem[3];
menuItems[0] = new MenuItem("Run Buy&Hold Strategy In Sample And Out of S.");
menuItems[1] = new MenuItem("Run Buy&Hold Strategy Only In Sample");
menuItems[2] = new MenuItem("Run Buy&Hold Strategy Only Out of S.");
menuItems[0].Click +=
new System.EventHandler(this.runStrategyClickEventHandlerInAndOutOfSample);
menuItems[1].Click +=
new System.EventHandler(this.runStrategyClickEventHandlerOnlyInSample);
menuItems[2].Click +=
new System.EventHandler(this.runStrategyClickEventHandlerOnlyOutOfSample);
ContextMenu contextMenu = new ContextMenu(menuItems);
contextMenu.Show(Form.ActiveForm, Form.MousePosition);
}
public void Run()
{
this.createAndShowContextMenu();
}
}
}
|
|
From: Marco M. <mi...@us...> - 2011-08-21 14:07:47
|
Update of /cvsroot/quantproject/QuantProject/b4_Business
In directory vz-cvs-3.sog:/tmp/cvs-serv20022
Modified Files:
Business_SD.csproj
Log Message:
Updated Business project file
Index: Business_SD.csproj
===================================================================
RCS file: /cvsroot/quantproject/QuantProject/b4_Business/Business_SD.csproj,v
retrieving revision 1.43
retrieving revision 1.44
diff -C2 -d -r1.43 -r1.44
*** Business_SD.csproj 16 Jan 2011 19:52:31 -0000 1.43
--- Business_SD.csproj 21 Aug 2011 14:07:45 -0000 1.44
***************
*** 61,64 ****
--- 61,69 ----
<Compile Include="a07_DataProviders\HistoricalQuoteProvider.cs" />
<Compile Include="a07_DataProviders\TickerNotExchangedException.cs" />
+ <Compile Include="a07_DataProviders\VirtualAndHistoricalAdjustedQuoteProvider.cs" />
+ <Compile Include="a07_DataProviders\VirtualQuotesProviding\IVirtualQuotesProvider.cs" />
+ <Compile Include="a07_DataProviders\VirtualQuotesProviding\BasicDerivedVirtualQuoteProvider.cs" />
+ <Compile Include="a07_DataProviders\VirtualQuotesProviding\DerivedVirtualTicker.cs" />
+ <Compile Include="a07_DataProviders\VirtualQuotesProviding\ShortVirtualQuoteProvider.cs" />
<Compile Include="a1_Financial\a2_Accounting\AccountProviding\FixedCommissionsAndSlippageAccountProvider.cs" />
<Compile Include="a1_Financial\a2_Accounting\AccountProviding\IAccountProvider.cs" />
***************
*** 81,85 ****
--- 86,96 ----
<Compile Include="a1_Financial\a2_Accounting\Transactions\TimedTransaction.cs" />
<Compile Include="a1_Financial\a3_Ordering\HistoricalOrderExecutor.cs" />
+ <Compile Include="a1_Financial\a4_Fundamentals\BookValueProvider.cs" />
<Compile Include="a1_Financial\a4_Fundamentals\FairValueProviders\IFairValueProvider.cs" />
+ <Compile Include="a1_Financial\a4_Fundamentals\FairValueProviders\LinearRegression\BasicIndipendentValuesProvider.cs" />
+ <Compile Include="a1_Financial\a4_Fundamentals\FairValueProviders\LinearRegression\BasicLinearRegressionValuesProvider.cs" />
+ <Compile Include="a1_Financial\a4_Fundamentals\FairValueProviders\LinearRegression\ILinearRegressionValuesProvider.cs" />
+ <Compile Include="a1_Financial\a4_Fundamentals\FairValueProviders\LinearRegression\IIndipendentValuesProvider.cs" />
+ <Compile Include="a1_Financial\a4_Fundamentals\FairValueProviders\LinearRegression\LinearRegressionFairValueProvider.cs" />
<Compile Include="a1_Financial\a4_Fundamentals\FairValueProviders\PEGRatioFairValueProvider.cs" />
<Compile Include="a1_Financial\a4_Fundamentals\FundamentalDataProvider.cs" />
***************
*** 89,96 ****
--- 100,110 ----
<Compile Include="a1_Financial\a4_Fundamentals\RatioProviders\LastAvailableGrowthRateProvider.cs" />
<Compile Include="a1_Financial\a4_Fundamentals\RatioProviders\LastAvailablePEProvider.cs" />
+ <Compile Include="a1_Financial\a4_Fundamentals\ReturnOnAssetsProvider.cs" />
<Compile Include="a2_Strategies\BasicStrategyForBacktester.cs" />
<Compile Include="a2_Strategies\Benchmark.cs" />
<Compile Include="a2_Strategies\Eligibles\ByGroup.cs" />
<Compile Include="a2_Strategies\Eligibles\ByLiquidity.cs" />
+ <Compile Include="a2_Strategies\Eligibles\ByRelativeDifferenceBetweenPriceAndFairValue.cs" />
+ <Compile Include="a2_Strategies\Eligibles\ByPriceLiquidityLowestPEQuotedAtAGivenPercentage.cs" />
<Compile Include="a2_Strategies\Eligibles\ByMostDiscountedPrices.cs" />
<Compile Include="a2_Strategies\Eligibles\ByPriceLessLiquidAlwaysIntradayQuoted.cs" />
***************
*** 107,110 ****
--- 121,125 ----
<Compile Include="a2_Strategies\Eligibles\OftenExchanged.cs" />
<Compile Include="a2_Strategies\EndOfDayStrategies\BasicEndOfDayStrategyForBacktester.cs" />
+ <Compile Include="a2_Strategies\EndOfDayStrategies\BuyAndHoldStrategy.cs" />
<Compile Include="a2_Strategies\EndOfDayStrategies\EndOfDayStrategy.cs" />
<Compile Include="a2_Strategies\EndOfDayStrategies\EndOfDayTimerHandler.cs" />
***************
*** 131,134 ****
--- 146,150 ----
<Compile Include="a2_Strategies\Optimizing\Decoding\BasicDecoderForGeneticallyOptimizableTestingPositions.cs" />
<Compile Include="a2_Strategies\Optimizing\Decoding\BasicDecoderForTestingPositions.cs" />
+ <Compile Include="a2_Strategies\Optimizing\Decoding\BasicDecoderForTestingPositionsWithWeights.cs" />
<Compile Include="a2_Strategies\Optimizing\Decoding\DecoderForBalancedWeightedPositions.cs" />
<Compile Include="a2_Strategies\Optimizing\Decoding\DecoderForTestingPositionsWithBalancedWeights.cs" />
***************
*** 291,294 ****
--- 307,311 ----
</ProjectReference>
<Folder Include="a05_Timing\TimingManagement" />
+ <Folder Include="a07_DataProviders\VirtualQuotesProviding" />
<Folder Include="a1_Financial\a2_Accounting\AccountProviding" />
<Folder Include="a1_Financial\a2_Accounting\h5_Reporting\DateTimeSelectorsForEquityLine" />
***************
*** 296,299 ****
--- 313,317 ----
<Folder Include="a1_Financial\a4_Fundamentals" />
<Folder Include="a1_Financial\a4_Fundamentals\FairValueProviders" />
+ <Folder Include="a1_Financial\a4_Fundamentals\FairValueProviders\LinearRegression" />
<Folder Include="a1_Financial\a4_Fundamentals\RatioProviders" />
<Folder Include="a2_Strategies\EndOfDayStrategies" />
|
|
From: Marco M. <mi...@us...> - 2011-08-21 14:07:10
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/Eligibles
In directory vz-cvs-3.sog:/tmp/cvs-serv19997/Eligibles
Added Files:
ByRelativeDifferenceBetweenPriceAndFairValue.cs
Log Message:
ByRelativeDifferenceBetweenPriceAndFairValue has been added.
The class selects as eligibles the most over-valued and the most under-valued tickers on behalf of a given IFairValueProvider passed as parameter
--- NEW FILE: ByRelativeDifferenceBetweenPriceAndFairValue.cs ---
/*
QuantProject - Quantitative Finance Library
ByRelativeDifferenceBetweenPriceAndFairValue.cs
Copyright (C) 2011
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 QuantProject.ADT;
using QuantProject.ADT.Collections;
using QuantProject.ADT.Histories;
using QuantProject.ADT.Messaging;
using QuantProject.ADT.Statistics;
using QuantProject.Business.Financial.Fundamentals.FairValueProviders;
using QuantProject.Data.DataTables;
using QuantProject.Data.Selectors;
namespace QuantProject.Business.Strategies.Eligibles
{
/// <summary>
/// Implements IEligiblesSelector for selecting a given max number of tickers through
/// the following step-by-step selecting process:
/// -step 1: the first maxNumberOfEligibleTickersToBeChosen tickers
/// by liquidity, with a market price >= minPriceForTickers,
/// belonging to a given group (the group can be "temporized":
/// that is tickers are returned depending on the time the
/// selection is requested:
/// the group SP 500 should be like that)
/// are selected;
/// -step 2: from tickers selected by step 1,
/// maxNumberOfEligibleTickersToBeChosen / 2 tickers
/// with the highest negative difference between
/// their average current price (computed for a given
/// number of days) and their fair value
/// (provided by a IFairValueProvider)
/// are added to the first positions of the Eligible
/// Tickers. Choice of these tickers may be done
/// excluding the outliers within a given percentage
/// -step 3: just like step 2, but in this case
/// the focus is on tickers with the highest
/// positive difference (that is, the
/// most expensive with respect to the fair value)
/// </summary>
[Serializable]
public class ByRelativeDifferenceBetweenPriceAndFairValue : IEligiblesSelector
{
public event NewMessageEventHandler NewMessage;
private ITickerSelectorByDate tickerSelectorByDate;
private int maxNumberOfEligibleTickersToBeChosen;
private IFairValueProvider fairValueProvider;
private int firstPercentilesOfTheMostDiscountedOutliersToExclude;
private int firstPercentilesOfTheMostExpensiveOutliersToExclude;
private int numOfDaysForAverageMarketPriceComputation;
public string Description
{
get{
return
"MaxNumOfEligibles_" + this.maxNumberOfEligibleTickersToBeChosen.ToString() + "\n" +
"Most discounted price and the most expensive with respect to a given IFairValueProvider";
}
}
public ByRelativeDifferenceBetweenPriceAndFairValue(IFairValueProvider fairValueProvider,
ITickerSelectorByDate tickerSelectorByDate,
int maxNumberOfEligibleTickersToBeChosen,
int firstPercentilesOfTheMostDiscountedOutliersToExclude,
int firstPercentilesOfTheMostExpensiveOutliersToExclude,
int numOfDaysForAverageMarketPriceComputation)
{
this.fairValueProvider = fairValueProvider;
this.tickerSelectorByDate = tickerSelectorByDate;
this.maxNumberOfEligibleTickersToBeChosen =
maxNumberOfEligibleTickersToBeChosen;
this.firstPercentilesOfTheMostDiscountedOutliersToExclude =
firstPercentilesOfTheMostDiscountedOutliersToExclude;
this.firstPercentilesOfTheMostExpensiveOutliersToExclude =
firstPercentilesOfTheMostExpensiveOutliersToExclude;
this.numOfDaysForAverageMarketPriceComputation =
numOfDaysForAverageMarketPriceComputation;
}
private double getEligibleTickers_actually_getTableOfMostDiscountedAndMostExpensiveTickers_getMostExpensive_getValueFromPercentile(
DataTable initialTableFromWhichToChooseTickers )
{
double returnValue;
double[] relativeDifferencesBetweenFairValueAndPrice =
ExtendedDataTable.GetArrayOfDoubleFromColumn(initialTableFromWhichToChooseTickers,
"RelativeDifferenceBetweenFairAndMarketPrice");
double[] negativeRelativeDifferencesBetweenFairValueAndPrice =
DoubleArrayManager.ExtractNegative(relativeDifferencesBetweenFairValueAndPrice);
returnValue =
BasicFunctions.Percentile(negativeRelativeDifferencesBetweenFairValueAndPrice,
this.firstPercentilesOfTheMostExpensiveOutliersToExclude);
return returnValue;
}
private DataTable getEligibleTickers_actually_getTableOfMostDiscountedAndMostExpensiveTickers_getMostExpensive(
DataTable initialTableFromWhichToChooseTickers )
{
DataTable returnValue;
string filterString =
"AverageMarketPrice is not null AND FairPrice is not null AND " +
"RelativeDifferenceBetweenFairAndMarketPrice < 0 AND " +
"RelativeDifferenceBetweenFairAndMarketPrice >= " +
this.getEligibleTickers_actually_getTableOfMostDiscountedAndMostExpensiveTickers_getMostExpensive_getValueFromPercentile(initialTableFromWhichToChooseTickers);
returnValue =
ExtendedDataTable.CopyAndSort(initialTableFromWhichToChooseTickers,
filterString,
"RelativeDifferenceBetweenFairAndMarketPrice", true);
ExtendedDataTable.DeleteRows(
returnValue,
this.maxNumberOfEligibleTickersToBeChosen / 2 );
return returnValue;
}
private double getEligibleTickers_actually_getTableOfMostDiscountedAndMostExpensiveTickers_getMostDiscounted_getValueFromPercentile(
DataTable initialTableFromWhichToChooseTickers )
{
double returnValue;
double[] relativeDifferencesBetweenFairValueAndPrice =
ExtendedDataTable.GetArrayOfDoubleFromColumn(initialTableFromWhichToChooseTickers,
"RelativeDifferenceBetweenFairAndMarketPrice");
double[] positiveRelativeDifferencesBetweenFairValueAndPrice =
DoubleArrayManager.ExtractPositive(relativeDifferencesBetweenFairValueAndPrice);
returnValue =
BasicFunctions.Percentile(positiveRelativeDifferencesBetweenFairValueAndPrice, 100 - this.firstPercentilesOfTheMostDiscountedOutliersToExclude);
return returnValue;
}
private DataTable getEligibleTickers_actually_getTableOfMostDiscountedAndMostExpensiveTickers_getMostDiscounted(
DataTable initialTableFromWhichToChooseTickers )
{
DataTable returnValue;
string filterString =
"AverageMarketPrice is not null AND FairPrice is not null AND " +
"RelativeDifferenceBetweenFairAndMarketPrice > 0 AND " +
"RelativeDifferenceBetweenFairAndMarketPrice <= " +
this.getEligibleTickers_actually_getTableOfMostDiscountedAndMostExpensiveTickers_getMostDiscounted_getValueFromPercentile(initialTableFromWhichToChooseTickers);
returnValue =
ExtendedDataTable.CopyAndSort(initialTableFromWhichToChooseTickers,
filterString,
"RelativeDifferenceBetweenFairAndMarketPrice", false);
ExtendedDataTable.DeleteRows(
returnValue,
this.maxNumberOfEligibleTickersToBeChosen / 2 );
return returnValue;
}
private EligibleTickers getEligibleTickers_actually_getTableOfMostDiscountedAndMostExpensiveTickers(
DataTable initialTableFromWhichToChooseTickers, DateTime date )
{
double currentFairPrice;
DataTable tableOfEligibleTickers;
if(!initialTableFromWhichToChooseTickers.Columns.Contains("FairPrice"))
initialTableFromWhichToChooseTickers.Columns.Add("FairPrice", System.Type.GetType("System.Double"));
if(!initialTableFromWhichToChooseTickers.Columns.Contains("AverageMarketPrice"))
initialTableFromWhichToChooseTickers.Columns.Add("AverageMarketPrice", System.Type.GetType("System.Double"));
if(!initialTableFromWhichToChooseTickers.Columns.Contains("RelativeDifferenceBetweenFairAndMarketPrice"))
initialTableFromWhichToChooseTickers.Columns.Add("RelativeDifferenceBetweenFairAndMarketPrice", System.Type.GetType("System.Double"));
tableOfEligibleTickers = initialTableFromWhichToChooseTickers.Clone();
this.fairValueProvider.Run(date);
double averageMarketPrice = 0.0;
foreach(DataRow row in initialTableFromWhichToChooseTickers.Rows)
{
try{
double[] quotesForAveragePriceComputation =
Quotes.GetDoubleArrayOfAdjustedCloseQuotes((string)row[0], date.AddDays(-this.numOfDaysForAverageMarketPriceComputation), date);
averageMarketPrice = ADT.Statistics.BasicFunctions.SimpleAverage(quotesForAveragePriceComputation);
if(averageMarketPrice > 0.0)
{
currentFairPrice = this.fairValueProvider.GetFairValue( (string)row[0],
//date.AddDays(-this.numOfDaysForFairValueAnalysis),
date );
row["FairPrice"] = currentFairPrice;
row["AverageMarketPrice"] = averageMarketPrice;
row["RelativeDifferenceBetweenFairAndMarketPrice"] =
((double)row["FairPrice"]-(double)row["AverageMarketPrice"])/(double)row["AverageMarketPrice"];
}
}
catch(Exception ex)
{
string s = ex.ToString();
}
}
DataTable tableOfMostDiscounted =
this.getEligibleTickers_actually_getTableOfMostDiscountedAndMostExpensiveTickers_getMostDiscounted(
initialTableFromWhichToChooseTickers );
DataTable tableOfMostExpensive =
this.getEligibleTickers_actually_getTableOfMostDiscountedAndMostExpensiveTickers_getMostExpensive(
initialTableFromWhichToChooseTickers );
ExtendedDataTable.ImportRowsFromFirstRowOfSource(tableOfMostDiscounted, tableOfEligibleTickers);
ExtendedDataTable.ImportRowsFromLastRowOfSource(tableOfMostExpensive, tableOfEligibleTickers);
//the table has to be ordered in such a way that at the top you find
//the most discounted, at the bottom the most expensive (the nearer you go
//towards the middle from the top / bottom, the less discounted / expensive you find)
DataColumn[] columnPrimaryKeys = new DataColumn[1];
columnPrimaryKeys[0] = tableOfEligibleTickers.Columns[0];
tableOfEligibleTickers.PrimaryKey = columnPrimaryKeys;
string[] tableOfEligibleTickersForDebugging =
ExtendedDataTable.GetArrayOfStringFromRows(tableOfEligibleTickers);
return new EligibleTickers(tableOfEligibleTickers);
}
private EligibleTickers getEligibleTickers_actually(
History history )
{
DateTime currentDate = history.LastDateTime;
DataTable initialTable =
this.tickerSelectorByDate.GetTableOfSelectedTickers(currentDate);
return this.getEligibleTickers_actually_getTableOfMostDiscountedAndMostExpensiveTickers(
initialTable, currentDate);
}
private void getEligibleTickers_sendNewMessage(
EligibleTickers eligibleTickers )
{
string message = this.fairValueProvider.Description + "; " +
"Number of Eligible tickers: " +
eligibleTickers.Count;
NewMessageEventArgs newMessageEventArgs =
new NewMessageEventArgs( message );
if(this.NewMessage != null)
this.NewMessage( this , newMessageEventArgs );
}
/// <summary>
/// Returns the eligible tickers
/// </summary>
/// <returns></returns>
public EligibleTickers GetEligibleTickers(
History history )
{
EligibleTickers eligibleTickers =
this.getEligibleTickers_actually( history );
this.getEligibleTickers_sendNewMessage( eligibleTickers );
return eligibleTickers;
}
}
}
|
|
From: Marco M. <mi...@us...> - 2011-08-21 14:00:22
|
Update of /cvsroot/quantproject/QuantProject/b4_Business/a2_Strategies/Eligibles
In directory vz-cvs-3.sog:/tmp/cvs-serv18224/Eligibles
Added Files:
ByPriceLiquidityLowestPEQuotedAtAGivenPercentage.cs
Log Message:
ByPriceLiquidityLowestPEQuotedAtAGivenPercentage has been added
--- NEW FILE: ByPriceLiquidityLowestPEQuotedAtAGivenPercentage.cs ---
/*
QuantProject - Quantitative Finance Library
ByPriceLiquidityLowestPEQuotedAtAGivenPercentage.cs
Copyright (C) 2011
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 QuantProject.ADT;
using QuantProject.ADT.Histories;
using QuantProject.ADT.Messaging;
using QuantProject.Data.Selectors;
namespace QuantProject.Business.Strategies.Eligibles
{
/// <summary>
/// Implements IEligiblesSelector for selecting a given max number of
/// tickers through the following step-by-step selecting process:
/// -step 0: all tickers belonging to a given group
/// are selected (the group can be "temporized": that is tickers
/// are returned depending on the time the selection is requested:
/// the group SP 500 should be like that);
/// -step 1: from tickers selected by step 0, the most liquid
/// are selected (not more than maxNumberOfMostLiquidTickersToBeChosen);
/// -step 2: from tickers selected by step 1, the ones that have
/// the lowest Price/Earnings ratio are selected;
/// (not more than maxNumberOfEligibleTickersToBeChosen);
/// -step 3: from tickers selected by step 3, the ones that are
/// quoted at least at the given percentage of times
/// with respect to the given benchmark are selected
/// (not more than maxNumberOfEligibleTickersToBeChosen);
/// </summary>
[Serializable]
public class ByPriceLiquidityLowestPEQuotedAtAGivenPercentage : IEligiblesSelector
{
public event NewMessageEventHandler NewMessage;
private bool temporizedGroup;
private string tickersGroupID;
private int maxNumberOfEligibleTickersToBeChosen;
private int maxNumberOfMostLiquidTickersToBeChosen;
private int numOfDaysForAverageOpenRawPriceComputation;
private double minPrice;
private double maxPrice;
private double minPE;
private double maxPE;
private double minPercentageOfDaysWithQuotation;
public string Description
{
get{
return "ByPriceLiquidityLowestPEQuotedAtAGivenPercentage";
}
}
public ByPriceLiquidityLowestPEQuotedAtAGivenPercentage(
string tickersGroupID , bool temporizedGroup,
int maxNumberOfEligibleTickersToBeChosen,
int maxNumberOfMostLiquidTickersToBeChosen,
int numOfDaysForAverageOpenRawPriceComputation,
double minPrice, double maxPrice,
double minPE, double maxPE,
double minPercentageOfDaysWithQuotation)
{
this.temporizedGroup = temporizedGroup;
this.tickersGroupID = tickersGroupID;
this.maxNumberOfEligibleTickersToBeChosen =
maxNumberOfEligibleTickersToBeChosen;
this.maxNumberOfMostLiquidTickersToBeChosen =
maxNumberOfMostLiquidTickersToBeChosen;
this.numOfDaysForAverageOpenRawPriceComputation =
numOfDaysForAverageOpenRawPriceComputation;
this.minPrice = minPrice;
this.maxPrice = maxPrice;
this.minPE = minPE;
this.maxPE = maxPE;
this.minPercentageOfDaysWithQuotation =
minPercentageOfDaysWithQuotation;
}
private EligibleTickers getEligibleTickers_actually(
History history )
{
DateTime currentDate = history.LastDateTime;
SelectorByGroup group;
if(this.temporizedGroup)
//the group is "temporized": returned set of tickers
// depends on time
group = new SelectorByGroup(this.tickersGroupID,
currentDate);
else//the group is not temporized
group = new SelectorByGroup(this.tickersGroupID);
DataTable tickersFromGroup = group.GetTableOfSelectedTickers();
int numOfTickersInGroupAtCurrentDate = tickersFromGroup.Rows.Count;
SelectorByAverageRawOpenPrice byPrice =
new SelectorByAverageRawOpenPrice(tickersFromGroup,false,
currentDate.AddDays(-this.numOfDaysForAverageOpenRawPriceComputation),
currentDate,
numOfTickersInGroupAtCurrentDate,
this.minPrice,this.maxPrice, 0.00001, double.MaxValue);
DataTable dataTableByPrice =
byPrice.GetTableOfSelectedTickers();
SelectorByLiquidity mostLiquidSelector =
new SelectorByLiquidity( dataTableByPrice ,
false, history.FirstDateTime, currentDate,
this.maxNumberOfMostLiquidTickersToBeChosen);
DataTable dataTableMostLiquid =
mostLiquidSelector.GetTableOfSelectedTickers();
SelectorByPE tickersWithLowestPE =
new SelectorByPE(dataTableMostLiquid,
currentDate.AddDays(-this.numOfDaysForAverageOpenRawPriceComputation),
currentDate,
this.minPE, this.maxPE,
this.maxNumberOfEligibleTickersToBeChosen,
true);
// DataSet dataSet = new DataSet();
// dataSet.Tables.Add( dataTableLessVolatile );
// dataSet.WriteXml( "c:\\qpReports\\pairsTrading\\eligiblesCon_ByPriceMostLiquidLessVolatileOTCAlwaysQuoted.xml" );
DataTable dtTickersWithLowestPE = tickersWithLowestPE.GetTableOfSelectedTickers();
SelectorByQuotationAtAGivenPercentageOfDateTimes quotedAtAGivenPercentage =
new SelectorByQuotationAtAGivenPercentageOfDateTimes( dtTickersWithLowestPE ,
false, history, 0,
this.maxNumberOfEligibleTickersToBeChosen,
this.minPercentageOfDaysWithQuotation);
DataTable dataTableToBeReturned =
quotedAtAGivenPercentage.GetTableOfSelectedTickers();
string[] dataTableToBeReturnedForDebugging =
ExtendedDataTable.GetArrayOfStringFromRows(dataTableToBeReturned);
return
new EligibleTickers( dataTableToBeReturned );
}
private void getEligibleTickers_sendNewMessage(
EligibleTickers eligibleTickers )
{
string message = "Number of Eligible tickers: " +
eligibleTickers.Count;
NewMessageEventArgs newMessageEventArgs =
new NewMessageEventArgs( message );
if(this.NewMessage != null)
this.NewMessage( this , newMessageEventArgs );
}
/// <summary>
/// Returns the eligible tickers
/// </summary>
/// <returns></returns>
public EligibleTickers GetEligibleTickers(
History history )
{
EligibleTickers eligibleTickers =
this.getEligibleTickers_actually( history );
this.getEligibleTickers_sendNewMessage( eligibleTickers );
return eligibleTickers;
}
}
}
|