Научная статья на тему 'Implementation of Monte Carlo method in option valuation using statistical programming language r'

Implementation of Monte Carlo method in option valuation using statistical programming language r Текст научной статьи по специальности «Математика»

CC BY
165
36
i Надоели баннеры? Вы всегда можете отключить рекламу.
Ключевые слова
метод Монте Карло / оцінка / вартість / опціони / мова R / методМонте Карло / Оценка / СТОИМОСТЬ / опционы / язык R / Monte Carlo method / Valuation / Options / R language

Аннотация научной статьи по математике, автор научной работы — Vasylchenko I.

Автором детально рассмотрено теорию метода Монте Карло и проведено еепрактическую реализацию средствами статистического программного языка R для европейских опционоввыпущенных на индекс DAX.

i Надоели баннеры? Вы всегда можете отключить рекламу.
iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.
i Надоели баннеры? Вы всегда можете отключить рекламу.

Author thoroughly examines Monte Carlo method theory and then implements it using statistical programming language R for European DAX option.

Текст научной работы на тему «Implementation of Monte Carlo method in option valuation using statistical programming language r»

великого обсягу даних, а можливості обчислювальної техніки були досить обмеженими.

Ці проблеми було вирішено К.Йореско шляхом використання спеціальних алгоритмів для отримання оцінок коефіцієнтів за методом найбільшої правдоподібності. Назва створеного для цього програмного забезпечення [8] стала синонімом самого підходу моделювання.

Практичне застосування моделей призвело до виявлення ряду проблем, як прикладного, так і методологічного характеру. Основними з них є наступні: неліній-ність зв'язків між латентними змінними; включення до моделей якісних ознак; адекватність методів оцінювання параметрів моделей даним досліджуваних процесів; вибір виду зв'язків між латентними і спостережуваними змінними; неоднорідність сукупностей, за якими досліджуються моделі; особливості застосування в конкретних прикладних дослідженнях.

Необхідність їх вирішення призвела до подальшого, четвертого і поточного етапу розвитку, - теоретичного і практичного узагальнення та подальшого розвитку. В останні 15 років відбувається подальший розвиток методології, що, власне, і отримала узагальнюючу назву "моделювання латентних змінних". Ця методологія містить моделювання структурними рівняннями в свою чергу, як складову, і ґрунтується на концептуальному визначенні латентної змінної як такої, для якої не існує вибіркової реалізації щонайменше для окремих спостережень у даній вибірці [3, с. 612]. В цей період здійснено як теоретичні узагальнення і розробки методологічного характеру [9], так і визначено практичні шляхи вирішення ряду проблем [4]. Подальший розвиток методів оцінювання та критеріїв перевірки адекватності моделей дозволи узагальнити ряд методів статистичного аналізу, що істотно поглиблює рівень розуміння соціально-економічних явищ при їх застосуванні.

УДК 311.216

На сучасному етапі розвитку до моделей латентних змінних відносять наступні: моделі головних компонент; моделі розвідувального та підтверджуючого факторного аналізу; моделі структурних рівнянь з латентними змінними; розширені моделі з взаємодією екзогенних ознак і латентні моделі динаміки. Їх використання дозволяє здійснювати дослідження широкого кола складних соціально-економічних явищ і процесів.

В статті досліджено історію розвитку методології моделювання латентних змінних, визначено його основні етапи, визначено головні сучасні проблеми. Визначення шляхів вирішення цих проблем дозволить отримати подальший розвиток цій методології, що створює передумови для глибшого теоретичного розуміння та більш ефективного практичного аналізу при дослідженні економічних категорій.

1. Благуш П. Факторный анализ с обобщениями / П. К. Благуш - М.: Финансы и статистика, 1989. - 248 с. 2. Лоули Д. Максвелл А. Факторный анализ как статистический метод : Пер. с англ. / Лоули Д., Максвелл А. - М. : Мир, 1967. - 144 с. 3. Bollen K.A. Latent Variables in Psychology and the Social Sciences // Annual Review of Psychology. -2002. - V.53. - P.605-643. 4. Bartholomew, D. J. Latent variable models and factor analysis. - New York: Oxford University Press. - 1987 - p. 232.

