[SOLVED] 编程代写 Simulating Stocks in Discrete Time

30 $

File Name: 编程代写_Simulating_Stocks_in_Discrete_Time.zip
File Size: 442.74 KB

SKU: 8587976049 Category: Tags: , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Or Upload Your Assignment Here:


Simulating Stocks in Discrete Time
Summary of the week:
• Simulating stocks in discrete time.
• Utility functions

Copyright By PowCoder代写加微信 assignmentchef

• A discrete time version of the Merton problem
Last week we studied the Markowitz model.
That was a one-period investment problem: meaning that we choose what stocks to buy at time 0 and hold them to time T without making any changes. This week we will move on to consider multi-period problems. We will develop a multi-period model for stock prices and then see if we can find an optimal investment strategy.
We will continue to work in discrete time, so we will only trade at times on a fixed grid of times:
T = {0,δt,2δt,3δt…,…,nδt}.
When I write δt, this is a single number representing a small change in t. A lot of authors would write ∆t
instead, but the symbol ∆ has a special meaning in finance already, so I want to avoid it.
Another difference we will make from the approach in the Markowitz model is that we will no longer just consider the mean and the variance of returns. I’ve already remarked that the Markowitz approach of quantifying risk using variance cannot be justified if the precise distribution of returns depends on more parameters than just the mean and the variance. As we will see, in a multi-period problem where the return in one period is independent of the ereturn of previous periods, you cannot assume that returns are always normally distributed. This means that the mean variance approach becomes hard to justify, so we will introduce the alternative approach of utility functions.
We will apply utility functions and our stock price model to consider an optimal investment problem where you must decide dynamically how much money to put into a risky stock and how much to put in bonds. This will be a discrete time version of the Merton model. The Merton model is much easier to solve in general in continuous time, but this requires techniques from stochastic calculus. Since you don’t yet know stochastic calculus, we will work in discrete time, but that means we will have to restrict our attention to a special case where we can find the solution by symmetry arguments.
(1944+) in Economics 1997
• Problem: Continuous time portfolio selection
• Key Paper: Lifetime Portfolio Selection under Uncertainty: the Continuous-Time Case, The Re-
view of Economics and Statistics 1969
• Keywords: Continuous time, Utility
He may have been one of the most important financial mathematicians in history, but his career had it’s lows as well as it’s highs. Merton co-founded hedge fund, Long-Term Capital Management, which earned high returns for four years but later lost $4.6 billion in 1998 and was bailed out by a consortium of banks and closed out in early 2000.

1 Discrete Time Geometric Brownian Motion
We would like to develop a model for a stock price on a discrete time grid
T = {0,δt,2δt,…,nδt,…}
We will write St for the stock price at time t ∈ T . Each St will be a random variable.
We will develop a model for St which is as simple as possible. It is called discrete time geometric Brownian motion.
We want to come up with the simplest model that we can that captures the uncertainty of stock prices.
If you studied physics at school, you are probably used to people telling you how the world behaves, for example you are told that gravity obeys an inverse square law. But this is misleading. What actually hap- pened was that Newton proposed a model for gravity based on the theory that it obeys an inverse square

law which turns out to match the motion of planets very well. However, Newton’s law is now known to not match the data perfectly and you need to use general relativity if you want to model black holes rather than just planets – and even for the planet Mercury, Newton’s laws are slightly innaccurate. Even so, gen- eral relativity cannot be the end of the story as it is known not to be compatible with quantum mechanics. Nobody knows what the end of the story is.
In finance it is important to be honest that we do not know how the world behaves, all we can do is propose models.
Most people’s instinct when proposing models is to come up with a model that contains all the features they can think of. The mark of a genius is that they propose very simple models that capture the essential features. They don’t clutter their model with unnecessary features.
For example, in reality there is no such thing as a stock price. On any exchange, there is the ask price which is how much you must pay for a stock and the bid price which is how much you can sell one for. The ask price will always be higher than the bid price. Two different exchanges may have different bid and ask prices for the same stock. However, let’s act like a genius and simplify things by ignoring these minor issues. We will assume there is a single price at which you can buy and sell stock.
Similarly, stock prices must be whole numbers because there are no smaller currency denominations than dollars and cents. Again, let’s act like a genius and assume that stock prices can take any positive real value.
The same desire for simplicity motivates our next, more interesting, assumption.
Assumption 1: The distribution of returns from time t to time t + δt are independent and identically dis-
tributed with a known distribution. This is equivalent to assuming that:
• (Identically distributed): The stock remains an equally good investment at all times t ∈ T .
• (Independence): You can’t decide by looking at the history of the stock what will happen over the
next period.
To understand the signficance of these assumptions, it’s helpful to notice they also apply in the game of roulette.
Example: The returns in roulette are independent and identically distributed.
• (Identically distributed): For example, the probability of the ball landing on 17 is the same each time you play roulette
• (Independent):Knowingwhathappenedinthelastspinoftheroulettewheeldoesn’taffecttheprob- abilities on the next spin.
One difference with the game of roulette is that we do not assume that the average return is zero. If you invest in a stock index such as the S&P 500, most people agree that over the long term you will make a non-zero return.
An important difference between roulette and stocks that we do not attempt to model is that in roulette, the rules of the game are well known so we know the probability of the ball landing on any particular number. With stocks, nobody really knows the probability distribution of future stock prices. You might try to look at historic prices to calibrate a statistical model, or you might look at balance sheet data to develop a model of how a stock will perform in the future. There are many possible approaches to trying to estimate the probability distribution of future stock prices. In our model we are completely ignoring this challenging

