기본 콘텐츠로 건너뛰기

pandas_ta를 적용한 통계적 인덱스 지표

Exponential distribution

Exponential Distribution

The exponential distribution is one of the most used continuous distributions and is widely used to model the passage of time between certain events.

The distribution of a continuous random variable X having a probability density function (PDF) as in Equation 1 is called an exponential distribution, and the parameter λ means the mean frequency.

$$\begin{align}\tag{1} &X \sim \text{Exponential}(\lambda)\\ &f(x)=\begin{cases} \lambda e^{-\lambda x}&\quad x>0\\ 0 & \quad \text{otherwise} \end{cases}\\ & \quad \lambda >0 \end{align}$$

The cumulative distribution function of the exponential distribution is calculated by the integral of the probability density function.

Use the sympy.integrate() function.

import numpy as np
import pandas as pd 
import matplotlib.pyplot as plt
from sympy import *
from scipy import stats
x, l=symbols("x lambda", positive=True)
f=l*exp(-l*x)
f
$\qquad \color{blue}{\displaystyle l e^{- \lambda x}}$
F=integrate(f, (x, 0, x))
simplify(F)
$\qquad \color{blue}{\displaystyle 1-e^{- \lambda x}}$

The mean and variance of the exponential distribution are defined as Equation 2 according to their respective definitions.

$$\begin{align}\tag{2} &\begin{aligned}E(x)&=\mu\\&=\int^\infty_0 xf(x)\, dx\\&=\int^\infty_0 x\lambda e^{-\lambda x}\, dx\\&=\left. \frac{1}{\lambda}(-e^{-\lambda x}-xe^{-\lambda x})\right|^\infty_0\\&=\frac{1}{\lambda} \end{aligned}\\ &\begin{aligned}E(x^2)&=\int^\infty_0 x^2f(x)\, dx\\&=\int^\infty_0 x^2\lambda e^{-\lambda x}\, dx\\&=\frac{2}{\lambda^2} \end{aligned}\\ &\begin{aligned}\text{Var(X)}&=E(x^2)-(E(x))^2\\&=\frac{2}{\lambda^2}-\frac{1}{\lambda^2}\\&=\frac{1}{\lambda^2} \end{aligned} \end{align}$$
E=integrate(x*f,(x, 0, oo))
E
$\qquad \color{blue}{\displaystyle \frac{1}{\lambda}}$
E2=integrate(x**2*f, (x, 0, oo))
E2
$\qquad \color{blue}{\displaystyle \frac{2}{\lambda^2}}$
var=E2-E**2
var
$\qquad \color{blue}{\displaystyle \frac{1}{\lambda^2}}$

Statistics of random variables conforming to the exponential distribution can be calculated using various methods of the expon class of the scipy.stats module.

  • If λ > 1, scale (indicator of spread of data) < 1
  • if λ < 1, scale > 1

As a result, λ can be said to be a parameter that controls the spread of the data.

Example 1)
  It is said that the time it takes to repair a machine follows an exponential distribution with the parameter λ=3. Mean and standard deviation?

It is calculated using the probability density function of the exponential distribution as follows.

$$f(x)=\lambda e^{-\lambda x}$$
E=integrate(x*f,(x, 0, oo))
E.subs(l, 3)
$\qquad \color{blue}{\displaystyle \frac{1}{3}}$
var=E2-E**2
var.subs(l, 3)
$\qquad \color{blue}{\displaystyle \frac{1}{9}}$

Check the mean and standard deviation calculated above with the stats.expon class.

np.around(stats.expon.stats(scale=1/3, moments="mv"), 4)
array([0.3333, 0.1111])

Use the moment() method of this class to calculate the mean and variance.

E=stats.expon.moment(1,scale=1/3)
round(E, 4)
0.3333
E2=stats.expon.moment(2, scale=1/3)
round(E2, 4)
0.2222
var=E2-E**2
round(var, 4)
0.1111

The following shows the distribution change according to λ.

plt.figure(figsize=(7, 4))
lamda=[0.5, 1, 2]
for i in lamda:
    p=[stats.expon.pdf(j, 0, 1/i) for j in np.arange(0, 2, 0.001)]
    plt.plot(np.arange(0, 2, 0.001), p, label="Expon("+str(i)+")")
plt.xlabel("X", fontsize="13", fontweight="bold")
plt.ylabel("PDF", fontsize="13", fontweight="bold")
plt.legend(loc="best")
plt.show()

The exponential distribution above is similar to the geometric distribution of discrete variables. The following is the geometric distribution when the probability in one run is p.

plt.figure(figsize=(7, 4))
p=[0.05, 0.1, 0.5]
for j in p:
    p=[stats.geom.pmf(i, j) for i in np.arange(10)]
    plt.plot(np.arange(10), p, label="geom("+str(j)+")")
plt.xlabel("X", fontsize="13", fontweight="bold")
plt.ylabel("PDF", fontsize="13", fontweight="bold")
plt.legend(loc="best")
plt.show()