5. Factor Analysis at 100: Historical Developments and Future Directions // R. Cudeck, R.C. MacCallum (Editor). - Lawrence Hill. - 2007. - p. 389.

6. Goldberger A. S. Structural equation methods in the social sciences. // Econometrica - 1972, Vol. 40 - p. 979-1002. 7. Joreskog K.G. A general approach to confirmatory maximum likelihood factor analysis. // Psychometrika -1969, Vol. 3. - p. 183-202. 8. LISREL 8.8 [Computer program / Windows]. - Режим доступу : http://www.ssicentral.com/lisrel/downloads.html (27 лютого 2011). 9. Muthen, B. BEYOND SEM: GENERAL LATENT VARIABLE MODELING // Behaviormetrika - 2002, Vol.29, No.1. - p. 81-117 10. Spearman C. General intelligence, objectively determined and measured // American Journal of Psychology. - 1904, Vol. 15, N. 2. - P. 201-293. 11. Hotelling, H. Analysis of a complex of statistical variables into principal components, Journal of Educational Psycholog. - 1933. Vol. 24, - p. 417-441.

Надійшла до редколегії 01.07.11

I. Vasylchenko,

Taras Shevchenko National University of Kyiv

IMPLEMENTATION OF MONTE CARLO METHOD IN OPTION VALUATION USING STATISTICAL PROGRAMMING LANGUAGE R

Автором детально розглянуто теорію методу Монте Карло та здійсненоїї практичну реалізацію засобами ста-тистичноїпрограмної мови Rдля європейських опціонів випущених на індекс DAX.

Ключові слова: метод Монте Карло, оцінка, вартість, опціони, мова R.

Автором детально рассмотрено теорию метода Монте Карло и проведено еепрактическую реализацию средствами статистического программного языка R для европейских опционоввыпущенных на индекс DAX.

Ключевые слова: методМонте Карло, оценка, стоимость, опционы, язык R.

Author thoroughly examines Monte Carlo method theory and then implements it using statistical programming language R for European DAX option.

Keywords: Monte Carlo method, valuation, options, R language.

Recent decades global financial markets were followed by rapid growth of credit derivatives' turnover. A vast variety of products are present at the market, giving private and institutional investors ability to flexibly hedge their operations against different types of risks, which may contain interest rate and exchange rate exposures, uncertainty in future levelsof underlying asset's (stocks, commodities) prices etc.

Although, trading derivatives should be carried out carefully, while it can bring together with incomes considerably big losses, especially if a highly leveraged capital was used.In order to minimize operational losses and to prevent possible arbitrage opportunities, precise and adequate tools for pricing derivatives are in need.

Considerable amounts of research were dedicated to this question, which led to development of diverse

methodologies. Some of them, based on financial theories and relatively strict assumptions, give closedform solutions (e.g. Black-Scholes model), while others are rather numerical methods like binomial option pricing model (Cox, Ross-Rubinstein), neural networks algorithm or Monte Carlo method.

Latter has proved itself as a good approach in valuation of derivative securities and a lot of researches were focused on this question by such a scientists as John C. Hull, Alan White, Michael C. Fu, Jian-Qiang Hu, John R. Birge, Christian P. Robert, George Casella, George M. Jabbour, Yi-Kang Liu.

Throughout the paper we would like to discuss the main idea of Monte Carlo simulation approachand then move to practical implementation in programming environment R.Finally, using some real data of European options

© Vasylchenko I., 2011

calculate respective prices and compare them with the results of Black-Scholes model.

Monte Carlo method is a simulation technique that, with the use of random numbers and probability, can give solutions to a problem in case it is infeasible or impossible to compute an exact result with a deterministic algorithm. This method was devised by Stanislaw Ulam and John von Neumann in 1940s during their work in nuclear weapon projects and was primarily intended to help them with their experiments in physics. Later on it became widely used in mathematics (e.g. evaluation of definitive integrals) and invariety of fields where modeled phenomena have significant uncertainty of inputs (such as risk modeling in business).

