Visualisation of Risk Levelin Portfolio Management
Jonathan Mårtensson
U.U.D.M. Project Report 2005:12
Examensarbete i matematik, 10 poäng
Handledare och examinator: Maciej Klimek
Handledare: Jan Aronsson, Handelsbanken
November 2005
Department of Mathematics
Uppsala University
1
Abstract
In this dissertation a method of extracting raw market data in order to visualise portfolio risk is implemented. It concerns the risk in a Swedish stock portfolio, where the sample mean and the sample standard deviation are calculated from a 90 days interval. These numbers are then used in the Geometric Random Walk model in order to forecast a possible risk interval for the portfolio. A program called Forecast has been developed in Matlab in order to test if the implementation is possible. In Forecast six Swedish stocks are available and the forecast horizon ranges from one day to two years. A function called forecast within makes it possible to compare the real outcome of the portfolio to the forecasted interval and by using this function the forecast can be verified. The results show that it is only in special cases that the time series move outside the forecasted interval and thus the method seems reliable. The conclusion is that it is possible to create a risk visualisation for the end customer by extracting the portfolio data.
2
Contents 1 Introduction 4
1.1 Background...................................................................................4 1.2 Definition of the problem..............................................................4 1.3 The purpose of the project ............................................................5 1.4 Limitations ....................................................................................5
2 Theory 5
2.1 Assets ............................................................................................5 2.1.1 Stock .................................................................................5 2.1.2 Portfolio ............................................................................6 2.2 Mathematical background.............................................................7 2.2.1 Random variables..............................................................7 2.2.2 Expected value ..................................................................8 2.2.3 Variance – Standard deviation ..........................................9 2.2.4 Skewness – Kurtosis .........................................................9 2.2.5 Covariance ......................................................................10 2.2.6 Correlation ......................................................................10 2.2.7 Normal distribution.........................................................11 2.2.8 Lognormal distribution ...................................................11 2.3 Sampling .....................................................................................13 2.3.1 Sample mean and variance..............................................13 2.3.2 Confidence interval for the sample mean .......................14 2.3.3 Confidence interval for the sample variance ..................14 2.3.4 Sample covariance ..........................................................15 2.4 Stochastic processes....................................................................15 2.4.1 Autocovariance – Autocorrelation..................................15 2.4.2 Partial Autocorrelation function .....................................16 2.5 Time series ..................................................................................16 2.5.1 Stationary – non-stationary process ................................16 2.6 Forecasting..................................................................................20 2.6.1 Geometric Random Walk ...............................................20
3 Data 22
3.1 Data presentation ........................................................................22 3.2 Data analysis ...............................................................................22
4 Software for simulation 28
4.1 Important functions.....................................................................30
3
4.2 Implementation of the theory......................................................31 4.2.1 Create portfolio time series up to forecast date ..............31 4.2.2 Sampling .........................................................................32 4.2.3 Portfolio estimation.........................................................33 4.2.4 Portfolio recommendations.............................................34 4.2.5 Portfolio forecasting........................................................35
5 Simulation 36
6 Conclusions and suggestions to future studies 43
6.1 Conclusions.................................................................................44 6.2 Suggestions to future studies ......................................................44
7 Acknowledgements 45
A Appendix 47
4
1 Introduction The purpose of this dissertation is to show how risk in a customer portfolio can be visualised with the aid of the Geometric Random Walk model. The Geometric Random Walk is commonly used to model the behaviour of stocks and it will be described later in this paper. It will also include discussions regarding assumptions and requirements when implementing this model. Risk control has become an important factor for investors and when a group at J.P. Morgan released their RiskMetrics document in 1994 and publicly made available guidelines for evaluating portfolio risk, the awareness started to spread among initiated investors. The study of Geometric Random Walk is interesting since it captures the fundamental principles of the stock market behaviour which is essential in a risk model. With the aid of historic sampling and forecasting a visualisation of risk can be constructed and presented to end customers. This risk presentation will hopefully become an important factor for investors when analysing and constructing portfolios. With this paper the path from raw market data, through mathematics, to an understandable risk visualisation will be explained and analysed with the aid of a program called Forecast developed in Matlab for this sole purpose.
1.1 Background There is no perfect mathematical model for the behaviour of stocks. But during the 20th century mathematicians have developed different tools to model the behaviour reasonably well. Since the publication of RiskMetrics the field of risk analysis has risen in importance for regulatory bodies and large institutions. The widespread use of such factors has not yet been established among the public. Therefore it is interesting to analyse a possible way of visualising the portfolio risk for end customers.
1.2 Definition of the problem How can risk be visualised for the end customer with the aid of mathematics? And how can mathematics be used for recommendations concerning increasing or decreasing the portfolio risk for the end customer.
5
1.3 The purpose of the project The main purpose is to find a technique to visualise risk for the end customer. In doing so it is necessary to find a way of extracting information from raw market data. With the aid of the extracted information it is possible to compute the characteristic values of the data. These values can then be used in the Geometric Random Walk model to create a forecasted interval that will visualise the portfolio risk for the end customer. The characteristic values of the data can also be used to recommend stocks that will increase or decrease the risk in the customer’s portfolio.
1.4 Limitations The main purpose of this paper is to find a way from raw market data to a risk visualisation of a customer’s portfolio. The limitations have been established by Handelsbanken and the instruments have been limited to Swedish stocks. Therefore bonds, options and the risk-free asset are excluded. All of these excluded instruments are of course possible in the real world and it would be interesting to see how they would affect the recommendations, which in itself could be a whole new paper. Despite these limitations the main purpose is still fulfilled since the risk level of Swedish stocks is an important parameter for the end customers.
2 Theory In this section the mathematical background of the problem will be introduced.
2.1 Assets This section will address stocks and portfolios and introduce the notations used in this paper.
2.1.1 Stock A stock is an instrument that is traded continuously throughout the opening hours of the stock exchange so that the price can change during the day. Therefore if an investor buys a stock i at day 1−t , which is the
6
time index of the previous day, for the price 1, −tip and sells the stock at day t , i.e. today for tip , the rate of return is
1,
1,,,
~−
−−=
ti
tititi p
ppr (1)
Since 1ln1,
,
1,
, −≈⎟⎟⎠
⎞⎜⎜⎝
⎛
−− ti
ti
ti
ti
pp
pp
when 1,
,
−ti
ti
pp
is close to 1, which is true for
stocks, the log-return
⎟⎟⎠
⎞⎜⎜⎝
⎛=
−1,
,, ln
ti
titi p
pr (2)
can be used instead of (1). [1]
2.1.2 Portfolio There are many stocks available on the stock exchange and an investor can buy several to form a portfolio. The portfolio will then consist of multiple stocks with different returns tir ,
~ , where each stock will have a weight iw in the portfolio. For example if a portfolio consist of two stocks with a portfolio value of 40 SEK and 80 SEK respectively, the weights of each
stock in the portfolio are 31
1 =w and 32
2 =w . In general the return [1] of a
portfolio consisting of a stocks is
∑=
=a
itiit rwR
1,
~~ (3)
where the weights satisfy the condition
∑=
=a
iiw
11 (4)
7
2.2 Mathematical background In this section the mathematical background of the problem will be introduced. This paper is intended for readers with varying backgrounds and therefore some basic concepts will be discussed along with sections intended for more experienced readers.
2.2.1 Random variables In order to find a possible model for the behaviour of stocks, random variables are introduced. A random event is an outcome that cannot be predicted and in the case of stocks, the return as defined earlier is a random event since the sell price is unknown when the stock is bought. A random variable is a mathematical concept describing a quantity whose behaviour is non-deterministic. A full probabilistic description of a random variable X can be given in the form of its cumulative distribution function defined as ( ) =dFX Prob [ ]dX ≤ (5) for all real numbers d . A random variable is said to be discrete if the outcomes are values within a discrete set of numbers, which may be finite or not. For example stock prices or stock returns can be reasonably modelled by discrete random variables. In practice, however, it is more convenient to model these quantities by continuous random variables, i.e. random variables whose cumulative distribution functions are continuous. Such random variables can have outcomes of any value within an interval. A random variable X is said to have a probability density function Xf if, for some non-negative function Xf of one variable, it is true that the probability of all outcomes equal
( )∫∞
∞−
= 1dxxf X (6)
and
Prob [ ] ( )∫=<<c
bX dxxfcXb (7)
8
for all values b , c such that ∞≤<≤∞− cb . If this is the case then
( ) ( )dx
xdFxf XX = (8)
and
( ) ( )∫∞−
=x
XX dyyfxF (9)
for any real number x . This paper will use this type of random variables exclusively. Since the true characteristics of random variables are unknown, the data has to be analysed to find out if there is a model that approximately corresponds to the data. With the aid of a histogram the shape of the probability density function can be approximated. [2]
Figure 1: Histogram of the daily log-returns of Volvo B over 180 trading days.
2.2.2 Expected value A continuous random variable X has an expected value
( ) ∫∞
∞−
== dxxxfXE XX )(μ (10)
where Xf denotes the probability density function. [3]
9
2.2.3 Variance – Standard deviation The variance and the standard deviation are measures of dispersion around the expected value. If the value of the variance is low the probability of a number far from the expected value is low whereas if the variance is high a number far away has a higher probability. The formula for calculating the variance of X is [3] ( ) ( )[ ] ( ) 2222
XXX XEXEXVar μμσ −=−== (11) whereas the standard deviation of X is
( )XVarXX == 2σσ (12) which has the same units as the random variable. According to (11) the variance is always non-negative, i.e. 02 ≥Xσ (13) Furthermore if X is deterministic, the variance is 02 =Xσ (14)
2.2.4 Skewness – Kurtosis The skewness and kurtosis measures give a representation of the characteristics of the probability density function. The skewness value is a measure of how asymmetrical the function is, i.e. how much it leans to the left or to the right. The skewness measure is
( )[ ]3
3
X
XXESkewnessσ
μ−= (15)
The kurtosis value is a measure of how tall or flat the function is. The kurtosis measure is [4]
( )[ ]4
4
X
XXEKurtosisσ
μ−= (16)
10
2.2.5 Covariance The discussion so far has focused on the basic principles of a single random variable. It is also interesting to evaluate the dependence among two random variables. For instance if a portfolio consist of several stocks, i.e. several random variables, it is important to understand the characteristics of each random variable, but also how they relate to each other in order to fully understand the dynamics of the portfolio. The relationship between the outcomes of two random variables is called covariance, which is ( ) ( )( )[ ]221121, μμ −−= XXEXXCov (17) where 1μ and 2μ are the expected values of the respective random variables. The covariance thus measures the linear dependence among the random variables. A large covariance value indicates that the linear dependence among the variables is strong. If the covariance is positive the values of 1X and 2X increase at the same time whereas a negative value indicates that 1X decrease when 2X increase. If 1X and 2X are jointly normal and the covariance is zero, then the variables are independent. [2]
2.2.6 Correlation Since the covariance depend upon the scale of measurement it is hard to interpret if a high value indicates a strong covariance or not. Therefore correlation is introduced
( ) ( )21
2121
,,σσ
ρ XXCovXXCorr == (18)
where 1σ and 2σ are the standard deviations of 1X and 2X . The correlation coefficient standardises the value so that it is in the interval 11 ≤≤− ρ (19) The sign of the correlation is the same as the covariance but the scale has changed and hence 1 indicates perfect linear dependence among the variables. [2]
11
2.2.7 Normal distribution The normal distribution has been studied thoroughly and therefore its characteristics are well known. In this paper it is said that a random variable X is normally distributed if, for some constants 0>Xσ and Xμ , the probability density function of X is
( )( )
⎟⎟⎠
⎞⎜⎜⎝
⎛ −−
=2
2
2
21 X
Xx
XX exf σ
μ
πσ (20)
In this paper this fact is denoted by writing ( )2,~ XXNX σμ . By necessity
Xμ is the expected value and Xσ is the standard deviation of X . The shape of the graph of Xf is similar to the curve shown in Figure 1. The normal distribution has a skewness of 0 and a kurtosis value of 3. For other probability distributions a positive or negative value of skewness describes how non-symmetrical those distributions are, whereas a high value of kurtosis indicates that the distribution is more peaked at the centre and has fatter tails than the normal distribution. The normal distribution gives a reasonable approximation of the distribution of the log-returns of Volvo B in Figure 1. There is however one outlier at -0.08 which means that the distribution has fat tails, i.e. higher probability of extreme outcomes. Thus if the log-returns of Volvo B are modelled with the normal distribution the extreme outcomes are unlikely in the model. They are however quite rare which will be shown in the data section later in this paper. But the extreme outcomes are movements in the stock that can affect the portfolio severely and thus it is important to realise that the model is not a complete representation of the behaviour of stocks. On the other hand both mathematical models as well as fundamental analysis cannot predict extreme outcomes like a market crash or an extreme rally. Therefore this approximation is reasonable and common among practitioners. If the number of returns is increased, the histogram will be smoother and an approximation will be more reliable.
2.2.8 Lognormal distribution The random variable Y is log-normally distributed if XeY = , where X is normally distributed. Furthermore
12
( ) { }( ) }{( )( )
∫∞−
⎟⎟⎠
⎞⎜⎜⎝
⎛ −−
=≤=≤=y dxx
XY
X
X
eyXPyYPyFln
2 2
2
21ln σ
μ
σπ (21)
is its cumulative distribution function. Therefore the probability density function is
( ) ( )( )
⎟⎟⎠
⎞⎜⎜⎝
⎛ −−
==2
2
2ln
21 X
Xy
XYY e
yyF
dydyf σ
μ
σπ (22)
This gives the relationship between the normal and the lognormal probability distributions and therefore it is now possible to see how the means and variances correspond. The mean and variance of the normal distribution are denoted Xμ and 2
Xσ as previously stated and if the corresponding values of the lognormal distribution are denoted by m and
2s the relationships are [5]
( ) 2
2X
XeeEm Xσμ +
== (23) and
( ) ( ) ( )1122
2
222
2 −=−==⎟⎟⎠
⎞⎜⎜⎝
⎛+
XX
XX
emeeeVars X σσσμ
(24) This leads to the reverse relations
⎟⎟⎠
⎞⎜⎜⎝
⎛+= 1ln 2
22
ms
Xσ (25)
and
2
ln2X
X m σμ −= (26)
13
2.3 Sampling In order to forecast the risk of a portfolio the mean return, the variance and the covariance of stocks are important. Since the true values are not known there are different methods of approximating them. A common practice is to use historic sampling from the available portfolio data. Another method is to derive the necessary terms from options but this would not be suitable for this paper since options are not available on all Swedish stocks. There is also a problem with the forecast horizon when using the implied volatility from options, since a volatility derived from a six month option can only be used for a six month forecast. [6] Historic sampling is a method that is fairly reliable for the variance of a stock and the covariance between stocks but it is not as reliable for the mean return. It is therefore important to select a sampling interval that is sufficient and in this paper a 90 days interval will be used as recommended by [7]. That is equal to a period of about 4 months since there is no data for Saturdays and Sundays.
2.3.1 Sample mean and variance Given a set η,1, ,..., ii rr of independent observations of the random variable
ir the expected value and the variance are often estimated with the following unbiased estimators. The sample mean is
∑=
=η
η 1,
1ˆt
tii rr (27)
and the sample variance is
( ) ( )∑=
−−
=η
ησ
1
2, ˆ
11,ˆ
titiii rrrr (28)
These formulas can also be interpreted differently. Suppose that ( )tir , , where η,...,1=t , are observations from a sequence of independent identically distributed random variables. In this case (27) and (28) are estimates of the expected value
irμ and the variance 2
irσ common to all of
these random variables.
14
2.3.2 Confidence interval for the sample mean Since the true mean is approximated by the derived sample mean there is an uncertainty in the value. Therefore the confidence interval, at a
( )%1100 α− confidence level, for the sample mean ir̂ as stated in (27) is
according to [5] equal to ( ) ( )
⎥⎥⎦
⎤
⎢⎢⎣
⎡+−
ησ
ησ
ααii
iii
i
rrtr
rrtr
,ˆˆ,
,ˆˆ . An
example from the program Forecast is Volvo B where the sample size is 90 days, the daily sample mean 00109.0ˆ =ir and the daily sample
standard deviation ( ) 01606.0,ˆ =ii rrσ . At a 95% confidence level, a two-sided t -Student distribution with ( )891 =−η -degrees of freedom has the value 987.1025.0;89 =t . This leads to a confidence interval for ir̂ that is
[ ]004454.0,002274.090
01606.0987.100109.0,90
01606.0987.100109.0 −=⎥⎥⎦
⎤
⎢⎢⎣
⎡+−
Thus with 95% confidence the sample mean is in the interval -0.23% to 0.45%. This demonstrates a problem called the mean blur since the interval around the sample mean %11.0ˆ =ir is quite broad. A daily percentage return ranging from -0.23% to 0.45% does make a difference in the long run when forecasting.
2.3.3 Confidence interval for the sample variance The confidence interval for the sample variance is derived from the fact
that ( )2
,ˆ
ir
ii rrσ
ση has a 2χ -distribution with ( )1−η -degrees of freedom. As
shown in [5] the confidence interval for a ( )%1100 α− confidence level is
( ) ( )⎥⎥
⎦
⎤
⎢⎢
⎣
⎡
−2
2
2
21
,ˆ,,ˆ
αα χση
χση iiii rrrr which means that both the nominator and the
denominator depend on the sample size η . Thus in the Volvo B example with 05,0=α and ( ) 000258.0,ˆ =ii rrσ the confidence interval for the daily sample variance would be equal to
[ ]000197.0,000354.0136.118
000258.090,6466.65
000258.090 =⎥⎦
⎤⎢⎣
⎡. The confidence
interval for the sample variance is thus quite small. For the daily sample
15
standard deviation the interval would be [ ]01402.0,018807.0 where ( ) 016062.0,ˆ =ii rrσ . Therefore it is possible to use sampling as a method
of deriving the mean and variance but one should bear in mind that the mean blur can affect the end result.
2.3.4 Sample covariance In order to calculate the sample covariance between two time series the samples from the second time series must have the same characteristics as the ones previously defined in 2.3.1, i.e. ( )tjr , which is drawn from an independent identically distributed sequence. tir , and tjr , are also assumed to have a joint normal distribution that does not depend on t . The sample covariance is
( ) ( )( )∑=
−−−
=η
ησ
1,, ˆˆ
11,ˆ
tjtjitiji rrrrrr (29)
The sample mean, sample variance and the sample covariance will be used in this paper as the input parameters to the forecast model.
2.4 Stochastic processes The Greek word stokhos which means a target or bull’s-eye is the originator of the word stochastic. A stochastic process is a time ordered sequence of random variables. With a dart board in mind one can understand that a game of darts is a stochastic process. The player aims to hit the bull’s-eye each time but often the result will be a hit outside of the midpoint. So each throw is a random variable which can result in a hit of the bull’s-eye or some other place around the centre. Comparing this to the development of the stock price tip , one can see that the price tomorrow is unknown and hence random. Since this will be true each future day the price process, similar to the dart game, is a stochastic process.
2.4.1 Autocovariance – Autocorrelation In order to describe the evolution of a stochastic process tX , the concepts of autocovariance and autocorrelation are used. The functions offer a measure of the degree of dependence between the values at different time
16
steps, for example ht + and t , i.e. lag ( ) htht =−+ , the autocovariance function of tX at lag h is ( ) ( )( )[ ]μμ −−= ++ thttht XXEXXCov , (30) Since the coefficient of the autocovariance depends on the unit of tX the autocorrelation function that normalise the autocovariance function is introduced
( ) ( )( ) ( )hthttt
thttht
XXCovXXCov
XXCovXXCorr++
++ =
,,
,, (31)
With the aid of the autocorrelation function it is possible to study if there is a trend in the data or if there is a seasonal component, i.e. the data is not random. These functions will be used in Section 3.2 to analyse if transformed time series have a trend or a seasonal component. [8]
2.4.2 Partial Autocorrelation function The partial autocorrelation function is another measure of dependence. The value of the autocorrelation function can be affected by intermediate variables. For example the autocorrelation function between 1+tX and
3+tX can be affected by the correlation they have with the variable in between, i.e. 2+tX . This problem is eliminated by the partial autocorrelation function since it removes the correlations with the intermediate variables. [4]
2.5 Time series In this section the basics of time series will be discussed as well as different tests for determining the characteristics of a time series. A time series, in this paper a known development of the stock price tip , , is a particular realisation of a stochastic process that develops in time.
2.5.1 Stationary – non-stationary process It is important to understand what a stationary time series is and how a non-stationary time series can be transformed so that it can be tested for stationarity. If samples from a non-stationary time series would be used
17
they would not be valid for another time frame and thus not valid for a forecast model. [9] In order for a time series to be weakly stationary it must have constant mean and variance over time. The autocovariance must only depend on the lag between two time periods and not the time at which it is calculated. The weak form of stationarity is often enough and will therefore be used in this paper. The samples derived from a weakly stationary time series are suitable for the forecast model. An example of a non-stationary time series is the price process tp of Volvo B over the last 180 trading days.
Figure 2: Time series plot of the price process tp of Volvo B over 180 trading days. As seen in Figure 2 the positive trend in the time series is not constant and thus it is not stationary. In order to transform it into a stationary time series the first step is to use the return process instead of the price process. The result is seen in Figure 3.
18
Figure 3: Time series plot of the return process 1−t
t
pp of Volvo B over 180
trading days. In Figure 3 the fluctuating trend that was visible in Figure 2 has diminished. The final step in the transformation is to take the logarithm of the return process which results in the time series in Figure 4.
Figure 4: Time series plot of the log-return process ⎟⎟⎠
⎞⎜⎜⎝
⎛
−1
lnt
t
pp over 180
trading days. The time series in Figure 4 is based on the same data used for the histogram in Figure 1. In order to analyse if a time series is stationary there are several tests available where graphical analysis and correlogram test are two. The graphical analysis is simply a matter of checking the graph of the time series to see if there is a trend present in the data, as was
19
the case in Figure 2. In the correlogram test the plots of the autocorrelation function and the partial autocorrelation function are used to see if there is a trend present. Two correlograms of Volvo B over 180 days are seen in Figure 5 and Figure 6.
Figure 5: The Autocorrelation function of the price process tp of Volvo B over 180 trading days.
Figure 6: The Autocorrelation function of the log-return process ⎟⎟⎠
⎞⎜⎜⎝
⎛
−1
lnt
t
pp
of Volvo B over 180 trading days. As seen in the correlograms above, in Figure 5 there is a clear trend and several observations are outside the significance limits whereas in Figure 6 there are no significant autocorrelations and no observable trend. Hence the log-return process of Volvo B over 180 trading days seem to be stationary according to the correlogram test in Figure 6.
20
The unit root test is another method of analysing time series. The null hypothesis is that there is a unit root and thus the time series is non-stationary. The alternative hypothesis is that the time series is stationary. If the test rejects the null hypothesis the time series is stationary. In this paper the tests are performed with the statistical programs EViews and Minitab. The unit root tests used are the Augmented Dickey-Fuller test, that takes into account that the error terms can be correlated and the Phillips-Perron test that use nonparametric statistical methods to handle possible serial correlation in the error terms. [4] EViews is also used to test the transformed time series for normality. The tests used are Lilliefors, Cramer-von-Mises, Watson and Anderson-Darling where the null hypothesis is that the data is normally distributed.
2.6 Forecasting In order to forecast a time series the mean, variance and covariance of the time series is necessary. These statistics are derived by sampling from the transformed time series as discussed previously in this paper. The final step is to have a model for the behaviour of stock prices where the derived values will be used. Therefore the forecast model will be discussed in this section.
2.6.1 Geometric Random Walk There is a wide variety of models available to model the behaviour of stocks. Among popular volatility models are ARCH (Auto Regressive Conditional Heteroscedasticity), GARCH, IGARCH, EGARCH where the latter are versions of ARCH. These models are based on the notion that the volatility of time series is time dependent. There is however studies that have shown that over a longer time period these models do not outperform the geometric random walk [6]. Therefore this paper is based on the geometric random walk model which is a reasonable stock model. According to [5] a stochastic process tP , with discrete time
,...2,1,0=t , is called a geometric random walk with parameters 0>σ and ν if ( )t
tt ePP σεν ++ =1 (32)
where the random variables ( ) ( )1,0~ Ntε are independent. In order to have an interpretation of ν and σ it is observed that if
0≥> st , then
21
( ) ( )⎟⎟
⎠
⎞⎜⎜⎝
⎛+− ∑
=
−
=
1t
su
ust
st ePPεσν
(33)
and thus
( )stPPE
s
t −=⎟⎟⎠
⎞⎜⎜⎝
⎛νln (34)
and
( )stPPVar
s
t −=⎟⎟⎠
⎞⎜⎜⎝
⎛ 2ln σ (35)
In this case the ratio s
t
PP denotes the total return over the time period from
time s to time t and hence the quantities ν and σ are linked to the logarithmic return of portfolio P . Since the random variables ( )uε are independent, if 0P is deterministic and 0=s , then the relationship ( )ttPNPt
20 ,ln~ln σν+ (36)
is true. Which in turn means that tP is lognormal. If μ is defined as
2
2σνμ += (37)
the previous formulas leads to the final expressions for the expected value
( )st
s
t ePPE −=⎟⎟⎠
⎞⎜⎜⎝
⎛ μ (38)
and the variance
( ) ( )( )122 −=⎟⎟
⎠
⎞⎜⎜⎝
⎛ −− stst
s
t eePPVar σμ (39)
22
which will be used as the forecasted mean and variance of the price series tP in this paper. Note also that ν and 2σ are approximated by the
weighted sample mean and the weighted sample variance as previously defined.
3 Data In this section the data used in this paper will be presented along with results from statistical tests performed on the data.
3.1 Data presentation The price processes of the Swedish stocks ABB LTD SDB, Axis, Ericsson B, Readsoft, SHB A and Volvo B constitute the data used in this paper. The data is based on daily price observations and adjusted for splits and issues.
Stock Start date End date Number of observations ABB LTD SDB
Axis Ericsson B Readsoft SHB A Volvo B
1999-06-22 2000-06-27 1982-01-04 1999-06-22 1982-01-04 1982-06-14
2005-08-23 2005-08-23 2005-08-23 2005-08-23 2005-08-23 2005-08-23
1550 1295 6095 1550 6095 5980
Table 1: The start date, end date and the number of observations of the stocks used in this paper. These stocks are intended to represent a selection of possible stocks in a private portfolio. The time series are extracted from the technical analysis program Vikingen and the longest time series dates back to 1982.
3.2 Data analysis Since the data in Table 1 is transformed as described in Section 2.5.1 the number of observations of each time series is decreased by one. The data used in the sampling is analysed in the statistical programs Minitab and Eviews. Tests and measures are explained in the theory chapter.
23
Stock Mean SE Mean St. Dev. Skewness Kurtosis ABB LTD SDB
Axis Ericsson B Readsoft SHB A Volvo B
-0.00067 0.00006360.000614 0.000712 0.000557 0.000585
0.0011 0.00112 0.00036 0.00118 0.000259 0.000242
0.043128 0.040373 0.028071 0.046476 0.020248 0.018708
-6.15 0.24 -0.25 0.38 0.58 0.13
141.59 4.5 8.1 5.37 13.91 3.57
Table 2: The daily mean, standard error of mean, standard deviation, skewness and kurtosis of each full length log-return series. The mean, the standard error of the mean and the standard deviation of each time series in Table 2 are small because they are daily values. The skewness and kurtosis measures are not equal to the values of the normal distribution. The tests for normality in the last column of Table 3 indicate that the distribution of the full length log-return series is not normally distributed. This show that the assumptions for the model are not fulfilled for the full length series.
Stock ACF PACF ADF P-P Normal ABB LTD SDB
Axis Ericsson B Readsoft SHB A Volvo B
Yes Yes Yes No Yes Yes
Yes No Yes Yes Yes Yes
No No No No No No
No No No No No No
No No No No No No
Table 3: Autocorrelation function, partial autocorrelation function, Augmented Dickey-Fuller test, Phillips-Perron test and tests for normality of each full length log-return series. The autocorrelation functions for all stocks except Readsoft indicate that there are several significant values for the autocorrelation coefficient at different lags. This is also true for the partial autocorrelation functions except in this case Axis’s values are non-significant. The Augmented Dickey-Fuller and Phillips-Perron tests for unit root indicate that all the time series are stationary since they reject the null hypothesis that there is a unit root in the time series. Finally the tests for normality all indicate that the null hypothesis that the time series are normally distributed is rejected, i.e. they are not normal.
24
If the data of the last 90 trading days, that is the data used in the program, is analysed the result is shown in Table 4 and Table 5.
Stock Mean SE Mean St. Dev. Skewness Kurtosis ABB LTD SDB
Axis Ericsson B Readsoft SHB A
Volvo B
0.00201 0.00418 0.00264 0.00212
-0.00006440.00109
0.00172 0.00321 0.00146 0.00341 0.0009850.00169
0.016279 0.03048 0.013856 0.032249 0.009349 0.016062
-0.96 1.1 0.21 -1.25 -1.38 -1.78
3.5 4.3 1.29 8.1 5.88 7.92
Table 4: The daily mean, standard error of mean, standard deviation, skewness and kurtosis of each 90 days log-return series. In the time span of 90 days, the mean, the standard error of the mean and the standard deviation of the time series in Table 4 are small since they are daily values. The skewness measures are not close to zero but the kurtosis measures are not as extreme as in Table 2. They do however indicate that they are not normally distributed.
Stock ACF PACF ADF P-P Normal ABB LTD SDB
Axis Ericsson B Readsoft SHB A Volvo B
No No No No No No
No No No No No No
No No No No No No
No No No No No No
Yes No No No No No
Table 5: Autocorrelation function, partial autocorrelation function, Augmented Dickey-Fuller test, Phillips-Perron test and tests for normality of each 90 days log-return series. In this case there are no significant values for the autocorrelation function or partial autocorrelation function and thus the data does not contain a trend or a seasonal pattern. The ADF and P-P tests for unit root indicate that the time series are stationary since they reject the null hypothesis that there is a unit root in the time series. In the case of the tests for normality ABB LTD SDB cannot be rejected as normally distributed whereas all the other indicate that they are not normal.
25
If these time series are visualised with a time series plot and a histogram, the result indicate that they are approximately normally distributed except for the extreme outliers that cause the data to have fat tails.
Figure 7: Time series plot and histogram of the log-return process of ABB LTD SDB over 90 trading days.
Figure 8: Time series plot and histogram of the log-return process of Axis over 90 trading days.
26
Figure 9: Time series plot and histogram of the log-return process of Ericsson B over 90 trading days.
Figure 10: Time series plot and histogram of the log-return process of Readsoft over 90 trading days.
Figure 11: Time series plot and histogram of the log-return process of SHB A over 90 trading days.
27
Figure 12: Time series plot and histogram of the log-return process of Volvo B over 90 trading days. An interesting result is obtained if the single most extreme value in each 90 days time series is set to zero. The Anderson-Darling normality test indicates that some of the time series cannot be rejected as normally distributed. The p-values of the test are seen in Table 6.
Stock Anderson-Darling Test p-value ABB LTD SDB
Axis Ericsson B Readsoft SHB A Volvo B
0.185 0.012
< 0.005 0.162 0.010 0.673
Table 6: P-values of the Anderson-Darling test for normality when the single most extreme value is set to zero. ABB LTD SDB, Readsoft and Volvo B cannot be rejected as normally distributed at 95% confidence level. The tests performed on the transformed data indicate that the data is stationary and approximately normally distributed. The approximations of the Geometric Random Walk model do not incorporate all aspects of the real behaviour of stocks. The extreme values are not incorporated into the model and hence as discussed earlier the forecast will fail in the case of extreme outcomes.
28
4 Software for simulation In order to find a method of extracting raw market data, transforming the data and then forecasting the time series a program called Forecast has been developed in Matlab.
Figure 13: Screenshot of Forecast developed in Matlab. A portfolio of ABB LTD, Ericsson B and Volvo B is forecasted 6 months and stocks for increasing or decreasing the portfolio risk are recommended. A flowchart of the sampling and forecast steps is seen in Figure 14.
29
Figure 14: Flowchart of the key steps of the sampling and forecast.
Sampling Stock prices tip , of all stocks. 6 stocks in paper or 270 on Stockholmsbörsen up to time 0t
Conversion of tip , to log-returns tir ,
Sample mean ir̂ and covariance ( )ji rr ,σ̂ of log-returns of all stocks based on the last
90=η days
Conversion to estimated mean im and covariance ( )ji rrs , of returns of all stocks
Calculation of estimated mean M and covariance 2S of returns of portfolio
Conversion to estimated mean R~ and covariance ( )RR,~σ of log-returns of portfolio
Accuracy of samples computed by confidence intervals of normal distribution in Section 2.3
All values are in daily form
Weights of each stock in portfolio
Forecast
Mean price prediction
( )( ) ( )0
0
2,~~ ttRRR
tt ePPE−⎟
⎠⎞
⎜⎝⎛ +
=σ
Lower bound of confidence interval ( ) ( ) ( ) ( )( )00
0
,~96.1~ ttRRttRtt ePPLCI −−−= σ
Upper bound of confidence interval
( ) ( ) ( ) ( )( )00
0
,~96.1~ ttRRttRtt ePPUCI −+−= σ
Time 0tt >
30
4.1 Important functions The complete code for the program is available in the appendix but a brief discussion about the important functions in the program will be presented here. The Forecast_OpeningFcn is a function that imports the data and initialises all the different variables. The function Normalbutton1 is a function that corresponds to the Normal button in the graphical user interface. When the button is pressed this function creates a portfolio of the stocks that the user has chosen in the portfolio part of the graphical user interface. Once the portfolio is created it plots the portfolio without any forecast. Forecastbutton1 is a function that creates a portfolio of the selected stocks. With the aid of the Sampling function it creates the necessary statistics for a forecast of the chosen length. This function is activated when the Forecast button is pressed and it plots the time series along with the forecasted interval. The Forecastwithinbutton1 function is activated by the Forecast within button and works in the same way as Forecastbutton1. The difference is that the forecast date is set to a date within the time series. If the forecast length for instance is set to six months, the forecast date will be six months into the time series counted from the end date. This means that they will be plotted in the same time frame and thus the forecast can be compared to the real outcome of the time series. Sampling is the function that samples the data so that the sample mean and sample standard deviation can be calculated. These values are then used to compute the forecasted mean series along with the upper and lower confidence series that creates the forecast interval. The Create_Portfolio function creates a weighted portfolio of the selected stocks. The start date is set to the start date of the shortest time series in the chosen portfolio. Current_Risk_Contributors is a function that extracts the stocks that contribute to the risk in the portfolio. This is done by checking the sample variance of each stock. The risk contributors are then organised with the highest risk contributor as number one. It also calculates what stocks the user should add to the portfolio in order to increase or decrease the portfolio risk. This is done by asking the user for the value of the stock to be bought. This value is then used to calculate which new stock will increase or decrease the portfolio risk the most. These are also displayed in the graphical user interface with the one that increases or decreases risk the most as number one.
31
The calculations of the sample mean, the sample variance and the sample covariance for a specific interval have also been verified in EViews since both programs returned the same result for these calculations. This means that the program can import time series data, extract the necessary variables and use the Geometric Random Walk model to construct a forecasted risk interval. It can also give recommendations concerning current risk contributors and new stocks that will increase or decrease the portfolio risk.
4.2 Implementation of the theory In this section the framework used in the program is introduced in order to show how the theory is implemented in practice.
4.2.1 Create portfolio time series up to forecast date When the Forecast button in the program is activated by the user a reset of the values of the portfolio is initiated. The next step is to check the forecast length and to set the time when the portfolio is to be valued, i.e.
0t . Thereafter the function Create_Portfolio creates a portfolio with the following steps. The program checks each stock and if it is chosen in the graphical user interface it calculates the number of shares the user will hold for the invested value.
0
0
,
,
ti
tii p
vn = (40)
where in denotes the number of shares of the chosen stock,
0,tiv the wealth invested in this stock at time 0t and
0,tip denotes the price of one share of the stock at time 0t . The time series of the current stock is then added to the time series of the other stocks in the portfolio in order to create the time series of the portfolio up to time 0t
∑=
=a
itiit pnP
1, 0ttts ≤≤ (41)
where tP is the time series of the portfolio from the start date st of the stock with the shortest time series up to 0t and a is the number of assets in the portfolio.
32
The function Current_Portfolio_Weights is then used to calculate each stock weight in the portfolio, i.e.
∑=
= a
iti
tii
v
vw
1,
,
0
0 (42)
4.2.2 Sampling The function Sampling estimates the mean and variance of each stock. It extracts each time series data to create a log-return series by taking the logarithm of each price at time t divided by the price at time 1−t .
⎟⎟⎠
⎞⎜⎜⎝
⎛=
−1,
,, ln
ti
titi p
pr (43)
Then the daily sample mean, i.e. the average of the last 90=η days of daily log-returns, is calculated
⎟⎟⎠
⎞⎜⎜⎝
⎛=
−ηη0
0
,
,ln1ˆti
tii p
pr (44)
where η is the sample size and 0t is the end date of the time series. The program inserts the η elements from the log-return series of each stock into a matrix that is a a×η -matrix, where 6=a in the program since there are 6 stocks and the sample size is η . This matrix is used in the calculations of the variance and covariance of all the stocks. The daily sample variance - covariance matrix of the log-returns of all the stocks is calculated element by element
( ) ( ) ( )( )∑∑= =
−−−
=a
ji tjtjitiji rrrrrr
1, 1,, ˆˆ
11,ˆ
η
ησ (45)
where η is the sample size, i and j denote stock i and j , t denotes the time index. When ji = the result is the variance ( )ii rr ,σ̂ for stock i and when ji ≠ the result is the covariance ( )ji rr ,σ̂ between stock i and j .
33
In order to calculate the mean and variance – covariance values that can be used for a single stock or a portfolio, the samples are transformed from log-returns to returns, i.e. normally distributed to log-normally distributed. The transformation of the mean is
( )⎟
⎠⎞
⎜⎝⎛ +
=iii rrr
i em,ˆ
21ˆ σ
(46) where im denotes the estimated daily mean of stock i ’s returns. The transformation of the variance – covariance is
( ) ( ) ( ) ( ) ( )( )1,, ,ˆ,ˆ21ˆ,ˆ
21ˆ
−==⎟⎠⎞
⎜⎝⎛ +⎟⎠⎞
⎜⎝⎛ +
jijjjiii rrrrrrrr
jiji eerrCovrrs σσσ (47)
where ( )ji rrs , denotes the estimated daily variance – covariance of stock i ’s and j ’s returns. These transformed values can then be used when the portfolio is estimated.
4.2.3 Portfolio estimation The next step is to calculate the estimated daily mean and variance of returns of the chosen portfolio. These estimates are log-normally distributed. The estimated portfolio mean is
∑=
=a
iiimwM
1 (48)
where M denotes the estimated daily mean of the portfolio returns. The estimated variance of the portfolio is
( ) ( )∑∑= =
==a
i
a
jjiji rrswwRRVarS
1 1
2 ,, (49)
where 2S denotes the estimated daily variance of the portfolio returns. The derived estimates of mean and variance of the portfolio’s returns have to be transformed into estimates of log-returns in order to be utilised in the forecast. The transformation of the variance is
34
( ) ⎟⎟⎠
⎞⎜⎜⎝
⎛+= 1ln,~
2
2
MSRRσ (50)
where ( )RR,~σ denotes the daily estimated variance of log-returns of the portfolio. The transformation of the mean is
( ) ( )2,~
ln~ RRMR σ−= (51)
where R~ denotes the estimated daily mean of log-returns of the portfolio. These values are used in the forecasting of the portfolio. The estimated yearly mean M250 and yearly standard deviation 2250S of the portfolio are displayed in the plot.
4.2.4 Portfolio recommendations It is also possible to determine the current risk contributors which are derived from the weighted estimated variance of each stock return. The calculation for each stock is ( )iii rrsw ,2 (52) The stocks are ordered in descending order with the highest variance at number 1. In order to derive the stocks that will increase or decrease the portfolio risk, the user is prompted for the amount to be invested in the new stock, i.e.
0,thv . This value is used to calculate how many shares the user can buy of the stocks that are currently not in the portfolio.
0
0
,
,
th
thh p
vn = (53)
where hn is the number of stocks of each new stock h . In the program Forecast ah −= 6 , i.e. the number of stocks available to the user minus the number of stocks currently in the portfolio. In the real world, 6 is replaced by the stocks at the fundamental recommendation list from Handelsbanken with 40 to 50 stocks and not the whole Stockholm stock exchange with approximately 270 stocks.
35
The function Current_Portfolio_Weights is then used to calculate each new stock weight in the current portfolio, i.e.
00
0
,1
,
,
th
a
iti
tii
vv
vw
+=
∑=
(54)
It is also necessary to calculate the weights of the stocks that are currently not in the portfolio.
00
0
,1
,
,
th
a
iti
thh
vv
vw
+=
∑=
(55)
The weighted daily estimated mean of each possible portfolio is calculated
∑+
=
=1
1
a
iiimwM (56)
where the number of stocks in each possible portfolio is 1+a since a new stock is added to the current portfolio. The weighted daily estimated variance of each possible portfolio is calculated
( ) ( )∑∑+
=
+
=
==1
1
1
1
2 ,,a
i
a
jjiji rrswwRRVarS (57)
These variances are compared to the variance of the current portfolio so that they can be divided into a group of stocks that increase the portfolio risk and another group that decrease the portfolio risk. Finally these groups are ordered in descending order from the stock that increase or decrease risk the most at first place.
4.2.5 Portfolio forecasting In order to create a predicted interval of the portfolio, three data series are calculated. They are the mean data series, the upper confidence bound data series and the lower confidence bound data series. The first step is to calculate the portfolio value at 0t , i.e.
36
∑=
=a
itiit pnP
1, 00
(58)
The forecasted mean data series is
( )( ) ( )0
0
2,~~ ttRRR
tt ePPE−⎟
⎠⎞
⎜⎝⎛ +
=σ
fttt ≤≤0 (59) where f denotes the number of business days of the forecast. The sample mean and the sample standard deviation are daily values. The next step is to create the forecasted upper confidence bound data series
( ) ( ) ( ) ( )( )00
0
,~96.1~ ttRRttRtt ePPUCI −+−= σ fttt ≤≤0 (60)
Finally the forecasted lower confidence bound data series is ( ) ( ) ( ) ( )( )00
0
,~96.1~ ttRRttRtt ePPLCI −−−= σ fttt ≤≤0 (61)
These data series are added to time series objects with dates and thereafter visualised for the user along with the time series of the portfolio up to 0t . The end result is a time series plot of the portfolios historic trend up to 0t and the forecasted mean, upper confidence interval and lower confidence interval between 0t and the forecast end date ft .
5 Simulation In this section a selection of simulations performed in Forecast is discussed in order to evaluate if the program can achieve reasonable results and highlight some important topics. The Forecast within function is used to compare the forecast with the real outcome. The first forecast is a mixed portfolio with one third of the portfolio value in Axis, one sixth in Ericsson B and half in Volvo B.
37
Figure 15: Screenshot of Forecast with a portfolio of Axis, Ericsson B and Volvo B forecasted 6 months within the time series and the recommended stocks that will decrease the risk in the portfolio. In Figure 15 the portfolio consist of quite volatile stocks. The large movements are mainly due to movements in Axis which is a volatile stock that is one third of the portfolio. The development of the time series is inside the forecasted interval throughout the forecast period. The forecasted interval is widespread in august 2005, from 315 to 530, which gives the end customer a visualisation of the risk level in the portfolio. An example of a stock that moves outside the forecasted interval is seen in Figure 16.
38
Figure 16: Screenshot of Forecast with Axis forecasted 1 year within the time series and the recommended stocks that will decrease the risk in the portfolio. The true time series of Axis in Figure 16 moves outside the forecasted interval. When studying the time series over the forecasted period it is quite obvious that many models could not have forecasted an interval that would have covered the time series. There are two major movements in the stock over the forecasted period. The first move is so rapid that the time series moves outside of the interval. The second move occurs outside of the forecasted interval and thus the downward sloping forecast has definitely failed. These movements are triggered by the company’s interim reports and thus new information has been presented to the market that has definitely changed the markets view of the company. In this case it is quite probable that no model or fundamental analyst could have predicted the rapid upward movements in the stock. A period of one year is quite a long time for a forecast and a longer time frame must be considered quite unrealistic. If Axis is forecasted six months instead, the data is sampled from the first major movement. The result is seen in Figure 17.
39
Figure 17: Screenshot of Forecast with Axis forecasted six months within the time series and the recommended stocks that will decrease the risk in the portfolio. In Figure 17 it is obvious when studying the sample mean, which in this case is 2.3384, that the major movement in the stock previous to the forecast start date affected the sample mean. Since this value is used in the forecast, the prediction interval is quite upward trending. In this case the stock does continue upward due to the second interim report so the sample mean is relatively close to the real outcome. The interval forecasted in this case is broad, ranging from 58 to 150, which reflect the uncertainty in the stock due to the movement caused by the first interim report. This will hopefully give the end customer a picture of how risky a portfolio consisting of Axis alone is. If the end customer would instead hold a portfolio of Axis and Readsoft, as recommended by the program, the result is seen in Figure 18.
40
Figure 18: Screenshot of Forecast with Axis and Readsoft forecasted six months within the time series along with the recommended stocks that will decrease the risk in the portfolio. In Figure 18 the total portfolio value is still 50 SEK at the forecast date, but the portfolio consist of equal weights of Axis and Readsoft which lowers the sample mean to 2.247. The sample standard deviation is also lower with a value of 0.23512 instead of 0.34429. This leads to an interval six months later that range from 65 to 123 instead of 58 to 150. The end customer has thus created a portfolio that has a lower standard deviation and according to the program the downside risk is more upward trending than was the case for Axis alone. One should also bear in mind that the upside of the portfolio has decreased since the portfolio risk and the sample mean are lower. SHB A is the stock that has the lowest standard deviation out of the six stocks. An interesting example concerning the sample mean and the sample standard deviation is seen in Figure 19 and 20.
41
Figure 19: Screenshot of Forecast with SHB A forecasted six months within the time series and the recommended stocks that will increase or decrease the risk in the portfolio. As seen in Figure 19 SHB A has a low standard deviation of 0.15564 but Volvo B is recommended in order to decrease the risk even though it has a higher standard deviation. This is due to the fact that multiple stocks diversify away the risk of single stocks. In this case the covariance between SHB A and Volvo B is quite low. Increasing the number of stocks in a portfolio, as long as their covariance is relatively low, can decrease the risk in the portfolio as seen in Figure 20.
42
Figure 20: Screenshot of Forecast with SHB A and Volvo B forecasted six months along with the recommended stocks that will increase the risk in the portfolio. A portfolio consisting of SHB A and Volvo B will lead to a lower risk than a portfolio of SHB A alone, even though Volvo B has a sample standard deviation of 0.20827 compared to SHB A with 0.15564. This is due to the covariance between the two stocks and in this particular case the sample mean increase in the new portfolio. In the case of SHB A the sample mean is 1.2283 whereas in the new portfolio the sample mean is 1.375. The addition of Volvo B has thus created a portfolio with a lower risk but a higher expected return.
43
Figure 21: Screenshot of Forecast with ABB LTD SDB, Axis, Ericsson B and Volvo B forecasted six months along with the recommended stocks that will increase or decrease the risk in the portfolio. Figure 21 is an example of a forecast created for an end customer where the portfolios development is plotted to the forecast date. The interval in this case is relatively broad but the development of the portfolio during the year 2000 shows that the portfolio can perform rather large movements in a short time span.
6 Conclusions and suggestions to future studies In this section the conclusions of this paper will be discussed and areas of interest for future analysis will be suggested.
44
6.1 Conclusions The main purpose of this dissertation is to examine a way of extracting raw market data in order to present a visualisation of risk for the end customer. The program Forecast developed in Matlab confirm that it is possible to construct a program that will perform the necessary calculations in order to obtain the desired risk representation. This visualisation of risk is a method of transforming a number into something understandable. The numbers derived from the program can also be used to visualise risk in other ways, i.e. different graphs or compared to a risk index. A specific sample calculation has been verified with EViews which showed that the sample calculations performed in the program are correct. The sample mean, sample variance and sample covariance calculations can if implemented in a real system be executed each night. Therefore it is no problem if the heavy calculations with approximately 270 Swedish stocks requires a lot of time. The recommendation function that suggests stocks that will increase or decrease the risk has to be executed when the forecast is activated by the user. These calculations would however be considerably limited since the program will only suggests stocks that are recommended by the bank. This means that the program only suggests stocks based on mathematical calculations as well as fundamental analysis.
6.2 Suggestions to future studies This dissertation has shown that it is possible to go from market data to a risk representation of a customer portfolio. There are however some areas that would be interesting to study further. The first area of interest is of course to see how well it will perform if implemented in a real system where all the stocks on Stockholmsbörsen is available. It would also be interesting to compare the variance and covariance numbers derived for the stocks to the numbers derived from a professional system. Another topic of interest would be to see if other methods of calculating the sample variance and the sample covariance values would improve the obtained results. An interesting evaluation would be to compare this forecast method to other methods such as the RiskMetrics. It would also be interesting to study different methods of deriving the mean value. Finally it would be very interesting to utilise the derived values for mean – variance optimisation of portfolios.
45
7 Acknowledgements I would like to thank Professor Maciej Klimek at the Department of Mathematics at Uppsala University for his excellent support and dedication. I would also like to thank Jan Aronsson and Mikael Forssén at Handelsbanken for their ideas and enthusiasm throughout the process.
46
References [1] Luenberger David G. Investment Science. Oxford university press,
New York, 1998. [2] Wackerly Dennis D., Mendenhall III William, Scheaffer Richard L.
Mathematical Statistics with Applications. Duxbury, Pacific Grove, 2002.
[3] Yates Roy D, Goodman David J. Probability and Stochastic
Processes. John Wiley & Sons, New York, 1999. [4] Gujarati Damodar N. Basic Econometrics. McGraw-Hill/Irwin, New
York, 2003. [5] Klimek Maciej, Lecture Notes on Mathematics of Financial
Modeling. Uppsala University. 2002. [6] Morgan Guaranty Trust Company. Risk Metrics – Technical
document, 4th edition. J.P. Morgan/Reuters, New York, 1996. [7] Hull John C. Options, Futures, and Other Derivatives. Prentice-
Hall, New Jersey, 2003. [8] Brockwell Peter J., Davis Richard A. Introduction to Time Series
and Forecasting. Springer-Verlag, New York, 2002. [9] Chatfield Chris. The analysis of Time Series An Introduction.
Chapman & Hall/CRC, Boca Raton, 1996.
47
A Appendix The Matlab code for the Forecast program.
end
% E
nd in
itial
izat
ion
code
- D
O N
OT
ED
IT
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- E
xecu
tes
just
bef
ore
Fore
cast
is m
ade
visi
ble.
fu
nctio
n Fo
reca
st_O
peni
ngFc
n(hO
bjec
t, ev
entd
ata,
han
dles
, va
rarg
in)
%Lo
ad th
e da
ta fr
om th
e fil
es
hand
les.
abb
= as
cii2
fts('a
bb lt
d sd
b.tx
t');
hand
les.
axis
= a
scii2
fts('a
xis.
txt')
; ha
ndle
s.er
icss
onb
= as
cii2
fts('e
ricss
on b
.txt')
; ha
ndle
s.re
adso
ft =
asci
i2fts
('rea
dsof
t.txt
');
hand
les.
shba
= a
scii2
fts('s
hb a
.txt')
; ha
ndle
s.vo
lvob
= a
scii2
fts('v
olvo
b.tx
t');
%E
xtra
ct in
fo a
bout
the
times
erie
s ob
ject
s in
foab
b =
ftsin
fo(h
andl
es.a
bb);
info
axis
= ft
sinf
o(ha
ndle
s.ax
is);
info
eric
sson
b =
ftsin
fo(h
andl
es.e
ricss
onb)
; in
fore
adso
ft =
ftsin
fo(h
andl
es.re
adso
ft);
info
shba
= ft
sinf
o(ha
ndle
s.sh
ba);
info
volv
ob =
ftsi
nfo(
hand
les.
volv
ob);
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- F
orec
ast V
ersi
on 1
.0 C
opyr
ight
200
5, J
onat
han
Mår
tens
son
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- F
orec
ast
func
tion
vara
rgou
t = fo
reca
st(v
arar
gin)
%
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Beg
in in
itial
izat
ion
code
- D
O N
OT
ED
IT
gui_
Sing
leto
n =
1;
gui_
Sta
te =
stru
ct('g
ui_N
ame'
,
mfil
enam
e, ..
.
'g
ui_S
ingl
eton
', g
ui_S
ingl
eton
, ...
'gui
_Ope
ning
Fcn'
, @Fo
reca
st_O
peni
ngFc
n, ..
.
'g
ui_O
utpu
tFcn
', @
Fore
cast
_Out
putF
cn, .
..
'g
ui_L
ayou
tFcn
', []
, ...
'g
ui_C
allb
ack'
, []
); if
narg
in &
& is
char
(var
argi
n{1}
)
gui
_Sta
te.g
ui_C
allb
ack
= st
r2fu
nc(v
arar
gin{
1});
end
if na
rgou
t
[var
argo
ut{1
:nar
gout
}] =
gui_
mai
nfcn
(gui
_Sta
te, v
arar
gin{
:});
else
gui
_mai
nfcn
(gui
_Sta
te, v
arar
gin{
:});
48
text
(0.9
5,0.
5,nu
m2s
tr(ha
ndle
s.cu
rrent
_por
tfolio
_val
ue(1
,1))
, ...
'U
nits
','N
orm
aliz
ed','
Hor
izon
talA
lignm
ent',
'righ
t');
axes
(han
dles
.Val
ue_o
f_A
xis)
; cl
a;
text
(0.9
5,0.
5,nu
m2s
tr(ha
ndle
s.cu
rrent
_por
tfolio
_val
ue(1
,2))
, ...
'U
nits
','N
orm
aliz
ed','
Hor
izon
talA
lignm
ent',
'righ
t');
axes
(han
dles
.Val
ue_o
f_E
ricss
on);
cla;
te
xt(0
.95,
0.5,
num
2str(
hand
les.
curre
nt_p
ortfo
lio_v
alue
(1,3
)), .
..
'Uni
ts','
Nor
mal
ized
','H
oriz
onta
lAlig
nmen
t','ri
ght')
; ax
es(h
andl
es.V
alue
_of_
Rea
dsof
t);
cla;
te
xt(0
.95,
0.5,
num
2str(
hand
les.
curre
nt_p
ortfo
lio_v
alue
(1,4
)), .
..
'Uni
ts','
Nor
mal
ized
','H
oriz
onta
lAlig
nmen
t','ri
ght')
; ax
es(h
andl
es.V
alue
_of_
SHB
); cl
a;
text
(0.9
5,0.
5,nu
m2s
tr(ha
ndle
s.cu
rrent
_por
tfolio
_val
ue(1
,5))
, ...
'U
nits
','N
orm
aliz
ed','
Hor
izon
talA
lignm
ent',
'righ
t');
axes
(han
dles
.Val
ue_o
f_Vo
lvo)
; cl
a;
text
(0.9
5,0.
5,nu
m2s
tr(ha
ndle
s.cu
rrent
_por
tfolio
_val
ue(1
,6))
, ...
'U
nits
','N
orm
aliz
ed','
Hor
izon
talA
lignm
ent',
'righ
t');
%S
et th
e nu
mbe
r of s
tock
s in
the
curre
nt p
ortfo
lio
hand
les.
num
ber_
of_s
tock
s =
1;
%S
et th
e st
artd
ate
of th
e po
rtfol
io
hand
les.
portf
olio
_sta
rt_da
te =
0;
%S
et th
e po
rtfoi
o sa
mpl
e m
ean
hand
les.
portf
olio
_sam
ple_
mea
n =
0;
%C
reat
e a
vect
or w
ith th
e di
ffere
nt ti
mes
erie
s st
artd
ates
ha
ndle
s.st
ocks
_sta
rt_da
te =
[dat
enum
(info
abb.
star
tdat
e), .
..
dat
enum
(info
axis
.sta
rtdat
e), d
aten
um(in
foer
icss
onb.
star
tdat
e), .
..
dat
enum
(info
read
soft.
star
tdat
e), d
aten
um(in
fosh
ba.s
tartd
ate)
, ...
d
aten
um(in
fovo
lvob
.sta
rtdat
e)];
%C
reat
e a
vect
or w
ith th
e tim
eser
ies
endd
ates
ha
ndle
s.st
ocks
_end
_dat
e =
date
num
(info
abb.
endd
ate)
; %
Cre
ate
a ve
ctor
with
the
diffe
rent
num
ber o
f dat
es
hand
les.
stoc
ks_n
data
= [i
nfoa
bb.n
data
, inf
oaxi
s.nd
ata,
...
in
foer
icss
onb.
ndat
a, in
fore
adso
ft.nd
ata,
info
shba
.nda
ta, .
..
info
volv
ob.n
data
]; %
Set
cur
rent
dat
a to
AB
B
hand
les.
curre
nt_d
ata
= ha
ndle
s.ab
b;
%C
reat
e a
vect
or to
kee
p tra
ck o
f the
cur
rent
sto
ck in
the
portf
olio
(AB
B
%ch
oose
n as
def
ault)
ha
ndle
s.cu
rrent
_por
tfolio
= [1
,0,0
,0,0
,0];
%C
reat
e a
vect
or w
ith th
e cu
rren
t num
ber o
f sha
res
boug
ht
hand
les.
curre
nt_s
tock
_sha
res
= [0
,0,0
,0,0
,0];
%S
et th
e cu
rrent
sto
ck p
rice
vect
or to
zer
o ha
ndle
s.cu
rrent
_sto
ck_p
rice
= [0
,0,0
,0,0
,0];
%S
et th
e po
rtfol
io v
alue
to 5
0 fo
r AB
B (w
here
the
last
0 is
use
d by
the
%C
urre
nt_R
isk_
Con
tribu
tors
func
tion
hand
les.
curre
nt_p
ortfo
lio_v
alue
= [5
0,0,
0,0,
0,0,
0];
%S
et th
e te
xt in
all
the
Val
ue_o
f_ fi
gure
s ax
es(h
andl
es.V
alue
_of_
AB
B);
cla;
49
%S
et th
e co
varia
nce
retu
rn m
atrix
ha
ndle
s.co
varia
nce_
retu
rn_m
atrix
= 0
; %
Set
act
ive
chec
kbox
to c
heck
box1
se
t(han
dles
.che
ckbo
x1,'V
alue
',1);
set(h
andl
es.c
heck
box2
,'Val
ue',0
); se
t(han
dles
.che
ckbo
x3,'V
alue
',0);
set(h
andl
es.c
heck
box4
,'Val
ue',0
); se
t(han
dles
.che
ckbo
x5,'V
alue
',0);
set(h
andl
es.c
heck
box6
,'Val
ue',0
); %
Set
che
ckbo
x7 to
no
reco
mm
enda
tion
set(h
andl
es.c
heck
box7
,'Val
ue',0
); %
Set
cur
rent
fore
cast
leng
th to
6 M
onth
s se
t(han
dles
.For
ecas
tbut
ton6
m,'V
alue
',1);
%S
et th
e fo
reca
st_b
utto
n to
sho
w th
at th
e ca
ll do
es n
ot c
ome
from
%
Nor
mal
butto
n1
hand
les.
fore
cast
_but
ton
= 0;
%
Set
the
sam
ple
size
ha
ndle
s.sa
mpl
e_si
ze =
90;
%
Plo
t the
cur
rent
dat
a ax
es(h
andl
es.G
raph
); zo
om o
ut;
cla;
pl
ot(h
andl
es.c
urre
nt_d
ata)
; tit
le('N
orm
al p
lot')
; le
gend
('AB
B L
TD S
DB
');
xlab
el('D
ate'
); yl
abel
('Val
ue (S
EK
)');
zoom
on;
%S
et th
e po
rtfol
io s
ampl
e st
anda
rd d
evia
tion
hand
les.
portf
olio
_sam
ple_
stan
dard
_dev
iatio
n =
0;
%S
et th
e nu
mbe
r of d
ates
in th
e po
rtfol
io
hand
les.
portf
olio
_nda
ta =
0;
%S
et th
e cu
rrent
sto
ck w
eigh
ts
hand
les.
curre
nt_s
tock
_wei
ghts
= [0
,0,0
,0,0
,0];
%S
et th
e cu
rrent
por
tfolio
val
ue d
ate
hand
les.
curre
nt_p
ortfo
lio_v
alue
_dat
e =
0;
%S
et th
e m
ean
vect
or
hand
les.
mea
n_ve
ctor
= 0
; %
Set
the
cova
rianc
e ve
ctor
ha
ndle
s.co
varia
nce_
vect
or =
0;
%S
et th
e co
varia
nce
mat
rix
hand
les.
cova
rianc
e_m
atrix
= 0
; %
Set
the
wei
ghte
d co
varia
nce
vect
or
hand
les.
wei
ghte
d_co
varia
nce_
vect
or =
0;
%S
et th
e w
eigh
ted
cova
rianc
e m
atrix
ha
ndle
s.w
eigh
ted_
cova
rianc
e_m
atrix
= 0
; %
Set
the
wei
ghte
d m
ean
vect
or
hand
les.
wei
ghte
d_m
ean_
vect
or =
0;
%S
et th
e m
ean
retu
rn v
ecto
r ha
ndle
s.m
ean_
retu
rn_v
ecto
r = 0
;
50
%R
otat
e th
e fig
ure
to fi
ll th
e pa
per
orie
nt ro
tate
d;
%S
et th
e pa
pers
ize
to A
4 se
t(gcf
, 'P
aper
Pos
ition
Mod
e', '
man
ual')
; se
t(gcf
, 'P
aper
Uni
ts',
'cen
timet
ers'
); se
t(gcf
, 'P
aper
Pos
ition
', [1
1 2
5 19
]);
%P
rint
prin
tdlg
(han
dles
.figu
re1)
%
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Fun
ctio
n fo
r the
Exi
t men
u ch
oice
fu
nctio
n E
xitM
enuI
tem
_Cal
lbac
k(hO
bjec
t, ev
entd
ata,
han
dles
) %
Use
a q
uest
ion
dial
og to
ask
if th
e us
er w
ants
to e
xit
sele
ctio
n =
ques
tdlg
(['D
o yo
u w
ant t
o ex
it ' g
et(h
andl
es.fi
gure
1,'N
ame'
)...
'?
'],['E
xit '
get
(han
dles
.figu
re1,
'Nam
e') '
...'],
...
'Yes
','No'
,'Yes
');
%If
the
user
ans
wer
s N
o re
turn
to th
e pr
ogra
m
if st
rcm
p(se
lect
ion,
'No'
)
retu
rn;
end
%O
ther
wis
e en
d th
e pr
ogra
m
dele
te(h
andl
es.fi
gure
1)
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
-
% C
hoos
e de
faul
t com
man
d lin
e ou
tput
for F
orec
ast
hand
les.
outp
ut =
hO
bjec
t; %
Upd
ate
hand
les
stru
ctur
e gu
idat
a(hO
bjec
t, ha
ndle
s);
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- O
utpu
ts fr
om th
is fu
nctio
n ar
e re
turn
ed to
the
com
man
d lin
e.
func
tion
vara
rgou
t = F
orec
ast_
Out
putF
cn(h
Obj
ect,
even
tdat
a, h
andl
es)
% v
arar
gout
cel
l arra
y fo
r ret
urni
ng o
utpu
t arg
s (s
ee V
AR
AR
GO
UT)
; %
Get
def
ault
com
man
d lin
e ou
tput
from
han
dles
stru
ctur
e va
rarg
out{1
} = h
andl
es.o
utpu
t; %
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Fun
ctio
n fo
r the
File
men
u fu
nctio
n Fi
leM
enu_
Cal
lbac
k(hO
bjec
t, ev
entd
ata,
han
dles
) %
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Fun
ctio
n fo
r the
Prin
t men
u ch
oice
fu
nctio
n P
rintM
enuI
tem
_Cal
lbac
k(hO
bjec
t, ev
entd
ata,
han
dles
) %
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
51
c
la;
te
xt(0
.95,
0.5,
num
2str(
hand
les.
curre
nt_p
ortfo
lio_v
alue
(1,1
)),..
.
'
Uni
ts','
Nor
mal
ized
','H
oriz
onta
lAlig
nmen
t','ri
ght')
; en
d %
Set
fore
cast
_but
ton
to 2
so
that
Cre
ate
Por
tfolio
set
s th
e co
rrect
%
curre
nt_p
ortfo
lio_v
alue
_dat
e ha
ndle
s.fo
reca
st_b
utto
n =
2;
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,h
andl
es);
% --
----
----
----
-----
----
----
----
----
-----
----
----
----
-----
----
----
---
% C
all t
he C
reat
Por
tfolio
Fun
ctio
n to
set
the
hand
les.
curre
nt_d
ata
%
fiel
d to
the
valu
e of
the
choo
sen
portf
olio
C
reat
e_P
ortfo
lio(h
andl
es.fi
gure
1,[],
hand
les)
; %
----
----
----
-----
----
----
----
----
-----
----
----
----
----
-----
----
----
- %
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
%P
lot t
he c
urre
nt p
ortfo
lio
axes
(han
dles
.Gra
ph);
zoom
out
; cl
a;
plot
(han
dles
.cur
rent
_dat
a);
tit
le('N
orm
al p
lot')
; xl
abel
('Dat
e');
ylab
el('V
alue
(SE
K)')
; %
Set
the
lege
nd to
the
nam
e of
the
stoc
k if
only
one
sto
ck is
cho
osen
if(
1 ==
sum
(han
dles
.cur
rent
_por
tfolio
))
lege
nd(C
urre
nt_L
egen
d(ha
ndle
s.fig
ure1
,[],h
andl
es))
; el
se
le
gend
('off'
)
% --
- Fun
ctio
n fo
r the
Hel
p m
enu
func
tion
Hel
pMen
u_C
allb
ack(
hObj
ect,
even
tdat
a, h
andl
es)
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- F
unct
ion
for t
he A
bout
men
u ch
oice
fu
nctio
n A
bout
Fore
cast
_Cal
lbac
k(hO
bjec
t, ev
entd
ata,
han
dles
) %
Use
a h
elp
dial
og to
pre
sent
the
info
rmat
ion
help
dlg(
'For
ecas
t Ver
sion
1.0
Cop
yrig
ht 2
005,
Jon
atha
n M
årte
nsso
n', .
..
'
Abo
ut F
orec
ast')
%
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Exe
cute
s on
but
ton
pres
s in
Nor
mal
butto
n1.
func
tion
Nor
mal
butto
n1_C
allb
ack(
hObj
ect,
even
tdat
a, h
andl
es, v
arar
gin)
%
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
%If
no s
tock
s ar
e se
lect
ed a
utom
atic
ally
sel
ect A
BB
if
(0 =
= su
m(h
andl
es.c
urre
nt_p
ortfo
lio))
%
Set
act
ive
chec
kbox
to c
heck
box1
set
(han
dles
.che
ckbo
x1,'V
alue
',1);
%
Cre
ate
a ve
ctor
to k
eep
track
of t
he c
urre
nt s
tock
in th
e po
rtfol
io
h
andl
es.c
urre
nt_p
ortfo
lio =
[1,0
,0,0
,0,0
];
%S
et th
e po
rtfol
io v
alue
to 5
0 fo
r AB
B
h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
= [5
0,0,
0,0,
0,0,
0];
%
Set
the
text
in V
alue
_of_
AB
B to
50
a
xes(
hand
les.
Val
ue_o
f_A
BB
);
52
%
Set
act
ive
chec
kbox
to c
heck
box1
set
(han
dles
.che
ckbo
x1,'V
alue
',1);
%
Cre
ate
a ve
ctor
to k
eep
track
of t
he c
urre
nt s
tock
in th
e po
rtfol
io
h
andl
es.c
urre
nt_p
ortfo
lio =
[1,0
,0,0
,0,0
];
%S
et th
e po
rtfol
io v
alue
to 5
0 fo
r AB
B
h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
= [5
0,0,
0,0,
0,0,
0];
%
Set
the
text
in V
alue
_of_
AB
B to
50
a
xes(
hand
les.
Val
ue_o
f_A
BB
);
cla
;
text
(0.9
5,0.
5,nu
m2s
tr(ha
ndle
s.cu
rrent
_por
tfolio
_val
ue(1
,1)),
...
'U
nits
','N
orm
aliz
ed','
Hor
izon
talA
lignm
ent',
'righ
t');
end
%S
et to
zer
o so
that
the
func
tion
Sam
plin
g kn
ows
that
the
call
%co
mes
from
For
ecas
tbut
ton1
ha
ndle
s.fo
reca
st_b
utto
n =
0;
% --
- Che
ck th
e le
ngth
of t
he fo
reca
st
n =
Fore
cast
_Len
gth(
hand
les.
figur
e1,[]
,han
dles
); %
Set
the
curre
nt p
ortfo
lio v
alue
dat
e te
mp_
date
num
bers
= g
etfie
ld(h
andl
es.a
bb,'d
ates
');
hand
les.
curre
nt_p
ortfo
lio_v
alue
_dat
e =
tem
p_da
tenu
mbe
rs(e
nd);
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,
hand
les)
; %
----
----
----
-----
----
----
----
----
-----
----
----
----
----
-----
----
----
- %
Cal
l the
Cre
at P
ortfo
lio F
unct
ion
to s
et th
e ha
ndle
s.cu
rrent
_dat
a
% fi
eld
to th
e va
lue
of th
e ch
oose
n po
rtfol
io
Cre
ate_
Por
tfolio
(han
dles
.figu
re1,
[],ha
ndle
s);
% --
----
----
----
-----
----
----
----
----
-----
----
----
----
-----
----
----
---
end
%S
et th
e tic
ks o
n th
e x-
axis
to th
e co
rrec
t dat
es
curre
nt_d
ate_
leng
th =
han
dles
.sto
cks_
end_
date
-ha
ndle
s.po
rtfol
io_s
tart_
date
; t1
= h
andl
es.p
ortfo
lio_s
tart_
date
; t2
= h
andl
es.p
ortfo
lio_s
tart_
date
+(cu
rrent
_dat
e_le
ngth
)/8;
t3 =
han
dles
.por
tfolio
_sta
rt_da
te+(
curre
nt_d
ate_
leng
th)/4
; t4
= h
andl
es.p
ortfo
lio_s
tart_
date
+(cu
rrent
_dat
e_le
ngth
)*3/
8;
t5 =
han
dles
.por
tfolio
_sta
rt_da
te+(
curre
nt_d
ate_
leng
th)/2
; t6
= h
andl
es.s
tock
s_en
d_da
te-(c
urre
nt_d
ate_
leng
th)*
3/8;
t7
= h
andl
es.s
tock
s_en
d_da
te-(c
urre
nt_d
ate_
leng
th)/4
; t8
= h
andl
es.s
tock
s_en
d_da
te-(c
urre
nt_d
ate_
leng
th)/8
; t9
= h
andl
es.s
tock
s_en
d_da
te;
set(g
ca,'X
Tick
Labe
l',{d
ates
tr(t1
,1);d
ates
tr(t2
,1);d
ates
tr(t3
,1);
...
d
ates
tr(t4
,1);d
ates
tr(t5
,1);d
ates
tr(t6
,1);d
ates
tr(t7
,1);
...
d
ates
tr(t8
,1);d
ates
tr(t9
,1)}
); se
t(gca
,'XTi
ck',[
t1 t2
t3 t4
t5 t6
t7 t8
t9]);
zo
om o
n;
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,h
andl
es);
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- E
xecu
tes
on b
utto
n pr
ess
in F
orec
astb
utto
n1.
func
tion
Fore
cast
butto
n1_C
allb
ack(
hObj
ect,
even
tdat
a, h
andl
es, v
arar
gin)
%
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
%If
no s
tock
s ar
e se
lect
ed a
utom
atic
ally
sel
ect A
BB
if
(0 =
= su
m(h
andl
es.c
urre
nt_p
ortfo
lio))
53
title
('For
ecas
t plo
t');
xlab
el('D
ate'
); yl
abel
('Val
ue (S
EK
)');
%S
et th
e le
gend
to th
e na
me
of th
e st
ock
if on
ly o
ne s
tock
is c
hoos
en
if(1
== s
um(h
andl
es.c
urre
nt_p
ortfo
lio))
le
gend
(Cur
rent
_Leg
end(
hand
les.
figur
e1,[]
,han
dles
));
else
lege
nd('o
ff')
end
text
(0.3
4,0.
97,'S
ampl
e M
ean:
','U
nits
','Nor
mal
ized
', ...
'Bac
kgro
undC
olor
',[1
1 1]
); te
xt(0
.58,
0.97
,num
2str(
(han
dles
.por
tfolio
_sam
ple_
mea
n-1)
*250
+1),
...
'U
nits
','N
orm
aliz
ed','
Bac
kgro
undC
olor
',[1
1 1]
); te
xt(0
.34,
0.93
,'Sam
ple
Sta
ndar
d D
evia
tion:
','Uni
ts','N
orm
aliz
ed',
...
'B
ackg
roun
dCol
or',[
1 1
1]);
text
(0.5
8,0.
93,n
um2s
tr(ha
ndle
s.po
rtfol
io_s
ampl
e_st
anda
rd_d
evia
tion
* ...
sqr
t(250
)),'U
nits
','N
orm
aliz
ed','
Bac
kgro
undC
olor
',[1
1 1]
); %
Set
the
ticks
on
the
x-ax
is to
the
corr
ect d
ates
cu
rrent
_dat
e_le
ngth
= d
ates
(end
)-ha
ndle
s.po
rtfol
io_s
tart_
date
; t1
= h
andl
es.p
ortfo
lio_s
tart_
date
; t2
= h
andl
es.p
ortfo
lio_s
tart_
date
+(cu
rrent
_dat
e_le
ngth
)/8;
t3 =
han
dles
.por
tfolio
_sta
rt_da
te+(
curre
nt_d
ate_
leng
th)/4
; t4
= h
andl
es.p
ortfo
lio_s
tart_
date
+(cu
rrent
_dat
e_le
ngth
)*3/
8;
t5 =
han
dles
.por
tfolio
_sta
rt_da
te+(
curre
nt_d
ate_
leng
th)/2
; t6
= d
ates
(end
)-(c
urre
nt_d
ate_
leng
th)*
3/8;
t7
= d
ates
(end
)-(c
urre
nt_d
ate_
leng
th)/4
; t8
= d
ates
(end
)-(c
urre
nt_d
ate_
leng
th)/8
; t9
= d
ates
(end
); se
t(gca
,'XTi
ckLa
bel',
{dat
estr(
t1,1
);dat
estr(
t2,1
);dat
estr(
t3,1
); ...
dat
estr(
t4,1
);dat
estr(
t5,1
);dat
estr(
t6,1
);dat
estr(
t7,1
); ...
dat
estr(
t8,1
);dat
estr(
t9,1
)});
set(g
ca,'X
Tick
',[t1
t2 t3
t4 t5
t6 t7
t8 t9
]);
zoom
on;
%C
alcu
late
the
fore
cast
ed lo
wer
con
fiden
ce d
ata
serie
s fo
r t =
1:n
+1
fo
reca
st_l
ower
_con
fiden
ce_d
ata(
t,1) =
...
su
m(h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
) * ..
.
exp(
sam
ple_
mea
n *
(t-1)
- 1.
96 *
...
sq
rt(sa
mpl
e_va
rianc
e) *
sqr
t(t-1
));
end
%C
reat
e th
e fo
reca
st lo
wer
con
fiden
ce ti
mes
erie
s fo
reca
st_l
ower
_con
fiden
ce_v
ecto
r = fi
nts(
date
s, ..
.
fore
cast
_low
er_c
onfid
ence
_dat
a);
%R
eset
the
fore
cast
_upp
er_c
onfid
ence
_dat
a ve
ctor
fo
reca
st_u
pper
_con
fiden
ce_d
ata(
1:n+
1,1)
=0;
%C
alcu
late
the
fore
cast
ed u
pper
con
fiden
ce d
ata
serie
s fo
r t =
1:n
+1
fo
reca
st_u
pper
_con
fiden
ce_d
ata(
t,1) =
...
su
m(h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
) * ..
.
exp(
sam
ple_
mea
n *
(t-1)
+ 1
.96
* ...
sqrt(
sam
ple_
varia
nce)
* s
qrt(t
-1))
; en
d %
Cre
ate
the
fore
cast
upp
er c
onfid
ence
tim
eser
ies
fore
cast
_upp
er_c
onfid
ence
_vec
tor =
fint
s(da
tes,
...
fo
reca
st_u
pper
_con
fiden
ce_d
ata)
; %
--- P
lot t
he d
ata
axes
(han
dles
.Gra
ph);
zoom
out
; cl
a;
plot
(fore
cast
_low
er_c
onfid
ence
_vec
tor);
pl
ot(fo
reca
st_u
pper
_con
fiden
ce_v
ecto
r);
plot
(plo
t_da
ta);
54
%S
et th
e cu
rrent
por
tfolio
val
ue d
ate
to th
e la
st d
ate
min
us th
e le
ngth
of
%th
e fo
reca
st
tem
p_da
tenu
mbe
rs =
get
field
(han
dles
.abb
,'dat
es');
ha
ndle
s.cu
rrent
_por
tfolio
_val
ue_d
ate
= te
mp_
date
num
bers
(end
-n);
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,
hand
les)
; %
----
----
----
-----
----
----
----
----
-----
----
----
----
----
-----
----
----
- %
Cal
l the
Cre
at P
ortfo
lio F
unct
ion
to s
et th
e ha
ndle
s.cu
rrent
_dat
a
% fi
eld
to th
e va
lue
of th
e ch
oose
n po
rtfol
io
Cre
ate_
Por
tfolio
(han
dles
.figu
re1,
[],ha
ndle
s);
% --
----
----
----
-----
----
----
----
----
-----
----
----
----
-----
----
----
---
%Lo
ad th
e cu
rren
t han
dles
ha
ndle
s =
guid
ata(
gcbo
); %
----
----
----
-----
----
----
----
----
-----
----
----
----
----
-----
----
----
- %
Cal
l the
Cur
rent
Por
tfolio
Wei
ghts
to s
et th
e
% h
andl
es.c
urre
nt_p
ortfo
lio_w
eigh
ts fi
eld
to th
e va
lue
of th
e ch
oose
n %
por
tfolio
C
urre
nt_P
ortfo
lio_W
eigh
ts(h
andl
es.fi
gure
1,[],
hand
les)
; %
----
----
----
-----
----
----
----
----
-----
----
----
----
----
-----
----
----
- %
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
% --
----
----
----
-----
----
----
----
----
-----
----
----
----
-----
----
----
---
% C
all t
he S
ampl
ing
func
tion
to c
alcu
late
the
sam
ple
mea
n
% a
nd s
ampl
e st
anda
rd d
evia
tion
Sam
plin
g(ha
ndle
s.fig
ure1
,[],h
andl
es);
% --
----
----
----
-----
----
----
----
----
-----
----
----
----
-----
----
----
---
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,
hand
les)
; %
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Exe
cute
s on
but
ton
pres
s in
For
ecas
twith
inbu
tton1
. fu
nctio
n Fo
reca
stw
ithin
butto
n1_C
allb
ack(
hObj
ect,
even
tdat
a, h
andl
es)
%Lo
ad th
e cu
rren
t han
dles
ha
ndle
s =
guid
ata(
gcbo
); %
If no
sto
cks
are
sele
cted
aut
omat
ical
ly s
elec
t AB
B
if (0
==
sum
(han
dles
.cur
rent
_por
tfolio
))
%S
et a
ctiv
e ch
eckb
ox to
che
ckbo
x1
s
et(h
andl
es.c
heck
box1
,'Val
ue',1
);
%C
reat
e a
vect
or to
kee
p tra
ck o
f the
cur
rent
sto
ck in
the
portf
olio
han
dles
.cur
rent
_por
tfolio
= [1
,0,0
,0,0
,0];
%
Set
the
portf
olio
val
ue to
50
for A
BB
han
dles
.cur
rent
_por
tfolio
_val
ue =
[50,
0,0,
0,0,
0,0]
;
%S
et th
e te
xt in
Val
ue_o
f_A
BB
to 5
0
axe
s(ha
ndle
s.V
alue
_of_
AB
B);
c
la;
te
xt(0
.95,
0.5,
num
2str(
hand
les.
curre
nt_p
ortfo
lio_v
alue
(1,1
)), ..
.
'
Uni
ts','
Nor
mal
ized
','H
oriz
onta
lAlig
nmen
t','ri
ght')
; En
d %
Set
han
dles
.fore
cast
_but
ton
to o
ne s
o th
at th
e fu
nctio
n
%S
ampl
ing
know
s th
at th
e ca
ll co
mes
from
For
ecas
twith
inbu
tton1
ha
ndle
s.fo
reca
st_b
utto
n =
1;
% --
- Che
ck th
e le
ngth
of t
he fo
reca
st
n =
Fore
cast
_Len
gth(
hand
les.
figur
e1,[]
,han
dles
);
55
% E
xtra
ct th
e da
tes
with
in th
e cu
rrent
tim
eser
ies
to u
se th
em fo
r the
%
fore
cast
vec
tors
da
te_m
atrix
= g
etfie
ld(h
andl
es.c
urre
nt_d
ata,
'dat
es');
da
tes
= da
te_m
atrix
(end
-n:e
nd);
%C
reat
e th
e fo
reca
st m
ean
vect
or
fore
cast
_mea
n_ve
ctor
= fi
nts(
date
s, fo
reca
st_m
ean_
data
); %
Res
et th
e fo
reca
st_l
ower
_con
fiden
ce_d
ata
vect
or
fore
cast
_low
er_c
onfid
ence
_dat
a(1:
n+1,
1)=0
; %
Cal
cula
te th
e fo
reca
sted
low
er c
onfid
ence
dat
a se
ries
for t
= 1
:n+1
fore
cast
_low
er_c
onfid
ence
_dat
a(t,1
) = ..
.
sum
(han
dles
.cur
rent
_por
tfolio
_val
ue) *
...
ex
p(sa
mpl
e_m
ean
* (t-
1) -
1.96
* ..
.
sqrt(
sam
ple_
varia
nce)
* s
qrt(t
-1))
; en
d %
Cre
ate
the
fore
cast
low
er c
onfid
ence
tim
eser
ies
fore
cast
_low
er_c
onfid
ence
_vec
tor =
fint
s(da
tes,
...
f
orec
ast_
low
er_c
onfid
ence
_dat
a);
%R
eset
the
fore
cast
_upp
er_c
onfid
ence
_dat
a ve
ctor
fo
reca
st_u
pper
_con
fiden
ce_d
ata(
1:n+
1,1)
=0;
%C
alcu
late
the
fore
cast
ed u
pper
con
fiden
ce d
ata
serie
s fo
r t =
1:n
+1
fo
reca
st_u
pper
_con
fiden
ce_d
ata(
t,1) =
...
su
m(h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
) * ..
.
exp(
sam
ple_
mea
n *
(t-1)
+ 1
.96
* ...
sqrt(
sam
ple_
varia
nce)
* s
qrt(t
-1))
; en
d
%Lo
ad th
e cu
rren
t han
dles
ha
ndle
s =
guid
ata(
gcbo
); %
Res
et s
ampl
e_va
rianc
e sa
mpl
e_va
rianc
e =
0;
%Tr
ansf
orm
the
daily
sam
ple
stan
dard
dev
iatio
n of
the
portf
olio
retu
rns
%
into
the
daily
sam
ple
varia
nce
of lo
g-re
turn
s of
the
portf
olio
sa
mpl
e_va
rianc
e =
log(
...
(h
andl
es.p
ortfo
lio_s
ampl
e_st
anda
rd_d
evia
tion
* ...
han
dles
.por
tfolio
_sam
ple_
stan
dard
_dev
iatio
n) /
...
(h
andl
es.p
ortfo
lio_s
ampl
e_m
ean
* ...
han
dles
.por
tfolio
_sam
ple_
mea
n) +
1);
%R
eset
sam
ple_
mea
n sa
mpl
e_m
ean
= 0;
%
Tran
sfor
m th
e da
ily s
ampl
e m
ean
of th
e po
rtfol
io re
turn
s in
to th
e da
ily
%sa
mpl
e m
ean
of lo
g-re
turn
s of
the
portf
olio
sa
mpl
e_m
ean
= lo
g(ha
ndle
s.po
rtfol
io_s
ampl
e_m
ean)
- ...
sam
ple_
varia
nce
/ 2;
%R
eset
the
fore
cast
_mea
n_da
ta v
ecto
r fo
reca
st_m
ean_
data
(1:n
+1,1
)=0;
%
Cal
cula
te th
e fo
reca
sted
mea
n da
ta s
erie
s fo
r t =
1:n
+1
fo
reca
st_m
ean_
data
(t,1)
= s
um(h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
) * ..
.
exp
((sam
ple_
mea
n +
0.5
* sa
mpl
e_va
rianc
e) *
(t-1
));
end
56
t3 =
han
dles
.por
tfolio
_sta
rt_da
te+(
curre
nt_d
ate_
leng
th)/4
; t4
= h
andl
es.p
ortfo
lio_s
tart_
date
+(cu
rrent
_dat
e_le
ngth
)*3/
8;
t5 =
han
dles
.por
tfolio
_sta
rt_da
te+(
curre
nt_d
ate_
leng
th)/2
; t6
= h
andl
es.s
tock
s_en
d_da
te-(c
urre
nt_d
ate_
leng
th)*
3/8;
t7
= h
andl
es.s
tock
s_en
d_da
te-(c
urre
nt_d
ate_
leng
th)/4
; t8
= h
andl
es.s
tock
s_en
d_da
te-(c
urre
nt_d
ate_
leng
th)/8
; t9
= h
andl
es.s
tock
s_en
d_da
te;
set(g
ca,'X
Tick
Labe
l',{d
ates
tr(t1
,1);d
ates
tr(t2
,1);d
ates
tr(t3
,1);
...
d
ates
tr(t4
,1);d
ates
tr(t5
,1);d
ates
tr(t6
,1);d
ates
tr(t7
,1);
...
d
ates
tr(t8
,1);d
ates
tr(t9
,1)}
); se
t(gca
,'XTi
ck',[
t1 t2
t3 t4
t5 t6
t7 t8
t9]);
zo
om o
n;
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,
hand
les)
; %
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Fun
ctio
n fo
r the
For
ecas
tpan
el1
func
tion
Fore
cast
pane
l1_B
utto
nDow
nFcn
(hO
bjec
t, ev
entd
ata,
han
dles
) %
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Exe
cute
s on
but
ton
pres
s in
che
ckbo
x1.
func
tion
chec
kbox
1_C
allb
ack(
hObj
ect,
even
tdat
a, h
andl
es)
%Lo
ad th
e cu
rren
t han
dles
ha
ndle
s =
guid
ata(
gcbo
);
%C
reat
e th
e fo
reca
st u
pper
con
fiden
ce ti
mes
erie
s fo
reca
st_u
pper
_con
fiden
ce_v
ecto
r = fi
nts(
date
s, ..
.
for
ecas
t_up
per_
conf
iden
ce_d
ata)
; %
--- P
lot t
he d
ata
axes
(han
dles
.Gra
ph);
zoom
out
; cl
a;
plot
(fore
cast
_low
er_c
onfid
ence
_vec
tor);
pl
ot(fo
reca
st_u
pper
_con
fiden
ce_v
ecto
r);
plot
(fore
cast
_mea
n_ve
ctor
); pl
ot(h
andl
es.c
urre
nt_d
ata)
; tit
le('F
orec
ast p
lot')
; xl
abel
('Dat
e');
ylab
el('V
alue
(SE
K)')
; %
Set
the
lege
nd to
the
nam
e of
the
stoc
k if
only
one
sto
ck is
cho
osen
if(
1 ==
sum
(han
dles
.cur
rent
_por
tfolio
))
lege
nd(C
urre
nt_L
egen
d(ha
ndle
s.fig
ure1
,[],h
andl
es))
; el
se
le
gend
('off'
) en
d te
xt(0
.34,
0.97
,'Sam
ple
Mea
n:','
Uni
ts','N
orm
aliz
ed',
...
'B
ackg
roun
dCol
or',[
1 1
1]);
text
(0.5
8,0.
97,n
um2s
tr((h
andl
es.p
ortfo
lio_s
ampl
e_m
ean-
1)*2
50+1
), ...
'Uni
ts','
Nor
mal
ized
','B
ackg
roun
dCol
or',[
1 1
1]);
text
(0.3
4,0.
93,'S
ampl
e S
tand
ard
Dev
iatio
n:','U
nits
','Nor
mal
ized
', ...
'Bac
kgro
undC
olor
',[1
1 1]
); te
xt(0
.58,
0.93
,num
2str(
hand
les.
portf
olio
_sam
ple_
stan
dard
_dev
iatio
n *
...
s
qrt(2
50))
,'Uni
ts','N
orm
aliz
ed','
Bac
kgro
undC
olor
',[1
1 1]
); %
Set
the
ticks
on
the
x-ax
is to
the
corr
ect d
ates
cu
rrent
_dat
e_le
ngth
= h
andl
es.s
tock
s_en
d_da
te-
hand
les.
portf
olio
_sta
rt_da
te;
t1 =
han
dles
.por
tfolio
_sta
rt_da
te;
t2 =
han
dles
.por
tfolio
_sta
rt_da
te+(
curre
nt_d
ate_
leng
th)/8
;
57
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,h
andl
es);
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- E
xecu
tes
on b
utto
n pr
ess
in c
heck
box2
. fu
nctio
n ch
eckb
ox2_
Cal
lbac
k(hO
bjec
t, ev
entd
ata,
han
dles
) %
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
if (g
et(h
Obj
ect,'
Val
ue')
== g
et(h
Obj
ect,'
Max
'))
h
andl
es.c
urre
nt_p
ortfo
lio(1
,2) =
1;
te
mp
= in
putd
lg('E
nter
the
valu
e of
Axi
s at
the
Fore
cast
dat
e', .
..
'
Val
ue o
f Axi
s',1
,cel
lstr(
'50'
),'of
f');
w
hile
(0 =
= is
scal
ar(s
tr2nu
m(te
mp{
1,1}
)))
tem
p =
inpu
tdlg
('Ent
er th
e va
lue
of A
xis
at th
e Fo
reca
st d
ate'
, ...
'
Val
ue o
f Axi
s',1
,cel
lstr(
'50'
),'of
f');
e
nd
h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
(1,2
) = s
tr2nu
m(te
mp{
1,1}
);
axe
s(ha
ndle
s.V
alue
_of_
Axi
s);
c
la;
te
xt(0
.95,
0.5,
num
2str(
hand
les.
curre
nt_p
ortfo
lio_v
alue
(1,2
)), ..
.
'
Uni
ts','
Nor
mal
ized
','H
oriz
onta
lAlig
nmen
t','ri
ght')
; el
se
h
andl
es.c
urre
nt_p
ortfo
lio(1
,2) =
0;
h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
(1,2
) = 0
;
axe
s(ha
ndle
s.V
alue
_of_
Axi
s);
c
la;
te
xt(0
.95,
0.5,
num
2str(
hand
les.
curre
nt_p
ortfo
lio_v
alue
(1,2
)), ..
.
'
Uni
ts','
Nor
mal
ized
','H
oriz
onta
lAlig
nmen
t','ri
ght')
; en
d
% If
the
chec
kbox
is m
arke
d if
(get
(hO
bjec
t,'V
alue
') ==
get
(hO
bjec
t,'M
ax'))
% S
et th
e ha
ndle
s.cu
rrent
_por
tfolio
(1,1
) to
1 to
incl
ude
AB
B in
% p
ortfo
lio
h
andl
es.c
urre
nt_p
ortfo
lio(1
,1) =
1;
%
Use
an
inpu
t dia
log
to a
sk th
e va
lue
of th
e st
ock
at fo
reca
st d
ate,
if
%
the
inpu
t is
not a
num
ber a
sk a
gain
unt
il it
is a
num
ber
te
mp=
inpu
tdlg
('Ent
er th
e va
lue
of A
BB
LTD
SD
B a
t the
For
ecas
t dat
e',..
.
'
Val
ue o
f AB
B L
TD S
DB
',1,c
ells
tr('5
0'),'
off')
;
whi
le (0
==
issc
alar
(str2
num
(tem
p{1,
1}))
)
te
mp
= in
putd
lg( .
..
'E
nter
the
valu
e of
AB
B L
TD S
DB
at t
he F
orec
ast d
ate'
, ...
'
Val
ue o
f AB
B L
TD S
DB
',1,c
ells
tr('5
0'),'
off')
;
end
%S
et th
e cu
rrent
_por
tfolio
_val
ue(1
,1) t
o th
e ch
oose
n va
lue
h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
(1,1
) = s
tr2nu
m(te
mp{
1,1}
);
%U
pdat
e th
e ha
ndle
s.Va
lue_
of_A
BB fi
gure
with
the
choo
sen
valu
e
axe
s(ha
ndle
s.V
alue
_of_
AB
B);
c
la;
te
xt(0
.95,
0.5,
num
2str(
hand
les.
curre
nt_p
ortfo
lio_v
alue
(1,1
)), ..
.
'
Uni
ts','
Nor
mal
ized
','H
oriz
onta
lAlig
nmen
t','ri
ght')
; %
If th
e ch
eckb
ox is
unm
arke
d el
se
%
Set
the
hand
les.
curre
nt_p
ortfo
lio(1
,1) t
o 0
to e
xclu
de A
BB
from
the
%
por
tfolio
han
dles
.cur
rent
_por
tfolio
(1,1
) = 0
;
%S
et th
e cu
rrent
_por
tfolio
_val
ue(1
,1) t
o ze
ro
h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
(1,1
) = 0
;
%U
pdat
e th
e ha
ndle
s.Va
lue_
of_A
BB
figu
re w
ith th
e va
lue
zero
axe
s(ha
ndle
s.V
alue
_of_
AB
B);
c
la;
te
xt(0
.95,
0.5,
num
2str(
hand
les.
curre
nt_p
ortfo
lio_v
alue
(1,1
)), ..
.
'
Uni
ts','
Nor
mal
ized
','H
oriz
onta
lAlig
nmen
t','ri
ght')
; en
d
58
end
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,h
andl
es);
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- E
xecu
tes
on b
utto
n pr
ess
in c
heck
box4
. fu
nctio
n ch
eckb
ox4_
Cal
lbac
k(hO
bjec
t, ev
entd
ata,
han
dles
) %
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
if (g
et(h
Obj
ect,'
Val
ue')
== g
et(h
Obj
ect,'
Max
'))
h
andl
es.c
urre
nt_p
ortfo
lio(1
,4) =
1;
te
mp
= in
putd
lg('E
nter
the
valu
e of
Rea
dsof
t at t
he F
orec
ast d
ate'
, ...
'V
alue
of R
eads
oft',
1,ce
llstr(
'50'
),'of
f');
w
hile
(0 =
= is
scal
ar(s
tr2nu
m(te
mp{
1,1}
)))
tem
p =
inpu
tdlg
( ...
'
Ent
er th
e va
lue
of R
eads
oft a
t the
For
ecas
t dat
e', .
..
'V
alue
of R
eads
oft',
1,ce
llstr(
'50'
),'of
f');
e
nd
h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
(1,4
) = s
tr2nu
m(te
mp{
1,1}
);
axe
s(ha
ndle
s.V
alue
_of_
Rea
dsof
t);
c
la;
te
xt(0
.95,
0.5,
num
2str(
hand
les.
curre
nt_p
ortfo
lio_v
alue
(1,4
)), ..
.
'
Uni
ts','
Nor
mal
ized
','H
oriz
onta
lAlig
nmen
t','ri
ght')
; el
se
h
andl
es.c
urre
nt_p
ortfo
lio(1
,4) =
0;
h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
(1,4
) = 0
;
axe
s(ha
ndle
s.V
alue
_of_
Rea
dsof
t);
c
la;
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,h
andl
es);
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- E
xecu
tes
on b
utto
n pr
ess
in c
heck
box3
. fu
nctio
n ch
eckb
ox3_
Cal
lbac
k(hO
bjec
t, ev
entd
ata,
han
dles
) %
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
if (g
et(h
Obj
ect,'
Val
ue')
== g
et(h
Obj
ect,'
Max
'))
h
andl
es.c
urre
nt_p
ortfo
lio(1
,3) =
1;
te
mp=
inpu
tdlg
('Ent
er th
e va
lue
of E
ricss
on B
at t
he F
orec
ast d
ate'
, ...
'V
alue
of E
ricss
on B
',1,c
ells
tr('5
0'),'
off')
;
whi
le (0
==
issc
alar
(str2
num
(tem
p{1,
1}))
)
te
mp
= in
putd
lg( .
..
'E
nter
the
valu
e of
Eric
sson
B a
t the
For
ecas
t dat
e', .
..
'V
alue
of E
ricss
on B
',1,c
ells
tr('5
0'),'
off')
;
end
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,3) =
str2
num
(tem
p{1,
1});
a
xes(
hand
les.
Val
ue_o
f_E
ricss
on);
c
la;
te
xt(0
.95,
0.5,
num
2str(
hand
les.
curre
nt_p
ortfo
lio_v
alue
(1,3
)), ..
.
'
Uni
ts','
Nor
mal
ized
','H
oriz
onta
lAlig
nmen
t','ri
ght')
; el
se
h
andl
es.c
urre
nt_p
ortfo
lio(1
,3) =
0;
h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
(1,3
) = 0
;
axe
s(ha
ndle
s.V
alue
_of_
Eric
sson
);
cla
;
text
(0.9
5,0.
5,nu
m2s
tr(ha
ndle
s.cu
rrent
_por
tfolio
_val
ue(1
,3)),
...
'U
nits
','N
orm
aliz
ed','
Hor
izon
talA
lignm
ent',
'righ
t');
59
c
la;
te
xt(0
.95,
0.5,
num
2str(
hand
les.
curre
nt_p
ortfo
lio_v
alue
(1,5
)), ..
.
'
Uni
ts','
Nor
mal
ized
','H
oriz
onta
lAlig
nmen
t','ri
ght')
; en
d %
Upd
ate
hand
les
stru
ctur
e gu
idat
a(hO
bjec
t,han
dles
); %
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Exe
cute
s on
but
ton
pres
s in
che
ckbo
x6.
func
tion
chec
kbox
6_C
allb
ack(
hObj
ect,
even
tdat
a, h
andl
es)
%Lo
ad th
e cu
rren
t han
dles
ha
ndle
s =
guid
ata(
gcbo
); if
(get
(hO
bjec
t,'V
alue
') ==
get
(hO
bjec
t,'M
ax'))
han
dles
.cur
rent
_por
tfolio
(1,6
) = 1
;
tem
p =
inpu
tdlg
('Ent
er th
e va
lue
of V
olvo
B a
t the
For
ecas
t dat
e', .
..
'
Val
ue o
f Vol
vo B
',1,c
ells
tr('5
0'),'
off')
;
whi
le (0
==
issc
alar
(str2
num
(tem
p{1,
1}))
)
te
mp
= in
putd
lg( .
..
'E
nter
the
valu
e of
Vol
vo B
at t
he F
orec
ast d
ate'
, ...
'
Val
ue o
f Vol
vo B
',1,c
ells
tr('5
0'),'
off')
;
End
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,6) =
str2
num
(tem
p{1,
1});
a
xes(
hand
les.
Val
ue_o
f_V
olvo
);
cla
;
text
(0.9
5,0.
5,nu
m2s
tr(ha
ndle
s.cu
rrent
_por
tfolio
_val
ue(1
,6)),
...
'U
nits
','N
orm
aliz
ed','
Hor
izon
talA
lignm
ent',
'righ
t');
te
xt(0
.95,
0.5,
num
2str(
hand
les.
curre
nt_p
ortfo
lio_v
alue
(1,4
)), ..
.
'
Uni
ts','
Nor
mal
ized
','H
oriz
onta
lAlig
nmen
t','ri
ght')
; en
d %
Upd
ate
hand
les
stru
ctur
e gu
idat
a(hO
bjec
t,han
dles
); %
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Exe
cute
s on
but
ton
pres
s in
che
ckbo
x5.
func
tion
chec
kbox
5_C
allb
ack(
hObj
ect,
even
tdat
a, h
andl
es)
%Lo
ad th
e cu
rren
t han
dles
ha
ndle
s =
guid
ata(
gcbo
); if
(get
(hO
bjec
t,'V
alue
') ==
get
(hO
bjec
t,'M
ax'))
han
dles
.cur
rent
_por
tfolio
(1,5
) = 1
;
tem
p =
inpu
tdlg
('Ent
er th
e va
lue
of S
HB
A a
t the
For
ecas
t dat
e', .
..
'
Val
ue o
f SH
B A
',1,c
ells
tr('5
0'),'
off')
;
whi
le (0
==
issc
alar
(str2
num
(tem
p{1,
1}))
)
te
mp
= in
putd
lg('E
nter
the
valu
e of
SH
B A
at t
he F
orec
ast d
ate'
, ...
'
Val
ue o
f SH
B A
',1,c
ells
tr('5
0'),'
off')
;
end
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,5) =
str2
num
(tem
p{1,
1});
a
xes(
hand
les.
Val
ue_o
f_S
HB
);
cla
;
text
(0.9
5,0.
5,nu
m2s
tr(ha
ndle
s.cu
rrent
_por
tfolio
_val
ue(1
,5)),
...
'U
nits
','N
orm
aliz
ed','
Hor
izon
talA
lignm
ent',
'righ
t');
else
han
dles
.cur
rent
_por
tfolio
(1,5
) = 0
;
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,5) =
0;
a
xes(
hand
les.
Val
ue_o
f_S
HB
);
60
%C
heck
whi
ch s
tock
is c
hoos
en a
nd s
et l
to th
e na
me
of th
e st
ock
if (1
==
get(h
andl
es.c
heck
box1
,'Val
ue'))
l =
'AB
B LT
D S
DB
'; el
seif
(1 =
= ge
t(han
dles
.che
ckbo
x2,'V
alue
'))
l
= 'A
xis'
; el
seif
(1 =
= ge
t(han
dles
.che
ckbo
x3,'V
alue
'))
l
= 'E
ricss
on B
'; el
seif
(1 =
= ge
t(han
dles
.che
ckbo
x4,'V
alue
'))
l
= 'R
eads
oft';
el
seif
(1 =
= ge
t(han
dles
.che
ckbo
x5,'V
alue
'))
l
= 'S
HB
A';
else
if (1
==
get(h
andl
es.c
heck
box6
,'Val
ue'))
l =
'Vol
vo B
'; en
d %
Upd
ate
hand
les
stru
ctur
e gu
idat
a(hO
bjec
t,han
dles
); %
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Fun
ctio
n fo
r det
erm
inin
g fo
reca
st le
ngth
dep
endi
ng o
n us
er c
hoic
e.
func
tion
n =
Fore
cast
_Len
gth(
hObj
ect,
even
tdat
a, h
andl
es, v
arar
gin)
%
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
%C
heck
the
choo
sen
leng
th a
nd s
et it
to th
e co
rrect
val
ue
if (1
==
get(h
andl
es.F
orec
astb
utto
n1d,
'Val
ue'))
n =
1;
else
if (1
==
get(h
andl
es.F
orec
astb
utto
n1w
,'Val
ue'))
n =
5;
else
han
dles
.cur
rent
_por
tfolio
(1,6
) = 0
;
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,6) =
0;
a
xes(
hand
les.
Val
ue_o
f_V
olvo
);
cla
;
text
(0.9
5,0.
5,nu
m2s
tr(ha
ndle
s.cu
rrent
_por
tfolio
_val
ue(1
,6)),
...
'U
nits
','N
orm
aliz
ed','
Hor
izon
talA
lignm
ent',
'righ
t');
end
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,h
andl
es);
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- E
xecu
tes
on b
utto
n pr
ess
in c
heck
box7
. fu
nctio
n ch
eckb
ox7_
Cal
lbac
k(hO
bjec
t, ev
entd
ata,
han
dles
) %
Use
d to
che
ck if
use
r wan
ts re
com
men
datio
ns a
bout
new
sto
cks
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- F
unct
ion
for s
ettin
g th
e co
rrect
lege
nd in
the
figur
e.
func
tion
l = C
urre
nt_L
egen
d(hO
bjec
t, ev
entd
ata,
han
dles
, var
argi
n)
%Lo
ad th
e cu
rren
t han
dles
ha
ndle
s =
guid
ata(
gcbo
); l =
0;
61
%C
heck
the
star
tdat
e of
the
curre
nt p
ortfo
lio
hand
les.
portf
olio
_sta
rt_da
te =
max
(han
dles
.cur
rent
_por
tfolio
.* ..
.
han
dles
.sto
cks_
star
t_da
te);
%C
heck
the
num
ber o
f dat
es in
the
portf
olio
j =
1;
for i
= 1
:6
if
(0 =
= ha
ndle
s.cu
rrent
_por
tfolio
(1,i)
)
els
e
t
emp_
ndat
a(1,
j) =
hand
les.
stoc
ks_n
data
(1,i)
;
j
= j
+ 1;
end
en
d %
Set
the
num
ber o
f dat
es to
the
low
est v
alue
of t
emp_
ndat
a ha
ndle
s.po
rtfol
io_n
data
= m
in(te
mp_
ndat
a);
%C
hang
e th
e cu
rrent
por
tfolio
val
ue d
ate
if th
e ca
ll co
mes
from
%
Nor
mal
butto
n1
if(2
== h
andl
es.fo
reca
st_b
utto
n)
h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
_dat
e =
hand
les.
portf
olio
_sta
rt_da
te;
end
%S
et th
e cu
rrent
sto
ck s
hare
s to
zer
o ha
ndle
s.cu
rrent
_sto
ck_s
hare
s =
[0,0
,0,0
,0,0
]; %
Set
the
curre
nt s
tock
pric
e to
zer
o ha
ndle
s.cu
rrent
_sto
ck_p
rice
= [0
,0,0
,0,0
,0];
%C
reat
e th
e po
rtfol
io
%S
et th
e fla
g to
zer
o is
data
= 0
;
else
if (1
==
get(h
andl
es.F
orec
astb
utto
n1m
,'Val
ue'))
n =
20;
el
seif
(1 =
= ge
t(han
dles
.For
ecas
tbut
ton3
m,'V
alue
'))
n
= 6
0;
else
if (1
==
get(h
andl
es.F
orec
astb
utto
n6m
,'Val
ue'))
n =
120
; el
seif
(1 =
= ge
t(han
dles
.For
ecas
tbut
ton1
y,'V
alue
'))
n
= 2
50;
else
if (1
==
get(h
andl
es.F
orec
astb
utto
n2y,
'Val
ue'))
n =
500
; en
d %
Upd
ate
hand
les
stru
ctur
e gu
idat
a(hO
bjec
t, ha
ndle
s);
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- F
unct
ion
for c
reat
ing
a po
rtfol
io.
func
tion
Cre
ate_
Por
tfolio
(hO
bjec
t, ev
entd
ata,
han
dles
, var
argi
n)
%Lo
ad th
e cu
rren
t han
dles
ha
ndle
s =
guid
ata(
gcbo
); %
Res
et c
urre
nt p
ortfo
lio
hand
les.
curre
nt_d
ata
= 0;
%
Res
et th
e cu
rrent
sto
ck s
hare
s ha
ndle
s.cu
rrent
_sto
ck_s
hare
s =
[0 0
0 0
0 0
]; %
Num
ber o
f sto
cks
in p
ortfo
lio
hand
les.
num
ber_
of_s
tock
s =
sum
(han
dles
.cur
rent
_por
tfolio
);
62
if (1
==
hand
les.
curre
nt_p
ortfo
lio(1
,3))
h
andl
es.c
urre
nt_s
tock
_pric
e(1,
3) =
get
field
(han
dles
.eric
sson
b, ..
.
's
erie
s1',h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
_dat
e);
h
andl
es.c
urre
nt_s
tock
_sha
res(
1,3)
= ..
.
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,3)/h
andl
es.c
urre
nt_s
tock
_pric
e(1,
3);
if
(0 =
= is
data
)
h
andl
es.c
urre
nt_d
ata
= ha
ndle
s.er
icss
onb.
* ...
h
andl
es.c
urre
nt_s
tock
_sha
res(
1,3)
;
i
sdat
a =
1;
e
lse
han
dles
.cur
rent
_dat
a =
...
hand
les.
eric
sson
b(en
d-ha
ndle
s.po
rtfol
io_n
data
+1:e
nd).*
...
hand
les.
curr
ent_
stoc
k_sh
ares
(1,3
) + ..
.
ha
ndle
s.cu
rrent
_dat
a(en
d-ha
ndle
s.po
rtfol
io_n
data
+1:e
nd);
e
nd
end
if (1
==
hand
les.
curre
nt_p
ortfo
lio(1
,4))
h
andl
es.c
urre
nt_s
tock
_pric
e(1,
4) =
get
field
(han
dles
.read
soft,
...
'ser
ies1
',han
dles
.cur
rent
_por
tfolio
_val
ue_d
ate)
;
h
andl
es.c
urre
nt_s
tock
_sha
res(
1,4)
= ..
.
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,4)/h
andl
es.c
urre
nt_s
tock
_pric
e(1,
4);
if
(0 =
= is
data
)
h
andl
es.c
urre
nt_d
ata
= ha
ndle
s.re
adso
ft.*
...
han
dles
.cur
rent
_sto
ck_s
hare
s(1,
4);
isd
ata
= 1;
els
e
h
andl
es.c
urre
nt_d
ata
= ...
ha
ndle
s.re
adso
ft(en
d-ha
ndle
s.po
rtfol
io_n
data
+1:e
nd).*
...
hand
les.
curr
ent_
stoc
k_sh
ares
(1,4
) + ..
.
ha
ndle
s.cu
rrent
_dat
a(en
d-ha
ndle
s.po
rtfol
io_n
data
+1:e
nd);
e
nd
end
%If
AB
B L
TD S
DB
is c
hoos
en a
dd it
to th
e cu
rrent
_dat
a m
atrix
if
(1 =
= ha
ndle
s.cu
rrent
_por
tfolio
(1,1
))
%E
xtra
ct th
e cu
rrent
sto
ck p
rice
of A
BB
han
dles
.cur
rent
_sto
ck_p
rice(
1,1)
= g
etfie
ld(h
andl
es.a
bb, .
..
's
erie
s1',h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
_dat
e);
%
Cal
cula
te th
e nu
mbe
r of s
hare
s of
AB
B b
ough
t at t
he fo
reca
st d
ate
in
%
orde
r to
have
the
choo
sen
valu
e of
AB
B
h
andl
es.c
urre
nt_s
tock
_sha
res(
1,1)
= ..
.
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,1)/h
andl
es.c
urre
nt_s
tock
_pric
e(1,
1);
%
Sca
le th
e A
BB
tim
eser
ies
with
the
num
ber o
f sto
ck s
hare
s
han
dles
.cur
rent
_dat
a =
hand
les.
abb.
*han
dles
.cur
rent
_sto
ck_s
hare
s(1,
1);
%
Set
the
flag
to o
ne s
o th
at th
e ne
xt s
tep
know
s th
at it
sha
ll ad
d th
e
%ne
w ti
mes
erie
s
isda
ta =
1;
end
if (1
==
hand
les.
curre
nt_p
ortfo
lio(1
,2))
h
andl
es.c
urre
nt_s
tock
_pric
e(1,
2) =
get
field
(han
dles
.axi
s, ..
.
's
erie
s1',h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
_dat
e);
h
andl
es.c
urre
nt_s
tock
_sha
res(
1,2)
= ..
.
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,2)/h
andl
es.c
urre
nt_s
tock
_pric
e(1,
2);
%
Che
ck if
the
times
erie
s sh
ould
be
a ne
w o
r add
ed to
a c
urre
nt
if
(0 =
= is
data
)
h
andl
es.c
urre
nt_d
ata
= ha
ndle
s.ax
is.*
...
han
dles
.cur
rent
_sto
ck_s
hare
s(1,
2);
isd
ata
= 1;
els
e
h
andl
es.c
urre
nt_d
ata
= ...
ha
ndle
s.ax
is(e
nd-h
andl
es.p
ortfo
lio_n
data
+1:e
nd).*
...
hand
les.
curr
ent_
stoc
k_sh
ares
(1,2
) + ..
.
ha
ndle
s.cu
rrent
_dat
a(en
d-ha
ndle
s.po
rtfol
io_n
data
+1:e
nd);
e
nd
end
63
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,
hand
les)
; %
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Fun
ctio
n fo
r exe
cutin
g th
e S
ampl
ing.
fu
nctio
n S
ampl
ing(
hObj
ect,
even
tdat
a, h
andl
es, v
arar
gin)
%
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
%C
heck
if c
all c
omes
from
For
cast
or F
orec
astw
ithin
f =
han
dles
.fore
cast
_but
ton;
%
--- C
heck
the
leng
th o
f the
fore
cast
n
= Fo
reca
st_L
engt
h(ha
ndle
s.fig
ure1
,[],h
andl
es);
%S
et th
e va
lues
to z
ero
colu
mn
= 1;
ha
ndle
s.m
ean_
vect
or =
0;
hand
les.
cova
rianc
e_ve
ctor
= 0
; ha
ndle
s.co
varia
nce_
mat
rix =
0;
hand
les.
wei
ghte
d_m
ean_
vect
or =
0;
hand
les.
wei
ghte
d_co
varia
nce_
vect
or =
0;
hand
les.
wei
ghte
d_co
varia
nce_
mat
rix =
0;
portf
olio
_log
_ret
urn_
mat
rix =
0;
portf
olio
_wei
ghts
_mat
rix =
0;
%E
xtra
ct th
e da
ta fr
om th
e A
BB
tim
eser
ies
abb_
data
_vec
tor =
get
field
(han
dles
.abb
, 'se
ries1
');
if (1
==
hand
les.
curre
nt_p
ortfo
lio(1
,5))
h
andl
es.c
urre
nt_s
tock
_pric
e(1,
5) =
get
field
(han
dles
.shb
a, ..
.
'
serie
s1',h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
_dat
e);
h
andl
es.c
urre
nt_s
tock
_sha
res(
1,5)
= ..
.
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,5)/h
andl
es.c
urre
nt_s
tock
_pric
e(1,
5);
if
(0 =
= is
data
)
h
andl
es.c
urre
nt_d
ata
= ha
ndle
s.sh
ba.*
...
han
dles
.cur
rent
_sto
ck_s
hare
s(1,
5);
isd
ata
= 1;
els
e
h
andl
es.c
urre
nt_d
ata
= ...
ha
ndle
s.sh
ba(e
nd-h
andl
es.p
ortfo
lio_n
data
+1:e
nd).*
...
hand
les.
curr
ent_
stoc
k_sh
ares
(1,5
) + ..
.
ha
ndle
s.cu
rrent
_dat
a(en
d-ha
ndle
s.po
rtfol
io_n
data
+1:e
nd);
e
nd
end
if (1
==
hand
les.
curre
nt_p
ortfo
lio(1
,6))
h
andl
es.c
urre
nt_s
tock
_pric
e(1,
6) =
get
field
(han
dles
.vol
vob,
...
'se
ries1
',han
dles
.cur
rent
_por
tfolio
_val
ue_d
ate)
;
h
andl
es.c
urre
nt_s
tock
_sha
res(
1,6)
= ..
.
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,6)/h
andl
es.c
urre
nt_s
tock
_pric
e(1,
6);
if
(0 =
= is
data
)
h
andl
es.c
urre
nt_d
ata
= ...
h
andl
es.v
olvo
b.*h
andl
es.c
urre
nt_s
tock
_sha
res(
1,6)
;
i
sdat
a =
1;
e
lse
han
dles
.cur
rent
_dat
a =
...
hand
les.
volv
ob(e
nd-h
andl
es.p
ortfo
lio_n
data
+1:e
nd).*
...
hand
les.
curr
ent_
stoc
k_sh
ares
(1,6
) + ..
.
ha
ndle
s.cu
rrent
_dat
a(en
d-ha
ndle
s.po
rtfol
io_n
data
+1:e
nd);
end
en
d
64
read
soft_
sam
ple_
mea
n =
1/ha
ndle
s.sa
mpl
e_si
ze *
...
l
og(r
eads
oft_
data
_vec
tor(
end-
n*f)
/ ...
r
eads
oft_
data
_vec
tor(e
nd-h
andl
es.s
ampl
e_si
ze-n
*f));
hand
les.
mea
n_ve
ctor
(1,c
olum
n) =
read
soft_
sam
ple_
mea
n;
colu
mn
= co
lum
n +
1;
shba
_dat
a_ve
ctor
= g
etfie
ld(h
andl
es.s
hba,
'ser
ies1
');
shba
_log
_ret
urn_
vect
or =
log(
shba
_dat
a_ve
ctor
(2:e
nd)./
...
shb
a_da
ta_v
ecto
r(1:e
nd-1
));
shba
_sam
ple_
mea
n =
1/ha
ndle
s.sa
mpl
e_si
ze*lo
g(sh
ba_d
ata_
vect
or(e
nd-
n*f)
/...
shb
a_da
ta_v
ecto
r(end
-han
dles
.sam
ple_
size
-n*f)
); ha
ndle
s.m
ean_
vect
or(1
,col
umn)
= s
hba_
sam
ple_
mea
n;
colu
mn
= co
lum
n +
1;
volv
ob_d
ata_
vect
or =
get
field
(han
dles
.vol
vob,
'ser
ies1
');
volv
ob_l
og_r
etur
n_ve
ctor
= lo
g(vo
lvob
_dat
a_ve
ctor
(2:e
nd)./
...
vo
lvob
_dat
a_ve
ctor
(1:e
nd-1
));
volv
ob_s
ampl
e_m
ean
= 1/
hand
les.
sam
ple_
size
* ..
.
log(
volv
ob_d
ata_
vect
or(e
nd-n
*f) /
...
vo
lvob
_dat
a_ve
ctor
(end
-han
dles
.sam
ple_
size
-n*f)
); ha
ndle
s.m
ean_
vect
or(1
,col
umn)
= v
olvo
b_sa
mpl
e_m
ean;
co
lum
n =
colu
mn
+ 1;
%
Cre
ate
a po
rtfol
io lo
g re
turn
mat
rix fo
r the
var
ianc
e - c
ovar
ianc
e %
calc
ulat
ions
po
rtfol
io_l
og_r
etur
n_m
atrix
= [
...
a
bb_l
og_r
etur
n_ve
ctor
(end
-han
dles
.sam
ple_
size
-n*f
+1:e
nd-n
*f) .
..
axi
s_lo
g_re
turn
_vec
tor(
end-
hand
les.
sam
ple_
size
-n*f
+1:e
nd-n
*f) .
..
eric
sson
b_lo
g_re
turn
_vec
tor(e
nd-h
andl
es.s
ampl
e_si
ze-n
*f+1:
end-
n*f)
...
r
eads
oft_
log_
retu
rn_v
ecto
r(end
-han
dles
.sam
ple_
size
-n*f+
1:en
d-n*
f) ...
shb
a_lo
g_re
turn
_vec
tor(e
nd-h
andl
es.s
ampl
e_si
ze-n
*f+1
:end
-n*f
) ...
v
olvo
b_lo
g_re
turn
_vec
tor(e
nd-h
andl
es.s
ampl
e_si
ze-n
*f+1:
end-
n*f)]
;
%C
reat
e th
e A
BB
log
retu
rn m
atrix
ab
b_lo
g_re
turn
_vec
tor =
log(
abb_
data
_vec
tor(
2:en
d)./
...
abb_
data
_vec
tor(
1:en
d-1)
); %
Cal
cula
te th
e da
ily A
BB
sam
ple
mea
n ab
b_sa
mpl
e_m
ean
= 1/
hand
les.
sam
ple_
size
*log(
abb_
data
_vec
tor(e
nd-
n*f)/
...
abb_
data
_vec
tor(
end-
hand
les.
sam
ple_
size
-n*f)
); %
Set
the
mea
n ve
ctor
s fir
st e
lem
ent t
o da
ily A
BB
sam
ple
mea
n ha
ndle
s.m
ean_
vect
or(1
,col
umn)
= a
bb_s
ampl
e_m
ean;
%
Set
the
colu
mn
inde
x to
2
colu
mn
= co
lum
n +
1;
axis
_dat
a_ve
ctor
= g
etfie
ld(h
andl
es.a
xis,
'ser
ies1
');
axis
_log
_ret
urn_
vect
or =
log(
axis
_dat
a_ve
ctor
(2:e
nd)./
...
axi
s_da
ta_v
ecto
r(1:e
nd-1
));
axis
_sam
ple_
mea
n =
1/ha
ndle
s.sa
mpl
e_si
ze*lo
g(ax
is_d
ata_
vect
or(e
nd-
n*f)/
...
axi
s_da
ta_v
ecto
r(en
d-ha
ndle
s.sa
mpl
e_si
ze-n
*f));
ha
ndle
s.m
ean_
vect
or(1
,col
umn)
= a
xis_
sam
ple_
mea
n;
colu
mn
= co
lum
n +
1;
eric
sson
b_da
ta_v
ecto
r = g
etfie
ld(h
andl
es.e
ricss
onb,
'ser
ies1
');
eric
sson
b_lo
g_re
turn
_vec
tor =
log(
eric
sson
b_da
ta_v
ecto
r(2:e
nd)./
...
eric
sson
b_da
ta_v
ecto
r(1:e
nd-1
));
eric
sson
b_sa
mpl
e_m
ean
= 1/
hand
les.
sam
ple_
size
* ..
.
log
(eric
sson
b_da
ta_v
ecto
r(en
d-n*
f) / .
..
eric
sson
b_da
ta_v
ecto
r(en
d-ha
ndle
s.sa
mpl
e_si
ze-n
*f));
ha
ndle
s.m
ean_
vect
or(1
,col
umn)
= e
ricss
onb_
sam
ple_
mea
n;
colu
mn
= co
lum
n +
1;
read
soft_
data
_vec
tor =
get
field
(han
dles
.read
soft,
'ser
ies1
');
read
soft_
log_
retu
rn_v
ecto
r = lo
g(re
adso
ft_da
ta_v
ecto
r(2:
end)
./ ...
rea
dsof
t_da
ta_v
ecto
r(1:e
nd-1
));
65
h
andl
es.w
eigh
ted_
mea
n_ve
ctor
(1,i)
= ..
.
han
dles
.cur
rent
_sto
ck_w
eigh
ts(1
,i) *
...
h
andl
es.m
ean_
retu
rn_v
ecto
r(1,i)
; en
d %
Cal
cula
te th
e to
tal w
eigh
ted
daily
por
tfolio
sam
ple
mea
n ha
ndle
s.po
rtfol
io_s
ampl
e_m
ean
= su
m(h
andl
es.w
eigh
ted_
mea
n_ve
ctor
); %
Cre
ate
a po
rtfol
io w
eigh
ts m
atrix
so
that
it c
an e
xtra
ct th
e w
eigh
ted
%co
varia
nces
from
the
hand
les.
cova
rianc
e_re
turn
_mat
rix
for i
= 1
:6
f
or j
= 1:
6
if(i =
= j)
por
tfolio
_wei
ghts
_mat
rix(i,
j) =
...
h
andl
es.c
urre
nt_s
tock
_wei
ghts
(1,i)
;
else
p
ortfo
lio_w
eigh
ts_m
atrix
(i,j)
= 0;
end
e
nd
end
%C
reat
e a
wei
ghte
d co
varia
nce
mat
rix fr
om th
e ha
ndle
s.co
varia
nce_
retu
rn
%_m
atrix
whe
re p
ortfo
lio w
eigh
ts m
atrix
is u
sed
in o
rder
to e
xtra
ct th
e %
curre
nt p
ortfo
lio e
lem
ents
and
set
the
othe
r to
zero
ha
ndle
s.w
eigh
ted_
cova
rianc
e_m
atrix
= p
ortfo
lio_w
eigh
ts_m
atrix
* ..
.
han
dles
.cov
aria
nce_
retu
rn_m
atrix
*por
tfolio
_wei
ghts
_mat
rix;
%
Cal
cula
te th
e da
ily p
ortfo
lio s
ampl
e st
anda
rd d
evia
tion
by ta
king
the
%sq
uare
root
of t
he s
um o
f all
varia
nce
cova
rianc
e el
emen
ts
hand
les.
portf
olio
_sam
ple_
stan
dard
_dev
iatio
n =
...
sqr
t(sum
(sum
(han
dles
.wei
ghte
d_co
varia
nce_
mat
rix)))
;
%C
alcu
late
the
varia
nce
- cov
aria
nce
mat
rix fo
r all
the
stoc
ks
for i
= 1
:6
fo
r j =
1:6
h
andl
es.c
ovar
ianc
e_m
atrix
(i,j)
= 1/
(han
dles
.sam
ple_
size
-1) *
...
sum
((por
tfolio
_log
_ret
urn_
mat
rix(1
:end
,i) -
...
han
dles
.mea
n_ve
ctor
(1,i)
).* ..
.
(p
ortfo
lio_l
og_r
etur
n_m
atrix
(1:e
nd,j)
- ...
h
andl
es.m
ean_
vect
or(1
,j)));
end
en
d %
Cal
cula
te th
e da
ily s
ampl
e m
ean
vect
or o
f the
sto
ck re
turn
s fo
r i =
1:6
han
dles
.mea
n_re
turn
_vec
tor(1
,i) =
exp
(han
dles
.mea
n_ve
ctor
(1,i)
+ ...
0
.5 *
han
dles
.cov
aria
nce_
mat
rix(i,
i));
end
%C
alcu
late
the
daily
sam
ple
varia
nce
- cov
aria
nce
mat
rix o
f the
sto
ck
%re
turn
s of
all
the
stoc
ks
for i
= 1
:6
fo
r j =
1:6
h
andl
es.c
ovar
ianc
e_re
turn
_mat
rix(i,
j) =
(exp
( ...
(han
dles
.mea
n_ve
ctor
(1,i)
+ 0
.5 *
...
hand
les.
cova
rianc
e_m
atrix
(i,i))
* ..
.
(h
andl
es.m
ean_
vect
or(1
,j) +
0.5
* ..
.
ha
ndle
s.co
varia
nce_
mat
rix(j,
j))))
* ...
(e
xp(h
andl
es.c
ovar
ianc
e_m
atrix
(i,j))
- 1)
;
end
en
d %
Cal
cula
te th
e w
eigh
ted
daily
sam
ple
mea
n ve
ctor
of t
he s
tock
retu
rns
for i
= 1
:6
66
else
han
dles
.cur
rent
_sto
ck_w
eigh
ts(1
,1) =
0;
end
if (1
==
hand
les.
curre
nt_p
ortfo
lio(1
,2))
h
andl
es.c
urre
nt_s
tock
_wei
ghts
(1,2
) = ..
.
(h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
(1,2
)) /
...
(sum
(han
dles
.cur
rent
_por
tfolio
_val
ue));
el
se
h
andl
es.c
urre
nt_s
tock
_wei
ghts
(1,2
) = 0
; en
d if
(1 =
= ha
ndle
s.cu
rrent
_por
tfolio
(1,3
))
han
dles
.cur
rent
_sto
ck_w
eigh
ts(1
,3) =
...
(han
dles
.cur
rent
_por
tfolio
_val
ue(1
,3))
/ ...
(s
um(h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
));
else
han
dles
.cur
rent
_sto
ck_w
eigh
ts(1
,3) =
0;
end
if (1
==
hand
les.
curre
nt_p
ortfo
lio(1
,4))
h
andl
es.c
urre
nt_s
tock
_wei
ghts
(1,4
) = ..
.
(h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
(1,4
)) /
...
(sum
(han
dles
.cur
rent
_por
tfolio
_val
ue));
el
se
h
andl
es.c
urre
nt_s
tock
_wei
ghts
(1,4
) = 0
; en
d if
(1 =
= ha
ndle
s.cu
rrent
_por
tfolio
(1,5
))
han
dles
.cur
rent
_sto
ck_w
eigh
ts(1
,5) =
...
(han
dles
.cur
rent
_por
tfolio
_val
ue(1
,5))
/ ...
(s
um(h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
));
else
han
dles
.cur
rent
_sto
ck_w
eigh
ts(1
,5) =
0;
end
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,
hand
les)
; %
----
----
----
-----
----
----
----
----
-----
----
----
----
----
-----
----
----
- %
Cal
l the
Cur
rent
Ris
k C
ontri
buto
rs to
upd
ate
the
hand
les.
Por
tfolio
_ris
k
% fi
gure
, han
dles
.Ris
k_in
crea
se a
nd h
andl
es.R
isk_
decr
ease
fiel
ds
Cur
rent
_Ris
k_C
ontri
buto
rs(h
andl
es.fi
gure
1,[],
hand
les)
; %
----
----
----
-----
----
----
----
----
-----
----
----
----
----
-----
----
----
- %
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,
hand
les)
; %
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Fun
ctio
n fo
r cal
cula
ting
the
Cur
rent
Por
tfolio
Wei
ghts
. fu
nctio
n C
urre
nt_P
ortfo
lio_W
eigh
ts(h
Obj
ect,
even
tdat
a, h
andl
es, v
arar
gin)
%
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
hand
les.
curre
nt_s
tock
_wei
ghts
= [0
0 0
0 0
0];
%C
alcu
late
the
portf
olio
wei
ghts
at t
he c
urre
nt d
ate
(the
pric
es a
t the
%
day
of h
andl
es.p
ortfo
lio_v
alue
_dat
e if
(1 =
= ha
ndle
s.cu
rrent
_por
tfolio
(1,1
))
han
dles
.cur
rent
_sto
ck_w
eigh
ts(1
,1) =
...
(han
dles
.cur
rent
_por
tfolio
_val
ue(1
,1))
/ ...
(s
um(h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
));
67
%S
et th
e en
d_in
dex
in th
e fo
r loo
p to
cur
rent
num
ber o
f sto
cks
end_
inde
x =
sum
(han
dles
.cur
rent
_por
tfolio
); %
Che
ck w
hich
sto
ck c
ontri
bute
s m
ost t
o th
e ris
k an
d pl
ace
them
in o
rder
of
%
the
high
est c
ontri
buto
r firs
t fo
r i =
1:e
nd_i
ndex
[C,I]
= m
ax(te
mp_
vect
or);
te
mp_
orde
r_ve
ctor
(1,i)
= I;
tem
p_ve
ctor
(1,I)
= 0
; en
d %
Plo
t the
text
in th
e P
ortfo
lio_r
isk
figur
e ax
es(h
andl
es.P
ortfo
lio_r
isk)
; cl
a;
text
(0.0
5,0.
75,'1
.','U
nits
','Nor
mal
ized
');
text
(0.0
5,0.
5,'2
.','U
nits
','Nor
mal
ized
');
text
(0.0
5,0.
25,'3
.','U
nits
','Nor
mal
ized
');
%S
et th
e en
d_in
dex
of th
e fo
r loo
p to
3 o
r if t
here
are
less
sto
cks
%in
the
portf
olio
set
it to
the
num
ber o
f sto
cks
in th
e po
rtfol
io
end_
inde
x =
0;
end_
inde
x =
min
(3,s
um(h
andl
es.c
urre
nt_p
ortfo
lio));
%
Set
the
stoc
ks in
the
corre
ct o
rder
in th
e P
ortfo
lio_r
isk
figur
e fo
r i =
1:e
nd_i
ndex
if(1
==
tem
p_or
der_
vect
or(1
,i))
tex
t(0.1
8,(1
-0.2
5*i),
'AB
B L
TD S
DB
','Uni
ts','N
orm
aliz
ed');
els
eif(2
==
tem
p_or
der_
vect
or(1
,i))
tex
t(0.1
8,(1
-0.2
5*i),
'Axi
s','U
nits
','Nor
mal
ized
');
e
lsei
f(3 =
= te
mp_
orde
r_ve
ctor
(1,i)
)
t
ext(0
.18,
(1-0
.25*
i),'E
ricss
on B
','Uni
ts','N
orm
aliz
ed');
els
eif(4
==
tem
p_or
der_
vect
or(1
,i))
tex
t(0.1
8,(1
-0.2
5*i),
'Rea
dsof
t','U
nits
','Nor
mal
ized
');
if (1
==
hand
les.
curre
nt_p
ortfo
lio(1
,6))
h
andl
es.c
urre
nt_s
tock
_wei
ghts
(1,6
) = ..
.
(h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
(1,6
)) /
...
(sum
(han
dles
.cur
rent
_por
tfolio
_val
ue));
el
se
h
andl
es.c
urre
nt_s
tock
_wei
ghts
(1,6
) = 0
; en
d %
Upd
ate
hand
les
stru
ctur
e gu
idat
a(hO
bjec
t, ha
ndle
s);
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
- %
--- F
unct
ion
for u
pdat
ing
the
Por
tfolio
_ris
k fie
ld.
func
tion
Cur
rent
_Ris
k_C
ontri
buto
rs(h
Obj
ect,
even
tdat
a, h
andl
es, v
arar
gin)
%
Load
the
curr
ent h
andl
es
hand
les
= gu
idat
a(gc
bo);
%R
eset
dat
a te
mp_
vect
or =
0;
tem
p_or
der_
vect
or =
0;
end_
inde
x =
0;
C =
0;
I = 0
; %
Cre
ate
a te
mpo
rary
wei
ghte
d ve
ctor
from
the
cova
rianc
e_re
turn
_mat
rix
for i
= 1
:6
te
mp_
vect
or(1
,i) =
han
dles
.cur
rent
_sto
ck_w
eigh
ts(1
,i) *
...
han
dles
.cur
rent
_sto
ck_w
eigh
ts(1
,i) *
...
han
dles
.cov
aria
nce_
retu
rn_m
atrix
(i,i);
en
d
68
C
urre
nt_P
ortfo
lio_W
eigh
ts(h
andl
es.fi
gure
1,[],
hand
les)
;
% --
-----
----
-----
----
----
----
----
-----
----
----
----
-----
----
----
----
--
%
Load
the
curre
nt h
andl
es
h
andl
es =
gui
data
(gcb
o);
%
Cre
ate
a po
rtfol
io w
eigh
ts m
atrix
so
that
it c
an e
xtra
ct th
e w
eigh
ted
%
cova
rianc
es fr
om th
e ha
ndle
s.co
varia
nce_
mat
rix
por
tfolio
_wei
ghts
_mat
rix =
0;
%
Cre
ate
an in
vers
e po
rtfol
io w
eigh
ts m
atrix
so
that
it c
an e
xtra
ct th
e
%w
eigh
ted
cova
rianc
es fr
om th
e ha
ndle
s.co
varia
nce_
mat
rix o
f the
st
ocks
%th
at a
re n
ot in
the
portf
olio
inve
rse_
portf
olio
_wei
ghts
_mat
rix =
0;
%
Cre
ate
a w
eigh
ted
diag
onal
mat
rix fo
r the
add
ition
al c
ovar
ianc
e
%ca
lcul
atio
n
wei
ghte
d_di
agon
al_m
atrix
= 0
;
%S
et th
e w
eigh
t for
the
new
sto
ck
n
ew_s
tock
_wei
ght =
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,7) /
...
s
um(h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
);
for i
= 1
:6
fo
r j =
1:6
if
(i ==
j)
p
ortfo
lio_w
eigh
ts_m
atrix
(i,j)
= ...
han
dles
.cur
rent
_sto
ck_w
eigh
ts(1
,i);
i
nver
se_p
ortfo
lio_w
eigh
ts_m
atrix
(i,j)
= ...
ab
s((h
andl
es.c
urre
nt_p
ortfo
lio(1
,i)-1
))*ne
w_s
tock
_wei
ght;
w
eigh
ted_
diag
onal
_mat
rix(i,
j) =
...
n
ew_s
tock
_wei
ght*
new
_sto
ck_w
eigh
t * ..
.
han
dles
.cov
aria
nce_
retu
rn_m
atrix
(i,j)*
...
a
bs((h
andl
es.c
urre
nt_p
ortfo
lio(1
,i)-1
));
els
e
e
lsei
f(5 =
= te
mp_
orde
r_ve
ctor
(1,i)
)
t
ext(0
.18,
(1-0
.25*
i),'S
HB
A','U
nits
','Nor
mal
ized
');
e
lsei
f(6 =
= te
mp_
orde
r_ve
ctor
(1,i)
)
t
ext(0
.18,
(1-0
.25*
i),'V
olvo
B','U
nits
','Nor
mal
ized
');
e
nd
end
%If
the
Rec
omm
end
chec
kbox
is m
arke
d an
d no
t all
stoc
ks a
re c
hoos
en
%ca
lcul
ate
wha
t sto
cks
will
incr
ease
or d
ecre
ase
the
portf
olio
risk
if(
(1 =
= ge
t(han
dles
.che
ckbo
x7,'V
alue
')) &
...
(su
m(h
andl
es.c
urre
nt_p
ortfo
lio) <
6))
%
Use
an
inpu
t dia
log
to a
sk th
e va
lue
of th
e ne
w s
tock
at f
orec
ast
%
date
, if t
he in
put i
s no
t a n
umbe
r ask
aga
in u
ntil
it is
a n
umbe
r
tem
p =
inpu
tdlg
( ...
'Ent
er th
e va
lue
of th
e ne
w s
tock
you
wan
t to
buy
at th
e Fo
reca
st d
ate'
...
,'
Val
ue o
f new
sto
ck',1
,cel
lstr(
'50'
),'of
f');
w
hile
(0 =
= is
scal
ar(s
tr2nu
m(te
mp{
1,1}
)))
tem
p =
inpu
tdlg
( ...
'Ent
er th
e va
lue
of th
e ne
w s
tock
you
wan
t to
buy
at th
e Fo
reca
st d
ate'
...
,'
Val
ue o
f new
sto
ck',1
,cel
lstr(
'50'
),'of
f');
e
nd
%
Set
the
curre
nt_p
ortfo
lio_v
alue
(1,7
) to
the
choo
sen
valu
e in
ord
er to
%ge
t the
cor
rect
wei
ghts
in C
urre
nt_P
ortfo
lio_W
eigh
ts
h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
(1,7
) = s
tr2nu
m(te
mp{
1,1}
);
% U
pdat
e ha
ndle
s st
ruct
ure
g
uida
ta(h
Obj
ect,
hand
les)
;
% --
-----
----
-----
----
----
----
----
-----
----
----
----
-----
----
----
----
--
%
Cal
l the
Cur
rent
Por
tfolio
Wei
ghts
to s
et th
e
%
han
dles
.cur
rent
_por
tfolio
_wei
ghts
fiel
d to
the
valu
e of
the
choo
sen
% p
ortfo
lio
69
%
Cal
cula
te th
e da
ily s
tand
ard
devi
atio
n fo
r the
pos
sibl
e po
rtfol
ios
w
eigh
ted_
stan
dard
_dev
iatio
n_ve
ctor
= ..
.
s
qrt(w
eigh
ted_
cova
rianc
e_ve
ctor
);
%R
eset
dat
a
tem
p_ve
ctor
= 0
;
tem
p_or
der_
vect
or =
0;
e
nd_i
ndex
= 0
;
C =
0;
I
= 0;
%
Set
the
end_
inde
x of
the
for l
oop
to th
e nu
mbe
r of s
tock
s no
t in
the
%
curre
nt p
ortfo
lio
e
nd_i
ndex
= 6
-sum
(han
dles
.cur
rent
_por
tfolio
);
%C
heck
wha
t sto
cks
incr
ease
the
risk
and
plac
e th
em in
ord
er o
f
%th
e hi
ghes
t con
tribu
tor f
irst
te
mp_
vect
or =
wei
ghte
d_st
anda
rd_d
evia
tion_
vect
or;
te
mp_
orde
r_ve
ctor
_len
gth
= 0;
for i
= 1
:end
_ind
ex
[C
,I] =
max
(tem
p_ve
ctor
);
i
f(C >
han
dles
.por
tfolio
_sam
ple_
stan
dard
_dev
iatio
n)
tem
p_or
der_
vect
or(1
,i) =
I;
tem
p_or
der_
vect
or_l
engt
h =
tem
p_or
der_
vect
or_l
engt
h +
1;
els
e
e
nd
tem
p_ve
ctor
(1,I)
= 0
;
end
%P
lot t
he te
xt in
the
Ris
k_in
crea
se fi
gure
axe
s(ha
ndle
s.R
isk_
incr
ease
);
cla
;
por
tfolio
_wei
ghts
_mat
rix(i,
j) =
0;
inve
rse_
portf
olio
_wei
ghts
_mat
rix(i,
j) =
0;
wei
ghte
d_di
agon
al_m
atrix
(i,j)
= 0;
e
nd
en
d
end
%C
reat
e a
wei
ghte
d co
varia
nce
mat
rix fr
om th
e ha
ndle
s.co
varia
nce_
retu
rn
%
_mat
rix w
here
por
tfolio
wei
ghts
mat
rix is
use
d in
ord
er to
ext
ract
the
%
cur
rent
por
tfolio
ele
men
ts a
nd s
et th
e ot
her t
o ze
ro
w
eigh
ted_
cova
rianc
e_m
atrix
= p
ortfo
lio_w
eigh
ts_m
atrix
* ..
.
han
dles
.cov
aria
nce_
retu
rn_m
atrix
*por
tfolio
_wei
ghts
_mat
rix;
%
Sum
the
wei
ghte
d co
varia
nce
mat
rix to
kno
w th
e cu
rren
t sum
wei
ghte
d_co
varia
nce_
sum
= s
um(s
um(w
eigh
ted_
cova
rianc
e_m
atrix
));
%
Set
the
wei
ghte
d_ad
ditio
nal_
cova
rianc
e_m
atrix
to z
ero
w
eigh
ted_
addi
tiona
l_co
varia
nce_
mat
rix =
0;
%
Con
stru
ct th
e w
eigh
ted_
addi
tiona
l_co
varia
nce_
mat
rix b
y ta
king
the
%co
varia
nces
from
eac
h st
ock
colu
mn
not i
n th
e po
rtfol
io a
nd
%
mul
tiply
ing
them
by
two
for t
he c
orre
ct c
alcu
latio
n an
d by
add
ing
%
the
varia
nces
for t
hose
sto
cks
w
eigh
ted_
addi
tiona
l_co
varia
nce_
mat
rix =
(por
tfolio
_wei
ghts
_mat
rix *
...
han
dles
.cov
aria
nce_
retu
rn_m
atrix
* ..
.
i
nver
se_p
ortfo
lio_w
eigh
ts_m
atrix
).*2
+...
wei
ghte
d_di
agon
al_m
atrix
;
%C
reat
e a
vect
or w
ith th
e su
ms
of th
e co
lum
ns
w
eigh
ted_
addi
tiona
l_co
varia
nce_
vect
or =
...
sum
(wei
ghte
d_ad
ditio
nal_
cova
rianc
e_m
atrix
);
%C
reat
e a
vect
or w
ith th
e to
tal p
ortfo
lio c
ovar
ianc
es
wei
ghte
d_co
varia
nce_
vect
or =
wei
ghte
d_ad
ditio
nal_
cova
rianc
e_ve
ctor
+...
((ab
s(ha
ndle
s.cu
rrent
_por
tfolio
-1)).
*wei
ghte
d_co
varia
nce_
sum
);
70
%
Res
et d
ata
te
mp_
vect
or =
0;
in
vers
e_te
mp_
orde
r_ve
ctor
= 0
;
tem
p_or
der_
vect
or =
0;
e
nd_i
ndex
= 0
;
C =
0;
I
= 0;
%S
et th
e en
d_in
dex
of th
e fo
r loo
p to
the
num
ber o
f sto
cks
not i
n th
e
%cu
rrent
por
tfolio
end
_ind
ex =
6-s
um(h
andl
es.c
urre
nt_p
ortfo
lio);
%
Che
ck w
hat s
tock
s de
crea
se th
e ris
k an
d pl
ace
them
in o
rder
of
%
the
low
est c
ontri
buto
r firs
t so
that
the
vect
or e
nds
up w
ith th
e
%
corre
ct le
ngth
tem
p_or
der_
vect
or_l
engt
h =
0;
te
mp_
vect
or =
wei
ghte
d_st
anda
rd_d
evia
tion_
vect
or;
j
= 1;
for i
= 1
:end
_ind
ex
[C
,I] =
max
(tem
p_ve
ctor
);
i
f(C <
han
dles
.por
tfolio
_sam
ple_
stan
dard
_dev
iatio
n)
inve
rse_
tem
p_or
der_
vect
or(1
,j) =
I;
tem
p_or
der_
vect
or_l
engt
h =
tem
p_or
der_
vect
or_l
engt
h +
1;
j = j
+ 1;
e
lse
end
t
emp_
vect
or(1
,I) =
0;
e
nd
%
Rea
rrang
e th
e or
der s
o th
at th
e st
ock
that
will
decr
ease
the
risk
the
%
mos
t is
plac
ed fi
rst i
n te
mp_
orde
r_ve
ctor
te
xt(0
.05,
0.75
,'1.',
'Uni
ts','N
orm
aliz
ed');
text
(0.0
5,0.
5,'2
.','U
nits
','Nor
mal
ized
');
te
xt(0
.05,
0.25
,'3.',
'Uni
ts','N
orm
aliz
ed');
%S
et th
e en
d_in
dex
to th
e m
inim
um o
f 3 o
r the
num
ber o
f sto
cks
not i
n
%
the
portf
olio
or t
he n
umbe
r of s
tock
s th
at w
ill in
crea
se th
e ris
k
end
_ind
ex =
0;
e
nd_i
ndex
= m
in(m
in(3
,sum
(6-h
andl
es.c
urre
nt_p
ortfo
lio)),
...
te
mp_
orde
r_ve
ctor
_len
gth)
;
%S
et th
e st
ocks
in th
e co
rrec
t ord
er in
the
Ris
k_in
crea
se fi
gure
for i
= 1
:end
_ind
ex
if(1
==
tem
p_or
der_
vect
or(1
,i))
text
(0.1
8,(1
-0.2
5*i),
'AB
B L
TD S
DB
','Uni
ts','N
orm
aliz
ed');
e
lsei
f(2 =
= te
mp_
orde
r_ve
ctor
(1,i)
)
te
xt(0
.18,
(1-0
.25*
i),'A
xis'
,'Uni
ts','N
orm
aliz
ed');
e
lsei
f(3 =
= te
mp_
orde
r_ve
ctor
(1,i)
)
te
xt(0
.18,
(1-0
.25*
i),'E
ricss
on B
','Uni
ts','N
orm
aliz
ed');
e
lsei
f(4 =
= te
mp_
orde
r_ve
ctor
(1,i)
)
te
xt(0
.18,
(1-0
.25*
i),'R
eads
oft',
'Uni
ts','N
orm
aliz
ed');
e
lsei
f(5 =
= te
mp_
orde
r_ve
ctor
(1,i)
)
te
xt(0
.18,
(1-0
.25*
i),'S
HB
A','U
nits
','Nor
mal
ized
');
els
eif(6
==
tem
p_or
der_
vect
or(1
,i))
text
(0.1
8,(1
-0.2
5*i),
'Vol
vo B
','Uni
ts','N
orm
aliz
ed');
e
nd
e
nd
%
Res
et th
e va
lue
of th
e re
com
men
ded
stoc
k
han
dles
.cur
rent
_por
tfolio
_val
ue(1
,7) =
0;
%
Set
che
ckbo
x7 to
no
reco
mm
enda
tion
s
et(h
andl
es.c
heck
box7
,'Val
ue',0
);
71
else
if((
1 ==
get
(han
dles
.che
ckbo
x7,'V
alue
')) &
...
(6 =
= (s
um(h
andl
es.c
urre
nt_p
ortfo
lio)))
)
%
Use
a h
elp
dial
og to
pre
sent
the
info
rmat
ion
hel
pdlg
( ...
'The
re a
re n
o ne
w s
tock
s le
ft to
reco
mm
end.
Loo
k at
the
Cur
rent
risk
co
ntrib
utor
s in
ord
er to
low
er th
e po
rtfol
io ri
sk '.
..
,'All
avai
labl
e st
ocks
are
alre
ady
in th
e po
rtfol
io');
%
Res
et th
e va
lue
of th
e re
com
men
ded
stoc
k
h
andl
es.c
urre
nt_p
ortfo
lio_v
alue
(1,7
) = 0
;
%
Set
che
ckbo
x7 to
no
reco
mm
enda
tion
set
(han
dles
.che
ckbo
x7,'V
alue
',0);
e
nd
%
Cle
ar th
e te
xt in
the
Ris
k_in
crea
se fi
gure
axe
s(ha
ndle
s.R
isk_
incr
ease
);
cla
;
%C
lear
the
text
in th
e R
isk_
decr
ease
figu
re
a
xes(
hand
les.
Ris
k_de
crea
se);
c
la;
end
% U
pdat
e ha
ndle
s st
ruct
ure
guid
ata(
hObj
ect,
hand
les)
; %
----
----
----
----
----
----
----
----
----
-----
----
----
----
-----
----
----
----
---
% --
- Fun
ctio
n fo
r the
For
ecas
t Hel
p m
enu
choi
ce
func
tion
Fore
cast
Hel
p_C
allb
ack(
hObj
ect,
even
tdat
a, h
andl
es)
fo
r i =
1:te
mp_
orde
r_ve
ctor
_len
gth
tem
p_or
der_
vect
or(1
,i) =
inve
rse_
tem
p_or
der_
vect
or(1
, ...
te
mp_
orde
r_ve
ctor
_len
gth+
1-i);
end
%P
lot t
he te
xt in
the
Ris
k_de
crea
se fi
gure
axe
s(ha
ndle
s.R
isk_
decr
ease
);
cla
;
text
(0.0
5,0.
75,'1
.','U
nits
','Nor
mal
ized
');
te
xt(0
.05,
0.5,
'2.',
'Uni
ts','N
orm
aliz
ed');
text
(0.0
5,0.
25,'3
.','U
nits
','Nor
mal
ized
');
%
Set
the
end_
inde
x to
the
min
imum
of 3
or t
he n
umbe
r of s
tock
s no
t in
%th
e po
rtfol
io o
r the
num
ber o
f sto
cks
that
will
decr
ease
the
risk
e
nd_i
ndex
= 0
;
end
_ind
ex =
min
(min
(3,s
um(6
-han
dles
.cur
rent
_por
tfolio
)), ..
.
tem
p_or
der_
vect
or_l
engt
h);
%
Set
the
stoc
ks in
the
corr
ect o
rder
in th
e R
isk_
decr
ease
figu
re
fo
r i =
1:e
nd_i
ndex
i
f(1 =
= te
mp_
orde
r_ve
ctor
(1,i)
)
te
xt(0
.18,
(1-0
.25*
i),'A
BB
LTD
SD
B','U
nits
','Nor
mal
ized
');
els
eif(2
==
tem
p_or
der_
vect
or(1
,i))
text
(0.1
8,(1
-0.2
5*i),
'Axi
s','U
nits
','Nor
mal
ized
');
els
eif(3
==
tem
p_or
der_
vect
or(1
,i))
text
(0.1
8,(1
-0.2
5*i),
'Eric
sson
B','U
nits
','Nor
mal
ized
');
els
eif(4
==
tem
p_or
der_
vect
or(1
,i))
text
(0.1
8,(1
-0.2
5*i),
'Rea
dsof
t','U
nits
','Nor
mal
ized
');
els
eif(5
==
tem
p_or
der_
vect
or(1
,i))
text
(0.1
8,(1
-0.2
5*i),
'SH
B A
','Uni
ts','N
orm
aliz
ed');
e
lsei
f(6 =
= te
mp_
orde
r_ve
ctor
(1,i)
)
te
xt(0
.18,
(1-0
.25*
i),'V
olvo
B','U
nits
','Nor
mal
ized
');
end
end
72
%U
se a
hel
p di
alog
to p
rese
nt th
e in
form
atio
n he
lpdl
g('T
he N
orm
al b
utto
n dr
aws
a gr
aph
of th
e cu
rrent
por
tfolio
with
the
stoc
k va
lues
at t
he s
tart
date
. The
For
ecas
t but
ton
mak
es a
fore
cast
of t
he
curre
nt p
ortfo
lio fo
r the
spe
cifie
d le
ngth
with
the
valu
es a
t the
fore
cast
da
te. T
he F
orec
ast w
ithin
but
ton
is ju
st li
ke th
e Fo
reca
st b
utto
n bu
t the
st
art d
ate
is s
et to
the
last
dat
e m
inus
the
fore
cast
leng
th. T
he F
orec
ast
pane
l is
used
to s
et th
e le
ngth
of t
he fo
reca
st. H
ow to
cre
ate
a po
rtfol
io:
Clic
k in
the
chec
kbox
in fr
ont o
f the
sto
ck y
ou w
ant i
n yo
ur p
ortfo
lio. T
hen
set t
he v
alue
for t
he s
tock
at t
he fo
reca
st d
ate.
Rep
eat u
ntil
all t
he s
tock
s yo
u w
ant i
n th
e po
rtfol
io a
re c
hose
n. If
you
wan
t to
rem
ove
a st
ock
from
th
e po
rtfol
io c
lick
the
chec
kbox
aga
in to
unc
heck
it.
How
to g
et
reco
mm
enda
tions
: C
lick
the
Rec
omm
end
chec
kbox
. The
n cl
ick
Fore
cast
or
For
ecas
t with
in a
nd s
et th
e bu
y va
lue
at th
e fo
reca
st d
ate.
If y
ou w
ant t
o fo
llow
a re
com
men
datio
n si
mpl
y ad
d th
e st
ock
to th
e po
rtfol
io w
ith th
e bu
y va
lue
and
clic
k Fo
reca
st o
r For
ecas
t with
in.
How
to z
oom
: E
ither
clic
k in
th
e gr
aph
to z
oom
or s
elec
t a re
gion
to z
oom
. To
zoom
out
hol
d th
e A
lt ke
y w
hile
clic
king
in th
e gr
aph
or d
oubl
e cl
ick
in th
e gr
aph
to re
turn
to th
e no
rmal
sca
le.
How
to p
rint:
Go
to th
e Fi
le m
enu
and
choo
se P
rint.
The
who
le s
cree
n w
ill be
prin
ted.
', ...
'
Fore
cast
Hel
p')
%--
----
----
----
----
----
----
----
----
-----
----
----
----
----
-----
----
----
----
-