# Discrete Random Variable Example
r <- c(-0.3, 0, 0.1, 0.2, 0.3) # Possible returns
p <- c(0.05, 0.20, 0.5, 0.2, 0.05) # Associated Probabilities
sum(p) # Check that sum is 1
Copyright By PowCoder代写 加微信 powcoder
# Expected Value:
sum(r * p)
mu <- sum(r * p) # save to mu
# Variance
sum((r - mu)^2 * p) # Variance
sqrt(sum((r - mu)^2 * p)) # Standard Deviation
# Working with X ~ Normal(0, 1)
pnorm(0) # Probability(X <= 0) = ?
pnorm(1) # Pr(X <= 1) = ?
pnorm(1) - pnorm(-1) # Pr(-1 <= X <= 1) = ?
qnorm(0.5) # 50% Quantile, i.e. Pr(X <= ?) = 0.5
qnorm(0.10) # 10% Quantile, i.e. Pr(X <= ?) = 0.1
# Working with X ~ Normal(0, 5)
pnorm(0, mean = 2, sd = sqrt(5)) # Pr(X <= 0) = ?
pnorm(0, 2, sqrt(5)) # Alternate form
pnorm(-0.10, 0.02, 0.10) # Pr(R_A <= -0.10)
pnorm(-0.10, 0.01, 0.05) # Pr(R_B <= -0.10)
# Plotting Distributions
#1. X ~ Uniform(-1, 1)
x <- seq(-3, 3, length = 1000)
y <- dunif(x, -1, 1)
plot(x, y, type = 'l')
# X ~ Normal(0, 1)
y <- dnorm(x, 0, 1)
plot(x, y, type = 'l')
# R_A ~ Normal(0.02, 0.10); R_B ~ Normal(0.01, 0.05)
x <- seq(-0.5, 0.5, length = 1000)
y1 <- dnorm(x, 0.02, 0.10) #R_A
y2 <- dnorm(x, 0.01, 0.05) #R_B
plot(x, y1, type = 'l', ylim = c(0, max(y1, y2)))
lines(x, y2)
# R ~ Normal(0.05, 0.50^2)
# Pr(R < -1)
pnorm(-1, 0.05, 0.50)
# R_A ~ Normal(0.02, 0.10);
# Pr(R < -1)
pnorm(-1, 0.02, 0.10)
# r ~ N(0.05, 0.5^2)
x <- seq(-2, 4, length = 1000) # lognormal is not symmetric
plot(x, dnorm(x, 0.05, 0.5), type = 'l', ylim=c(0,1))
lines(x, dlnorm(x, 0.05, 0.5), col='blue', lty=2)
legend("topright", legend = c("Normal", "LogNormal"), lty = c(1,2), col = c("black", "blue"))
# X ~ Gamma distribution
x <- seq(0, 10, by = 0.01)
plot(x, dgamma(x, shape = 2, scale = 1), type = 'l', main = "Gamma Distribution")
# X ~ Beta distribution
x <- seq(0, 1, length = 1000)
plot(x, dbeta(x, shape1 = 10, shape2 = 5), type = 'l', main = "Beta Distribution")
# Discrete Random Variable Example
r <- c(-0.3, 0, 0.1, 0.2, 0.3) # Possible returns
p <- c(0.05, 0.20, 0.5, 0.2, 0.05) # Probabilities
# Skewness & Kurtosis:
mu <- sum(r * p) # Expected value / mean
sigma <- sqrt( sum((r - mu)^2 * p) ) # SD
skew <- sum((r - mu)^3 * p) / sigma^3 # Skewness
kurt <- sum((r - mu)^4 * p) / sigma^4 # Kurtosis
# Student's t-distribution
x <- seq(-5, 5, length = 1000)
plot(x, dnorm(x), type = 'l', lwd = 2)
lines(x, dt(x, 1), lty = 2, col = 'blue')
lines(x, dt(x, 5), lty = 3, col = 'darkgreen')
lines(x, dt(x, 10), lty = 4, col = 'purple')
lines(x, dt(x, 50), lty = 5, col = 'darkred')
legend("topleft",
legend = c("Normal", "t-1", "t-5", "t-10", "t-50"),
lty = 1:5,
col = c("black", "blue", "darkgreen", "purple", "red"))
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com