One of the first applications of this idea to derivative's pricing was done by Phelim Boyle in 1977. In that particular case these were European options, however later on Monte Carlo method appeared to be especially useful in valuation of exotic options (e.g. Asian options, Barrier options, American options).

This simulation is classified as a sampling method because the inputs are randomly generated from probability distributions to simulate the process of sampling from an actual population.

To explain givenstatement, let us first consider the case of a general random variable х, whose expected value E [ x ] = ^ and variance Var [ x ] = a2are unknown. We are

interested in finding these values and we are able to generate independent samples of х using some pseudorandom number generator.

From the Law of Large Numbers we know, that computing average value of relevantly large number of samples can give us quite a good approximation to the needed unknown parameter E[x] = ^. So, for example,

given the independent random variables x1,x2,x3,...xn identically distributed with х, the value

1 ^

^ = n £ x

n i=1

can be a good approximation to ^. It is easy to see that this estimator is unbiased (while E [^n] = ^ . Following this we can estimate variance, using estimated value ^n:

„2 Im(*, ^ )2

Or for nonbiased case:

„2 -^n)2

n n - 1

Following Central Limit Theorem, we can state that:

► N (0, ct 2 )

n| o,n

As a result we can build a 95% confidence interval for unknown parameter ^:

J 1,96a - 1,96 a) nnc

P\»n-------T=~ - ^ - ^n + ^^1 = 0,95

vn

n ' Г

vn

Or replacing unknown a with an estimated value an we receive interval in which unknown value ^ lies with probability 95%:

n s '^n' vn

This analysis gives us some basic notion about Monte Carlo method for approximating unknown parameter ^.

Firstly we take n independent samples and calculate ^n. Then by calculating an we can build confidence intervals of the true parameter ^ . As far as the number of samples n grows, the more shrinks the confidence interval.

Similarly looks the problem of evaluating definite integral. Monte Carlo approach can help us to find solution, especially if closed-form formula is hard to compute or even does not exist.

To illustrate it, let us assume that we need to calculate such an integral:

'g =J>(x )f (x) dx

where g (x) is an arbitrary function and f (x) is some density function. Basically this integral is a mean E[g (x)] , where x is distributed with probability density

function f (x) over a support A.

Analogously to previous example, this integral can be evaluated by generating n sample values of xi having

probability density function f (x), then finding correspondent values g (x,.) and averaging them to produce the Monte Carlo estimate:

ig = £ g(x,)

n i=1

This results in such an unbiased variance estimator:

n 2

1,96

n -

and in the same way, Central Limit Theorem together with the Law of Large numbers shows us that:

ig - 'g N ( 0,2l)

Our error ig - Ig of Monte Carlo integral value estimate

is also approximately normally distributed with mean 0 and „2

variance — , while latter converges to zero with a growing n

sample size n.

Now we are ready to move on to option valuation with the help of Monte Carlo simulation. Further on we would talk about European call options, while they are quite a good basic example, however similar logic is applicable to more complex derivative products asAmerican, Exotic options etc.

Option value of a European call at the present point of time is the discounted payoff that we would receive at the time of maturity and we can write it down as [5]:

ct,.2 =

C OS, t) = e-%E [max 00, ST - K) | Sf = S]

Where t - time to maturity, r - risk-free rate, ST - stock price at the maturity time, K - option's strike price and Sf

denotes the spot price at the given point of time.

Considering the fact, that conditional distribution of ST given Sf = S is lognormal with parameters

