Skip to content

Instantly share code, notes, and snippets.

Maturity Spot_Rate
1 0.01
2 0.012
3 0.014
4 0.016
5 0.018
6 0.02
7 0.022
8 0.024
9 0.026
@fyyying
fyyying / koalas_forward_rate.py
Last active May 23, 2020 13:35
Calculate forward rate with koalas
# Implementation with Koalas
import databricks.koalas as ks
# Read in the data from csv
data = ks.read_csv(rate_path)
# Shift the spot rate down along the maturity axis and calculate forward rate
data["Spot_Rate_Shift"] = data["Spot_Rate"].shift(1, fill_value=0)
data["Forward_Rate"] = (((1 + data["Spot_Rate"]) ** data["Maturity"]) /
((1 + data["Spot_Rate_Shift"]) ** (data["Maturity"] - 1)) - 1)
Maturity Spot_Rate Currency Spot_Rate_Shift Forward_Rate
1 0.01 USD 0.0 0.01
2 0.012 USD 0.01 0.014
3 0.014 USD 0.012 0.018
4 0.016 USD 0.014 0.022
5 0.018 USD 0.016 0.026
6 0.02 USD 0.018 0.03
7 0.022 USD 0.02 0.034
8 0.024 USD 0.022 0.038
9 0.026 USD 0.024 0.042
# Implementation with PySpark
from pyspark.sql import SparkSession
from pyspark.sql import Window
from pyspark.sql import functions as f
# Define Spark settings
builder = SparkSession.builder.appName("Forward_Rate_Calculation")
spark = builder.getOrCreate()
# Read in the spot rate data as csv
# Implementation with PySpark
from pyspark.sql import SparkSession
from pyspark.sql import Window
from pyspark.sql import functions as f
# Define Spark settings
builder = SparkSession.builder.appName("Koalas")
spark = builder.getOrCreate()
# Read in the spot rate data
Maturity Spot_Rate Spot_Rate_Shift
1 0.01 0.0
2 0.012 0.01
3 0.014 0.012
4 0.016 0.014
5 0.018 0.016
6 0.02 0.018
7 0.022 0.02
8 0.024 0.022
9 0.026 0.024
@fyyying
fyyying / pandas_forward_rate.py
Last active May 23, 2020 17:21
Calculate forward rate with Pandas #forward_rate
# Implementation with Pandas
import pandas as pd
# Read in the data from csv
data = pd.read_csv(rate_path)
# Shift the spot rate down along the maturity axis and calculate forward rate
data["Spot_Rate_Shift"] = data["Spot_Rate"].shift(1, fill_value=0)
data["Forward_Rate"] = (((1 + data["Spot_Rate"]) ** data["Maturity"]) /
((1 + data["Spot_Rate_Shift"]) ** (data["Maturity"] - 1)) - 1)
Maturity Spot_Rate Currency
1 0.010 USD
2 0.012 USD
3 0.014 USD
4 0.016 USD
5 0.018 USD
6 0.020 USD
7 0.022 USD
8 0.024 USD
9 0.026 USD

Calculate forward rate

Formula to calculate forward rate from spot rate