A geometric distribution is a distribution that shows the probability that success occurs for the first time by repeating Bernoulli trials with probability p. If this distribution is similar to the exponential distribution, which is the distribution of continuous variables, it can be considered that there is a correlation between the parameter p of the geometric distribution and λ, the parameter of the exponential distribution. In the case of the continuous distribution λ, it is a parameter related to the decay rate of the probability, and the smaller it is, the smaller the change in the probability. Similarly, the smaller the p of the geometric distribution, the smaller the change in probability. Therefore, the exponential distribution can be interpreted as a case in which the probability of first success in any trial is very small. For example, the probability distribution for the data that customers visit a store in a very short time interval can be thought of as an exponential distribution.

As such, the interpretation of the exponential distribution can be understood as the characteristics of the geometric distribution. Important of these characteristics is that they are not constrained by any previous conditions. If a coin toss is repeated and heads (success) have not been observed so far, the probability from that point on is not limited by the previous results. These attributes are called memoryless. That is, a continuous variable X following an exponential distribution with a parameter of λ > 0 is a memoryless random variable, which is proved by the following equations.

$$\begin{align} &P(X>x+a | X>a)=P(X>x)\\ &\begin{aligned}F(x)&=\int^x_0 \lambda e^{-\lambda t}\,dt\\&=1-e^{-\lambda x}\end{aligned}\\ &\begin{aligned}P(X>x+a | X>a)&=\frac{P(X>x+a) \cap P(X>a)}{P(X>a)}\\&=\frac{P(X>x+a)}{P(X>a)}\\&=\frac{1-F(x+a)}{1-F(a)}\\&=\frac{e^{-\lambda (x+a)}}{e^{-\lambda a}}\\&=e^{-\lambda x}\\&=1-F(x)\\&=P(X>x)\end{aligned} \end{align}$$

Example 2)
 An employee at a company makes an average of 6 calls every 10 minutes. In this case, it is assumed that the number of minutes between the call and the next call is called the random variable t, and that this variable follows an exponential distribution.
Determine the following:

1) The average frequency of calls per minute is λ, which is 0.6 calls per minute. Therefore, the probability density function of this distribution is

$$f(x)=0.6 \exp(-0.6 t), \quad t \gt 0$$

2) What is the probability that the next call will be within 5 minutes after the call?

t=symbols('t', positive=True)
f=0.6*exp(-0.6*t)
Flt5=f.integrate((t, 0, 5))
N(Flt5,4)
0.9502

3) Probability that the next call will be more than 2 minutes after a call?

Fgt2=1-f.integrate((t, 0, 2))
N(Fgt2,4)
0.3012
round(stats.expon.sf(2, scale=1/0.6), 4)
0.3012

Example 3)
 The daily fluctuations of the high and low prices of the Philadelphia Semiconductor Index(SOXX) over the following period are applied to an exponential distribution.

import FinanceDataReader as fdr
st=pd.Timestamp(2020,1, 1)
et=pd.Timestamp(2021, 12, 14)
da=fdr.DataReader("SOXX", st, et)
change=(da['High']-da['Low'])/da['Low']*100
change
Date
2020-01-02    1.300395
2020-01-03    1.095792
2020-01-06    0.982771
2020-01-07    1.584830
2020-01-08    1.106440
                ...   
2021-12-08    1.253281
2021-12-09    2.854305
2021-12-10    2.663311
2021-12-13    3.369283
2021-12-14    1.853975
Length: 493, dtype: float64

According to the expression 2, the reciprocal of the mean of change is the parameter λ.

plt.figure(figsize=(7,4))
rng=np.sort(change)
lam=1/rng.mean()
p=[stats.expon.pdf(i, loc=lam, scale=1/lam ) for i in rng]
f=plt.hist(rng, bins=10,density=True, alpha=0.4, label='daily change')
plt.plot(rng, p, linewidth=2, label='Expon('+str(round(lam,3))+')')
plt.xlabel('Change(%)', fontsize='13', fontweight='bold')
plt.ylabel('PDF(Density)', fontsize='13', fontweight='bold')
plt.legend(loc='best')
plt.show()

According to the above result, the probability that the rate of change between the low and high prices is 3% or more is as follows.

cf=stats.expon.sf(3, lam, 1/lam)
round(cf, 4)
0.3357

댓글

이 블로그의 인기 게시물

[Linear Algebra] 유사변환(Similarity transformation)

