If
you know what you want...
ZIP FILE with All
A_plus_BX
A_plus_BX_plus_CXsq
AlignCorrectly
Alpha2Number
base2decp
beep
BLSIMPVp
BuySell
BX
BX_plus_CXsq
catp
cdd
CDFPooru
Clean
CleanData
CleanNumericBloombergData
CleanOutliers
CleanOutliersStd
CleanOutliersWin
CleanSpikes
ClockElapse
ClockP
Combinep
CombineTimeSeries
CompareSize
CompleteMonths
ConditionalEval
ConditionalMax
ConditionalMin
ConvertRunningToUpfrontCDS
CopyFiles
corrcoefoverlap
corrcoefp
CoSkewness
CountIf
CountWord
Csv2Mat
cumsump
Datamine
Datenump
Datestr
Dec2basep
DecimalDigits
DecimalPlace
DirDotExt
DirExtSize
Einstein
EinsteinCheck
elapsetime
Even
exe
ExpectationXY
fgetln
FGLS
FileExists
FileLength
FindAndReplace
FindNext
FindNext2
finishtime
FiveBetaMeanReversion
Flip
Frac
FuzzyScreen
GetBloombergDailyData
GetBloombergDataByField
GetBloombergHistoricData
GetBloombergTickBarData
GetBloombergTickData
GetBloombergTickFields
GetCalibrationMA
GetCommonDatapoints
GetConditionalCorrelation
GetCS01
GetCVaR
GetErrorStructure
GetEWMA
GetGainLossRatio
GetHighSinceLastLowPrice
GetItem
GetKeatingShadwick
GetLag
GetLastHighPrice
GetLastLowPrice
GetLeeAndReady
GetLitzenbergerRamaswamy
GetLogTime
GetLowSinceLastHighPrice
GetMergedData
GetMergedDataStats
GetMonthlyFundValues
GetMovingSlope
GetOptimalTriggers
GetOrthogonal
GetPairsTradingBidAskPrices
GetPerformanceStats
GetPrevailingDatapoints
GetSharpeRatio
GetSimulationResults
GetSpot
GetStatsForecast
GetStatsReturns
GetStopLossLevel
GetStopLossLevelPercent
GetStopLossLevelRatio
GetTradeQuantity
GetTradeSimulationResults
GetTriggerMA
GetTriggerMeanRev
GetTriggerStatArb
GetTriggerTrend
GetWeeklyFundValues
GroupSummary
Gunzip
GunzipAll
HasNoStar
Histfitp
histp
HypotheticalPosition
InsertInHeader
interp1input
Intersection
InvertStockPrices
IsDelayLongNuff
isnegative
ispositive
IsSignificant
JarqueBera
Jumble
keep
Left
LineLengths
MA
MAE
MakeHTMLContents
MAPE
mean0p
MeanSquareDistance
MergeIntraDayBins
Mid
Mirror
mkcontnt
MovingAverage
MovingAverageForward
MovingSum
MovingVariance
MovingWindowFilter
MPE
mscan
NameNSE
NofCols
NofRows
Number2Alpha
Odd
OptimalPnL
Order
orth_nwest
PackPooru
PadOut
PadZero
PanelFGLS
pausefor
PDFPooru
Percentile
PileUpForBins
PileUpIn3D
PooruStats
Price2Returns
Randomize
RemoveOutliers
RemoveOutliersStd
reshapep
Right
RMSE
RMSPE
Roundp
save_ascii
SevenBetaMeanReversion
signrankp
simple
SimulateFutureARMAprices
SimulateFutureARprices
SimulateFutureGBMprices
SimulateFutureMAprices
SingleBetaMeanReversion
SortAlphabetically
SortStringArray
SPACFp
sql
sqld
Standardise
StandardiseMA
Str2Double
Str2Doublep
str2nump
str2strs
strcatp
strim
SumIf
Surfp
SVaR_Getbqminus
SVaR_Getbrplus
SVaR_Getcxie
SVaR_GetDeltaijx
SVaR_GetLambda_i_epsilonminus
SVaR_GetLambda_i_epsilonplus
SVaR_GetLambdaq
SVaR_GetLambdar
SVaR_GetMi
SVaR_GetPsi
SVaR_GetThetaik
table
Theil
ThreeBetaMeanReversion
TwoBetaMeanReversion
WhereNext2
Width
ZeroCoupon.m
zipload
zipsave
|
If
you want more details...
You can download individual m-files by clicking
on the names below, or download
all in a zip file.
A_plus_BX
out = A_plus_BX(X)
returns X transformed in a manner
suitable for use in
ols(y,RHS)
where RHS = intecept(=A)+slope(=B)*X
i.e. saves you the hassle of specifying:
ones for the intercept
the X terms
see also: BX, A_plus_BX_plusCXsq, BX_plus_CXsq
copyright(c): PNath@London.edu 31-October-2001
A_plus_BX_plus_CXsq
out = A_plus_BX_plus_CXsq(X)
returns X transformed in a manner
suitable for use in
ols(y,RHS)
where RHS = intecept(=A)+slope(=B)*X + slope(=C)*X^2
i.e. saves you the hassle of specifying:
ones for the intercept
the X terms
the X^2 terms
see also: BX, A_plus_BX, BX_plus_CXsq
copyright(c): PNath@London.edu 31-October-2001
AlignCorrectly
CorrectedSeries = AlignCorrectly(IncorrectSeries, CorrectSeries, FrequencyOfAlignment, FirstAlignmentAt)
returns CorrectedSeries which is the IncorrectSeries,
readjusted for being out of line with CorrectSeries
e.g. if IncorrectSeries represents a trader's inventory
created from dirty data, then this function will try and
make up for those missing values by adjusting the entries
at every FrequencyOfAlignment starting at FirstAlignmentAt
Note: If CorrectSeries is longer than IncorrectSeries then
it ignores the last few of CorrectSeries.
If CorrectSeries is shorter than IncorrectSeries then
it keeps the last few of IncorrectSeries unchanged.
Copyright (c): PNath@London.edu 2-12-2000
Alpha2Number
Alpha2Number('letter') returns the position in the
English alphabet of 'letter'.
Not cASe-sENsitiVe.
if letter is a number {e.g. 5}
then 30+letter {e.g. 35} is returned
see also Number2Alpha
Copyright(c): PNath@London.edu 8/12/00
base2decp
BASE2DEC Convert base B string to decimal integer.
BASE2DEC(S,B) converts the string number S of base B into its
decimal (base 10) equivalent. B must be an integer
between 2 and 62.
If S is a character array, each row is interpreted as a base B string.
Example
base2dec('212',3) returns 23
See also DEC2BASEP, BASE2DEC, DEC2BASE, HEX2DEC, BIN2DEC.
Copyright (c) PNath@London.edu 19-July-2000
Copyright (c) 1984-98 by The MathWorks, Inc.
$Revision: 1.13 $ $Date: 1997/11/21 23:47:04 $
Douglas M. Schwarz, 18 February 1996
beep
BLSIMPVp
Purnendu's version of BLSIMPV that does not use the Matlab
provided optimization routines that use "inline" which is
not permitted for COM object construction.
Purnendu's technique actually solves for the optimal (implied
volatility) point by iteration in the code itself.
Copyright(c): PNath.PhD98@London.edu, June-2004
BuySell
out = BuySell(Action, BuyCode, SellCode)
returns +1 or -1 depending on whether the
Action matches BuyCode(1) or SellCode(-1)
If there is no match, 0 is returned.
Copyright(c): PNath@London.edu 8-12-2000
BX
out = BX(X)
returns X transformed in a manner
suitable for use in
ols(y,RHS)
where RHS = slope(=B)*X
i.e. saves you the hassle of specifying:
the X terms
see also: A_plus_BX, A_plus_BX_plusCXsq, BX_plus_CXsq
copyright(c): PNath@London.edu 31-October-2001
BX_plus_CXsq
out = BX_plus_CXsq(X)
returns X transformed in a manner
suitable for use in
ols(y,RHS)
where RHS = slope(=B)*X + slope(=c)*X^2
i.e. saves you the hassle of specifying:
the X terms
the X^2 terms
see also: BX, A_plus_BX, A_plus_BX_plus_CXsq
copyright(c): PNath@London.edu 31-October-2001
catp
out = catp(DIM,A,B,[PadWith])
works similarly to CAT for DIM > 0
but for DIM=0
appends B along the diagonal of A
[ A 0 ]
out = [ 0 B ]
e.g. catp(0,rand(3,3),rand(2,2))
and for DIM=-X appends along dimension X allowing
for unequal sizes. Unexpected spaces are padded with
PadWith (default=0) where required. Works for DIM=-1,-2,-3.
e.g.
X = [-1 -3] Y = [-4]
[-2 5]
catp(-1,X,Y) produces
[-1 -3]
[-2 5]
[-4 ]
Copyright(c): PNath@London.edu 18-Oct-2001
revised: PNath@London.edu 25-Jan-2002
cdd
CDD Change directories using the wildcard *
Change directories using * as a wildcard in the search
directory string name. The wildcard (*) may be placed either
at the beginning or end of the search string. Only a
single wildcard (*) is allowed.
CDD .. moves to the parent directory of the current one.
CDD, by itself, displays the current working directory.
WD = CDD returns the current directory in the string WD.
The functional form of CDD, such as CDD('DirectoryWildcard'),
may be used when the target directory specification is
stored in the string DirectoryWildcard.
For example, to change to directory TargetDirectory,
CDD Tar* or CDD *dire or CDD *tory
CDD is case sensitive, but insensitive to the occurrence of
spaces in the name of the target directory so that
CDD Pro* or CDD *File
changes to the directory "Program Files".
Created by A. Prasad
Updated 8 May 1999
See also CD, PWD
CDFPooru
function CDF = CDFPooru(Returns,NoOfBins)
returns 2 columns...
col 1 = bins (upper-end of data bin)
col 2 = the numerical Cumulative Distribution Function (CDF)
... for the dataseries Returns.
NoOfBins [default=min(20,length(Returns)]
and the first bin is always zero.
see also: PDFPooru, HIST, HISTPOORU, HISTC, HISTFIT
Copyright(c): PNath@London.edu 11-Feb-2002
Clean
CleanMatrixOut = Clean(DirtyMatrixIn,[ErrorFlag])
sets all NaN and -/+Inf in DirtyMatrixIn to
ErrorFlag [default=0] and returns CleanMatrixOut
e.g. Clean(Array,9999999) will set any Inf and NaN
in Array to 9999999
e.g. Clean(Array) will set any Inf and NaN
in Array to 0
see also: CLEANDATA
Copyright(c): PNath@London.edu 19-Dec-2000
amended: PNath@London.edu 12-June-2001
CleanData
CleanedMatrix = CleanData(DirtyMatrix,DIM,NumberOfEndElements,AverageOver,AverageDirection,HaveDelisted,Dirt)
returns a CleanedMatrix by working on DirtyMatrix which is
expected to contain (e.g. time series) data along dimension
DIM = 1 => each series is down a column [default]
DIM = 2 => each series is along a row
but some elements of which have Dirt [default=0] (e.g. missing prices).
The user may specify:
NumberOfEndElements [default=1] from the end over which each series is
examined, to judge that there is indeed trading after missing
data (e.g. the stock hasn't been delisted). The function checks
that the average over the last NumberOfEndElements days is not zero,
and in such a case, works on that column.
The [default=1] number (AverageOver) of previous/future days that the function should
average over to replace zero values. It uses the direction
specified by AverageDirection.
AverageDirection =
-1 [default] (=> use AverageOver historic values for averaging)
+1 (=> use AverageOver future values for averaging)
0 (=> use AverageOver historic and AverageOver future values for averaging)
If HaveDelisted=0 [default] CleanData will not work on those vectors which
have zeros just before the sample period ends.
If you have such vectors then set HaveDelisted=1. In this case the
argument NumberOfEndElements is ignored and the cleaning is only done
between the first and last non-zero elements of each vector.
see also: CLEAN
Copyright(c): PNath@London.edu 29-Dec-2000
improved for Bond data on 1-Nov-2001
CleanNumericBloombergData
BloombergData = CleanNumericBloombergData({Data},[ErrorFlag])
returns in a cellarray the {Data} cleaned
i.e. '#N/A N.A.' returned as ErrorFlag [default=NaN].
Copyright(c): PNath@London.edu
CleanOutliers
CleanedData
= CleanOutliers(DirtyData,DIM,DirtIn,ReturnDirtAs,...
CleanIntraDay,TimeCol,FilterMethod,...
Threshold,ZerosAreData)
returns CleanedData by cleaning DirtyData
The cleaning process:
- works along dimension DIM (default = 2 i.e. data in columns).
- for column/row DirtIn (default = 1 i.e. first column/row).
- replaces outliers with ReturnDirtAs.
- CleanIntraDay=1 (default=0) specifies that each day in the
data should be cleaned independently of other days.
- if CleanIntraDay=1 then the column(row) with the timestamp
in Matlab format needs to be specified (default=1).
- FilterMethod specifies the cleaning technique:
'STD'[default] :type "help CleanOutliersStd" for more info
'WIN' :type "help CleanOutliersWin" for more info
- Threshold is the filter level and works differently for
different FilterMethods.
Default = 3 when FilterMethod = 'STD'
= 0.1 when FilterMethod = 'WIN'
- ZerosAreData = 1 (default=1) implies that zeros in the data
are authentic observations and should be included in the
filter.
e.g. CleanOutliers(DirtyData,1,2,300,1,5,'WIN',0.1,0)
This will return CleanedData by first noting that
- the data is in rows
- that the dirt to be cleaned is in the 2nd row
- the dirt should be replaced by the value 300
- the cleaning will be done intraday
- using the 5th row as the row which has the timestamps
- the FilterMethod 'WIN' will be used to remove spikes
- wherever an observation is more than 10% away (on either
side of the previous observation
- and zeros in the data (2nd row) are to be ignored and
not returned
NOTE: If you would like to remove the dirt completely rather than
replace it with a specified value, then set ReturnDirtAs = []
see also: CleanOutliersStd, CleanOutliersWin
Copyright(c): PNath@London.edu 3-August-2001
CleanOutliersStd
CleanedData = CleanOutliersStd(DirtyData,DIM,DirtIn,ReturnDirtAs,Threshold)
returns CleanedData by cleaning DirtyData
The cleaning process:
- works along dimension DIM (default = 2 i.e. data in columns)
- for column/row DirtIn (default = 1 i.e. first column/row)
- and replaces "dirty" elements with ReturnDirtAs (default = 0)
- "dirt" is defined as those observations greater than
Threshold * StandardDeviations away from the Mean
- Threshold (default = 3 i.e. a 3-std_deviation band on either
side of the mean)
NOTE: To remove "dirty" data completely, set ReturnDirtAs = []
e.g. CleanOutliersStd(DirtyData,1,5,[],2) will work on the fifth
column and throw away all rows that are more than
2 standard deviations from the mean, returning the
"cleaned" array.
see also: CleanOutliersStd, CleanOutliers
Copyright(c): PNath@London.edu 3-Aug-2001
CleanOutliersWin
CleanedData = CleanOutliersWin(DirtyData,DIM,DirtIn,ReturnDirtAs,Threshold)
returns CleanedData by cleaning DirtyData
The cleaning process:
- works along dimension DIM (default = 2 i.e. data in columns)
- for column/row DirtIn (default = 1 i.e. first column/row)
- and replaces "dirty" elements with ReturnDirtAs (default = 0)
- "dirt" is defined as those observations which appear as spikes
greater than the previous_observation by Threshold percent.
- Threshold (default = 0.1 i.e. a 10% spike)
NOTE: To remove "dirty" data completely, set ReturnDirtAs = []
: If there are 2 adjacent outliers they will not be treated
as dirt.
e.g. CleanOutliersWin(DirtyData,1,5,[],1.2) will work on the fifth
column and throw away all rows that have a spike in price
more 20% from the previous price
see also: CleanOutliers, CleanOutliersStd
Copyright(c): PNath@London.edu 3-Aug-2001
CleanSpikes
this currently does a rough job.... need to improve it
Copyright(c): PNath.PhD98@london.edu
ClockElapse
ElapsedTime = ClockElapse(TimeInSeconds)
This function, returns the TimeInSeconds in the
format "3-days 21-hrs 14-mins 3 secs"
Copyright (c): PNath@London.edu 16-August-01
ClockP
OutTime = ClockP
There are no input arguments.
This function, returns the time in the
format "11-Jul-2001 21:07:49"
Copyright (c): PNath@London.edu 11-July-01
Combinep
NewVariableSameName = COMBINEP(VariableName, filename, Direction, path)
allows you to combine a variable in the current workspace
with a different instance of the same variable name saved in
filename (path is optional).
Best to use as follows:
say a = rand(10,10)
and say file 'zeros' saved on 'D:\PhD Stuff\Matlab\Data'
contains a different instance of 'a' e.g. a = zeros(10, 10)
then, using:
>> a = combinep(a, 'v', 'random', 'D:\PhD Stuff\Matlab\Data')
will return
a = 20 x 10 array of [rand(10,10) ; zeros(10,10)]
This is perfect to use when you run a routine several times and
have saved the variable under a different filename each time.
Normally, if you use load, the variable in the workspace gets
over-written by the loaded variable. It also makes you lose
the opportunity to append the 2 variables together.
If you use COMBINEP, you can get around the problem.
using Direction = 'v' or 'V' concatenates vertically
using Direction = 'h' or 'H' concatenates horizontally
see also COMBINE
written by: PNath@London.edu 27/2/00
CombineTimeSeries
NewMaster = CombineTimeSeries(Master, DIM, NewTimeSeries, DefaultValues)
adds NewTimeSeries to Master in appended column (DIM=1)
blanks in original Master and blanks in NewTimeSeries
are buffered with DefaultValues in NewMaster
Copyright(c): PNath.PhD98@london.edu 6-Sep-2004
CompareSize
SameSize = CompareSize(A,B)
returns:
SameSize = 1 if A and B are of the same size
SameSize = 0 otherwise
see also: SIZE
Copyright(c): PNath@London.edu
CompleteMonths
NoOfMonths = CompleteMonths(DateStart, DateEnd)
Gives you the number of complete months
between DateStart and DateEnd
useful for actuaries
Copyright(c): Purnendu Nath (PNath@London.edu) Nov-2002
ConditionalEval
evaluation = ConditionalEval(Matrix,Dim,EvalCommand,[Condition1],[Condition2],[Condition3])
is the generic form of COUNTIF, SUMIF, ConditionalMax/Min
The user specifies what type of EvalCommand is required e.g. 'count', 'mean'
i.e. it returns the Evaluation of elements along dimension Dim (1 or 2)
of a 2-D or 3-D Matrix that satisfy between zero and 3 conditions.
DIM = 1 => eval of elements down each column
DIM = 2 => eval of elements along each row
e.g. a = 10*rand(10,10)
SumOfNumberGreaterThan0 = ConditionalEval(a,1,'sum');
SumOfNumberGreaterThan3 = ConditionalEval(a,1,'sum','>3');
SumOfNumberBetween3and8 = ConditionalEval(a,1,'sum','>3','<8');
see also SUMIF, SUM, FIND, ConditionalMin
Copyright(c): PNath@London.edu 28-Nov-2002
ConditionalMax
maximum = ConditionalMax(Matrix,Dim,[Condition1],[Condition2],[Condition3])
works similar to COUNTIF in Microsoft Excel
i.e. it returns the Maximum of elements along dimension Dim (1 or 2)
of a 2-D or 3-D Matrix that satisfy between zero and 3 conditions.
DIM = 1 => max of elements down each column
DIM = 2 => max of elements along each row
e.g. a = 10*rand(10,10)
MaximumNumberGreaterThan0 = ConditionalMax(a,1,);
MaximumNumberGreaterThan3 = ConditionalMax(a,1,'>3');
MaximumNumberBetween3and8 = ConditionalMax(a,1,'>3','<8');
see also SUMIF, SUM, FIND, ConditionalMin
Copyright(c): PNath@London.edu 28-Nov-2002
ConditionalMin
minimum = ConditionalMin(Matrix,Dim,[Condition1],[Condition2],[Condition3])
works similar to COUNTIF in Microsoft Excel
i.e. it returns the minimum of elements along dimension Dim (1 or 2)
of a 2-D or 3-D Matrix that satisfy between zero and 3 conditions.
DIM = 1 => min of elements down each column
DIM = 2 => min of elements along each row
e.g. a = 10*rand(10,10)
MinimumNumberGreaterThan0 = ConditionalMin(a,1,);
MinimumNumberGreaterThan3 = ConditionalMin(a,1,'>3');
MinimumNumberBetween3and8 = ConditionalMin(a,1,'>3','<8');
see also SUMIF, SUM, FIND, ConditionalMax
Copyright(c): PNath@London.edu 28-Nov-2002
ConvertRunningToUpfrontCDS
out = ConvertRunningToUpfrontCDS(CDS_Spread_Annual, Recovery, PremiumFrequency, RiskfreeRate, CDSMaturityForQuote, TimeRemaining)
e.g.
CDS_Spread_Annual = 0.03 i.e. 300bp
Recovery = 0.4 i.e. 40% recovery
PremiumFrequency = 0.25 i.e. quarterly premia
RiskfreeRate = 0.035 i.e. 3.5%
CDSMaturityForQuote = 5 i.e. 5 year benchmark quote
TimeRemaining = 4.8 i.e. you want the value of a CDS
that has only 4.8 years left to run.
Copyright(c): PNath@London.edu 11-Sep-2003
CopyFiles
corrcoefoverlap
CorrelationCoefficent = corrcoefoverlap(Series1, Series2, DIM, NoOverlapFlag)
if DIM = 1 [default] i.e. each series is in a column
-----------------------------------------------------
assumes that each SeriesX data of the form
[Time Data] i.e. Series1=[Time1 Data1] and Series2=[Time2 Data2]
and then returns the "no nonsense" correlation coefficent
between Data1 and Data2 where these two series overlap in Time1/2.
if DIM = 2 i.e. each series is in a row
----------------------------------------
assumes that each SeriesX data of the form
[Time] [Time1] [Time2]
[Data] i.e. Series1=[Data1] and Series2=[Data2]
and then returns the "no nonsense" correlation coefficent
between Data1 and Data2 where these two series overlap in Time1/2.
This function is ideal for when you have two different time-series
that do not overlap in time perfectly and you want the correlation
based on the sub-samples that do overlap.
If there happens to be no overlap in time, the NoOverlapFlag (default=999999)
chosen by the user is returned.
Copyright(c): PNath@London.edu 1-November-2002
corrcoefp
CorrelationCoefficent = corrcoefp(Series1, Series2)
returns the "no nonsense" correlation coefficent
between Series1 and Series2 i.e element (2,1) of
corrcoef(Series1, Series2)
a 2-fields struct is returned
corr e.g. 0.3
tstat (of corr)
Copyright(c): PNath@London.edu 19-December-2000
amended Sep-2004 to include t-stat
CoSkewness
CoSkewness(MarketReturn,FundReturns)
as defined by Harvey & Siddique (Journal of Finance, 2000)
FundReturn = intercept + Beta*MarketReturn + Gamma*Resid_Of_MarketSq_on_Market
MarketReturn = Tx1
FundReturns = TxN
result is a structure of the form:
---------------------------------------------------
results.meth = 'ols'
results.intercept = intercept {1xN}
results.beta = Beta {1xN}
results.gamma = Gamma {1xN}
results.tstat = t-stats {3xN}
results.rsqr = rsquared {1xN}
results.rbar = rbar-squared {1xN}
results.dw = Durbin-Watson Statistic {1xN}
results.nobs = nobs {1xN}
---------------------------------------------------
Copyright(c): PNath@London.edu 22-May-2002
CountIf
total = CountIf(Matrix,Dim,[Condition1],[Condition2],[Condition3])
works similar to COUNTIF in Microsoft Excel
i.e. it returns the number of elements along dimension Dim (1 or 2)
of a 2-D or 3-D Matrix that satisfy between zero and 3 conditions.
DIM = 1 => counts elements down each column
DIM = 2 => counts elements along each row
e.g. a = 10*rand(10,10)
NumbersGreaterThan0 = CountIf(a,1,);
NumbersGreaterThan3 = CountIf(a,1,'>3');
NumbersBetween3and8 = CountIf(a,1,'>3','<8');
see also SUMIF, SUM, FIND
Copyright(c): PNath@London.edu 29-Dec-2000
CountWord
NumberOfOccurences = CountWord(Filename, Word)
returns the number of occurences of the string Word
in the file Filename.
Copyright (c): PNath@London.edu Dec-2002
Csv2Mat
Csv2Mat(csvfilename, matfilename, [csvdir], [matdir])
loads in csvfilename from path=csvdir [default is current working dir]
and saves as Matlab variable matfilename in file=matfilename
in path=matdir [default is csvdir]
e.g. csv2mat(Trades, 'GovPXdata.csv')
saves data in GovPXdata.csv as a Matlab variable Trades
in a file called Trades.mat in the current working directory.
Copyright(c): PNath@London.edu 28-Dec-2000
cumsump
out = cumsump(Array, DIM)
is like cumsum but in addition allows
DIM to be negative which effectively
does the summing up from the "other end"
e.g. a = 1 2 3 4
100 99 98 97
cumsump(a,1) = cumsum(a,1)
= 1 2 3 4
101 101 101 101
cumsump(a, -1)
101 101 101 101
100 99 98 97
Copyright(c): pnath.phd98@london.edu; 16-April 2004
Datamine
DatamineResults = Datamine(endogenous, exogenous, Max_Number_Exogenous, AlwaysX, YesIntercept, method)
carries out regression:
endogenous = intercept + Beta*AlwaysX + Gamma*exogenous2
where (AlwaysX and exogenous2) = exogenous
returns:
[intercept Beta-x1 Betacoeff-x2 .... Beta-xN ...
... tstat-intercept tstat-x1 tstat-x2 .... tstat-xN...
... Nobs Nvars R-Square R-bar-Sq
intercept Beta-x1 Betacoeff-x2 .... Beta-xN ...
... tstat-intercept tstat-x1 tstat-x2 .... tstat-xN...
... Nobs Nvars R-Square R-bar-Sq
....
etc... ]
for all possible combinations of exogenous2 variables
taking upto a maximum of Max_Number_Exogenous variables
if you want to do all possible combinations then just
set Max_Number_Exogenous to be a large number.
use AlwaysX to indicate which columns should always be on the RHS
and only the rest of them will be used in various combinations.
If you want to take various combinations of all columns then
set AlwaysX = []
use YesIntercept = 0 [default=1] if you don't want an intercept
(e.g. your exogenous data already contains it)
method = 'ols' => do OLS [default]
'probit' => do PROBIT
when ols is used R-Square and R-bar-Sq is as "usual".
for probit R-Square = Estrella R^2
R-bar-Sq = McFadden pseudo-R^2
e.g. datamine(y,x,2, [1 3], 'ols')
will do OLS on y = a + Beta*z + Gamma*x[1 3]
where z is the range of combinations of x
not including x(1) x(3) which are always included
Note: if you set AlwaysX = 1:#-exogenous you get the same
result as doing the single regression on all vars.
Copyright(c): PNath@London.edu 21-Jan-2001
Datenump
out = DATENUMP(DateNumber,OptionNumber)
makes up for the deficiency in the standard
DATENUM function to allow for a date input
in the number format YYYYMMDD
or string format "YYYYMMDD".
'out' is then a date of the format depending on
OptionNumber = 1 => out = [Year Month Day]
OptionNumber = 2 => out = Matlab date integer <-- DEFAULT
OptionNumber = 'x' or 'X' => out = Excel date integer
see also: DATENUM, DATESTR, M2XDATE, X2MDATE
written by: PNath@London.edu
Datestr
DATESTR String representation of date.
DATESTR(D,DATEFORM) converts a serial data number D (as returned by
DATENUM) into a date string. The string is formatted according to the
format number or string DATEFORM (see table below). By default,
DATEFORM is 1, 16, or 0 depending on whether D contains dates, times
or both. Date strings with 2 character years are interpreted to be
within the 100 years centered around the current year.
DATESTR(D,DATEFORM,PIVOTYEAR) uses the specified pivot year as the
starting year of the 100-year range in which a two-character year
resides. The default pivot year is the current year minus 50 years.
DATEFORM = -1 uses the default format.
DATEFORM number DATEFORM string Example
0 'dd-mmm-yyyy HH:MM:SS' 01-Mar-1995 15:45:17
1 'dd-mmm-yyyy' 01-Mar-1995
2 'mm/dd/yy' 03/01/95
3 'mmm' Mar
4 'm' M
5 'mm' 3
6 'mm/dd' 03/01
7 'dd' 1
8 'ddd' Wed
9 'd' W
10 'yyyy' 1995
11 'yy' 95
12 'mmmyy' Mar95
13 'HH:MM:SS' 15:45:17
14 'HH:MM:SS PM' 3:45:17 PM
15 'HH:MM' 15:45
16 'HH:MM PM' 3:45 PM
17 'QQ-YY' Q1-96
18 'QQ' Q1
19 'dd/mm/yyyy' 01/03/1995
20 'dd/mm/yy' 01/03/95
21 'mm/dd/yyyy' 03/01/1995
22 'yyyymmdd' 19950301
23 'yymmdd' 950301
24 'yyyyMMddHHmm' 199503011545
See also DATE, DATENUM, DATEVEC.
amended by: PNath@London 15/3/00
amended by: PNath.PhD98@london.edu on 25-Sep-04 to include DATEFORM=24
Copyright (c) 1984-98 by The MathWorks, Inc.
$Revision: 1.20 $ $Date: 1998/08/12 13:30:37 $
Dec2basep
DEC2BASE Convert decimal integer to base B string.
DEC2BASE(D,B) returns the representation of D as a string in
base B. D must be a non-negative integer smaller than 2^52
and B must be an integer between 2 and 36.
DEC2BASE(D,B,N) produces a representation with at least N digits.
Examples
dec2basep(23,3) returns '212'
dec2basep(23,3,5) returns '00212'
See also BASE2DECP, BASE2DEC, DEC2BASE DEC2HEX, DEC2BIN.
Copyright (c) PNath@London.edu 19-July-2000
Copyright (c) 1984-98 by The MathWorks, Inc.
$Revision: 1.8 $ $Date: 1997/11/21 23:47:11 $
written by Douglas M. Schwarz
Eastman Kodak Company
schwarz@kodak.com
18 February 1996
DecimalDigits
out = DecimalPlace(Data, FromPosition, ToPosition)
returns the digits in the decimal places
specified by FromPosition [default=1] upto ToPosition [default=2]
e.g. decimaldigits(-33.123456789,3,5) returns 345
Can also retrieve numbers on the LHS of the
decimal point by using -ve Position
e.g. decimaldigits(4321.1234,-2,-4) returns 432
see also DecimalPlace, ROUNDP, ROUND, FLOOR, CEIL, FIX, ROUNDOFF
Copyright(c): PNath@London.edu 19-October-2001
DecimalPlace
out = DecimalPlace(Data, Position)
returns the digit in the decimal place
specified by Position [default=1]
e.g. decimalplace(-33.123456789,8) returns 8
Can also retrieve numbers on the LHS of the
decimal point by using -ve Position
e.g. decimalplace(4321.1234,-2) returns 2
see also DecimalDigits, ROUNDP, ROUND, FLOOR, CEIL, FIX, ROUNDOFF
Copyright(c): PNath@London.edu 8-June-2001
DirDotExt
filelist = DirDotExt(Extension,[DataSourcePath],[StartSearch], [NoOfChars], [MakeUpper])
returns the list of files:
- in path "DataSourcePath" (default = current directory)
- with extension "Extension"
- looking in the filenames from character
position StartSearch to position
=StartSearch+NoOfChars-1.
The default is to search through the entire length of the filenames.
e.g. DirDotExt('TRD') will list all the files
with the string "TRD" in the name in the current directory.
i.e. it will find alpha.TRD or TRD.alp
e.g. If you want to list all the *.zip files only, then use
DirDotExt('.zip')
e.g. DirDotExt('TRD',cd,1,3) will search for the string
'TRD' in the first 3 characters in the current working directory.
Copyright: (c) PNath@London.edu 21-July-2000
DirExtSize
[Filenames, Filesizes] = DirExtSize(Extension, DataSourcePath)
returns the list of filenames and filesizes (in bytes):
- in path "DataSourcePath" (default = current directory)
- with extension "Extension"
e.g. DirExtSize('TRD') will list all the files
of the form *.TRD in the current directory
e.g. [x, y] = DirExtSize('GTF', cd) will return in
x = all the filenames
y = the corresponding filesizes (in bytes)
Copyright: (c) PNath@London.edu 13-July-2001
Einstein
EinsteinCheck
first check that the green house is not on the extreme right
elapsetime
prints, to the screen, a line like:
"Elapsed time: 3-days 21-hrs 14-mins 3 secs"
Copyright (c): PNath@London.edu 16-Aug-01
Even
out = odd(number)
returns 1 if an odd integer
returns 0 otherwise
Copyright: PNath@London.edu 04-June-2000
exe
EXE Execute script using wildcard *
EXE ScriptWildCard determines the closest match between
ScriptWildcard and all M-files in current directory and
executes the targeted script file.
For example, the usage
EXE TargetSc*
to execute the script TargetScriptFile. EXE is case
sensitive and the wildcard (*) is placed at the end of the
search string ScriptWildCard.
EXE can be used only with those script files which do not
have an input or an output argument list.
Created by A. Prasad
Updated 10 May 1999
See also RUN
ExpectationXY
returns E(XY) = E(X)E(Y) + Cov(X,Y)
Copyright(c): PNath@London.edu 22-May-2002
fgetln
LINEIS = fgetln(fid, N) returns the Nth line from
the current position in the text file with file-id "fid"
see also: FINDNEXT, FINDNEXT2, GETITEM
written by: PNath@London.edu 27/2/00
FGLS
results = FGLS (Y, X, MaximumLag,Threshold)
Feasible Generalized Least Squares (FGLS) estimation
for the multivariate model
Y = X*B + E, mean(E) = 0, cov(vec(E)) = (s^2)*O
with Y ... T x NoOfY As usual, each row of Y and X is an observation
X ... T x k and each column a variable.
B ... k x NoOfY
E ... T x NoOfY
O ... T*NoOfY x T*NoOfY.
RESULTS has the structure:
results.meth = 'fgls'
results.beta = GLS estimator for B.
results.sige = GLS estimator for s^2
results.resid = matrix of GLS residuals
results.p = p of AR(p) of residuals from
ols(y,x)
results.O = O
results.tstat = t-stats
results.dw = Durbin-Watson Statistic
The matrix of autocorrelations O is estimated by this
function by making calls to SPACFP(X,MaximumLag,Threshold)
to ascertain the p of AR(p) within the O.
MaximumLag [default] = 5
Threshold [default] = 2
see also GLS, SPACFP, PanelFGLS, GetErrorStructure
Copied from GLS of Copyright (C) 1996 John W. Eaton
which was originally a part of Octave.
Copyright(c): PNath@London.edu 17-Oct-2001
FileExists
out = FileExists(Filename, [DataSourcePath])
returns 1 if Filename exists in the DataSourcePath (optional)
returns 0 if it does not
e.g. FileExists('Trades') will check to see if the file
'Trades' is in the current working directory (default option)
Copyright: (c) PNath@London.edu 11-Dec-2000
FileLength
out = FileLength(Filename)
outputs to the screen the number of lines in file Filename
see also LINELENGTHS
Copyright(c): PNath@London.edu 9-12-2000
FindAndReplace
StringOut = FindAndReplace(StringIn,ReplaceFrom,ReplaceTo)
returns StringOut after replacing in String any
occurences of ReplaceFrom with ReplaceTo
e.g. FindAndReplace('the quick brown fox...
the quick brown fox','brown','red')
gives:
'the quick red fox the quick red fox'
Copyright(c): PNath@London.edu 10-August-2001
FindNext
LINEIS = findnext(fid, startat, endat, findstring)
returns the next line at which it found "findstring"
at position range [startat, endat]
in the text file with file-id "fid"
see also: FINDNEXT2, FGETLN, GETITEM
written by: PNath@London.edu 27/2/00
FindNext2
LINEIS = findnext2(fid, startat, endat, findstring, startat2, endat2, findstring2)
returns the next line at which it found "findstring" or "findstring2"
at position range [startat, endat] and [starat2, endat2] respectively
in the text file with file-id "fid"
see also: FINDNEXT, FGETLN, GETITEM
written by: PNath@London.edu 27/2/00
finishtime
prints, to the screen, a line like:
"Completed at 11-Jul-2001 21:06:02"
Copyright (c): PNath@London.edu 11-July-01
FiveBetaMeanReversion
[Eta, EtaTstat, RSquare, HalfLife, XNobs] = FiveBetaMeanReversion(TimeSeriesMatrix3D,Boundaries,Stack)
returns the mean reversion coefficients Eta (5x1 col vector)
the implied half lives (5x1 col vector) HalfLife
for a "five beta" mean reversion model.
Also returns the t-stat of Eta: EtaTstat (5x1 col vector)
as well as the number of observations in each "band" in XNobs
Delta_I(t) = a + Eta1*I(t-1)+ Eta2*I(t-1)+ Eta3*I(t-1)
+ Eta4*I(t-1) + Eta5*I(t-1)+ error_term
assumes TimeSeriesMatrix3D has STANDARDISED INVENTORIES in
Days(rows) x Gilts(cols) x MarketMakers (sheets)
the 5-betas are defined by Boundaries (1x4) or (4x1)
e.g. Boundaries = [-2 -1 1 2]
=> Band:1 x < -2*StdDev
Band:2 -2*StdDev < x < -1*StdDev
Band:3 -1*StdDev < x < +1*StdDev
Band:4 +1*StdDev < x < +2*StdDev
Band:5 +2*StdDev < x
Stack = 0 => [default] return individual gilt figures
= 1 => stack all gilts/GEMMs
Does Newey-West with 5 lags.
EXAMPLE:
>> x = [0.01:0.001:100];
>> [E,Et,RSq,HL] = FiveBetaMeanReversion(sin(500*x'),[-1.3 -1 1 1.3])
Copyright (c): PNath@London.edu 25-Jan-2001
Flip
FlippedBox = Flip(Box,NewFrontIs)
takes a Box (3-D Array) as shown
___________________
/ /|
/ TOP / |
/ / |
/__________________/ |
| : | S |
| ..... rows.... | I |
| : | D |
| cols | E |
| FRONT : | |
| | /
| | /
|__________________|/
and for NewFrontIs = 'TOP' [default] flips it down
so that the TOP becomes the FRONT i.e.
___________________
/ /|
/ BACK / |
/ / |
/__________________/ |
| : | |
| ..... rows.... | |
| : |SIDE
| cols | |
| TOP : | |
| | /
| | /
|__________________|/
ROWS x COLS x SHEETS ---> SHEETS x COLS x ROWS
or
for NewFrontIs = 'SIDE' rotates it east-->west so that
the SIDE becomes the FRONT i.e.
___________________
/ /|
/ TOP / |
/ / |
/__________________/ |
| : | K
| ..... rows.... | C|
| S : | A |
| I cols |B |
| D : | |
| E | /
| | /
|__________________|/
ROWS x COLS x SHEETS ---> SHEETS x ROWS x COLS
This is useful to use in conjuction with mean0p
(type > help mean0p) if your intraday data is sliced
into, say, hourly time slots (along the 3rd DIM) and
some of them have zeros and you want to find a
daily average ignoring the 3rd dimension.
see also: MIRROR
Copyright(c): PNath@London.edu 4-March-2001
Frac
out = frac(DecimalNumber)
returns the decimal (fractional) part
the DecimalNumber.
e.g. frac(3.3) = 0.3
e.g. frac(-3.3) = -0.3
Copyright (c): PNath@London.edu 24-10-2000
FuzzyScreen
FuzzyScreen is a ....
silly program that just asks you how many pixels you want along each
axis of the screen and then creates an NxN pixel screen with random
colours and changes the colours sequentially as many times as you ask it
to.
A waste of time product developed by: PNath@LBS.ac.uk
GetBloombergDailyData
function BloombergData = GetBloombergDailyData(Ticker, Field, StartDate, EndDate)
e.g. spx = getbloombergdailydata('SPX Index', 'PX_LAST', today-1000, today);
to see the list of valid 'Fields' type "load @bloomberg/bbfields" and
examine the variable 'bbfieldnames'.
Copyright(c): PNath.PhD98@london.edu, Sep-2004
GetBloombergDataByField
BloombergData = GetBloombergDataByField( {Tickers} , {Fields} )
returns in a cellarray the Field values for each Ticker
Tickers needs to be a cellarray
Fields needs to be a cellarray
e.g. Tickers = {'IBS US Equity', 'BAY LN Equity'}
Fields = {'NAME', 'Last Price', 'PX_BID', 'PX_ASK'}
GetBloombergHistoricData
BloombergData = GetBloombergHistoricData(Tickers,Fields)
returns in a cellarray the Field values for each Ticker
Tickers needs to be a cellarray
Fields needs to be a cellarray
e.g. Tickers = {'IBS US Equity', 'BAY LN Equity'}
Fields = {'NAME', 'Last Price', 'PX_BID', 'PX_ASK'}
GetBloombergTickBarData
BloombergData = GetBloombergTickBarData({Tickers},Fields, StartDatenum, EndDatenum,BarSize,BarField)
returns in a cellarray the Field values for each Ticker
Tickers needs to be a cellarray with ONLY one ticker
Fields needs to be a cellarray
e.g. GetBloombergTickBarData({'NINFO IS Equity'}, 'BID', now-5, now-4, 5, 'Open')
valid fields are:
BID, MID, ASK
BEST_BID, BEST_ASK
BID_YIELD, LAST_YLD, ASK_YIELD
BID_COND_CODE, ALL_PRICE_COND_CODE, ASK_COND_CODE
LAST_PRICE, VOLUME
BarSize should be an integer > 0
BarFields has valid values of
'Volume'
'High'
'Low'
'Close'
'Open'
'Value'
'Count'
GetBloombergTickData
BloombergData = GetBloombergTickData({Tickers},Fields, StartDatenum, EndDatenum)
returns in a cellarray the Field values for each Ticker
Tickers needs to be a cellarray with ONLY one ticker
Fields needs to be a cellarray
e.g. GetBloombergTickData({'NINFO IS Equity'}, 'BID', now-5, now-4)
valid fields are:
BID, MID, ASK
BEST_BID, BEST_ASK
BID_YIELD, LAST_YLD, ASK_YIELD
BID_COND_CODE, ALL_PRICE_COND_CODE, ASK_COND_CODE
LAST_PRICE, VOLUME
GetBloombergTickFields
ValidFields = GetBloombergTickFields(Ticker, DaysBeforeToday)
valid fields are:
BID, MID, ASK
BEST_BID, BEST_ASK
BID_YIELD, LAST_YLD, ASK_YIELD
BID_COND_CODE, ALL_PRICE_COND_CODE, ASK_COND_CODE
LAST_PRICE, VOLUME
GetCalibrationMA
GetCommonDatapoints
out = GetCommonDatapoints(Series1, Series2, PivotColumn)
returns
out.Series1
out.Series2
which are values for the overlapping dates in Series1
and Series2. The data is assumed to have datenum in the
PivotColumn column. If there are multiple values for a given
datetime only the first set of values is returned.
The values are returned sorted by the datetime column [default=1]
Copyright(c): PNath.PhD98@london.edu
GetConditionalCorrelation
out = GetConditionalCorrelation(FundReturns, BenchmarkReturns)
returns a struct:
out.ConditionPositive
out.ConditionNegative
by splitting the observations into 2 parts:
those periods when the BenchmarkReturns are +ve
and those when the BenchmarkReturns are -ve
Copyright(c): PNath.PhD98@london.edu Sep-2004
GetCS01
CS01 = GetCS01(Recovery, CDSSpread, DiscountRates)
CDSSpread = 0.02 for 200 bp
if DiscountRates is a scalar e.g. 0.02 then
it works out the CS01 assuming a flat yield curve
using the DiscountRates as the FLAT YIELD by first
working out the equivalent quarterly discount rates
Copyright(c): PNath@London.edu Aug-2003
GetCVaR
ConditionalVaR = GetCVaR(Returns,DIM,alpha)
returns the Conditional Value at Risk for a
set of Returns with a critical level given by
alpha e.g. 0.95 [default]
CVaR = E(Loss|Loss > critical level)
DIM = 1 [default] => each column is a security
DIM = 2 => each row is a security
Copyright(c): PNath@London.edu 29-March-2002
CriticalValue = prctile(Returns,(1-alpha)*100);
Losses = Returns(find(Returns<=CriticalValue));
GetErrorStructure
[SigmaMatrix, p] = GetErrorStructure(Y,X,MaximumLag,RestrictLag,Threshold)
returns SigmaMatrix, the error covariance matrix
and p, the AR(p) of SigmaMatrix based on
MaximumLag and Threshold
If RestrictLag=1 then the lag IS forced to be MaximumLag.
if =0 [default] there is no forced restriction
see also: FGLS, GLS, SPACFP, SACF, SPACF
Copyright(c): PNath@London.edu
first do OLS to get residuals
GetEWMA
function z = GetEWMA(data,lambda)
replicates http://lorien.ncl.ac.uk/ming/filter/filewma.htm
lambda = 0 >> returns original series
= 1 >> returns zeros
Copyright(c): PNath.PhD98@london.edu Sep-2004
GetGainLossRatio
GainLossRatio = GetGainLossRatio(FundReturns,[ReferenceReturns])
Copyright(c): PNath@London.edu 5-Feb-2002
GetHighSinceLastLowPrice
HighSinceLastLowPrice = GetHighSinceLastLowPrice.m(Prices,DIM)
returns a matrix the same size as Prices but
with the "low since the last high price" at each tick i.e. row (if DIM=1).
DIM = 1 => each series is down a column [default]
DIM = 2 => each series is along a row
see GetLastHighPrice, GetHighSinceLastLowPrice
Copyright(c): PNath.PhD98@London.edu 27-Feb-2004
GetItem
out = GetItem(CurrentLine, item, delimiter)
returns the item requested from a delimiter separated
character string
e.g. GetItem(a,3,'|') on a = '123|abc|hot,*&L' returns 'hot'
Copyright (c): PNath@London.edu Jan-2000
GetKeatingShadwick
GammaMeasure = GetKeatingShadwick(Returns, NoOfBins)
calculates the Gamma (risk) measure as defined in the paper
"A Universal Risk Measure" - Con Keating + William Shadwick
Copyright(c): PNath@London.edu 11-Feb-2002
GetLag
LaggedValues = GetLag(Data, DIM, LagAmount, DefaultValues)
default: DIM=1; LagAmount=1; DefaultValues=0
e.g. if A =
11 12 13
21 22 23
31 32 33
GetLag(A,1,1,-99) returns
-99 -99 -99
11 12 13
21 22 23%
Copyright(c): PNath.PhD98@london.edu 6th-Sep-2004
GetLastHighPrice
LastHighPrice = GetLastHighPrice(Prices,DIM)
returns a matrix the same size as LastHighPrice but
with the "last high price" at each tick i.e. row (if DIM=1).
DIM = 1 => each series is down a column [default]
DIM = 2 => each series is along a row
see GetLastLowPrice
Copyright(c): PNath.PhD98@London.edu 27-Feb-2004
GetLastLowPrice
LastLowPrice = GetLastLowPrice(Prices,DIM)
returns a matrix the same size as LastLowPrice but
with the "last Low price" at each tick i.e. row (if DIM=1).
DIM = 1 => each series is down a column [default]
DIM = 2 => each series is along a row
see GetLastHighPrice
Copyright(c): PNath.PhD98@London.edu 27-Feb-2004
GetLeeAndReady
BuySellIndicator = GetLeeAndReady(TradePrices)
works out the BuySellIndicator
Buy = +1
Sell = -1
based on Lee & Ready (1991), Journal of Finance
using the "tick test".
Copyright(c): PNath@London.edu 22-Feb-2002
GetLitzenbergerRamaswamy
[OverallBeta, OverallTstat] = GetLitzenbergerRamaswamy(Betas, BetaStdError)
This code is not checked....
it returns the overall beta coefficient and its t-stat
based on Litzenberger & Ramaswamy's GLS technique
in Journal of Financial Economics (1979)
Copyright(c): PNath@London.edu 16-Feb-2002
GetLogTime
out = GetLogTime(Datetimenumber, formattype)
returns a string of the format (default = 1)
formattype:
1 = YYYYMMDDHHMMSS
2 = YYMMDDHHMMSS
3 = YYYYMMDDHHMM
4 = YYMMDD
5 = HHMMSS
6 = HHMM
Copyright(c): PNath@London.edu - 2003
GetLowSinceLastHighPrice
LowSinceLastHighPrice = GetLowSinceLastHighPrice.m(Prices,DIM)
returns a matrix the same size as Prices but
with the "low since the last high price" at each tick i.e. row (if DIM=1).
DIM = 1 => each series is down a column [default]
DIM = 2 => each series is along a row
see GetLastLowPrice, GetHighSinceLastLowPrice
Copyright(c): PNath.PhD98@London.edu 27-Feb-2004
GetMergedData
NewMaster = GetMergedData(Master, DIM, NewData, KeepValuesOf)
DIM = 1 (default) => data in columns
= 2 => data in rows
both Master and NewData assumed to have same number of fields
with datetime in the first column (row) if DIM =1 (2).
Where there are overlapping datetimes e.g. importing some new
values from NewData into Master where some already exist in Master
then KeepValuesOf = 0 << retains Master's values
or KeepValuesOf = 1 << uses NewData's values
note: the results are sorted by the Datetime i.e. 1st column (row)
Copyright(c): PNath.PhD98@london.edu
GetMergedDataStats
Results = GetMergedDataStats(Master, DIM, NewData, KeepValuesOf)
returns descriptive statistics of the results of the merging process
GetMergedData (type "help GetMergedData" to see more).
DIM = 1 (default) => data in columns
= 2 => data in rows
both Master and NewData assumed to have same number of fields
with datetime in the first column (row) if DIM =1 (2).
Where there are overlapping datetimes e.g. importing some new
values from NewData into Master where some already exist in Master
then KeepValuesOf = 0 << retains Master's values
or KeepValuesOf = 1 << uses NewData's values
note: this doesn't actually do the merging but gives you information
of what would happen if you tried to do it using GetMergedData
Copyright(c): PNath.PhD98@london.edu
GetMonthlyFundValues
MonthAndValues = GetMonthlyFundValues(Dates, FundValues)
returns [Dates FundValues]
starting with the first date and then the first date of every
future month, and ending with the last date/value of the series
Copyright(c): PNath.PhD98@london.edu Sep-2004
GetMovingSlope
GetOptimalTriggers
GetOrthogonal
out = GetOrthogonal(X,Y)
returns that component of X that is orthogonal to Y
copyright(c): PNath@London.edu 8-Oct-2003
GetPairsTradingBidAskPrices
Strategy = GetPairsTradingBidAskPrices(BidA, AskA, BidB, AskB, QuantityRatio, PivotColumn, TimeValidFor)
assumes
Long Spread => Long A + Short B.*QuantityRatio
Short Spread => Short A + Long B.*QuantityRatio
and returns, a struct with fields:
.BidPrice
.AskPrice
The datetime is taken to be in PivotColumn [default=1]
and quotes are matched to be stale after TimeValidFor days
e.g. for 10 secs [default] use 10/(24*60*60)
see GetPrevailingDatapoints
Copyright(c): PNath.PhD98@london.edu
GetPerformanceStats
Results = GetPerformanceStats(Observations)
Observations.meth = 'forecast':
requires:
Observations.Expected
Observations.Actual
Observations.Threshold
and runs GetStatsForecast. Type "help GetStatsForecast"
___________________________________________________________
Observations.meth = 'portfolio':
requires:
Observations.Dates
Observations.PortfolioValue
Observations.Riskfree
and runs GetStatsReturns. Type "help GetStatsReturns"
___________________________________________________________
Copyright(c): PNath@London.edu 10-Feb-2004
extended to use multiple methods 7-Sep-2004
GetPrevailingDatapoints
out = GetPrevailingDatapoints(Series1, Series2, TimeValidFor)
returns a struct with fields:
.Series11 --___ same number of rows M
.Series12 --
.Series21 --___ same number of rows N
.Series22 --
which are values for the union of datetimes in Series1
and Series2. The data is assumed to have datenum in the
PivotColumn [default=1] column. If there are multiple values for a given
datetime only the first set of values is returned. The TimeValidFor
is used to check if a value is valid at a certain time e.g. if Series1
has a value that is more than TimeValidFor [default=10 seconds] older then it is counted
as a "dead value" and so for that datetime there is no observation
and so the result will not contain that datetime.
The values are returned sorted by the datetime column, PivotColumn
The datetimes in Series12 and Series 21 are of the original Series2 and Series1
in case the user wants to check what the original timestamps were.
Copyright(c): PNath.PhD98@london.edu
GetSharpeRatio
GainLossRatio = GetSharpeRatio(FundReturns,[ReferenceReturns])
Copyright(c): PNath@London.edu 5-Feb-2002
GetSimulationResults
Results = GetSimulationResults(Strategy)
takes in a struct Strategy and returns a struct with results
Copyright(c): PNath.PhD98@London.edu 27-Feb-2004
GetSpot
spotrate = GetSpot(aaj, tabhi)
returns the United Kingdom spot rate
on date = aaj
for
a future date = tabhi
This uses the Bank of England zero coupon yield curve data
2yr, 2.5yrs, 3yrs..... 24.5yrs, 25yrs
and
the XXXXXXXXXXXX for the
For maturities > 25yrs, the spot rate for 25yrs is returned.
written by: PNath@London.edu on 19/3/00
GetStatsForecast
Results = GetStatsForecast(Actual, Expected, Threshold)
takes your forecast/actual returns and assuming you
go long (short) if your forecast is greater (less) than
threshold (-threshold) outputs the simulated results in
3 segments:
Short: Actual < -Threshold
Hold: -Threshold < Actual < Threshold
Long: Threshold < Actual
RETURNS Results, a structure
with fields:
ShortPositionsStats
HoldPositionsStats
LongPositionsStats
which contain the stats for each of the short/hold/long
e.g. Results = GetStatsForecast(randn(1000,1), randn(1000,1), 0.1)
Copyright(c): PNath@London.edu 10-Feb-2004
GetStatsReturns
Results = GetStatsReturns(Dates, FundValues, Riskfree)
returns a struct with various summary stats on performance:
Results.PooruStats see "help PooruStats" to see what this covers
Results.AnnualizedReturn
Results.DailyReturns
Results.DailyReturnsAnnualized
Results.WeeklyReturns
Results.WeeklyReturnsAnnualized
Results.MonthlyReturns
Results.MonthlyReturnsAnnualized
Results.SharpeRatio
Results.DailyMin
Results.DailyMax
Results.DailyNegNo
Results.DailyNegAvg
Results.DailyPosNo
Results.DailyPosAvg
Results.WeeklyMin
Results.WeeklyMax
Results.WeeklyNegNo
Results.WeeklyNegAvg
Results.WeeklyPosNo
Results.WeeklyPosAvg
Results.MonthlyMin
Results.MonthlyMax
Results.MonthlyNegNo
Results.MonthlyNegAvg
Results.MonthlyPosNo
Results.MonthlyPosAvg
Copyright(c): PNath.PhD98@london.edu Oct-2004
GetStopLossLevel
StopLossLevel = GetStopLossLevel(LossThreshold, BasePrice, TradeQuantity, LongOrShort)
e.g. GetStopLossLevel(1000, 20, 500, -1) returns 22
Copyright(c): PNath.PhD98@london.edu
GetStopLossLevelPercent
StopLossLevelPercent = GetStopLossLevelPercent(LossThreshold, BasePrice, TradeQuantity, LongOrShort)
e.g. GetStopLossLevelPercent(1000, 20, 500, -1) returns 0.1 (i.e. +10%)
Copyright(c): PNath.PhD98@london.edu
GetStopLossLevelRatio
StopLossLevelRatio = GetStopLossLevelRatio(LossThreshold, BasePrice, TradeQuantity, LongOrShort)
e.g. GetStopLossLevelRatio(1000, 20, 500, -1)(1000, 20, 500, -1) returns 1.1
Copyright(c): PNath.PhD98@london.edu
GetTradeQuantity
returns the quantity to trade for
a trade opening at PriceOpen
where we're happy only to experience a loss of LossThreshold
which corresponds to a -ve return of StopLossReturn
e.g. GetTradeQuantity((1000, 20, -0.1) returns 500 contracts
Copyright(c): PNath.PhD98@london.edu
GetTradeSimulationResults
Results.HighSinceLastLowPrice = HighSinceLastLowPrice;
Results.LowSinceLastHighPrice = LowSinceLastHighPrice;
GetTriggerMA
TriggerPoints = GetTriggerMA(Signals,DIM,LongOrShort,Trigger)
returns a matrix the same size as Signals but
with the "open trade P&L" at each tick for a
long or short position.
DIM = 1 => each series is down a column [default]
DIM = 2 => each series is along a row
LongOrShort = 1 => interested in long positions
LongOrShort = -1 => interested in short positions
The trade is triggered when the Signal is Trigger% above (below)
the previous low (high) for a long (short) position.
Copyright(c): PNath.PhD98@London.edu Sep-2004
GetTriggerMeanRev
TriggerPoints = GetTriggerMeanRev(Signals,DIM,LongOrShort,Trigger)
returns a matrix the same size as Signals but
with the "open trade P&L" at each tick for a
long or short position.
DIM = 1 => each series is down a column [default]
DIM = 2 => each series is along a row
LongOrShort = 1 => interested in long positions
LongOrShort = -1 => interested in short positions
The trade is triggered when the Signal is Trigger percentile above (below)
the median.
Copyright(c): PNath.PhD98@London.edu 1-Sep-2004
GetTriggerStatArb
TriggerPoints = GetTriggerStatArb(Signals,DIM,LongOrShort,Trigger)
returns a matrix the same size as Signals but
with the "open trade P&L" at each tick for a
long or short position.
DIM = 1 => each series is down a column [default]
DIM = 2 => each series is along a row
LongOrShort = 1 => interested in long positions
LongOrShort = -1 => interested in short positions
The trade is triggered when the Signal is Trigger percentile above (below)
the median.
see GetOpenTriggerC1
Copyright(c): PNath.PhD98@London.edu 1-Sep-2004
GetTriggerTrend
TriggerPoints = GetTrendTrigger(Prices,DIM,LongOrShort,Trigger)
returns a matrix the same size as Prices but
with the "open trade P&L" at each tick for a
long or short position.
DIM = 1 => each series is down a column [default]
DIM = 2 => each series is along a row
LongOrShort = 1 => interested in long positions
LongOrShort = -1 => interested in short positions
The trade is triggered when the price is Trigger% above (below)
the previous low (high) for a long (short) position.
see GetLastLowPrice
Copyright(c): PNath.PhD98@London.edu 27-Feb-2004
GetWeeklyFundValues
WeekAndValues = GetWeeklyFundValues(Dates, FundValues)
returns [Dates FundValues]
starting with the first date and then the Friday of every
future Week, and ending with the last date/value of the series
Copyright(c): PNath.PhD98@london.edu Sep-2004
GroupSummary
Groups = GroupSummary(Data,DIM,PivotNumber,LookupNumber,Statistic)
Looks down the PivotNumber column (DIM=2 [default]) or row (DIM=1)
to create groups based on distinct entries in that column/row
and then summarises the data in the LookupNumber (default=1)
column/row by returning for each group the Statistic (default='mean')
requested.
e.g.
Data=
[1 2
2 4
3 6
4 8
5 10
6 12
7 14
8 16
9 18
10 20
1 2
2 4
3 6
4 8
5 10
6 12
7 14
8 16
9 18
10 20]
GroupSummary(Data,2,1,2,'sum') returns
1 4
2 8
3 12
4 16
5 20
6 24
7 28
8 32
9 36
10 40
Copyright(c): PNath@London.edu 24-Jan-2002
Gunzip
Gunzip(FileToUnzip, [PathOfZipFile])
performs >> !Gunzip -N FileToUnzip
on the FileToUnzip in the folder
PathOfZipFile (default = current working directory)
see also GUNZIPALL
Copyright (c): PNath@London.edu 21-July-2000
GunzipAll
GunzipAll([PathOfZipFiles], [Extension])
performs >> !Gunzip -N filename
on all the *.Extension files (default is *.GZ)
in the folder:
PathOfZipFiles (default = current working directory)
see also GUNZIP
Copyright (c): PNath@London.edu 21-July-2000
HasNoStar
out = HasNoStar(CurrentString, Star)
returns 1 if there is no character(=Star) in CurrentString
returns 0 otherwise
e.g. HasNoStar(a, '*') on a = '12*34' returns 0
e.g. HasNoStar(a, '*') on a = '1234' returns 1
written by PNath@London.edu
Histfitp
HISTFIT Histogram with superimposed fitted normal density.
HISTFIT(DATA,NBINS,[PlotColor]) plots a histogram of the values in the vector DATA.
using NBINS bars in the histogram. With one input argument, NBINS is set
to the square root of the number of elements in DATA.
PlotColor default is 'b' (blue)
H = HISTFIT(DATA,NBINS) returns a vector of handles to the plotted lines.
H(1) is a handle to the histogram, H(2) is a handle to the density curve.
Amended by: PNath@London.edu 15-Jan-2002
B.A. Jones 2-14-95
Copyright (c) 1993-98 by The MathWorks, Inc.
$Revision: 2.7 $ $Date: 1998/05/28 20:13:55 $
histp
HISTp Histogram.
N = HISTp(Y) bins the elements of Y into 10 equally spaced containers
and returns the number of elements in each container. If Y is a
matrix, HIST works down the columns.
N = HISTp(Y,M), where M is a scalar, uses M bins.
N = HISTp(Y,X), where X is a vector, returns the distribution of Y
among bins with centers specified by X. Note: Use HISTC if it is
more natural to specify bin edges instead.
[N,X] = HISTp(...) also returns the position of the bin centers in X.
HISTp(..., PlotColor) without output arguments produces a histogram bar plot of
the results using PlotColor { r g b y m c k w }. This plot color option was
put in place by PNath@London.edu 24-Dec-2000
See also HISTC, HIST.
J.N. Little 2-06-86
Revised 10-29-87, 12-29-88 LS
Revised 8-13-91 by cmt, 2-3-92 by ls.
Copyright (c) 1984-98 by The MathWorks, Inc.
$Revision: 5.16 $ $Date: 1998/05/22 15:51:00 $
HypotheticalPosition
[LowerPosition, HigherPosition, EqualFlag] = HypotheticalPosition(DataVector, SearchFor, PositionOption)
returns:
LowerPosition: the position in DataVector of the largest element smaller than SearchFor
HigherPosition: the position in DataVector of the smallest element larger than SearchFor
EqualFlag = 1 if there was a perfect match (0 otherwise)
In cases where there are multiple solutions, the PositionOption can be used to choose
PositionOption = 1
=> return the highest/lowest possible value of LowerPosition/HigherPosition
PositionOption = 2
=> return the lowest/highest possible value of LowerPosition/HigherPosition
PositionOption = 3
=> return the highest/highest possible value of LowerPosition/HigherPosition
PositionOption = 4
=> return the lowest/lowest possible value of LowerPosition/HigherPosition
e.g DataVector = [1 3 5 7 9 2 4 6 8 5 6]
[x y z] = HypotheticalPosition(DataVector, 5.5, 1)
returns:
x = 10
y = 8
z = 0
Copyright(c): PNath@London.edu 14-12-00
InsertInHeader
Master = InsertInHeader(Master,Where,VectorToInsert,SortMasterFirst,PivotCellDead)
Returns Master (array) after inserting in either the top
row (Where=1) or the first column (Where=2) the elements of
VectorToInsert such that columns (Where=1) or rows (Where=2)
are inserted to maintain an ascending order in the top row (Where=1)
or first column (Where=2).
SortMasterFirst = 1 => first ensure that the pivot
row/col (Where=1/2) is sorted
[default] = 0 => don't check [SAVES TIME!]
PivotCellDead = 1 => the data is in the format
[ 1 2 3 4 5 6 7]
[101 ]
[102 ]
[103 ]
[104 ]
[105 ]
[106 ]
i.e. there is a pivot cell in the top LHS corner that is of no use
-- OR --
PivotCellDead = 0 => the data is in the format
[ 1 2 3 4 ] [1 ]
[ ] [2 ]
[ ] [3 ]
[ ] OR [4 ]
[ ] [5 ]
[ ] [6 ]
[ ] [7 ]
i.e. there is no pivot cell in the top LHS corner.
This works also if Master is an empty matrix [].
Copyright(c): PNath@London.edu 24-October-2001
interp1input
[x, y, xx, yy] = interp1input(x, y, xx, [yy])
takes dirty input for the interpolation routine
interp1.m of Matlab and returns clean input.
The cleaning simply makes sure that there are
no one-to-many mappings for the x,y variables
e.g. if there is more than 1 trade at a single time
The cleaned data returns the last y, and yy, at
every distinct x and xx.
[yy] is optional
Copyright(c): PNath@London.edu 12-July-01
Intersection
[Aout, Bout] = Intersection(DIM,A,Apivot,B,Bpivot)
looks along DIM
DIM = 1 => common elements expected in cols Apivot and Bpivot [default]
DIM = 2 => common elements expected in rows Apivot and Bpivot
and returns the rows (DIM=1) or cols (DIM=2) that have
a common element in the Apivot/Bpivot position.
Useful when have two daily stock price histories with some
different dates missing in both files. This routine will
help you create versions of the histories that are common
to both stocks.
Copyright(c): PNath@London.edu 13-June-2002
InvertStockPrices
out = InvertStockPrices(MatlabStockFormat)
returns the stock price tree in the usual
finance format i.e. with out(node,time)
Copyright: PNath@London.edu 16/6/00
IsDelayLongNuff
ItIs = IsDelayLongNuff(ReferenceTime,SecondsToPause,TimeStepCounter,BufferTime)
returns 1 (else 0) if elapsed time, ElapsedTime, since ReferenceTime
satisfies:
SecondsToPause*TimeStepCounter < ElapsedTime < SecondsToPause*TimeStepCounter + BufferTime
This is an ideal indicator to decide if e.g. need to backup a file
because 10min have passed since the program commenced.
ReferenceTime = start time of loop (place outside the loop)
TimeStepCounter = loop counter from 1...
see PAUSE, PAUSEFOR
Copyright (c): PNath@London.edu 18-Nov-02
isnegative
out = isnegative(Matrix)
returns
1 = where the element is -ve
0 = elsewhere
see also ISPOSITIVE
Copyright(c): PNath@London.edu 21-Jan-2001
ispositive
out = ispositive(Matrix)
returns
1 = where the element is +ve
0 = elsewhere i.e. 0 or -ve
see also ISNEGATIVE
Copyright(c): PNath@London.edu 21-Jan-2001
IsSignificant
IsSignificant(UpperBound, LowerBound)
returns 1 if the estimate (not required as an argument
to the function) is signficant
returns 0 otherwise
Copyright (c): PNath@London.edu 29-10-2000
JarqueBera
JBpvalue = JarqueBera(Variable)
returns the p-value of the Jarqu-Bera
test of Normality.
NOTE: a low p-value (e.g. 0.03) => NOT Normal
a high p-value (e.g. 0.1) => Normal
Copyright(c): PNath@London.edu 25-Jan-2001
Jumble
JumbledMatrix = Jumble(MatrixToJumble,[DIM])
returns JumbledMatrix containing the same elements
of MatrixToJumble but with the elements moved around randomly.
DIM (optional) specifies the dimension along which you want the
jumbling done. If left out, it returns a matrix with all the elemens
jumbled by first randomising the order across the columns and then
across the rows (DIM=1)
see also RAND, SORT, SORTROWS
Copyright(c): PNath@London.edu 12-Jan-2001
keep
KEEP keeps the base workspace variables of your choice and clear the rest.
CALL: keep var1 var2 var3 ...
Yoram Tal 5/7/98 yoramtal@internet-zahav.net
MATLAB version 5.2
Based on a program by Xiaoning (David) Yang
15/9/99 Bug fix - empty delete sring (due to Hyrum D Johnson)
Find variables in base workspace
Left
out = Left(StringIn, ReturnSoMany)
works similarly to Excel's LEFT() function by
returning the part of StringIn starting at the
leftmost character and including ReturnSoMany characters
If you ask for too many characters i.e. more than
exist in StringIn, it will return StringIn
Copyright(c): PNath@London.edu 8-12-2000
LineLengths
out = linelengths(fid)
outputs to the screen the lengths of lines in file Filename
see also FILELENGTH
Copyright(c): PNath@London.edu 9-12-2000
MA
AveragedSeries = MA(TimeSeries, p, DIM)
returns MA(p) for the TimeSeries
User may specify:
DIM (default = 1) i.e. data in rows
Copyright(c): PNath@London.edu 22-January-2001
MAE
out = MAE(Actual, Expected)
Copyright (c): PNath@London.edu 30-July-2000
MakeHTMLContents
MakeHTMLContents(SourcePath,DestinationPath,ContentsFilename,PageTitle,URLPath,BlankLinesBetween,HideHelp,ShowPercent)
does not return ANYTHING!
It writes an html file specified by ContentsFilename (e.g. ContentsFilename='Utilities.html')
to the path DestinationPath (e.g. DestinationPath='G:\Website')
containing the names of the m-files in SourcePath (e.g. SourcePath='E:\Matlab\Utilities')
with a PageTitle at the top (e.g. PageTitle = 'Utilities m-files by PNath.PhD98@London.edu')
and creates hyperlinks with the parent url given by
URLPath e.g. URLPath = 'http://phd.london.edu/pnath/matlab/utilities/'
and leaves space between m-files specified by BlankLinesBetween (e.g. BlankLinesBetween=3)
Setting
HideHelp=1 will hide the help text inside each m-file
HideHelp=0 will also show all help lines begining with "%" immediately
after the header line in your code
If HideHelp=0 then ShowPercent=1 => shows the % in the help text
ShowPercent=0 => hides the % in the help text
Note: This code is "clever" and will only work upto the first set of % it sees
so make sure your help code is at the top but don't worry about it showing
comments within the body of your code.
Copyright(c): PNath@London.edu 10th January 2002
amended: 4-Jan-2005
MAPE
out = MAPE(Actual, Expected)
Copyright (c): PNath@London.edu 30-July-2000
mean0p
MEAN0p Average or mean value excluding the values that are zero.
adapted from standard Mean(x, dim) of Matlab
by PNath@London.edu [Copyright(c) 18-Dec-2000]
and works for 1D and 2D arrays (not checked for 3D).
type >> help mean for more details
Example: If X = [0 1 2
3 4 5]
then mean(X,1) is [3 2.5 3.5] and mean(X,2) is [1.5
4]
See also MEAN, MEDIAN, STD, MIN, MAX, COV.
Copyright (c) 1984-98 by The MathWorks, Inc.
$Revision: 5.13 $ $Date: 1997/11/21 23:23:55 $
MeanSquareDistance
DistanceMeasure = MeanSquareDistance(Series1, Series2, DIM, NoOverlapFlag)
if DIM = 1 [default] i.e. each series is in a column
-----------------------------------------------------
assumes that each SeriesX data of the form
[Time Data] i.e. Series1=[Time1 Data1] and Series2=[Time2 Data2]
and then returns the Mean Squared Distance between
Data1 and Data2 where these two series overlap in Time1/2.
The Mean Square Distance is computed by first standardising
(see "standardise.m") and then computing the mean of the squared
difference between the 2 series.
if DIM = 2 i.e. each series is in a row
----------------------------------------
assumes that each SeriesX data of the form
[Time] [Time1] [Time2]
[Data] i.e. Series1=[Data1] and Series2=[Data2]
and then returns the Mean Squared Distance between
Data1 and Data2 where these two series overlap in Time1/2.
The Mean Square Distance is computed by first standardising
(see "standardise.m") and then computing the mean of the squared
difference between the 2 series.
This function is ideal for when you have two different time-series
that do not overlap in time perfectly and you want the distance
based on the sub-samples that do overlap e.g. for doing "pairs trading".
If there happens to be no overlap in time, the NoOverlapFlag (default=999999)
chosen by the user is returned.
Copyright(c): PNath@London.edu 26-November-2002
MergeIntraDayBins
SingleSeries = MergeIntraDayBins(ThreeDSeries, SecurityNeeded, Skip)
Works on a ThreeDSeries which has intra-day
time-series (e.g. security prices)down columns and
for the security in each column, the day's split of
time-intervals is along the 3rd dimension.
So, for example, for 5 securities over 100 days and 8 one-hour
intervals ThreeDSeries is of size 100 x 5 x 8
The problem that MergeIntraDayBins solves is recombining
the time bins for SecurityNeeded which are along the
3rd dimension into a single series which progresses through
time both intraday and interday. The SingleSeries returned is
in a single column.
Skip (default = 0) helps the user target either bid or ask
prices, e.g. where even sheets in the 3rd dimension have bid
prices and odd sheets in the 3rd dimension have ask prices.
Skip = 1 => use odd sheets
Skip = 2 => use even sheets
Skip = 0 => use all sheets (e.g. if ThreeDSeries has midquotes)
Copyright(c): PNath@London.edu 24-Feb-2001
Mid
out = Mid(StringIn, StartAt, ReturnSoMany)
works similarly to Excel's MID() function by
returning the part of StringIn starting at StartAt
and including ReturnSoMany characters
Copyright(c): PNath@London.edu 8-12-2000
Mirror
MirrorImage = Mirror(Matrix, DIM)
returns the mirror image (i.e. flipped)
along the dimension DIM (= 1, 2 or 3).
e.g. a = 1 2 3 4
100 99 98 97
Mirror(a,1) returns
100 99 98 97
1 2 3 4
whereas, Mirror(a,2) returns
4 3 2 1
97 98 99 100
see also: FLIP
Copyright(c): PNath@London.edu 29-Dec-2000
mkcontnt
MKCONTNT Make new contents.m file in the current working directory
Copies the H1 line (first comment line) of all m-files found
in the current working directory to a file named "contents.m".
If such a file already exists, a backup copy of it is made to
"contents.old".
For example, if the user has written several m-files
in the directory C:\MATLAB\MY_MFILES, he needs to make this the
current working directory (using either CD or the path browser)
and then type "mkcontnt" at the Matlab prompt.
It is important to note that any fancy editing done to a previous
version of contents.m will be lost. Only the top two lines from the
old version are copied to the new version, but that number can easily
be increased by minor modifications to the code. Use the top few
lines of your contents.m files to describe in general terms what kinds
of tasks are performed by your m-files.
Take the habit of writing informative H1 lines!!!
Tested with Matlab 5.2.1 for Windows 95
Author: Denis Gilbert, Ph.D., physical oceanography
Maurice Lamontagne Institute, Department of Fisheries and Oceans Canada
email: gilbertd@dfo-mpo.gc.ca
August 1998; Last revision: December 07, 1998
MovingAverage
TimeSeriesMA = MovingAverage(TimeSeries,DIM,AveragingPeriod,ZerosIn)
returns the moving average of TimeSeries using an averaging
window of length AveragingPeriod [default = 1].
TimeSeries is assumed to have each timeseries along dimension
DIM = 1 i.e. each series is in a column [default]
DIM = 2 i.e. each series is along a row
Works for TimeSeries input upto 3-D
The entries/size of the array returned depend on
ZerosIn = 0 => the last AveragingPeriod number of rows(cols) are zero
= 1 => the first AveragingPeriod number of rows(cols) are zero
= 2 => [default] the results have AveragingPeriod number of
rows(cols) less
= 3 => the last AveragingPeriod number of rows(cols) are the same as TimeSeries
= 4 => the first AveragingPeriod number of rows(cols) are the same as TimeSeries
see also: MovingVariance, MovingSum
Copyright (c): PNath@London.edu 13-Nov-2000
improved version 1-Nov-2001
ZerosIn (3,4) on 25-Aug-2004
MovingAverageForward
TimeSeriesMA = MovingAverageForward(TimeSeries,DIM,AveragingPeriod,ZerosIn)
returns the moving average of TimeSeries using a forward looking averaging
window of length AveragingPeriod [default = 1].
TimeSeries is assumed to have each timeseries along dimension
DIM = 1 i.e. each series is in a column [default]
DIM = 2 i.e. each series is along a row
Works for TimeSeries input upto 3-D
The entries/size of the array returned depend on
ZerosIn = 1 => the last AveragingPeriod number of rows(cols) are zero
= 0 => the first AveragingPeriod number of rows(cols) are zero
= 2 => [default] the results have AveragingPeriod number of
rows(cols) less
see also: MovingVariance, MovingSum, MovingAverage
Copyright (c): PNath@London.edu 8-Mar-2002
MovingSum
TimeSeriesMA = MovingSum(TimeSeries,DIM,SummingPeriod,ZerosIn)
returns the moving sum of TimeSeries using a summing
window of length SummingPeriod [default = 1].
TimeSeries is assumed to have each timeseries along dimension
DIM = 1 i.e. each series is in a column [default]
DIM = 2 i.e. each series is along a row
Works for TimeSeries input upto 3-D
The entries/size of the array returned depend on
ZerosIn = 0 => the last SummingPeriod number of rows(cols) are zero
= 1 => the first SummingPeriod number of rows(cols) are zero
= 2 => [default] the results have SummingPeriod number of
rows(cols) less
see also: MovingVariance, MovingAverage
Copyright (c): PNath@London.edu 22-January-2002
MovingVariance
TimeSeriesMA = MovingVariance(TimeSeries,DIM,VariancePeriod,ZerosIn)
returns the moving variance of TimeSeries using a rolling
window of length VariancePeriod [default = 1].
TimeSeries is assumed to have each timeseries along dimension
DIM = 1 i.e. each series is in a column [default]
DIM = 2 i.e. each series is along a row
Works for TimeSeries input upto 3-D
The entries/size of the array returned depend on
ZerosIn = 0 => the last VariancePeriod number of rows(cols) are zero
= 1 => the first VariancePeriod number of rows(cols) are zero
= 2 => [default] the results have VariancePeriod number of
rows(cols) less
see also: MovingAverage, MovingSum
Copyright (c): PNath@London.edu Dec-2001
MovingWindowFilter
HitPositions = MovingWindowFilter(Data,DIM,Window,Condition,Direction)
returns a matrix, HitPositions, of the same size as Data
with 1 or 0 in each position depending on whether the
* Condition [default = '==0'] is satisfied
* along a certain DIM [default = 2]
* over a certain Window [default = 1]
* looking backward (Direction = -1 [default])
or forward (Direction = 1)
or both (Direction = 0)
The aim of this poweful function is best explained by example:
e.g. mark those positions with 1 where the stock price
on previous days was below a certain level
e.g. mark those positions with 1 where the stock price
on following days was above a certain level
e.g. mark those positions with 1 where the stock price
on previous and following days was within a certain band
Copyright(c): PNath@London.edu 9-Feb-2001
MPE
out = MPE(Actual, Expected)
Copyright (c): PNath@London.edu 30-July-2000
mscan
MSCAN Version 1.0 Copyright (C) Peter Rydester 1998-12-13
This makes your m-files look better and helps
you find non matching for,if,while,try,else,end
Tested with matlab 5.x
Syntax:
mscan name option
mscan(name,option)
name is filename with/without path and can also
hold wildcard (*) to work on multiple files. If an
optional string argument with an 'r' in is added
it will work on ALL sub directories.
Updates m-files, replaces tabs with spaces and
indents for block structures. Also fixes end of
line: windows (^M ) <--> unix
It works with wildcards and can
Use with care. Backup your m-files first!
Example 1:
mscan /home/mrxx/matlab/*.m r
OR
mscan('/home/mrxx/matlab/*.m','r')
Converts all *.m files in the path and sub
derectories.( Optional r.)
Example 2:
mscan('test*.m');
OR
mscan test*.m
Converts all m-files beginning with 'test' in
current dir. No sub directories.
Comment by PNath@London.edu:
To change tabsize for indent or case (e.g. to set it to be the same
as your editor, change the variables tbsize and casesub.
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.
Please send me an e-mail if you use this:
Peter.Rydesater@ite.mh.se
Mitthgskolan
stersund
Sweden
NameNSE
FullName = NameNSE(StringPart, StockNumber, StockDigits, DayNumber, DayDigits)
returns a string FullName that has 3 parts
StringPart,StockNumber,DayNumber
with appropriate number of zeros
preceding the StockNumber and DayNumber
in case the StockNumber and DayNumber are smaller
than 10^StockDigits and 10^DayDigits
e.g. NameNSE('xyz', 98, 4, 35, 3)
returns xyz0098035
----===
and NameNSE('xyz', 98, 2, 35, 2)
returns xyz9835
Copyright(c): PNath@London.edu
NofCols
out = NofCols(InArray)
returns the number of columns in InArray
see also NofRows, Width
Copyright(c): PNath@London.edu 17-Dec-2000
NofRows
out = NofRows(InArray)
returns the number of rows in InArray
see also Width, NofCols
Copyright(c): PNath@London.edu 17-Dec-2000
Number2Alpha
Number2Alpha('number') returns the letter from the
English alphabet which is in postion 'number'
Not sensitive to fractions, which are rounded to nearest roundeger.
If the number is a 29<40, the integer (number-3) is returned
e.g. Number2Alpha(5) = 'E'
Number2Alpha(35) = '5'
see also Alpha2Number
Copyright(c): PNath@London.edu
Odd
out = odd(number)
returns 1 if an odd integer
returns 0 otherwise
Copyright: PNath@London.edu 04-June-2000
OptimalPnL
Order
Orders = Order(JumbledMatrix,OrderType,OrderDirection)
returns a matrix, Orders, of the same size
as JumbledMatrix with each element of Orders
containing the ranking of the elements in each
column of JumbledMatrix.
e.g. X = [3:-1:0 1:1:3; 1:1:4 2:1:4]'
X =
3 1
2 2
1 3
0 4
1 2
2 3
3 4
then Order(X) returns a matrix
6 1
4 2
2 4
1 6
3 3
5 5
7 7
OrderType = 1 [default] is as above
OrderType = 2 ranks equal observations by their
average rank e.g. for Wilcoxon Sign Test
OrderDirection = 1 [default] is with the rank(smallest) = 1
OrderDirection = 2 is with the rank(largest) = 1
So, Order(X,2,1) returns
6.5 1
4.5 2.5
2.5 4.5
1 6.5
2.5 2.5
4.5 4.5
6.5 6.5
whereas, Order(X,2,2) returns
1.5 7
3.5 5.5
5.5 3.5
7 1.5
5.5 5.5
3.5 3.5
1.5 1.5
Copyright(c): PNath@London.edu 19-Dec-2000
amended: PNath@London.edu 12-Mar-2001
amended: PNath@London.edu 16-Mar-2001
orth_nwest
PURPOSE: computes Newey-West adjusted heteroscedastic-serial
consistent Least-squares Regression
by replacing the column # X2_col of x by
residuals from running
x(:,X2_col) = intercept + x(:,X1_col) + residual
---------------------------------------------------
USAGE: results = orth_nwest(y,x,X1_col,X2_col,nlag)
where: y = dependent variable vector (nobs x 1)
x = independent variables matrix (nobs x nvar)
nlag = lag length to use
---------------------------------------------------
RETURNS: a structure
results.meth = 'newlyw'
results.beta = bhat
results.tstat = t-stats
results.yhat = yhat
results.resid = residuals
results.sige = e'*e/(n-k)
results.rsqr = rsquared
results.rbar = rbar-squared
results.dw = Durbin-Watson Statistic
results.nobs = nobs
results.nvar = nvars
results.y = y data vector
--------------------------------------------------
SEE ALSO: prt_reg(results), plt_reg(results), nwest
---------------------------------------------------
References: Gallant, R. (1987),
"Nonlinear Statistical Models," pp.137-139.
---------------------------------------------------
Copyright(c): PNath@London.edu 19-Oct-2001
PackPooru
PadOut
out = padout(InArray,NoOfPads)
returns a matrix of size:
#-rows = size(InArray,1)*NoOfPads
#-cols = size(InArray,2)
where the extra rows are replicas of the
rows in InArray but inserted between the original
rows (as opposed to repmat, which does it around
the original array.
e.g. InArray = [1 2 3
4 5 6]
then padout(InAray,3) returns
[1 2 3
1 2 3
1 2 3
4 5 6
4 5 6
4 5 6]
Copyright (c): PNath@London.edu 27-10-2000
PadZero
out = PadZero(A,B,DIM,PadWith)
returns A in a matrix of the
same size as B, but with the
extra spaces (if A smaller than B
along DIM{default=1}) filled in with PadWith [default of ZEROs].
e.g. padzero(rand(2,2),rand(3,3))
If B happens to be smaller than A
along any dimension, it doesn't bite.
e.g. padzero(rand(3,4),rand(3,3))
Currently works for DIM=1,2,3 but easily extended for DIM>3
Copyright(c): PNath@London.edu 20-Nov-2001
PanelFGLS
results = PanelFGLS (Y, X, NoOfX, MaximumLag,RestrictLag,Threshold)
Feasible Generalized Least Squares (FGLS) estimation
for the multivariate panel data model
Y = X*B + E, mean(E) = 0, cov(vec(E)) = (s^2)*O
As usual, each row of Y and X is an observation
and each column a variable.
with Y ... T x NoOfY
X ... T x [NoOfX...dummies + k...X_variables]
B ... [NoOfX + k] x NoOfY
E ... T x NoOfY
O ... T*NoOfY x T*NoOfY.
NoOfX ... [default=1] The user specifies this so that
the function can work out the dummy variables.
The supplied X does not need to have the different
dummies in order, as long as they are in chronological
order e.g. the code will automatically pick up, the
observations for the 1st dummy by looking for ones in
in the first column and maintaining the order of their
intermittent appearance in the data.
RESULTS has the structure:
results.meth = 'panel_fgls'
results.beta = GLS estimator for B.
results.sige = GLS estimator for s^2
results.resid = matrix of GLS residuals
results.p = p of AR(p) of residuals from
ols(y,x)
results.O = O
results.tstat = t-stats
results.dw = Durbin-Watson Statistic
The matrix of autocorrelations O is estimated by this
function by making calls to SPACFP(X,MaximumLag,Threshold)
to ascertain the p of AR(p) within the O.
MaximumLag [default] = 5
Threshold [default] = 2
If RestrictLag=1 then the lag IS forced to be MaximumLag.
if =0 [default] there is no forced restriction
see also GLS, SPACFP, FGLS, GetErrorStructure
Copied from GLS of Copyright (C) 1996 John W. Eaton
which was originally a part of Octave.
Copyright(c): PNath@London.edu 17-Oct-2001
pausefor
PauseFor(ReferenceTime,SecondsToPause,TimeStepCounter)
does PAUSE(n) i.e. for n seconds
and is ideal for using in a loop
e.g. for downloading prices at regular intervals
Using the Matlab standard command PAUSE(n) does not
work well for something like the above example because
of the non-zero CPU time spent performing even simple
lines of code.
This function pauses for the right amount of time so that
the loop execution commences at regular intervals spaced
by SecondsToPause. In order to do this, the user needs to
define:
ReferenceTime = start time of loop (place outside the loop)
TimeStepCounter = loop counter from 1...
see PAUSE, IsDelayLongNuff
Copyright (c): PNath@London.edu 9-Nov-02
PDFPooru
function PDF = PDFPooru(Returns,NoOfBins)
returns 2 columns...
col 1 = bins (upper-end of data bin)
col 2 = the numerical Probability Distribution Function (PDF)
... for the dataseries Returns.
NoOfBins [default=min(20,length(Returns)]
and the first bin is always zero.
see also: CDFPooru, HIST, HISTPOORU, HISTC, HISTFIT
Copyright(c): PNath@London.edu 11-Feb-2002
Percentile
PercentileData = Percentile(Data, PivotColumn, Percent, Bin, StragglersIn)
returns only those rows that correspond to the Bin# when the
Data (each row is one observation) is transformed into
quantiles of Percent using the PivotColumn of Data as the
column of interest for creating percentile bins.
This function sorts the data (using PivotColumn) and so the user
does not need to pre-sort the data before sending it to this
function.
If there are any deficient rows then
StragglersIn = 0 puts the deficient rows in the bottom Bin
StragglersIn = 1 puts the deficient rows in the top Bin
e.g. X = repmat([1:1:11]',[1 3])
Percentile(X,1,0.25,3,1)
returns:
7 7 7
8 8 8
9 9 9
whereas, Percentile(X,1,0.25,3,0)
returns:
6 6 6
7 7 7
8 8 8
see also PRCTILE, QUANTILE
Copyright(c): PNath@London.edu 25-12-2000
PileUpForBins
will return the elements of y
replicated by the number of times
as indicated in the vector x
e.g. if y(3) = 7 and x(3) = 4
then 7 will appear 4 times in the output
as the third DISTINCT element (after the
y(1) and y(2) elements).
Copyright(c): PNath@London.edu 15-Dec-2002
PileUpIn3D
ConCatStats = PileUpIn3D(FilenameChar, DataSourcePath,...
DataDestinationPath, FileToSaveIn, varargin)
Does not return anything!
It looks up all files which start with FilenameChar
in DataSourcePath and from each file extracts
all the variable names specified after the input
argument, FileToSaveIn, which are in these files.
It stores these 2-D variables in separate 3-D arrays (each "sheet"
corresponding to one of the files whose name starts with
FilenameChar). It saves these 3-D arrays with the same
variable names but in 3-D format in DataDestinationPath
in a filename specified by FileToSaveIn.
e.g. PileUpIn3D('TWO', cd, cd,'TWOBIG',...
'ONvOFFOFFl','ONvOFFOFFs','ONvOFFl','ONvOFFs')
will:
look for all filenames beginning with TWO
load them up one at a time
from the current working directory (cd)
and from each pick the 4 variables
'ONvOFFOFFl','ONvOFFOFFs','ONvOFFl','ONvOFFs'
and store each in 4(four) 3-D arrays called by the
same names and save these 3-D arrays in
a file called TWOBIG.mat in the
current working directory (cd)
Copyright(c): PNath@London.edu 5th-August-2001
PooruStats
VariableStats = PooruStats(Variable)
RETURNS (for Variable): a structure
VariableStats.NoOfDataPoints = prod(size(Variable));
VariableStats.Minimum = min(Variable);
VariableStats.Maximum = max(Variable);
VariableStats.Median = median(Variable);
VariableStats.Mean = mean(Variable);
VariableStats.StdDev = std(Variable);
VariableStats.Variance = var(Variable);
VariableStats.Skewness = skewness(Variable);
VariableStats.Kurtosis = kurtosis(Variable);
VariableStats.StdError = VariableStats.StdDev./sqrt(VariableStats.NoOfDataPoints);
VariableStats.TStat = VariableStats.Mean./VariableStats.StdError;
VariableStats.PValue = 1-tcdf(abs(VariableStats.TStat),VariableStats.NoOfDataPoints-1);
Copyright(c): PNath@London.edu 22-Dec-2000
Price2Returns
ReturnsMatrix = Price2Returns(PriceMatrix,DIM,Horizon,ReturnsType,ZerosIn,ErrorFlag)
gives you the ReturnsMatrix from the PriceMatrix assuming the time
series data is along dimension DIM (1|2 if each series is in a col|row).
Returns are calculated over a "Horizon" period (e.g. 5 days)
for each day of the sample period.
ReturnsType = 0 does "simple return" {P(t)/P(t-1) - 1}
= 1 does "continuously compounded return" ln{P(t)/P(t-1)}
ZerosIn = 0 => the last Horizon number of rows(cols) are zero
= 1 => the first Horizon number of rows(cols) are zero
= 2 => [default] the results have Horizon number of
rows(cols) less
Also note:
- size(ReturnsMatrix) is the same as size(PriceMatrix)
- errors (e.g. division by zero) are cleaned
and set to ErrorFlag [default=zero] automatically.
see also RET2TICK, TICK2RET, EWSTATS
Copyright(c): PNath@London.edu 31-Dec-2000
Randomize
RandomizedData = Randomize(Data,DIM,WithReplacement)
if Data has (e.g. time-series) observations along
dimension DIM (e.g. DIM=2 => each row is an observation
and the observations are along columns i.e. DIM=2 [default])
then the RandomizedData is drawn from Data.
WithReplacment = 1 => with replacement [default]
WithReplacment = 0 => without replacement
Copyright(c): PNath@London.edu 16-December-2001
RemoveOutliers
WithoutOutliers = RemoveOutliers(DirtyData, Threshold, DIM, DirtIn)
returns WithoutOutliers by cleaning DirtyData
The cleaning process:
- works along dimension DIM (default = 2 i.e. data in columns)
- for column/row DirtIn (default = 1 i.e. first column/row)
- throws out rows/columns with observation greater than
Threshold * StandardDeviations away from the Mean
e.g. RemoveOutliers(DirtyData, 3) will work on the first
column and throw away all rows that are more than
3 standard deviations from the mean, returning the
"cleaned" array.
Copyright(c): PNath@London.edu 3-May-2001
RemoveOutliersStd
WithoutOutliers = RemoveOutliersStd(DirtyData, Threshold, DIM, DirtIn)
returns WithoutOutliers by cleaning DirtyData
The cleaning process:
- works along dimension DIM (default = 2 i.e. data in columns)
- for column/row DirtIn (default = 1 i.e. first column/row)
- throws out rows/columns with observation greater than
Threshold * StandardDeviations away from the Mean
e.g. RemoveOutliers(DirtyData, 3) will work on the first
column and throw away all rows that are more than
3 standard deviations from the mean, returning the
"cleaned" array.
Copyright(c): PNath@London.edu 3-May-2001
reshapep
ReshapedVector = reshapep(Matrix)
takes any Matrix and squeezes it into a long
vector, ReshapedVector.
Copyright(c): PNath@London.edu 27-Dec-2000
Right
out = Right(StringIn, ReturnSoMany)
works similarly to Excel's RIGHT() function by
returning the part of StringIn starting at the
rightmost character and including ReturnSoMany characters
If you ask for too many characters i.e. more than
exist in StringIn, it will return StringIn
Copyright(c): PNath@London.edu 8-12-2000
RMSE
out = RMSE(Actual, Expected)
Copyright (c): PNath@London.edu 30-July-2000
RMSPE
out = RMSPE(Actual, Expected)
Copyright (c): PNath@London.edu 30-July-2000
Roundp
out = Roundp(Data, DecimalPlaces, RoundType)
rounds Data to the DecimalPlaces [default=0] specified
in the format RoundType (string):
'round' => Round towards nearest integer
'floor' => Round towards minus infinity
'ceil' => Round towards plus infinity
'fix' => Round towards zero
e.g. RoundP(33.123456,4,'floor') returns 33.1235
see also DecimalPlace, DecimalDigits, ROUND, FLOOR, CEIL, FIX, ROUNDOFF
Copyright(c): PNath@London.edu 8-June-2001
save_ascii
Saves current variables in a delineated ASCII file:
variable names 1st, horizontally, with data for each below the name.
Usage/Input: save_ascii(loadname,savename,dataformat,delineator);
where,
-"loadname" = filename of the *.mat file to save as ASCII
-"savename" = filename to save this text output to
-"dataformat" = format of 'double array' data (e.g. '%6f' for
six digit fixed-point notation)
-"delineator" = what to delineate data blocks with (e.g. '\t' for tab)
eg. save_ascii('data.mat','textfile.txt','%6f','\t');
Limitations: This script can only handle two data types: 'char' and
'double', where the 'char' types can only be one dimensional
(e.g. size = 1X15), and the 'double array's can be one or two dimensional
(e.g. sizes = 52X1, 1X52, or 30X344).
Notes: Since this saves the matrices as they exist, I suggest keeping one
dimensional arrays in columnar form, so they get saved that way. For
example, ensure the size is 52X1, not 1X52, as the latter will get saved
as a row of data, not as a column (this doesn't apply to char arrays).
Loops within loops, whew. Perhaps this isn't the most elegant way
to do this, but it works. It can be quite time consuming on even
moderately sized files. Also expect a large change in size as this file
changes from binary to ASCII.
The 'loadname' file cannot contain the following variables:
bl, c, dataformat, delineator, fid, i, j, loadname, perdone, r,
savename, & vrbls
Variables will be saved in alphabetical order; the same order as they
appear with the command 'whos'.
Output: Text file of name input as 'savename'.
eg.:
load data.mat
whos
Name Size Bytes Class
box 2x2 32 double array
col 4x1 32 double array
row 1x4 32 double array
text 1x4 8 char array
save_ascii('data.mat','textfile.txt','%6f','\t');
Then, if open 'textfile.txt' in a spreadsheet:
| box | | col | row | | | | text |
| 1 | 2 | 1 | 1 | 2 | 3 | 4 | test |
| 3 | 4 | 2 | | | | | |
| | | 3 | | | | | |
| | | 4 | | | | | |
see also: save
Author: Kirk Ireson, 28 Feb 1999 (kireson@ucsd.edu)
Tested on Matlab v. 5.2.0.3084
Copyright (c) Kirk Ireson,
Marine Life Research Group,
Scripps Institution of Oceanography,
University of California, San Diego
Permission is granted to modify and re-distribute this
code in any manner as long as this notice is preserved.
All standard disclaimers apply.
Please notify me if you find this script useful, it's nice to get
feedback!
SevenBetaMeanReversion
[Eta, EtaTstat, RSquare, HalfLife, XNobs] = SevenBetaMeanReversion(TimeSeriesMatrix3D,Boundaries,Stack)
returns the mean reversion coefficients Eta (7x1 col vector)
the implied half lives (7x1 col vector) HalfLife
for a "seven beta" mean reversion model.
Also returns the t-stat of Eta: EtaTstat (7x1 col vector)
as well as the number of observations in each "band" in XNobs
Delta_I(t) = a + Eta1*I(t-1)+ Eta2*I(t-1)+ Eta3*I(t-1)
+ Eta4*I(t-1) + Eta5*I(t-1)
+ Eta6*I(t-1) + Eta7*I(t-1)+ error_term
assumes TimeSeriesMatrix3D has STANDARDISED INVENTORIES in
Days(rows) x Gilts(cols) x MarketMakers (sheets)
the 7-betas are defined by Boundaries (1x6) or (6x1)
e.g. Boundaries = [-2 -1 -0.5 0.5 1 2]
=> Band:1 x < -2*StdDev
Band:2 -2*StdDev < x < -1*StdDev
Band:3 -1*StdDev < x < -0.5*StdDev
Band:4 -0.5*StdDev < x < +0.5*StdDev
Band:5 +0.5*StdDev < x < +1*StdDev
Band:6 +1*StdDev < x < +2*StdDev
Band:7 +2*StdDev < x
Stack = 0 => [default] return individual gilt figures
= 1 => stack all gilts/GEMMs
Does Newey-West with 5 lags.
EXAMPLE:
>> x = [0.01:0.001:100];
>> [E,Et,RSq,HL] = SevenBetaMeanReversion(sin(500*x'),[-1.3 -1 -.5 0.5 1 1.3])
Copyright (c): PNath@London.edu 4-Mar-2002
signrankp
SIGNRANK Wilcoxon signed rank test of equality of means for
comparing samples of unequal size.
P = SIGNRANK(X,Y,ALPHA) returns the significance probability
that the means of two samples, X and Y are equal.
X and Y need not be vectors of equal length. ALPHA is the desired
level of significance. and must be a scalar between
zero and one.
[P, H] = SIGNRANK(X,Y,ALPHA) also returns the result of the
hypothesis test, H. H is zero if the difference in means of
X and Y is not significantly different from zero. H is one if
the two means are significantly different.
P is the probability of observing a result equally or more
extreme than the one using the data (X and Y) if the null
hypothesis is true. If P is near zero, this casts doubt on
this hypothesis.
Currently works for sample sizes > 25.
see also SIGNRANK, RANKSUM
Copyright(c): PNath@London.edu 12-Mar-2001
simple
SimulateFutureARMAprices
THIS CODE IS UNDER DEVELOPMENT AND WILL BE READY BY Feb-2002
StockPrice = SimulateFutureARMAprices(StartPrice,SigmaVol,ARp,MAq,NoOfSimulations,DeltaT,NoOfTimeSteps, RiskFreeRate)
returns simulated security prices starting at StartPrice
and going forward in time, where the underlying process
of the security is ARMA(p,q)
where p and q are the lengths of vectors ARp and MAq containing the coefficients of the
AR and MA parts.
S(t) = ARp(1)S(t-1) + ARp(2)S(t-2) + ARp(3)S(t-3)+...+ARp(p)S(t-p) + SigmaVol.dZ
The StockPrices returned is an array with
- # cols = NoOfTimeSteps + 1
- the first column = StartPrice
- # rows = NoOfSimulations
The simulation is done using the antithetic variable technique
and thus ensures that both the LHS and RHS halves of the normal
distribution are covered.
Copyright(c): PNath@London.edu 3-Jan-2002
SimulateFutureARprices
StockPrices = SimulateFutureARprices(a0, ARp, x0, SigmaVol, NoOfSimulations, NoOfTimeSteps)
returns simulated security prices where the underlying process
of the security is ARMA(p)
where p is the length of the vectors ARp containing the coefficients of the AR part.
S(t) = a0 + ARp(1)S(t-1) + ARp(2)S(t-2) + ARp(3)S(t-3)+...+ARp(p)S(t-p) + SigmaVol.dZ
x0 are the initialization values corresponding to each ARp so as to give the first
simulated value S(1) = a0 + ARp(1)x0(1) + ARp(2)x0(2) + ARp(3)x0(3) +...+ARp(p)x0(p) + SigmaVol.dZ
e.g. SimulateFutureARprices(0.1, [0.2; 0.3], [0; 0], 0.2, 50, 50)
The StockPrices returned is an array with
- # cols = NoOfTimeSteps
- # rows = NoOfSimulations
The simulation is done using the antithetic variable technique
and thus ensures that both the LHS and RHS halves of the normal
distribution are covered.
Copyright(c): PNath@London.edu 26-Nov-2003
SimulateFutureGBMprices
StockPrices
= SimulateFutureGBMprices(StartPrice, SigmaVol, ...
NoOfSimulations, DeltaT, NoOfTimeSteps, RiskFreeRate)
returns simulated security prices starting at StartPrice
and going forward in time, where the underlying process
of the security is Geometric Brownian Motion
dS = mu.dt + sigma.dZ
here: dStockPrice = RiskFreeRate.DeltaT + SigmaVol.dZ
The StockPrices returned is an array with
- # cols = NoOfTimeSteps + 1
- the first column = StartPrice
- # rows = NoOfSimulations
The simulation is done using the antithetic variable technique
and thus ensures that both the LHS and RHS halves of the normal
distribution are covered.
e.g. SimulateFutureGBMprices(1, 0.4, 10, 0.25, 50, 0.03)
Copyright(c): PNath@London.edu 19-July-2001
Revised to transpose: pnath.phd98@london.edu 27-Feb-2004
SimulateFutureMAprices
StockPrices = SimulateFutureMAprices(MAq, SigmaVol, NoOfSimulations, NoOfTimeSteps)
returns simulated security prices where the underlying process
of the security is ARMA(q)
where q is the length of the vectors MAq containing the coefficients of the AR part.
S(t) = a0 + MAq(1)S(t-1) + MAq(2)S(t-2) + MAq(3)S(t-3)+...+MAq(q)S(t-q) + SigmaVol.dZ
e.g. SimulateFutureMAprices([0.2; 0.3], 0.2, 50, 50)
The StockPrices returned is an array with
- # cols = NoOfTimeSteps
- # rows = NoOfSimulations
The simulation is done using the antithetic variable technique
and thus ensures that both the LHS and RHS halves of the normal
distribution are covered.
Copyright(c): PNath@London.edu 26-Nov-2003
SingleBetaMeanReversion
[Eta, EtaTstat, RSquare, HalfLife] = SingleBetaMeanReversion(TimeSeriesMatrix,[Type])
returns the mean reversion coefficients, Beta
and the Intercept [Intercept Beta] in Eta
Eta = #MM x 2
the implied half lives (row vector) HalfLife
for a "single beta" mean reversion model
Delta_I(t) = a + Eta * I(t-1) + error_term
If Type
= 'pooled' [default] then you get intercept dummies
and a common slope (i.e. mean reversion coeff/ half life)
= 'separate' then you get separate estimates for each MM
= 'compare' then you get each MM compared with the others
note: in this case the TimeSeriesMatrix should contain
two series in a cellarray:
TimeSeriesMatrix{1,1} and
TimeSeriesMatrix{2,1}
Does Newey-West with 5 lags.
Copyright (c): PNath@London.edu 16-Nov-2000
SortAlphabetically
out = SortAlphabetically(OriginalList)
sorts the character strings defined in OriginalList
by pure alphabetical order WITHOUT treating upper
and lower case differently and returns the sorted
list in the ORIGINAL case format i.e. without
converting any of the lower cases to upper or
vice versa.
Useful example: x = DirDotExt('.m')
x = SortAlphabetically(x)
will return the m-files in the current working
directory in alphabetical order treating
abdallah.m as coming before Bahrain.m which
is treated as coming before calcutta.m
see also: SortStringArray
Copyright(c): PNath@London.edu
SortStringArray
SortedStrings = SortStringArray(StringArray)
sorts StringArray
e.g a = [xyz abc lmn]
SortStringArray(a) returns [abc lmn xyz]
see also: SortAlphabetically
Copyright(c): PNath@London.edu 17-12-2000
SPACFp
PURPOSE: find sample partial autocorrelation coefficients
----------------------------------------------------------------------
USAGE: result = spacf(TimeSeries,MaximumLag,Threshold)
where: TimeSeries = a time-series (need not have mean zero)
MaximumLag = [default=5] # sample partial autocorr to compute
Threshold = [default=2] for ascertaining p in AR(p)
----------------------------------------------------------------------
RETURNS:
result as a structure
result.SPACF = an MaximumLag x 1 vector of sample pacf's
result.Threshold = a MaximumLag x 2 vector of Thresholds used
result.pMost = largest p of AR(p) such that p>Threshold
result.pMax = is the p of AR(p) with the largest abs(SPACF(p))
----------------------------------------------------------------------
SEE ALSO: sacf, spacf
----------------------------------------------------------------------
Copyright(c): PNath@London.edu 17-Oct-2001
sql
out = sql(SQLscript)
uses AIM Production (server) to
run the SQLscript and return the
results
Copyright(c): PNath.PhD98@london.edu 26-Apr-2004
sqld
out = sqld(SQLscript)
uses AIM Production (server) to
run the SQLscript and return the
results in a double array rather than cellarray
USE THIS ONLY when you KNOW the results are purely numeric.
Copyright(c): PNath.PhD98@london.edu 26-Apr-2004
Standardise
StandardisedData = Standardise(DataToStandardise, StartForStd,StepForStd, SubtractMean)
returns the DataToStandardise in a standardised format by
dividing by the standard deviation of the data sampled starting at
StartForStd, and taking every StepForStd. The (time-series) data
is assumed to be in columns.
The mean of the data is subtracted if
SubtractMean = 1
and the mean is not subtracted if
SubtractMean <> 1
Note:
if the input numbers are all zeros, then the output is zero
if the ouput has any Inf or Nan they are set to zero too
see also STANDARDISEMA
Copyright (c): PNath@London.edu 7-Nov-2000
StandardiseMA
StandardisedData = StandardiseMA(DataToStandardise, DIM, StartForStd,StepForStd, AveragingPeriod)
returns the DataToStandardise in a standardised format by
first subtracting the MovingAverage(DataToStandardise,AveragingPeriod)
and then dividing by the standard deviation of that Moving Average.
DataToStandardise is assumed to have each timeseries along dimension
DIM = 1 i.e. each series is in a column
DIM = 2 i.e. each series is along a row
DataToStandardise is assumed to have the timeseries in columns
e.g. if DataToStandardise is 3-D then time is assumed to progress along DIM=2
Data is sampled (for the MovingAverage) starting
at StartForStd, and taking every StepForStd.
Note: the first MovingAverage rows will be zeros
see also STANDARDISE
Copyright (c): PNath@London.edu 7-Nov-2000
Str2Double
out = Str2Double(String)
returns the following large number for a String argument:
e.g.
String = 9127946F6
doubleString = double(String)
= 57 49 50 55 57 52 54 70 54
then:
out = 54,070,054,052,057,055,050,049,057
written by PNath@LBS.ac.uk
Str2Doublep
out = Str2Doublep(String)
returns the following large number for a String argument:
e.g.
String = 9127946F6
doubleString = double(String)
= 57 49 50 55 57 52 54 70 54
then:
out = 54,070,054,052,057,055,050,049,057
written by PNath@LBS.ac.uk
str2nump
STR2NUM Convert string matrix to numeric array.
X = STR2NUM(S) converts a character array representation of a matrix of
numbers to a numeric matrix. For example,
S = ['1 2' str2num(S) => [1 2;3 4]
'3 4']
This works exactly like str2num except that an empty string returns a
0 (zero) rather than [].
The numbers in the string matrix S should be ASCII character
representations of a numeric values. Each number may contain digits,
a decimal point, a leading + or - sign, an 'e' preceding a power of
10 scale factor, and an 'i' for a complex unit.
If the string S does not represent a valid number or matrix,
STR2NUM(S) returns the empty matrix.
CAUTION: STR2NUM uses EVAL to convert the input argument, so side
effects can occur if the string contains calls to functions. Use
STR2DOUBLE to avoid such side effects or when S contains a single
number.
Also spaces can be signficant. For instance, str2num('1+2i') and
str2num('1 + 2i') produce x = 1+2i while str2num('1 +2i') produces
x = [1 2i]. These problems are also avoided when you use STR2DOUBLE.
See also STR2DOUBLE, NUM2STR, HEX2NUM, CHAR.
Copyright (c) 1984-98 by The MathWorks, Inc.
$Revision: 5.25 $ $Date: 1998/05/12 23:56:38 $
str2strs
this function takes s (a string deliminated by tabs, commas, etc.)
and breaks it up into sub strings stored in y (a cell array of strings)
spaces are eliminated by the function strcat so these are replaced in the
beginning by an underscore. space delimination can be handled, though s
should be checked for any pre-existing underscrores.
recovery of the individual elements is by using the char command
e.g., applying it to a tab deliminated string...
fields = str2strs('abc d%* 34_EF 5 s p a c e s') returns
'abc' 'd%*' '34_EF' '5' 's_p_a_c_e_s'
and then
char(fields(3)) returns
34_EF
David Malicky malicky@umich.edu
replace each space w/ a character that strcat won't miss
strcatp
STRCATP Concatenate strings.
T = STRCAT(S1,S2,S3,...) horizontally concatenates corresponding
rows of the character arrays S1, S2, S3 etc. The trailing
padding ARE NOT ignored. All the inputs must have the same number of
rows (or any can be a single string). When the inputs are all
character arrays, the output is also a character array.
T = STRCAT(S1,S2,...), when any of the inputs is a cell array of
strings, returns a cell array of strings formed by concatenating
corresponding elements of S1,S2, etc. The inputs must all have
the same size (or any can be a scalar). Any of the inputs can
also be character arrays.
Example
strcat({'Red','Yellow'},{'Green','Blue'})
returns
'RedGreen' 'YellowBlue'
See also STRVCAT, CAT, CELLSTR.
AMENDED by PNath@London.edu 24-10-2000 to NOT IGNORE TRAILING BLANKS
Copyright (c) 1984-98 by The MathWorks, Inc.
$Revision: 1.11 $ $Date: 1998/06/23 16:27:06 $
The cell array implementation is in @cell/strcat.m
strim
STRIM(S) strip the trailing and leading blanks of a string.
STRIM(S)is an extension of the MATLAB function DEBLANK(S)
and removes both leading and trailing blanks from the string S.
Date 11-08-98
Written by Stefan Baunack. Please send any bug
reports or other comments to: s.baunack@ifw-dresden.de.
SumIf
total = SumIf(Matrix,Dim,[Condition1],[Condition2],[Condition3])
works similar to SUMIF in Microsoft Excel
i.e. it returns the sum of elements along dimension Dim (1 or 2)
of a 2-D or 3-D Matrix that satisfy between zero and 3 conditions
DIM = 1 => sums elements down each column
DIM = 2 => sums elements along each row
e.g. a = 10*rand(10,10)
SumNumbersGreaterThan0 = SumIf(a,1,);
SumNumbersGreaterThan3 = SumIf(a,1,'>3');
SumNumbersBetween3and8 = SumIf(a,1,'>3','<8');
see also COUNTIF, SUM, FIND
Copyright(c): PNath@London.edu 29-Dec-2000
Surfp
does surf.m without you having to
worry about giving x and y axes values
i.e. just uses a counter 1:N and 1:M
where Z = M x N
Copyright(c): PNath@London.edu 6-December-2001
SVaR_Getbqminus
bqminus = SVaR_Getbqminus(f,DIM,i,epsilon,ShowPosition)
called by Smoothed VaR estimator
returns:
Copyright(c): PNath@London.edu 24-March-2002
SVaR_Getbrplus
brplus = SVaR_Getbrplus(f,DIM,i,epsilon,ShowPosition)
called by Smoothed VaR estimator
returns:
Copyright(c): PNath@London.edu 24-March-2002
SVaR_Getcxie
brplus = SVaR_Getcxie(f,DIM,i,epsilon,k,method,ShowPosition)
called by Smoothed VaR estimator
returns:
Copyright(c): PNath@London.edu 24-March-2002
SVaR_GetDeltaijx
Deltaijx = SVaR_GetDeltaijx(f,DIM,i,j,ShowPosition)
called by Smoothed VaR estimator
returns:
Deltaijx = f(i,:) - f(j,:) if DIM = 1
Deltaijx = f(:,i) - f(:,j) if DIM = 2
Copyright(c): PNath@London.edu 24-March-2002
SVaR_GetLambda_i_epsilonminus
Lambda_i_epsilonminus = SVaR_GetLambda_i_epsilonminus(f,DIM,i,epsilon,ShowPosition)
called by Smoothed VaR estimator
returns:
those observation numbers where the portfolio return
is greater than obs # i by not more than epsilon
DIM = 1 => time-series are down a column
DIM = 2 => observations are along a row
Copyright(c): PNath@London.edu 24-March-2002
SVaR_GetLambda_i_epsilonplus
Lambda_i_epsilonplus = SVaR_GetLambda_i_epsilonplus(f,DIM,i,epsilon,ShowPosition)
called by Smoothed VaR estimator
returns:
those observation numbers where the portfolio return
is less than obs # i by not more than epsilon
DIM = 1 => time-series are down a column
DIM = 2 => observations are along a row
Copyright(c): PNath@London.edu 24-March-2002
SVaR_GetLambdaq
Lambdaq = SVaR_GetLambdaq(f,DIM,i,epsilon,q,ShowPosition)
called by Smoothed VaR estimator
returns all different sets Labmdaik
f = N x 1
DIM = 1 => each column is a return series
= 2 => each row is a return series
i = 1 x 1
epsilon = 1 x 1
q = 1 x 1
Copyright(c): PNath@London.edu 24-March-2002
SVaR_GetLambdar
Lambdar = SVaR_GetLambdar(f,DIM,i,epsilon,r,ShowPosition)
called by Smoothed VaR estimator
returns all different sets Labmdaik
f = N x 1
DIM = 1 => each column is a return series
= 2 => each row is a return series
i = 1 x 1
epsilon = 1 x 1
r = 1 x 1
Copyright(c): PNath@London.edu 24-March-2002
SVaR_GetMi
Mi = SVaR_GetMi(N,i,ShowPosition)
called by Smoothed VaR estimator
returns all integers from 1 to N except i
N = 1 x 1
i = k x 1
Mi = N-1 x k
Copyright(c): PNath@London.edu 24-March-2002
SVaR_GetPsi
PsiZ = SVaR_GetPsi(Z,epsilon,ShowPosition)
called by Smoothed VaR estimator
Copyright(c): PNath@London.edu 24-March-2002
SVaR_GetThetaik
Thetaik = SVaR_GetThetaik(N,i,k)
called by Smoothed VaR estimator
returns all different sets Labmdaik
N = 1 x 1
i = 1 x 1
k = 1 x 1
(N-1)
Thetaik = C x k
k
[where C => Combinations]
Copyright(c): PNath@London.edu 24-March-2002
table
TABLE(X) displays the contents of matrix X (real elements only) in the Command Window
as a table (tab-separated string with precision %13.6e).
After marking the data it can tranferred to a spreadsheet by copy-and-paste.
Date 05-08-99
Written by Stefan Baunack. Please send any bug
reports or other comments to: s.baunack@ifw-dresden.de.
Theil
out = Theil(Actual, Expected)
Copyright (c): PNath@London.edu 30-July-2000
ThreeBetaMeanReversion
[Eta, EtaTstat, RSquare, HalfLife, XNobs] = ThreeBetaMeanReversion(TimeSeriesMatrix3D,Boundaries,Stack)
returns the mean reversion coefficients Eta (3x1 col vector)
the implied half lives (3x1 col vector) HalfLife
for a "single beta" mean reversion model.
Also returns the t-stat of Eta: EtaTstat (3x1 col vector)
as well as the number of observations in each "band" in XNobs
Delta_I(t) = a + Eta1*I(t-1)+ Eta2*I(t-1)+ Eta3*I(t-1)+ error_term
assumes TimeSeriesMatrix3D has STANDARDISED INVENTORIES in
Days(rows) x Gilts(cols) x MarketMakers (sheets)
the 3-betas are defined by Boundaries (1x2) or (2x1)
e.g. Boundaries = [-2 2]
=> Band:1 x < -2*StdDev
Band:2 -2*StdDev < x < +2*StdDev
Band:3 +2*StdDev < x
Stack = 0 => [default] return individual gilt figures
= 1 => stack all gilts/GEMMs
Does Newey-West with 5 lags.
EXAMPLE:
>> x = [0.01:0.001:100];
>> [E,Et,RSq,HL] = ThreeBetaMeanReversion(sin(500*x'),[-1.3 1.3])
Copyright (c): PNath@London.edu 25-Jan-2001
TwoBetaMeanReversion
[Eta, EtaTstat, RSquare, HalfLife, XNobs] = TwoBetaMeanReversion(TimeSeriesMatrix3D,Boundaries,Stack)
returns the mean reversion coefficients Eta (2x1 col vector)
the implied half lives (2x1 col vector) HalfLife
for a "two beta" mean reversion model.
Also returns the t-stat of Eta: EtaTstat (2x1 col vector)
as well as the number of observations in each "band" in XNobs
Delta_I(t) = a + Eta1*I(t-1)+ Eta2*I(t-1)+ error_term
assumes TimeSeriesMatrix3D has STANDARDISED INVENTORIES in
Days(rows) x Gilts(cols) x MarketMakers (sheets)
the 2-betas are defined by Boundaries (1x1) or (1x1)
e.g. Boundaries = [0]
=> Band:1 x <= 0*StdDev
Band:2 0*StdDev < x
Stack = 0 => [default] return individual gilt figures
= 1 => stack all gilts/GEMMs
Does Newey-West with 5 lags.
EXAMPLE:
>> x = [0.01:0.001:100];
>> [E,Et,RSq,HL] = TwoBetaMeanReversion(sin(500*x'),[0])
Copyright (c): PNath@London.edu 5-Mar-2002
WhereNext2
out = wherenext2(fid, where1, findstring1, AndOr, where2, findstring2, delimiter)
tells you after how many lines it found "findstring1" And/Or "findstring2"
at position range startat1 and starat2 respectively
in the text file with file-id "fid" and delimiter = "delimiter"
AndOr = & => does an AND search
AndOr = | => does an OR search
see also FindNext, FindNext2, GetItem
written by: PNath@London.edu
Width
out = Width(InArray)
returns the number of levels in 3rd dimension in InArray
see also NofRows, NofCols
Copyright(c): PNath@London.edu 17-Dec-2000
ZeroCoupon.m
8?F?R(M{11?{x&?_`?MlWK?뭚J?ByGsd?O~?Y9I-?;VgA?FXu?EH?8??dxK?7?N(D!T?`+?G
zipload
ZIPLOAD Load compressed data file created with ZIPSAVE
[data] = zipload( filename )
filename: string variable that contains the name of the
compressed file (do not include '.zip' extension)
Use only with files created with 'zipsave'
PNath says better to use DOS commands, {type help dos}
pkzip25.exe has to be in the matlab path. This file is a compression utility
made by Pkware, Inc. It can be dowloaded from: http://www.pkware.com
Or directly from ftp://ftp.pkware.com/pk250c32.exe, for the Windows 95/NT version.
This function was tested using 'PKZIP 2.50 Command Line for Windows 9x/NT'
It is important to use version 2.5 of the utility. Otherwise the command line below
has to be changed to include the proper options of the compression utility you
wish to use.
This function was tested in MATLAB Version 5.3 under Windows NT.
Fernando A. Brucher - May/25/1999
Example:
[loadedData] = zipload('testfile');
--------------------------------------------------------------------
zipsave
ZIPSAVE Save data in compressed format
zipsave( filename, data )
filename: string variable that contains the name of the resulting
compressed file (do not include '.zip' extension)
PNath says better to use DOS commands, {type help dos}
pkzip25.exe has to be in the matlab path. This file is a compression utility
made by Pkware, Inc. It can be dowloaded from: http://www.pkware.com
This function was tested using 'PKZIP 2.50 Command Line for Windows 9x/NT'
It is important to use version 2.5 of the utility. Otherwise the command line below
has to be changed to include the proper options of the compression utility you
wish to use.
This function was tested in MATLAB Version 5.3 under Windows NT.
Fernando A. Brucher - May/25/1999
Example:
testData = [1 2 3; 4 5 6; 7 8 9];
zipsave('testfile', testData);
------------------------------------------------------------------------
|