log(S) + (b -2 a2 It and o2t , the above expectation we can rewrite in terms of integral in such a way:

V2reaVTx

exp

logx — ^ logS +| b —^ct |t

2ct t

dx

As one can see, this integral looks close to that we have been speaking about a previously: given the payoff function

2

1

g (x ) = max (0,x - K ) and correspondent probability density function f (x ) = , . exp

v2rcaVTx

logx — ^logS + | b — ^ct |t

2ct t

Thus it can be evaluated with the use of Monte Carlo.

Our algorithm can be described with such sequence of steps:

• generate n random sample values zi ~ N (0,1);

• calculate respective stock price at the maturity time

(r -„- V+„VFz,

ST = V 2 J [5];

iНе можете найти то, что вам нужно? Попробуйте сервис подбора литературы.

• find discounted payoff with given stock price

Ci = e~rT max (, S'T - K);

„1 n

• calculate the expected value Cn = — £"=1 C:, which

would be our estimator for the price of the option at the present point of time.

Above presented steps can be nicely calculated with the use of statistical programming language R. Latter gains recently a lot of attention and popularity among scientists and statisticians,while it is light and free-to-use environment.

Functions that we would need are included in fOptions package which belongs to the R-metrics project [9].

Firstly we enter our input values that describe option, whose price we want to estimate (we consider that there are 252 trading days in a year):

S <<- 4948.5; K <<- 4850

Time<<- 0.02778; sigma <<- 0.17529; r <<- 0.02091

delta.t <<-1/252; pathLength<<- floor (Time/delta.t)

Next, we generate samples of random numbers zi that

would drive the movement of our stock price till the maturity time. In this code rnorm.pseudo generator is applied, that gives us normal pseudo random numbers, however, also low-discrepancy sequences can be used like Sobol or Halton, which would result in quasi-Monte Carlo method [4].

Innovations = function(mcSteps, pathLength, init) { innovations = rnorm.pseudo(mcSteps, pathLength, init) innovations }

Recalling the formula S[ = S0e^r-„“)t +®VTz, we

are ready to write down the function that would calculate the random stock price paths:

wienerPath = function(random_sample) { path = (r-sigma*sigma/2)*delta.t + sigma*sqrt(delta.t)*random_sample path }

Also we need a function to calculate our payoffs for every single path the stock price goes. While in this paper we consider European calls, resulted code would look somehow like this:

plainVanillaPayoff = function(path) {

ST = S*exp(sum(path)) payoff = exp(-r*Time)*max(ST-K, 0) payoff }

Now we move to the core function from this package, which actually integrates all previous procedures together and calculates the whole Monte Carlo mechanism.

mc = MonteCarloOption(delta.t = delta.t, pathLength = pathLength, mcSteps = 5000, mcLoops = 1000, init = TRUE,innovations.gen = Innovations, path.gen = wienerPath, payoff.calc = plainVanillaPayoff, antithetic = TRUE, standardization = FALSE, trace = TRUE)

In each loop random stock price paths are generated (mcSteps in total) using standard normal random samples zi we have drawn previously (called "innovations" in the

code). Payoffs are calculated for each of these paths, then they are averaged and we get the option price for this single loop. Such an algorithm is performed mcLoops times, and the final option price would be the average of the option price estimations obtained in each of the loops.

Parameter antithetic corresponds to the usage of antithetic variates method. Normally the error has a square

root convergence speed, which leads to a need of yjn

large number of sample paths in order to get significantly small errors. In order to overcome this problem antithetic variates are used to reduce the variance that results in a less number of simulations needed [1].

The evolution of the option price, depending on the number of loops already processed, can be illustrated with the Plot.1. One can observe, that the more loops we execute, the more option price converges to the true value.

Monte Carlo Loops Plot.1. European DAX call option price evolution

In order to conduct comparison of this simulation technique with Black-Scholes model we took some real data, which was provided by the Center for Applied Statistics and Economics at the Humboldt University of Berlin [8]. Database contained several years of history of the European style DAX call options that were traded at the

EUREX stock exchange.Among them we have randomly chosen several to illustrate our question of interest.

For each of the options we calculated the Monte Carlo price with parameters mcSteps=5000, mcLoops=1000an the Black-Scholes price. Detailed information about the options as far as calculated prices you can observe at the Table 1.

Table 1. Monte Carlo estimation of European DAX call options

Trading day Volatility Time to maturity Strike price Spot price Risk-free rate Monte Carlo price Black-Scholes price

02.09.2005 0.14102 0.03889 4850 4832.11348 0.02091 44.61098 47.00066

06.09.2005 0.13631 0.12521 5000 4960.53858 0.02095 81.91368 82.99559

09.09.2005 0.12953 0.01944 4950 4989.02479 0.02092 56.68247 59.99555

12.09.2005 0.55742 0.01111 4400 5029.90874 0.02091 629.9472 631.9995

19.09.2005 0.24552 0.08889 4500 4873.86792 0.02093 402.7712 405.0027

21.09.2005 0.14271 0.08333 5000 4899.53358 0.02092 42.72371 43.49781

27.09.2005 0.15029 0.06667 4950 4967.98185 0.02097 89.12414 89.80347

30.09.2005 0.14321 0.05833 5200 5040.84716 0.02101 17.75148 18.98607

Selected options have different parameters such as time to maturity, volatility, strike price, spot price that resulted in differences between their prices. Comparing results from Black-Scholes model and Monte Carlo simulation we can summarize that latter has given us accurate values that are close to true ones and can serve as a good approximations.

1. Christian P. Robert, George Casella; Introducing Monte Carlo Methods with R, 2010, Springer; 2. Desmond J. Higham; An introduction to financial option valuation: mathematics, stochastics and computation, 2004,

Cambridge University Press; 3. George M. Jabbour, Yi-Kang Liu; Option pricing and Monte Carlo simulations, Journal of Business & Economics Research, Vol. 3, No. 9; 4. John R. Birge; Quasi-Monte Carlo approaches to option pricing, 1995; 5. Jürgen Franke, Wolfgang K. Härdle, Christian M. Hafner; Statistics of Financial Markets, Second Edition, 2008, SpringerVerlag Berlin Heidelberg; 6. Michael C. Fu, Jian-Qiang Hu, Sensitivity Analysis for Monte Carlo simulation of option pricing, Probability in the Engineering and Information Sciences, Vol. 9, No. 3, 1995; 7. Wolfgang Härdle, Torsten Kleinow, Gerhard Stahl; Applied Quantitative Finance, 2002, Springer, Berlin; 8. http://www.case.hu-berlin.de/. 9. http://cran.r-project.org/web/packages/fOptions/

Надійшла до редколегії 01.07.11

УДК 331:213.3:331

О. Горобець,

Феодосійська фінансово-економічна академія Київського університету ринкових відносин

СТАТИСТИЧНЕ МОДЕЛЮВАННЯ ПОКАЗНИКІВ ВІДТВОРЕННЯ НАСЕЛЕННЯ АВТОНОМНОЇ РЕСПУБЛІКИ КРИМ

За результатами моделювання показників відтворення населення визначено періоди формування демографічної ситуації в Криму. Зіставлення бета-коефіцієнтів дозволило оцінити внесок кожного фактора в результативний показник за різних періодів відтворення.

Ключові слова: природне відтворення населення, демографічні моделі, трендові моделі.

Построены модели, характеризующие общий прирост (снижение) численности населения региона (на примере Автономной Республики Крым) в зависимости от периода воспроизводства: устойчивого развития, кризисного состояния и улучшения. Рассчитано влияние каждого фактора в общий прирост (снижение).

Ключевые слова: природное воспроизводство населения, демографические модели, трендовые модели.

The modeling of general growth of Crimean population is done during three periods of reproduction process development: of the past development, crises state and the period of reproduction process improvement, every factor contribution into resulting process is given.

Keywords: natural reconstruction of the population, demographic forecast, trend model.

Взаємозв'язки між демографічними явищами та процесами, а, відповідно, і між параметрами демографічної

ситуації в регіоні належать до стохастичних, зокрема, кореляційних зв'язків, при яких зміна середнього значен-

© Горобець О., 2011

i Надоели баннеры? Вы всегда можете отключить рекламу.