유사변환(Similarity transformation) n×n 차원의 정방 행렬 A, B 그리고 가역 행렬 P 사이에 식 1의 관계가 성립하면 행렬 A와 B는 유사행렬(similarity matrix)이 되며 행렬 A를 가역행렬 P와 B로 분해하는 것을 유사 변환(similarity transformation) 이라고 합니다. $$\tag{1} A = PBP^{-1} \Leftrightarrow P^{-1}AP = B $$ 식 2는 식 1의 양변에 B의 고유값을 고려한 것입니다. \begin{align}\tag{식 2} B - \lambda I &= P^{-1}AP – \lambda P^{-1}P\\ &= P^{-1}(AP – \lambda P)\\ &= P^{-1}(A - \lambda I)P \end{align} 식 2의 행렬식은 식 3과 같이 정리됩니다. \begin{align} &\begin{aligned}\textsf{det}(B - \lambda I ) & = \textsf{det}(P^{-1}(AP – \lambda P))\\ &= \textsf{det}(P^{-1}) \textsf{det}((A – \lambda I)) \textsf{det}(P)\\ &= \textsf{det}(P^{-1}) \textsf{det}(P) \textsf{det}((A – \lambda I))\\ &= \textsf{det}(A – \lambda I)\end{aligned}\\ &\begin{aligned}\because \; \textsf{det}(P^{-1}) \textsf{det}(P) &= \textsf{det}(P^{-1}P)\\ &= \textsf{det}(I)\end{aligned}\end{align} 유사행렬의 특성 유사행렬인 두 정방행렬 A와 B는 'A ~ B' 와 같...

유리함수 그래프와 점근선 그리기

내용 유리함수(Rational Function) 점근선(asymptote) 유리함수 그래프와 점근선 그리기 유리함수(Rational Function) 유리함수는 분수형태의 함수를 의미합니다. 예를들어 다음 함수는 분수형태의 유리함수입니다. $$f(x)=\frac{x^{2} - 1}{x^{2} + x - 6}$$ 분수의 경우 분모가 0인 경우 정의할 수 없습니다. 이와 마찬가지로 유리함수 f(x)의 정의역은 분모가 0이 아닌 부분이어야 합니다. 그러므로 위함수의 정의역은 분모가 0인 부분을 제외한 부분들로 구성됩니다. sympt=solve(denom(f), a); asympt [-3, 2] $$-\infty \lt x \lt -3, \quad -3 \lt x \lt 2, \quad 2 \lt x \lt \infty$$ 이 정의역을 고려해 그래프를 작성을 위한 사용자 정의함수는 다음과 같습니다. def validX(x, f, symbol): ① a=[] b=[] for i in x: try: b.append(float(f.subs(symbol, i))) a.append(i) except: pass return(a, b) #x는 임의로 지정한 정의역으로 불연속선점을 기준으로 구분된 몇개의 구간으로 전달할 수 있습니다. #그러므로 인수 x는 2차원이어야 합니다. def RationalPlot(x, f, sym, dp=100): fig, ax=plt.subplots(dpi=dp) # ② for k in x: #③ x4, y4=validX(k, f, sym) ax.plot(x4, y4) ax.spines['left'].set_position(('data', 0)) ax.spines['right...

부분분수의 미분

내용 방법 1 방법 2 방법 3 부분분수의 미분 분수의 미분은 일정한 공식 을 적용하여 계산할 수 있습니다. 그러나 분수 자체가 단순한 표현으로 이루어지지 않았다면 미분 과정이나 결과는 매우 복잡할 수 있습니다. 만약 복잡한 분수 함수를 간단한 분수들로 분해할 수 있다면 계산이 보다 간편해질 것입니다. 이와 같이 분해된 간단한 분수들을 부분분수 라고 합니다. 예를 들어 다음 두 분수의 합을 계산해 봅니다. $$\begin{align} \frac{1}{x+1}+\frac{2}{x-1}&=\frac{x-1+2(x+1)}{(x+1)(x-1)}\\ &=\frac{3x+1}{x^2-1} \end{align}$$ 위 과정은 3개 이상의 여러 분수에서도 이루어질 수 있습니다. 또한 역으로 진행될 수 있습니다. 즉, 분수를 부분 분수로 분할할 수 있습니다. 그러나 이러한 과정은 대수분수 (분자의 가장 큰 차수가 분모의 최고의 차수보다 작은 분수)에서만 이루어질 수 있습니다. 예를 들어 $\displaystyle \frac {x^2+2}{x^2-1}$의 경우는 분자와 분모의 차수는 2차로 같습니다. 이러한 경우 다음과 같이 분리할 수 있습니다. $$\frac{x^2+2}{x^2-1}=1+\frac{3}{x^2-1}$$ 위의 식 중 $\displaystyle \frac{3}{x^2-1}$은 분자의 차수가 분모의 차수 보다 낮은 대수 분수이므로 부분 분수로 분리할 수 있습니다. 이와같이 부분 분수로 분해하는 방법은 다음과 같이 몇 가지로 구분할 수 있습니다. 방법 1 위 예의 결과 $\displaystyle \frac{3x+1}{x^2-1}$의 경우를 역으로 생각해 봅니다. 분모의 인수분해가 가능하면 그 분모의 인수에 의해 다음과 같이 분해할 수 있습니다. $$\begin{align} \frac{3x+1}{x^2-1}&=\frac{3x+1}{(x+1)(x-1)}\\ &=\frac{A}{x+1...