Skip to content
Olibyte Blog
HomeGitHubStack OverflowLinkedIn

Stochastic Processes in Quantitative Finance

python, quantitavie finance, scikit-learn, tensorflow, time series, machine learning, data science, kaggle7 min read

Hello World

tldr; read [press release] Quantitative Finance with Python: A Practical Guide to Investment Management, Trading, and Financial Engineering by Chris Kelliher and your head will explode too Click here to download the PDF

My new hobby is trading stocks and cryptocurrency - I fancy myself as a half-decent python programmer, so why not do something useful with it? I'm deep down the rabbit-hole now at Stochastic Differential Equations - a far cry from today's DevOps BAU. Prior to fumbling my way through Yves Hilpisch, Ernest P. Chan & Sofien Kaabar, my only reference to the word "stochastic" was a very obscure line from Season 6 of The Simpsons:

So what does "Stochastic" mean?

"Stochastic" refers to a process that involves a random or probabilistic element. In the context of stochastic processes, randomness is an inherent part of the evolution of the system over time. Stochastic models are used to represent systems where uncertainty, variability, or randomness plays a significant role.

In finance, stochastic processes are commonly employed to model the behavior of financial instruments and markets. Here are a few key ways in which stochastic processes are used in finance:

Stock Price Modeling: Stochastic processes are frequently used to model the movement of stock prices. One of the most well-known stochastic processes for this purpose is the Geometric Brownian Motion (GBM), which incorporates a random component to simulate the unpredictable nature of stock price movements.

Option Pricing: Stochastic calculus, a branch of mathematics that deals with processes evolving over time with a random component, is used extensively in the pricing of financial derivatives, such as options. The Black-Scholes-Merton model, a widely used option pricing model, employs stochastic calculus.

Interest Rate Models: Stochastic models are used to describe and predict changes in interest rates. These models are crucial in the valuation of fixed-income securities, including bonds.

Risk Management: Stochastic models are applied in risk management to assess the uncertainty and variability of financial portfolios. Monte Carlo simulation, a stochastic modeling technique, is often used to simulate various future scenarios and assess the risk associated with different outcomes.

Econometric Models: Stochastic processes are used in econometrics to model economic variables and financial time series. These models help economists and analysts understand and predict economic trends and behaviors.

Stochastic RSI

The Stochastic Relative Strength Index (Stochastic RSI) is a technical indicator that combines elements of two popular indicators: the Relative Strength Index (RSI) and the Stochastic Oscillator. It is used to identify overbought and oversold conditions in a market.

  1. Calculate the RSI: Compute the standard RSI for a given period, which measures the relative strength of the price compared to its own past performance.

  2. Apply the Stochastic Oscillator Formula to the RSI: Use the Stochastic Oscillator formula on the RSI values calculated in step 1. The Stochastic Oscillator involves two lines, %K and %D.

    • %K (Stochastic RSI): Represents the current value of the RSI in relation to its range over a specified period.
    • %D (Signal Line): A moving average of %K, often a 3-period simple moving average (SMA) of %K.

The formula for %K is usually given by: $a^2 + b^2 = c^2$

\[ \%K = \frac{{\text{{Current RSI Value}} - \text{{RSI Minimum Value over the Period}}}}{{\text{{RSI Maximum Value over the Period}} - \text{{RSI Minimum Value over the Period}}}} \times 100 \]
  1. Smooth the %K Line: Apply a moving average (commonly a 3-period SMA) to the %K line to generate the %D line.
import pandas as pd
import numpy as np
def calculate_rsi(df, column_name='Close', rsi_period=14):
# Step 1: Calculate RSI
df['rsi'] = df[column_name].diff(1)
df['rsi_gain'] = np.where(df['rsi'] > 0, df['rsi'], 0)
df['rsi_loss'] = np.where(df['rsi'] < 0, -df['rsi'], 0)
avg_gain = df['rsi_gain'].rolling(window=rsi_period, min_periods=1).mean()
avg_loss = df['rsi_loss'].rolling(window=rsi_period, min_periods=1).mean()
rs = avg_gain / avg_loss
df['rsi'] = 100 - (100 / (1 + rs))
return df
def apply_stochastic_oscillator(df, rsi_column='rsi', stoch_period=14):
# Step 2: Apply Stochastic Oscillator formula to the RSI
df['stoch_rsi'] = (df[rsi_column] - df[rsi_column].rolling(window=stoch_period).min()) / \
(df[rsi_column].rolling(window=stoch_period).max() - df[rsi_column].rolling(window=stoch_period).min())
return df
def smooth_stoch_k(df, k_column='stoch_rsi', d_period=3):
# Step 3: Smooth the %K line to get %D
df['stoch_rsi_k'] = df[k_column].rolling(window=d_period).mean()
return df
# Example for a DataFrame 'df' with a 'Close' column and a 'datetime' index
# df = ...
# Step 1: Calculate RSI
df = calculate_rsi(df)
# Step 2: Apply Stochastic Oscillator formula to the RSI
df = apply_stochastic_oscillator(df)
# Step 3: Smooth the %K line to get %D
df = smooth_stoch_k(df)
# Display the resulting DataFrame
print(df[['rsi', 'stoch_rsi', 'stoch_rsi_k']])