question. We have said that returns have a known distribution. It is best to think of this as being our opinion on the future evolution of the stock without specifying how we arrived at that opinion.
Lemma: Write Zt = log St for the log of the stock price. It satisfies the recurrence relation Zt+δt = Zt + Xt
where the Xt are independent identically distributed random variables.
Proof: Write Rt for the returns. They are independent and identically distributed.
Rearrange Take logs
Rt := St+δt −St. St
St+δt = St(Rt + 1). Zt+δt = Zt + log(Rt + 1).
Use the fact that if random variables Yt are independent and identically distributed, so are f(Yt) for any function f. □
Definition:
Let FX and FY be cumulative distribution functions. FX is an affine transform of FY if FX (x) = FY (ax + b)
for some a, b. We will also say that the distributions of X and Y have the same functional form
This definition means that two distributions have the same functional form if their density functions “look
the same’ ’ up to a possible shifting and rescaling.
• All normal distributions are affine transforms of each other
• All exponential distributions are affine transforms of each other

We don’t want to have an essentially different model of the stock price at different times. Our desire for simplicity motivates our next assumption.
Assumption 2: The functional form of the distribution of the change in the log stock price is independent of the time interval.
This means that the distributions of Zt+nδt − Zt and Zt+mδt − Zt have the same functional form for all n and m.
Theorem: If
• (Assumption 1) stock price returns are independent and identically distributed
• (Assumption 2) the functional form of the distribution of the change in the log of the price is inde-
pendent of the time interval
• (Assumption3)thedistributionofthechangeinthelogofthestockpricehasfinitemeanandvariance
then the log of the stock price, Zt, obeys the difference equation √
Zt+δt =Zt +Xt =Zt +μ ̃δt+σ δtεt
for some constants μ ̃ and σ and independent standard normally distributed random variables εt. Proof:
By assumption 1 we can write

Zt+nδt − Zt = Xt + Xt+δt + Xt+2δt + . . . Xt+(n−1)δt n−1
Xt+iδt where the Xt are independent and identically distributed.
√n(Zt+nδt − Zt) = √n
This converges to a normal distribution by the central limit theorem (using assumption 3). So, by Assump-
tion 2, the only possibility is that Xt = Zt+δt − Zt is normally distributed.
So we can write Xt = a + bεt where ε is normally distributed.
Defineμ ̃=a.Defineσ=√b □ δt δt
We have introduced μ ̃ and σ so that our difference equation remains the same if we change the grid size. Lemma: If the log stock price Zt follows the process
Zt+δt =Zt +μ ̃δt+σ δtεt for independent standard normals εt, then for any interval ∆ we have
Zt+∆ = Zt + μ ̃∆ + σ√∆ε′t for some standard normally distributed random variable ε′t.
The larger the time interval, the greater the change in the log stock price. We see that the standard deviation in the change of the log stock price grows according to the square root of time.
s.d.(Zt+δt − Zt) = σ
• In finance the units of measurment of time is the year, which we write as y.
• For this equation to make sense, the units of volatility must be y− 21
• The volatility is usually quoted as a percentage. Volatility 20% means σ = 0.2y− 21 .
This fractional dimension of the volatility is related to the fact that when we simulate stock prices, they will be fractals
E ( S t ) = S 0 e ( μ ̃ + 21 σ 2 ) t