The Stochastic RSI generates values between 0 and 100, similar to the regular RSI. Traders and analysts use the Stochastic RSI to identify potential trend reversals or trend continuation opportunities. Readings above 80 are often considered overbought, suggesting a potential reversal to the downside, while readings below 20 are considered oversold, indicating a potential reversal to the upside.

As with any technical indicator, it's essential to use the Stochastic RSI in conjunction with other analysis tools and consider market conditions before making trading decisions.

In addition to the Stochastic RSI, there are other stochastic-based technical indicators that traders and analysts use to assess market conditions and potential price reversals. Here are a few:

Stochastic Oscillator: The classic Stochastic Oscillator measures the current closing price in relation to the high-low range over a specified period. It consists of two lines: %K and %D.

Fast Stochastic Oscillator: Similar to the Stochastic Oscillator, the Fast Stochastic uses a shorter time period for %K, making it more responsive to price changes.

Slow Stochastic Oscillator: The Slow Stochastic is a smoothed version of the Fast Stochastic, incorporating a moving average to %K, resulting in a slower-reacting indicator.

Full Stochastic Oscillator: The Full Stochastic includes a third line, %DS, which is a simple moving average of %D. It provides additional smoothing.

Williams %R: Developed by Larry Williams, this oscillator is a momentum indicator that measures overbought and oversold levels. It is essentially a reverse Stochastic Oscillator, with readings ranging from -100 to 0.

Fast %K and Slow %D: These are variations of the Stochastic Oscillator, where %K is the fast line, and %D is the slow line, similar to the Fast and Slow Stochastic Oscillators.

Relative Strength Index (RSI): While not purely stochastic, the RSI is a momentum oscillator that measures the speed and change of price movements. It is often used in conjunction with stochastic indicators.

Commodity Channel Index (CCI): Though not purely stochastic, the CCI measures the statistical variation from the average. It's used to identify overbought and oversold conditions.

Each of these indicators has its own characteristics and strengths. Traders often use a combination of indicators to get a more comprehensive view of market conditions. It's important to note that no single indicator is foolproof, and they should be used in conjunction with other forms of analysis.

Finally, a brief summary on where I'm at with Kelliher's Calculus refresher:

SDE (Stochastic Differential Equation):

A Stochastic Differential Equation (SDE) is a type of differential equation that incorporates random noise or stochastic processes. It is often used to model systems where randomness plays a significant role. In finance, SDEs are frequently employed to model the evolution of financial instruments' prices over time. The most common SDE used in finance is the geometric Brownian motion, which is a key component of the Black-Scholes-Merton model for option pricing.

The general form of a one-dimensional SDE is given by:

$$
\[dX_t = \mu(X_t, t) \, dt + \sigma(X_t, t) \, dW_t\]
$$

where:

  • (X_t) is the state variable (e.g., asset price),
  • (\mu(X_t, t)) is the drift term (deterministic component),
  • (\sigma(X_t, t)) is the diffusion term (stochastic component),
  • (dW_t) is the Wiener process (Brownian motion).

PDE (Partial Differential Equation):

A Partial Differential Equation (PDE) involves partial derivatives with respect to multiple variables. PDEs are used to describe how a quantity evolves over space and time. In finance, PDEs are commonly employed to derive pricing models for complex derivatives and to understand the evolution of financial variables in continuous time and space.

The Black-Scholes equation, which is a PDE, governs the pricing of European-style options and is derived from a geometric Brownian motion SDE. The Black-Scholes PDE is given by:

\[\frac{\partial V}{\partial t} + \frac{1}{2} \sigma^2 S^2 \frac{\partial^2 V}{\partial S^2} + rS\frac{\partial V}{\partial S} - rV = 0\]

where:

  • (V(S, t)) is the option price as a function of the underlying asset price (S) and time (t),
  • (\sigma) is the volatility of the asset,
  • (r) is the risk-free interest rate.

Share this post!

Thanks for reading! Don't forget to smash that share button and subscribe.

© 2024 by Olibyte Blog. All rights reserved.