E(St) = E(eZt )
= E(eZ0+μ ̃t+σ tε)
= E(S0(eμ ̃t+σ
∫∞ 1̃ √ x2 =S0 √ eμt+σ txe−2 dx
−∞ 2π Since ε follows a standard normal distribution.
You compute an infinite integral of an integral of the exponential of a quadratic by completing the square.
∞ 1 −(x−σ√t)2 +(μ ̃+1σ2)t =S0√e2 2dx
(μ ̃+1σ2)t =S0e2
∫ ∞ 1 −x2 +μ ̃t+σ√tx
1 −(x−σ t)2
= S 0 e ( μ ̃ + 12 σ 2 ) t
since the integral is just the integral of the density of a normal distribution with mean σ
and so must equal 1. □
If we define μ = μ ̃ + 12 σ2 we have
t over (−∞, ∞)
E(St) = S0eμt.
The term μ can be interpreted as an interest rate. It has units of y−1 or “per annum” just like any interest
μ is called the drift of the stock price.
The term μ ̃ = μ − 21 σ2 is usually written out in terms of the drift. We’ll do that from now on.
1.1 Summary
The simplest model we can think of for stock prices is discrete time geometric Brownian motion. Definition: The process (St)t∈T follows discrete-time geometric Brownian motion if its logarithm Zt =
Zt+δt = Zt + (μ − 12 σ2)δt + σ√δtεt
for all t ∈ T where the εt are independent standard normally distributed random variables.

We say that (Zt)t∈T itself follows discrete- time Brownian motion. Remember:
• Theexpectedvalueofthestockgrowswithcontinuouslycompoundedinterestrategivenbythedrift μ.
• The standard deviation of the log of the stock price grows according to the square root of the time interval and the rate of growth is determined by the volatility σ.
This slide is important, so learn it off by heart.
2 Simulating Discrete Time Brownian Motion
Is our model any good? A basic test is to perform some simulations to see if we obtain something that looks a bit like a stock price.
Here are the mathematical equations we need:
Z0 = log(S0)
Z(i+1)δt = Z(i)δt + (μ − 12 σ2)δt + σ√dt εiδt
Siδt = exp(Ziδt)
If we run through n_steps changes of the stock price, we will compute the value at (n_steps+1) different time points. So we will store the values of Z and S in numpy arrays of length (n_steps+1). So we will change the subscript iδt to an array index [i].
Z[0] = log(S[0])
Z[i + 1] = Z[i] + (μ − 12σ2)δt + σ√dtε[i]
S[i] = exp(Z[i])
where ε is a vector of length n_steps containing independent standard normal values.
def simulate_gbm( S0, mu, sigma, T, n_steps): Z = np.zeros( n_steps+1 )
dt = T/n_steps
Z[0] = log(S0)
epsilon = np.random.randn( n_steps) for i in range(0,n_steps):
Z[i+1] = Z[i] + (mu – 0.5*sigma**2) * dt + sigma*sqrt(dt)*epsilon[i]
S = np.exp(Z) return S

n_steps = 365 # Days in a year
sigma = 0.2 # 20% volatility per year mu = 0.08 # 8% growth per annum
times = np.linspace(0,1,n_steps+1)
S = simulate_gbm(S0,mu,sigma,T,n_steps)
ax = plt.gca()
ax.plot(times,S)
ax.set_xlabel(‘Time’)
ax.set_ylabel(‘Stock price’)
ax.set_title(‘Discrete time geometric Brownian motion’); #+
n_steps = 365 # Days in a year
sigma = 0.2 # 20% volatility per year mu = 0.08 # 8% growth per annum
ax = plt.gca()
for i in range(0,100):

S = simulate_gbm(S0,mu,sigma,T,n_steps)
ax.plot(times,S)
ax.set_xlabel(‘Time’)
ax.set_ylabel(‘Stock price’)
ax.set_title(‘Discrete time geometric Brownian motion’); #+
We will often want to generate a large number of stock price paths (millions!). We write a convenient function to generate lots of prices at once which also returns the time grid.
def simulate_gbm_paths( S0, mu, sigma, T, n_steps, n_paths): Z = np.zeros( [ n_paths, n_steps+1] )
dt = T/n_steps
Z[:,0] = log(S0)
times = np.linspace(0,T,n_steps+1)
epsilon = np.random.randn( n_paths, n_steps ) for i in range(0,n_steps):
Z[:,i+1] = Z[:,i] + (mu-0.5*sigma**2) * dt + sigma*sqrt(dt)*epsilon[:,i]
S = np.exp(Z) return S, times
simulate_gbm_paths generates a matrix of stock price paths. Each row in the matrix is a different path. 10

Each column represents a different time point. You can remember which way round the rows and columns are because I’ve made the matrix look like the plot: time goes horizontally, different paths are aligned vertically.
A good way to show the range of possible paths is by drawing a fan diagram. At each time we compute the median and 5th and 9th percentiles of the stock price and plot those together with a sample stock price path.
This shows clearly the likely range of values of the price path as well as the roughness of an individual price path.
The “spaghetti monster” showing 100s of price paths really isn’t as informative, especially when printed in black and white. CHoosing a larger number of paths than 2000 will give a smoother plot.
S, times = simulate_gbm_paths(S0,mu,sigma,T,n_steps,2000)
top_five_percent = np.percentile(S,95,0)
bottom_five_percent = np.percentile(S,5,0)
median = np.percentile(S,50,0)
plt.plot(times, top_five_percent, label=’95th Percentile’)
plt.plot(times,median, label=’Median’)
plt.plot(times, bottom_five_percent, label=’5th Percentile’)
plt.plot(times,S[0,:], label=’Sample Path’);
plt.xlim(0,1);
plt.legend(‘A fan diagram of geometric Brownian motion’) plt.legend(); #+

2.1 Writing a library
The function simulate_gbm_paths is the best function we will write on the course. We want to put it into a library so we can reuse it. I’ve created a file called fmlib containing the code so that we can import the function whenever we want to use it. fmlib is short for Financial Maths library.
import fmlib
S, times = fmlib.simulate_gbm_paths(S0,mu,sigma,T,n_steps,1)
plt.plot(times,S[0,:]);
3 Exercises 3.1 Exercise
True or False? It was shown in the lectures that discrete-time geometric Brownian motion gives a model for stock prices which fits market data well.
Answer with the Python keywords True or False 3.2 Exercise
Suppose that St follows discrete time geometric Brownian motion with drift μ and volatility σ = 0 on a grid of size δt. Suppose that T = nδt. Compute the value of ST in terms of S0, T, μ and n and use this to write a function compute_ST_vol0. Does your answer depend upon the choice of n?

3.3 Exercise
Suppose that St follows discrete time geometric Brownian motion with drift μ and volatility σ. What is the distribution of Zt at time t?
3.4 Exercise
Suppose that St follows discrete time geometric Brownian motion with drift μ and volatility σ. Show that the percentiles in the fan diagram of St do not depend upon the choice of δt.
Compute the equation for the 5-th percentiles in the fan diagram for St in terms of the function N−1. Here N −1 is the inverse of the cumulative distribution function N of the standard normal distribution. You can calculate this using the function scipy.stats.norm.ppf. ppf stands for percent point function which is another term for the inverse cumulative distribution function. Hint: If ε has a standard normal distribution, the 5-th percentile of ε is N−1(0.05), indeed this is why the inverse distribution function can be called the percent point function.
Write a function fifth_stock_percentile that computes the percentile given the parameters S0 , μ, σ and t using your equation. You should also check that your answer is correct with a plot.
3.5 Exercise
Suppose that St follows discrete time geometric Brownian motion with drift μ and volatility σ. Check numerically that the expected value of St satisfies
E(St) = S0eμt Prove that the standard deviation of St satisfies
s.d.(St) = S0eμt eσ2t − 1 Check numerically that this answer is correct.
Since you are checking your results yourself numerically, there are no automated tests for this exercise. One of the skills this is testing is your ability to write your own automated tests.
3.6 Exercise
Suppose that St follows discrete time geometric Brownian motion with drift μ = 0.08y−1 and volatility σ = 0.20y− 21 . Assume for simplicity that there is no inflation so the risk-free rate is 0.
Compute the probability of the stock price being below S0 at time t. You should write a function prob_making_loss that computes this. Plot a graph of this over a 100 year period.

4 Utility Functions
When we studied the Markowitz model, we decided to measure risk using the standard deviation. This makes sense if you know the distribution of assets will be normally distributed, but if you don’t know the shape of the distribution just comparing the mean and standard deviation might not be enough to decide which of two probability distributions you prefer.
We will take a brief look at the theory of preferences, but it is an interesting subject to look into further. Ultimately, if you want to choose an investment strategy that gives you the best possible outcome, you will need to know very clearly what you mean by “the best” as different measures of success will give different outcomes.
Suppose that you must choose between a number of possible probability distributions for your future wealth. It is natural to try to rank probability distributions. Suppose that you have some ordering ≺ on probability distributions so you prefer receiving the random income X to the random income Y if
d(X) ≺ d(Y ). Theorem: (von Utility theorem)
where d(X) denotes the distribution of X.
Under some very reasonable conditions on ≺ we can find a utility function u : R → R such that
d(X) ≺ d(Y ) ⇐⇒ E(u(X)) ≺ E(u(Y )) We say that the preferences are given by expected utility.
We won’t list all the conditions in this course as it would take us too far afield. It’s an interesting theorem be- cause there is some room for debate how “reasonable” the conditions are.

程序代写 CS代考加微信: assignmentchef QQ: 1823890830 Email: [email protected]

Reviews

There are no reviews yet.

Only logged in customers who have purchased this product may leave a review.

Shopping Cart
[SOLVED] 编程代写 Simulating Stocks in Discrete Time
30 $