Title: | Risk Tool Library - Trading, Risk, 'Analytics' for Commodities |
---|---|
Description: | A toolkit for Commodities 'analytics', risk management and trading professionals. Includes functions for API calls to <https://commodities.morningstar.com/#/>, <https://developer.genscape.com/>, and <https://www.bankofcanada.ca/valet/docs>. |
Authors: | Philippe Cote [aut, cre], Nima Safaian [aut] |
Maintainer: | Philippe Cote <[email protected]> |
License: | MIT + file LICENSE |
Version: | 1.3.6 |
Built: | 2024-11-23 05:35:06 UTC |
Source: | https://github.com/risktoollib/rtl |
Compute bond price, cash flow table or duration
bond(ytm = 0.05, C = 0.05, T2M = 1, m = 2, output = "price")
bond(ytm = 0.05, C = 0.05, T2M = 1, m = 2, output = "price")
ytm |
Yield to Maturity. |
C |
Coupon rate per annum. |
T2M |
Time to maturity in years. |
m |
Periods per year for coupon payments e.g semi-annual = 2. |
output |
"price", "df" or "duration". |
Returns price numeric
, cash flows tibble
, or duration numeric
Philippe Cote
bond(ytm = 0.05, C = 0.05, T2M = 1, m = 2, output = "price") bond(ytm = 0.05, C = 0.05, T2M = 1, m = 2, output = "df") bond(ytm = 0.05, C = 0.05, T2M = 1, m = 2, output = "duration")
bond(ytm = 0.05, C = 0.05, T2M = 1, m = 2, output = "price") bond(ytm = 0.05, C = 0.05, T2M = 1, m = 2, output = "df") bond(ytm = 0.05, C = 0.05, T2M = 1, m = 2, output = "duration")
Given a product group extracts all information to create SD Balances.
chart_eia_sd( market = "mogas", key = "your EIA.gov API key", from = "2011-01-01", legend.pos = list(x = 0.4, y = 0.53), output = "chart" )
chart_eia_sd( market = "mogas", key = "your EIA.gov API key", from = "2011-01-01", legend.pos = list(x = 0.4, y = 0.53), output = "chart" )
market |
"mogas", "dist", "jet" or "resid". |
key |
Your private EIA API token. |
from |
Date as character "2020-07-01". Default to all dates available. |
legend.pos |
Defaults to list(x = 0.4, y = 0.53). |
output |
"chart" for plotly object or "data" for dataframe. |
A plotly chart htmlwidget
or a tibble
.
Philippe Cote
## Not run: chart_eia_sd(key = key, market = "mogas") ## End(Not run)
## Not run: chart_eia_sd(key = key, market = "mogas") ## End(Not run)
Extract data and either plots or renders dataframe.
chart_eia_steo( market = "globalOil", key = "your EIA.gov API key", from = "2018-07-01", fig.title = "EIA STEO Global Liquids SD Balance", fig.units = "million barrels per day", legend.pos = list(x = 0.4, y = 0.53), output = "chart" )
chart_eia_steo( market = "globalOil", key = "your EIA.gov API key", from = "2018-07-01", fig.title = "EIA STEO Global Liquids SD Balance", fig.units = "million barrels per day", legend.pos = list(x = 0.4, y = 0.53), output = "chart" )
market |
"globalOil" only currently implemented. |
key |
Your private EIA API token. |
from |
Date as character "2020-07-01". Default to all dates available. |
fig.title |
Defaults to "EIA STEO Global Liquids SD Balance". |
fig.units |
Defaults to "million barrels per day" |
legend.pos |
Defaults to list(x = 0.4, y = 0.53) |
output |
"chart" for plotly object or "data" for dataframe. |
A plotly chart htmlwidget
or a tibble
.
Philippe Cote
## Not run: chart_eia_steo(key = EIAkey, market = "globalOil") ## End(Not run)
## Not run: chart_eia_steo(key = EIAkey, market = "globalOil") ## End(Not run)
Returns a plot of forward curves through time
chart_fwd_curves(df = dfwide, cmdty = "cmewti", weekly = TRUE, ...)
chart_fwd_curves(df = dfwide, cmdty = "cmewti", weekly = TRUE, ...)
df |
Wide dataframe with date column and multiple series columns (multivariate). |
cmdty |
Futures contract code in expiry_table object: unique(expiry_table$cmdty). |
weekly |
Defaults to TRUE for weekly forward curves. |
... |
other graphical parameters |
plot of forward curves through time. NULL
Philippe Cote
df <- dfwide %>% dplyr::select(date, dplyr::starts_with("CL")) %>% tidyr::drop_na() chart_fwd_curves( df = df, cmdty = "cmewti", weekly = TRUE, main = "WTI Forward Curves", ylab = "$ per bbl", xlab = "", cex = 2 )
df <- dfwide %>% dplyr::select(date, dplyr::starts_with("CL")) %>% tidyr::drop_na() chart_fwd_curves( df = df, cmdty = "cmewti", weekly = TRUE, main = "WTI Forward Curves", ylab = "$ per bbl", xlab = "", cex = 2 )
Plots pairwise scatter plots with the time dimension. Useful when exploring structural changes in timeseries properties for modeling.
chart_pairs(df = df, title = "Time Series Pairs Plot")
chart_pairs(df = df, title = "Time Series Pairs Plot")
df |
Wide data frame. |
title |
Chart title. |
A plotly object. htmlwidget
Philippe Cote
df <- dfwide %>% dplyr::select(date, CL01, NG01, HO01, RB01) %>% tidyr::drop_na() chart_pairs(df = df, title = "example")
df <- dfwide %>% dplyr::select(date, CL01, NG01, HO01, RB01) %>% tidyr::drop_na() chart_pairs(df = df, title = "example")
Multi Asset Display of Cumulative Performance and Drawdowns
chart_PerfSummary( ret = ret, geometric = TRUE, main = "Cumulative Returns and Drawdowns", linesize = 1.25 )
chart_PerfSummary( ret = ret, geometric = TRUE, main = "Cumulative Returns and Drawdowns", linesize = 1.25 )
ret |
Wide dataframe univariate or multivariate of percentage returns. |
geometric |
Use geometric returns TRUE or FALSE. |
main |
Chart title. |
linesize |
Size of lines in chart and legend. |
Cumulative performance and drawdown charts. ggplot
Philippe Cote
ret <- data.frame( date = seq.Date(Sys.Date() - 60, Sys.Date(), 1), CL01 = rnorm(61, 0, .01), RB01 = rnorm(61, 0, 0.02) ) chart_PerfSummary(ret = ret, geometric = TRUE, main = "Cumulative Returns and Drawdowns", linesize = 1.25)
ret <- data.frame( date = seq.Date(Sys.Date() - 60, Sys.Date(), 1), CL01 = rnorm(61, 0, .01), RB01 = rnorm(61, 0, 0.02) ) chart_PerfSummary(ret = ret, geometric = TRUE, main = "Cumulative Returns and Drawdowns", linesize = 1.25)
Plots specific contract pairs across years with time being days from expiry.
chart_spreads( cpairs = cpairs, daysFromExpiry = 200, from = "2012-01-01", conversion = c(1, 1), feed = "CME_NymexFutures_EOD", iuser = "[email protected]", ipassword = "pass", title = "March/April ULSD Nymex Spreads", yaxis = "$ per bbl", output = "chart" )
chart_spreads( cpairs = cpairs, daysFromExpiry = 200, from = "2012-01-01", conversion = c(1, 1), feed = "CME_NymexFutures_EOD", iuser = "[email protected]", ipassword = "pass", title = "March/April ULSD Nymex Spreads", yaxis = "$ per bbl", output = "chart" )
cpairs |
Tibble of contract pairs - see example for expiry when not expired yet. |
daysFromExpiry |
Number of days from expiry to compute spreads. |
from |
From date |
conversion |
Defaults to c(1,1) first and second contracts. 42 from $ per gallons to bbls. |
feed |
Morningstar Feed Table. |
iuser |
Morningstar user name as character - sourced locally in examples. |
ipassword |
Morningstar user password as character - sourced locally in examples. |
title |
Title for chart. |
yaxis |
y-axis label. |
output |
"chart" for |
A plotly object or a dataframe
Philippe Cote
## Not run: cpairs <- dplyr::tibble( year = c("2018", "2019", "2020","2021","2022","2023"), first = c("@HO8H", "@HO9H", "@HO0H","@HO21H","@HO22H","@HO23H"), second = c("@CL8H", "@CL9H", "@CL0H","@CL21H","@CL22H","@CL23H"), expiry = c(NA,NA,NA,NA,NA,"2023-02-23") ) chart_spreads( cpairs = cpairs, daysFromExpiry = 200, from = "2012-01-01", conversion = c(42, 1), feed = "CME_NymexFutures_EOD", iuser = "[email protected]", ipassword = "pass", title = "March/April ULSD Nymex Spreads", yaxis = "$ per bbl", output = "data" ) ## End(Not run)
## Not run: cpairs <- dplyr::tibble( year = c("2018", "2019", "2020","2021","2022","2023"), first = c("@HO8H", "@HO9H", "@HO0H","@HO21H","@HO22H","@HO23H"), second = c("@CL8H", "@CL9H", "@CL0H","@CL21H","@CL22H","@CL23H"), expiry = c(NA,NA,NA,NA,NA,"2023-02-23") ) chart_spreads( cpairs = cpairs, daysFromExpiry = 200, from = "2012-01-01", conversion = c(42, 1), feed = "CME_NymexFutures_EOD", iuser = "[email protected]", ipassword = "pass", title = "March/April ULSD Nymex Spreads", yaxis = "$ per bbl", output = "data" ) ## End(Not run)
Supports analytics and display of seasonal data. Z-Score is computed on residuals conditional on their seasonal period. Beware that most seasonal charts in industry e.g. (NG Storage) is not de-trended so results once you apply an STL decomposition will vary from the unajusted seasonal plot.
chart_zscore( df = df, title = "NG Storage Z Score", per = "yearweek", output = "zscore", chart = "seasons" )
chart_zscore( df = df, title = "NG Storage Z Score", per = "yearweek", output = "zscore", chart = "seasons" )
df |
Long data frame with columns series, date and value. |
title |
Default is a blank space returning the unique value in df$series. |
per |
Frequency of seasonality "yearweek" (DEFAULT). "yearmonth", "yearquarter" |
output |
"stl" for STL decomposition chart, "stats" for STL fitted statistics. "res" for STL fitted data. "zscore" for residuals Z-score, "seasonal" for standard seasonal chart. |
chart |
"seasons" for feasts::gg_season() (DEFAULT) "series" for feasts::gg_subseries() |
Time series of STL decomposition residuals Z-Scores, or standard seasonal chart with feast package.
Philippe Cote
## Not run: df <- eiaStocks %>% dplyr::filter(series == "NGLower48") title <- "NGLower48" chart_zscore(df = df, title = " ", per = "yearweek", output = "stl", chart = "seasons") chart_zscore(df = df, title = " ", per = "yearweek", output = "stats", chart = "seasons") chart_zscore(df = df, title = " ", per = "yearweek", output = "res", chart = "seasons") chart_zscore(df = df, title = " ", per = "yearweek", output = "zscore", chart = "seasons") chart_zscore(df = df, title = " ", per = "yearweek", output = "seasonal", chart = "seasons") ## End(Not run)
## Not run: df <- eiaStocks %>% dplyr::filter(series == "NGLower48") title <- "NGLower48" chart_zscore(df = df, title = " ", per = "yearweek", output = "stl", chart = "seasons") chart_zscore(df = df, title = " ", per = "yearweek", output = "stats", chart = "seasons") chart_zscore(df = df, title = " ", per = "yearweek", output = "res", chart = "seasons") chart_zscore(df = df, title = " ", per = "yearweek", output = "zscore", chart = "seasons") chart_zscore(df = df, title = " ", per = "yearweek", output = "seasonal", chart = "seasons") ## End(Not run)
CME WTI Calendar Month Average swap information
cma
cma
data frame
tibble
cme
European option binomial model on a stock without dividends.For academic purpose only. Use RTL::CRRoption for real-life usage.
CRReuro(S, X, sigma, r, T2M, N, type)
CRReuro(S, X, sigma, r, T2M, N, type)
S |
Stock price. |
X |
Strike price. |
sigma |
Implied volatility e.g. 0.20 |
r |
Risk-free rate. |
T2M |
Time to maturity in years |
N |
Number of time steps. Internally dt = T2M/N. |
type |
"call" or "put" |
List of asset price tree, option value tree and option price. list
Philippe Cote
CRReuro(S = 100, X = 100, sigma = 0.2, r = 0.1, T2M = 1, N = 5, type = "call")
CRReuro(S = 100, X = 100, sigma = 0.2, r = 0.1, T2M = 1, N = 5, type = "call")
Computes the price of European and American options using the Cox-Ross-Rubinstein binomial model. This function is optimized for performance and implemented in C++. Haug (2007) provides a detailed description of the model.
CRROption(S, X, sigma, r, b, T2M, N, type, optionStyle)
CRROption(S, X, sigma, r, b, T2M, N, type, optionStyle)
S |
Numeric, the current stock price (also known as the underlying asset price). |
X |
Numeric, the strike price of the option. |
sigma |
Numeric, the implied volatility of the underlying stock (annualized). |
r |
Numeric, the risk-free interest rate (annualized). |
b |
Numeric, the cost of carry, b = r - q for dividend paying assets, where q is the dividend yield rate. |
T2M |
Numeric, the time to maturity of the option (in years). |
N |
Integer, the number of time steps in the binomial tree. |
type |
Character, the type of option ("call" or "put"). |
optionStyle |
Character, the style of the option ("european" or "american"). |
A list containing the computed price of the option and a note indicating if the model is suitable for the provided parameters.
# CRROption(S = 100, X = 100, sigma = 0.25, r = 0.1, b = 0, T2M = 1, N = 500, # type = "call", optionStyle = "european") # CRROption(S = 100, X = 100, sigma = 0.25, r = 0.1, b = 0, T2M = 1, N = 500, # type = "call", optionStyle = "american")
# CRROption(S = 100, X = 100, sigma = 0.25, r = 0.1, b = 0, T2M = 1, N = 500, # type = "call", optionStyle = "european") # CRROption(S = 100, X = 100, sigma = 0.25, r = 0.1, b = 0, T2M = 1, N = 500, # type = "call", optionStyle = "american")
c1, c2, c1c2 and Cushing storage utilization
cushing
cushing
list
list
CME and EIA
Futures settlement data set.
dflong
dflong
data frame
tibble
Morningstar Commodities
Futures settlement data set.
dfwide
dfwide
data frame
tibble
Morningstar Commodities
Generates random portfolio weights statistics based on absolute returns.
efficientFrontier( nsims = 5000, x = RTL::fizdiffs %>% dplyr::select(date, dplyr::contains("WCS")), expectedReturns = NULL )
efficientFrontier( nsims = 5000, x = RTL::fizdiffs %>% dplyr::select(date, dplyr::contains("WCS")), expectedReturns = NULL )
nsims |
Number of portfolio simulations. Defaults to 5000 |
x |
List as provided by output of RTL::simMultivariates(). |
expectedReturns |
Defaults to NULL using periodic returns means. |
Unlike traditional portfolio management, in commodities many transactions are with derivatives (futures and swaps) and have zero or low initial investments.
This function is used for commodities where returns are dollars per units for real assets e.g. storage tanks, pipelines...Here we measure directly the periodic return in dollars per contract unit.
I would encourage you to pick a commodity futures contract of your choice and draw a scatter plot of price level versus the daily dollar per unit change as measure of risk. As a trading analyst or risk manager, then ask yourself about the implications of using log returns that you then re-apply to current forward curve level to arrive at a dollar risk measure per units instead of measuring directly risk in dollars per unit.
List of portfolios and chart of efficient frontier list
Philippe Cote
x = RTL::fizdiffs %>% dplyr::select(date, dplyr::contains("WCS")) efficientFrontier(nsims = 10, x = x, expectedReturns = NULL) efficientFrontier(nsims = 10, x = x, expectedReturns = c(0.5,0.8,0.9))
x = RTL::fizdiffs %>% dplyr::select(date, dplyr::contains("WCS")) efficientFrontier(nsims = 10, x = x, expectedReturns = NULL) efficientFrontier(nsims = 10, x = x, expectedReturns = c(0.5,0.8,0.9))
Extracts data from the Energy Information Administration (EIA) API to tibble format with optional custom series name. Makes a clean wrapper for use with purrr for multiple series extraction. Query Browser at https://www.eia.gov/opendata/qb.php.
eia2tidy(ticker, key, name = " ")
eia2tidy(ticker, key, name = " ")
ticker |
EIA series name. |
key |
Your private EIA API token as character "yourapikey". |
name |
Name you want to give the series. Defaults to ticker if set to " " |
A tibble object with class date for weekly, monthly, quarterly or annual data and class POSIXct for hourly. tibble
Philippe Cote
## Not run: # Single Series RTL::eia2tidy(ticker = "PET.MCRFPTX2.M", key = "yourapikey", name = "TexasProd") # Multiple Series # Use eia2tidy_all() or pivot_longer, drop_na and then pivot_wider to wrangled results. ## End(Not run)
## Not run: # Single Series RTL::eia2tidy(ticker = "PET.MCRFPTX2.M", key = "yourapikey", name = "TexasProd") # Multiple Series # Use eia2tidy_all() or pivot_longer, drop_na and then pivot_wider to wrangled results. ## End(Not run)
Extracts data from the Energy Information Administration (EIA) API to tibble format with optional custom series name. Makes a clean wrapper for use with purrr for multiple series extraction. Query Browser at https://www.eia.gov/opendata/qb.php.
eia2tidy_all( tickers = tibble::tribble(~ticker, ~name, "PET.W_EPC0_SAX_YCUOK_MBBL.W", "CrudeCushing", "NG.NW2_EPG0_SWO_R48_BCF.W", "NGLower48"), key, long = TRUE )
eia2tidy_all( tickers = tibble::tribble(~ticker, ~name, "PET.W_EPC0_SAX_YCUOK_MBBL.W", "CrudeCushing", "NG.NW2_EPG0_SWO_R48_BCF.W", "NGLower48"), key, long = TRUE )
tickers |
tribble of EIA series and names you want to assign. |
key |
Your private EIA API token as character "yourapikey". |
long |
TRUE (default) to return a long data frame or FASLE for wide. |
A tibble object with class date for weekly, monthly, quarterly or annual data and class POSIXct for hourly. tibble
Philippe Cote
## Not run: eia2tidy_all(tickers = tibble::tribble(~ticker, ~name, "PET.W_EPC0_SAX_YCUOK_MBBL.W", "CrudeCushing", "NG.NW2_EPG0_SWO_R48_BCF.W", "NGLower48"), key = "your API key", long = TRUE) ## End(Not run)
## Not run: eia2tidy_all(tickers = tibble::tribble(~ticker, ~name, "PET.W_EPC0_SAX_YCUOK_MBBL.W", "CrudeCushing", "NG.NW2_EPG0_SWO_R48_BCF.W", "NGLower48"), key = "your API key", long = TRUE) ## End(Not run)
EIA weekly crude, NG, ULSD and RBOB stocks.
eiaStocks
eiaStocks
data frame
tibble
EIA working storage capacity in kbs except NG in bcf.
eiaStorageCap
eiaStorageCap
data frame
tibble
ED futures contract for December 2024
eurodollar
eurodollar
data frame
tibble
Morningstar
This dataframe provides detailed information on major futures contracts specifications pertaining to last settlement, notices and delivery dates. It also provides tickers in some data service.
expiry_table
expiry_table
data frame
tibble
Parameter estimation for Ornstein–Uhlenbeck process using OLS
fitOU(spread, dt = 1/252)
fitOU(spread, dt = 1/252)
spread |
Spread time series. |
dt |
Time step size in fractions of a year. Default is 1/252. |
List of theta, mu, annualized sigma estimates. It returns half life consistent with periodicity list
Philippe Cote
spread <- simOU(nsims = 1, mu = 5, theta = .5, sigma = 0.2, T = 5, dt = 1 / 252) fitOU(spread = spread$sim1)
spread <- simOU(nsims = 1, mu = 5, theta = .5, sigma = 0.2, T = 5, dt = 1 / 252) fitOU(spread = spread$sim1)
Randomized data set for education purpose of selected physical crude differentials to WTI.
fizdiffs
fizdiffs
data frame
tibble
Exchange-traded contract month codes and specifications.
futuresRef
futuresRef
data frame
tibble
USDCAD historicals and forward curve
fxfwd
fxfwd
list
list
Morningstar and https://ca.investing.com/rates-bonds/forward-rates
Computes annualised Garch(1,1) volatilities using fGarch package.
garch(x = x, out = TRUE)
garch(x = x, out = TRUE)
x |
Wide dataframe with date column and single series (univariate). |
out |
"chart" to return |
replot_xts
chart, xts
data, or uGARCHfit
fit
Philippe Cote
## Not run: x <- dflong %>% dplyr::filter(series == "CL01") x <- returns(df = x, retType = "rel", period.return = 1, spread = TRUE) x <- rolladjust(x = x, commodityname = c("cmewti"), rolltype = c("Last.Trade")) summary(garch(x = x, out = "fit")) garch(x = x, out = "chart") garch(x = x, out = "data") ## End(Not run)
## Not run: x <- dflong %>% dplyr::filter(series == "CL01") x <- returns(df = x, retType = "rel", period.return = 1, spread = TRUE) x <- rolladjust(x = x, commodityname = c("cmewti"), rolltype = c("Last.Trade")) summary(garch(x = x, out = "fit")) garch(x = x, out = "chart") garch(x = x, out = "data") ## End(Not run)
Computes the price and Greeks of European call and put options using the Generalized Black-Scholes model.
GBSOption(S, X, T2M, r, b, sigma, type = "call")
GBSOption(S, X, T2M, r, b, sigma, type = "call")
S |
numeric, the current stock price (also known as the underlying asset price). |
X |
numeric, the strike price of the option. |
T2M |
numeric, the time to maturity (in years). Previously denoted as T. |
r |
numeric, the risk-free interest rate (annualized). |
b |
numeric, the cost of carry, b = r - q for dividend paying assets, where q is the dividend yield rate. |
sigma |
numeric, the volatility of the underlying asset (annualized). |
type |
character, the type of option to evaluate, either "call" or "put". Default is "call". |
A list containing the following elements:
price
: The price of the option.
delta
: The sensitivity of the option's price to a change in the
price of the underlying asset.
gamma
: The rate of change in the delta with respect to changes
in the underlying price.
vega
: The sensitivity of the option's price to the volatility of
the underlying asset.
theta
: The sensitivity of the option's price to the passage of time.
rho
: The sensitivity of the option's price to the interest rate.
GBSOption(S = 100, X = 100, T2M = 1, r = 0.05, b = 0.02, sigma = 0.2, type = "call")
GBSOption(S = 100, X = 100, T2M = 1, r = 0.05, b = 0.02, sigma = 0.2, type = "call")
Extracts series from the Bank of Canada's Valet API. API documentation at https://www.bankofcanada.ca/valet/docs.
getBoC(series)
getBoC(series)
series |
Array of series name: c("FXCADUSD","BD.CDN.2YR.DQ.YLD"). |
A long data frame. tibble
Philippe Cote
RTL::getBoC(series = c("FXCADUSD","BD.CDN.2YR.DQ.YLD"))
RTL::getBoC(series = c("FXCADUSD","BD.CDN.2YR.DQ.YLD"))
Returns forward curves from Morningstar API. See below for current feeds supported. You need your own credentials with Morningstar.
getCurve( feed = "CME_NymexFutures_EOD_continuous", contract = "CL", numOfcontracts = 12, date = "2023-08-24", fields = c("open_price, high_price, low_price, settlement_price, volume, open_interest"), iuser = "[email protected]", ipassword = "pass" )
getCurve( feed = "CME_NymexFutures_EOD_continuous", contract = "CL", numOfcontracts = 12, date = "2023-08-24", fields = c("open_price, high_price, low_price, settlement_price, volume, open_interest"), iuser = "[email protected]", ipassword = "pass" )
feed |
Morningstar Feed Table e.g "Crb_Futures_Price_Volume_And_Open_Interest". |
contract |
Morningstar contract root e.g. "CL" for CME WTI and "BG" for ICE Brent. |
numOfcontracts |
Number of listed contracts to retrieve. |
date |
Date yyyy-mm-dd. |
fields |
Defaults to c("open_price, high_price, low_price, settlement_price, volume, open_interest"). |
iuser |
Morningstar user name as character - sourced locally in examples. |
ipassword |
Morningstar user password as character - sourced locally in examples. |
wide data frame. tibble
CME_NymexFutures_EOD_continuous
Philippe Cote
## Not run: # CME WTI Futures getCurve( feed = "CME_NymexFutures_EOD_continuous", contract = "CL", date = "2023-08-24", fields = c("open_price, high_price, low_price, settlement_price, volume, open_interest"), iuser = "[email protected]", ipassword = "pass" ) ## End(Not run)
## Not run: # CME WTI Futures getCurve( feed = "CME_NymexFutures_EOD_continuous", contract = "CL", date = "2023-08-24", fields = c("open_price, high_price, low_price, settlement_price, volume, open_interest"), iuser = "[email protected]", ipassword = "pass" ) ## End(Not run)
Returns oil pipeline flows in barrels per day data from Genscape API.You need your own credentials. Refer to API documentation for argument values. It is assumed if you use this function that you know the pipelines you need to extract to build supply demand balances. Use the online API to identify the pipeline IDs. https://developer.genscape.com/docs/services/oil-transportation/operations/GetPipelineFlowValuesV2/
getGenscapePipeOil( frequency = "daily", regions = "Canada", pipelineIDs = c(97), revision = "revised", limit = 5000, offset = 0, startDate = "2015-01-01", endDate = as.character(Sys.Date()), apikey = "yourapikey" )
getGenscapePipeOil( frequency = "daily", regions = "Canada", pipelineIDs = c(97), revision = "revised", limit = 5000, offset = 0, startDate = "2015-01-01", endDate = as.character(Sys.Date()), apikey = "yourapikey" )
frequency |
"daily" DEFAULT. |
regions |
See API webpage. Multiple values separated by commas e.g. "Canada", "GulfCoast"). |
pipelineIDs |
See API webpage. c(98,54...) for specific pipes. |
revision |
See API webpage. |
limit |
See API webpage. Max 5000. |
offset |
See API webpage. |
startDate |
"yyyy-mm-dd". |
endDate |
"yyyy-mm-dd". |
apikey |
Your API key. |
wide data frame. tibble
Philippe Cote
## Not run: getGenscapePipeOil( frequency = "daily", regions = "Canada", pipelineIDs = c(97), revision = "revised", limit = 5000, offset = 0, startDate = "2015-01-01", endDate = as.character(Sys.Date()), apikey = "yourapikey" ) ## End(Not run)
## Not run: getGenscapePipeOil( frequency = "daily", regions = "Canada", pipelineIDs = c(97), revision = "revised", limit = 5000, offset = 0, startDate = "2015-01-01", endDate = as.character(Sys.Date()), apikey = "yourapikey" ) ## End(Not run)
Returns oil storage data from Genscape API.You need your own credentials. Refer to API documentation for argument values. https://developer.genscape.com/docs/services/oil-storage/operations/StorageVolumeByOwnerGet
getGenscapeStorageOil( feed = "owner-volumes", regions = "Canada", products = "Crude", revision = "revised", limit = 5000, offset = 0, startDate = "2011-01-01", endDate = as.character(Sys.Date()), apikey = "yourapikey" )
getGenscapeStorageOil( feed = "owner-volumes", regions = "Canada", products = "Crude", revision = "revised", limit = 5000, offset = 0, startDate = "2011-01-01", endDate = as.character(Sys.Date()), apikey = "yourapikey" )
feed |
"owner-volumes" DEFAULT or "tank-volumes". |
regions |
See API webpage. Multiple values separated by commas e.g. "Canada, Cushing"). |
products |
See API webpage. Multiple values separated by commas e.g. "Crude, JetFuel"). |
revision |
See API webpage. |
limit |
See API webpage. Max 5000. |
offset |
See API webpage. |
startDate |
"yyyy-mm-dd". |
endDate |
"yyyy-mm-dd". |
apikey |
Your API key as a character string. |
wide data frame tibble
Philippe Cote
## Not run: # where yourapikey = "yourapikey". getGenscapeStorageOil( feed = "owner-volumes", regions = "Canada", products = "Crude", revision = "revised", limit = 5000, offset = 0, startDate = "2011-01-01", endDate = "2020-11-01", apikey = yourapikey ) ## End(Not run)
## Not run: # where yourapikey = "yourapikey". getGenscapeStorageOil( feed = "owner-volumes", regions = "Canada", products = "Crude", revision = "revised", limit = 5000, offset = 0, startDate = "2011-01-01", endDate = "2020-11-01", apikey = yourapikey ) ## End(Not run)
Returns a SpatialPointsDataFrame from a shapefile URL. @section Examples with EIA and Government of Alberta
from https://www.eia.gov/maps/layer_info-m.php :
crudepipelines <- getGIS(url = "https://www.eia.gov/maps/map_data/CrudeOil_Pipelines_US_EIA.zip")
refineries <- getGIS(url = "https://www.eia.gov/maps/map_data/Petroleum_Refineries_US_EIA.zip")
from https://gis.energy.gov.ab.ca/Geoview/OSPNG
AB <- getGIS(url = "https://gis.energy.gov.ab.ca/GeoviewData/OS_Agreements_Shape.zip")
getGIS(url = "https://www.eia.gov/maps/map_data/CrudeOil_Pipelines_US_EIA.zip")
getGIS(url = "https://www.eia.gov/maps/map_data/CrudeOil_Pipelines_US_EIA.zip")
url |
URL of the zipped shapefile. |
SpatialPointsDataFrame. SpatialPolygonsDataFrame
Philippe Cote
## Not run: getGIS(url = "https://www.eia.gov/maps/map_data/CrudeOil_Pipelines_US_EIA.zip") ## End(Not run)
## Not run: getGIS(url = "https://www.eia.gov/maps/map_data/CrudeOil_Pipelines_US_EIA.zip") ## End(Not run)
Returns data from Morningstar API. See below for current feeds supported. You need your own credentials with Morningstar. In examples sourced locally.
getPrice( feed = "CME_NymexFutures_EOD", contract = "@CL21Z", from = "2020-09-01", iuser = "[email protected]", ipassword = "pass" )
getPrice( feed = "CME_NymexFutures_EOD", contract = "@CL21Z", from = "2020-09-01", iuser = "[email protected]", ipassword = "pass" )
feed |
Morningstar Feed Table. |
contract |
Morningstar key. |
from |
From date yyyy-mm-dd. |
iuser |
Morningstar user name as character - sourced locally in examples. |
ipassword |
Morningstar user password as character - sourced locally in examples. |
wide data frame. tibble
CME_CbotFuturesEOD and CME_CbotFuturesEOD_continuous
CME_NymexFutures_EOD, CME_NymexFuturesFinal_EOD andCME_NymexFutures_EOD_continuous
CME_NymexOptionsFinal_EOD and CME_NymexOptions_EOD
CME_CmeFutures_EOD and CME_CmeFutures_EOD_continuous
CME_Comex_FuturesSettlement_EOD and CME_Comex_FuturesSettlement_EOD_continuous
LME_AskBidPrices_Delayed
SHFE_FuturesSettlement_RT
ICE_EuroFutures and ICE_EuroFutures_continuous
ICE_NybotCoffeeSugarCocoaFutures and ICE_NybotCoffeeSugarCocoaFutures_continuous
CME_STLCPC_Futures
CFTC_CommitmentsOfTradersCombined. Requires multiple keys. Separate them by a space e.g. "N10 06765A NYME 01".
Morningstar_FX_Forwards. Requires multiple keys. Separate them by a space e.g. "USDCAD 2M".
ERCOT_LmpsByResourceNodeAndElectricalBus.
PJM_Rt_Hourly_Lmp.
AESO_ForecastAndActualPoolPrice.
Philippe Cote
## Not run: getPrice( feed = "CME_NymexFuturesFinal_EOD", contract = "CL 2024 07", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_NymexFutures_EOD", contract = "@CL21Z", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_NymexFutures_EOD_continuous", contract = "CL_006_Month", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_NymexOptionsFinal_EOD", contract = "06 2024 P LO 8000", from = "2020-03-15", iuser = username, ipassword = password ) getPrice( feed = "CME_NymexOptions_EOD", contract = "@LO21ZP4000", from = "2020-03-15", iuser = username, ipassword = password ) getPrice( feed = "CME_CbotFuturesEOD", contract = "C0Z", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_CbotFuturesEOD_continuous", contract = "ZB_001_Month", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_CmeFutures_EOD_continuous", contract = "HE_006_Month", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "Morningstar_FX_Forwards", contract = "USDCAD 2M", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_CmeFutures_EOD", contract = "LH0N", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_CmeFutures_EOD_continuous", contract = "HE_006_Month", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "ICE_EuroFutures", contract = "BRN0Z", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "ICE_EuroFutures_continuous", contract = "BRN_001_Month", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "ICE_NybotCoffeeSugarCocoaFutures", contract = "SB21H", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "ICE_NybotCoffeeSugarCocoaFutures_continuous", contract = "SF_001_Month", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "AESO_ForecastAndActualPoolPrice", contract = "Forecast_Pool_Price", from = "2021-04-01", iuser = username, ipassword = password ) getPrice( feed = "LME_MonthlyDelayed_Derived", contract = "AHD 2021-12-01 2021-12-31", from = "2021-04-01", iuser = username, ipassword = password ) ## End(Not run)
## Not run: getPrice( feed = "CME_NymexFuturesFinal_EOD", contract = "CL 2024 07", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_NymexFutures_EOD", contract = "@CL21Z", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_NymexFutures_EOD_continuous", contract = "CL_006_Month", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_NymexOptionsFinal_EOD", contract = "06 2024 P LO 8000", from = "2020-03-15", iuser = username, ipassword = password ) getPrice( feed = "CME_NymexOptions_EOD", contract = "@LO21ZP4000", from = "2020-03-15", iuser = username, ipassword = password ) getPrice( feed = "CME_CbotFuturesEOD", contract = "C0Z", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_CbotFuturesEOD_continuous", contract = "ZB_001_Month", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_CmeFutures_EOD_continuous", contract = "HE_006_Month", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "Morningstar_FX_Forwards", contract = "USDCAD 2M", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_CmeFutures_EOD", contract = "LH0N", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "CME_CmeFutures_EOD_continuous", contract = "HE_006_Month", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "ICE_EuroFutures", contract = "BRN0Z", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "ICE_EuroFutures_continuous", contract = "BRN_001_Month", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "ICE_NybotCoffeeSugarCocoaFutures", contract = "SB21H", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "ICE_NybotCoffeeSugarCocoaFutures_continuous", contract = "SF_001_Month", from = "2019-08-26", iuser = username, ipassword = password ) getPrice( feed = "AESO_ForecastAndActualPoolPrice", contract = "Forecast_Pool_Price", from = "2021-04-01", iuser = username, ipassword = password ) getPrice( feed = "LME_MonthlyDelayed_Derived", contract = "AHD 2021-12-01 2021-12-31", from = "2021-04-01", iuser = username, ipassword = password ) ## End(Not run)
Multiple Morningstar API calls using getPrice functions.
Refer to getPrices()
for list of currently supported data feeds.
getPrices( feed = "CME_NymexFutures_EOD", contracts = c("CL9Z", "CL0F", "CL0M"), from = "2019-01-01", iuser = "[email protected]", ipassword = "pass" )
getPrices( feed = "CME_NymexFutures_EOD", contracts = c("CL9Z", "CL0F", "CL0M"), from = "2019-01-01", iuser = "[email protected]", ipassword = "pass" )
feed |
Morningstar Feed Table. |
contracts |
Symbols vector. |
from |
From date yyyy-mm-dd. |
iuser |
Morningstar user name as character - sourced locally in examples. |
ipassword |
Morningstar user password as character - sourced locally in examples. |
wide data frame. tibble
Philippe Cote
## Not run: getPrices( feed = "CME_NymexFutures_EOD", contracts = c("@CL0Z", "@CL1F", "@CL21H", "@CL21Z"), from = "2020-01-01", iuser = username, ipassword = password ) ## End(Not run)
## Not run: getPrices( feed = "CME_NymexFutures_EOD", contracts = c("@CL0Z", "@CL1F", "@CL21H", "@CL21Z"), from = "2020-01-01", iuser = username, ipassword = password ) ## End(Not run)
Holiday calendars for NYMEX and ICE Brent
holidaysOil
holidaysOil
data frame
tibble
Computes NPV with discount factor interpolation. This function is used for teaching NPV and NPV at Risk and needs to be customized.
npv( init.cost = -375, C = 50, cf.freq = 0.25, TV = 250, T2M = 2, disc.factors = us.df, BreakEven = FALSE, BE.yield = 0.01 )
npv( init.cost = -375, C = 50, cf.freq = 0.25, TV = 250, T2M = 2, disc.factors = us.df, BreakEven = FALSE, BE.yield = 0.01 )
init.cost |
Initial investment cost. |
C |
Periodic cash flow. |
cf.freq |
Cash flow frequency in year fraction e.g. quarterly = 0.25. |
TV |
Terminal Value. |
T2M |
Time to Maturity in years. |
disc.factors |
Data frame of discount factors using ir.df.us() function. |
BreakEven |
TRUE when using a flat discount rate assumption. |
BE.yield |
Set the flat IR rate when BreakEven = TRUE. |
List of NPV and NPV Data frame. list
Philippe Cote
npv( init.cost = -375, C = 50, cf.freq = .5, TV = 250, T2M = 2, disc.factors = RTL::usSwapCurves, BreakEven = FALSE, BE.yield = .0399 )$npv npv( init.cost = -375, C = 50, cf.freq = .5, TV = 250, T2M = 2, disc.factors = RTL::usSwapCurves, BreakEven = FALSE, BE.yield = .0399 )$df
npv( init.cost = -375, C = 50, cf.freq = .5, TV = 250, T2M = 2, disc.factors = RTL::usSwapCurves, BreakEven = FALSE, BE.yield = .0399 )$npv npv( init.cost = -375, C = 50, cf.freq = .5, TV = 250, T2M = 2, disc.factors = RTL::usSwapCurves, BreakEven = FALSE, BE.yield = .0399 )$df
OHLC profile using historical CL 1st Contract OHLC
ohlc
ohlc
data frame
tibble
CME
Planet metrics from NASA
planets
planets
data frame
tibble
https://nssdc.gsfc.nasa.gov/planetary/factsheet/index.html
Returns betas of futures contracts versus front futures contract.
promptBeta(x = x, period = "all", betatype = "all", output = "chart")
promptBeta(x = x, period = "all", betatype = "all", output = "chart")
x |
Wide dataframe with date column and multiple series columns (multivariate). |
period |
"all" or numeric period of time in last n periods as character eg "100". |
betatype |
"all" "bull" "bear". |
output |
"betas" or "chart". |
betas data frame tibble
or plotly chart of betas htmlwidgets
Philippe Cote
## Not run: x <- dflong %>% dplyr::filter(grepl("CL",series)) %>% dplyr::mutate(series = readr::parse_number(series)) %>% dplyr::group_by(series) %>% RTL::returns(df = ., retType = "abs",period.return = 1,spread = TRUE) %>% RTL::rolladjust(x = .,commodityname = c("cmewti"),rolltype = c("Last.Trade")) %>% # removing the day it prices went negative... dplyr::filter(!date %in% c(as.Date("2020-04-20"),as.Date("2020-04-21"))) promptBeta(x = x, period = "all", betatype = "all", output = "chart") promptBeta(x = x, period = "all", betatype = "bull", output = "betas") promptBeta(x = x, period = "100", betatype = "bear", output = "betas") ## End(Not run)
## Not run: x <- dflong %>% dplyr::filter(grepl("CL",series)) %>% dplyr::mutate(series = readr::parse_number(series)) %>% dplyr::group_by(series) %>% RTL::returns(df = ., retType = "abs",period.return = 1,spread = TRUE) %>% RTL::rolladjust(x = .,commodityname = c("cmewti"),rolltype = c("Last.Trade")) %>% # removing the day it prices went negative... dplyr::filter(!date %in% c(as.Date("2020-04-20"),as.Date("2020-04-21"))) promptBeta(x = x, period = "all", betatype = "all", output = "chart") promptBeta(x = x, period = "all", betatype = "bull", output = "betas") promptBeta(x = x, period = "100", betatype = "bear", output = "betas") ## End(Not run)
Plain vanilla refinery optimization LP model.
refineryLP( crudes = RTL::refineryLPdata$inputs, products = RTL::refineryLPdata$outputs )
refineryLP( crudes = RTL::refineryLPdata$inputs, products = RTL::refineryLPdata$outputs )
crudes |
Data frame of crude inputs. |
products |
Data frame of product outputs and max outputs. |
Optimal crude slate and profits. tibble
Philippe Cote
refineryLP(crudes = RTL::refineryLPdata$inputs, products = RTL::refineryLPdata$outputs)
refineryLP(crudes = RTL::refineryLPdata$inputs, products = RTL::refineryLPdata$outputs)
Simple refinery to be used in running LP modeling for education purposes.
refineryLPdata
refineryLPdata
list
list
Computes periodic returns from a dataframe ordered by date
returns(df = dflong, retType = "abs", period.return = 1, spread = FALSE)
returns(df = dflong, retType = "abs", period.return = 1, spread = FALSE)
df |
Long dataframe with colnames = c("date","value","series"). |
retType |
"abs" for absolute, "rel" for relative, or "log" for log returns. |
period.return |
Number of rows over which to compute returns. |
spread |
TRUE if you want to spread into a long dataframe. |
A dataframe object of returns. tibble
Philippe Cote
x <- dflong %>% dplyr::filter(grepl("CL01", series)) returns(df = x, retType = "abs", period.return = 1, spread = TRUE)
x <- dflong %>% dplyr::filter(grepl("CL01", series)) returns(df = x, retType = "abs", period.return = 1, spread = TRUE)
Returns a xts price or return object adjusted for contract roll. The methodology used to adjust returns is to remove the daily returns on the day after expiry and for prices to adjust historical rolling front month contracts by the size of the roll at each expiry. This is conducive to quantitative trading strategies as it reflects the PL of a financial trader.
rolladjust(x, commodityname = c("cmewti"), rolltype = c("Last.Trade"), ...)
rolladjust(x, commodityname = c("cmewti"), rolltype = c("Last.Trade"), ...)
x |
A df of returns. |
commodityname |
Name of commodity in expiry_table: unique(expiry_table$cmdty) or "cmecan" for WCW |
rolltype |
Type of contract roll: "Last.Trade" or "First.Notice". |
... |
Other parms |
Roll-adjusted xts object of returns
Philippe Cote
ret <- dplyr::tibble(date = seq.Date(Sys.Date() - 60, Sys.Date(), 1), CL01 = rnorm(61, 0, 1)) rolladjust(x = ret, commodityname = c("cmewti"), rolltype = c("Last.Trade"))
ret <- dplyr::tibble(date = seq.Date(Sys.Date() - 60, Sys.Date(), 1), CL01 = rnorm(61, 0, 1)) rolladjust(x = ret, commodityname = c("cmewti"), rolltype = c("Last.Trade"))
Simulates a Geometric Brownian Motion process
simGBM( nsims = 1, S0 = 10, drift = 0, sigma = 0.2, T2M = 1, dt = 1/12, vec = TRUE )
simGBM( nsims = 1, S0 = 10, drift = 0, sigma = 0.2, T2M = 1, dt = 1/12, vec = TRUE )
nsims |
number of simulations. Defaults to 1. |
S0 |
Spot price at t=0. |
drift |
Drift term in percentage. |
sigma |
Standard deviation. |
T2M |
Maturity in years. |
dt |
Time step in period e.g. 1/250 = 1 business day. |
vec |
Vectorized implementation. Defaults to TRUE. |
A tibble of simulated values. tibble
Philippe Cote
simGBM(nsims = 2, S0 = 10, drift = 0, sigma = 0.2, T2M = 1, dt = 1 / 12, vec = TRUE)
simGBM(nsims = 2, S0 = 10, drift = 0, sigma = 0.2, T2M = 1, dt = 1 / 12, vec = TRUE)
Generates multivariate random epsilons using absolute returns.
simMultivariates(nsims = 10, x, s0 = NULL)
simMultivariates(nsims = 10, x, s0 = NULL)
nsims |
Number of simulations. Defaults to 10. |
x |
Wide data frame of prices with date as first column. |
s0 |
Vector of starting value for each variables. Defaults to NULL with zero. |
List of means, sds, covariance matrix, correlation matrix and simulated values. list
Philippe Cote
simMultivariates(nsims = 10, x = RTL::fizdiffs, s0 = NULL)
simMultivariates(nsims = 10, x = RTL::fizdiffs, s0 = NULL)
Simulates a Ornstein–Uhlenbeck process
simOU( nsims = 2, S0 = 5, mu = 5, theta = 0.5, sigma = 0.2, T2M = 1, dt = 1/12, epsilon = NULL )
simOU( nsims = 2, S0 = 5, mu = 5, theta = 0.5, sigma = 0.2, T2M = 1, dt = 1/12, epsilon = NULL )
nsims |
number of simulations. Defaults to 2. |
S0 |
S at t=0. |
mu |
Mean reversion level. |
theta |
Mean reversion speed. |
sigma |
Standard deviation. |
T2M |
Maturity in years. |
dt |
Time step size e.g. 1/250 = 1 business day. |
epsilon |
Defaults to NULL function generates its own. |
Simulated values. tibble
Philippe Cote
simOU(nsims = 5, S0 = 5, mu = 5, theta = .5, sigma = 0.2, T2M = 1, dt = 1 / 12, epsilon = NULL) simOU(nsims = 1, S0 = 5, mu = 5, theta = .5, sigma = 0.2, T2M = 1, dt = 1 / 12, epsilon = matrix(rnorm(12,0,sqrt(1/12)))) simOU(nsims = 2, S0 = 5, mu = 5, theta = .5, sigma = 0.2, T2M = 1, dt = 1 / 12, epsilon = replicate(2,rnorm(12,0,sqrt(1/12))))
simOU(nsims = 5, S0 = 5, mu = 5, theta = .5, sigma = 0.2, T2M = 1, dt = 1 / 12, epsilon = NULL) simOU(nsims = 1, S0 = 5, mu = 5, theta = .5, sigma = 0.2, T2M = 1, dt = 1 / 12, epsilon = matrix(rnorm(12,0,sqrt(1/12)))) simOU(nsims = 2, S0 = 5, mu = 5, theta = .5, sigma = 0.2, T2M = 1, dt = 1 / 12, epsilon = replicate(2,rnorm(12,0,sqrt(1/12))))
Simulates a Ornstein–Uhlenbeck process with Jumps
simOUJ( nsims = 2, S0 = 5, mu = 5, theta = 10, sigma = 0.2, jump_prob = 0.05, jump_avesize = 2, jump_stdv = 0.05, T2M = 1, dt = 1/250 )
simOUJ( nsims = 2, S0 = 5, mu = 5, theta = 10, sigma = 0.2, jump_prob = 0.05, jump_avesize = 2, jump_stdv = 0.05, T2M = 1, dt = 1/250 )
nsims |
number of simulations. Defaults to 2. |
S0 |
S at t=0. |
mu |
Mean reversion level. |
theta |
Mean reversion speed. |
sigma |
Standard deviation. |
jump_prob |
Probability of jumps. |
jump_avesize |
Average size of jumps. |
jump_stdv |
Standard deviation of jump average size. |
T2M |
Maturity in years. |
dt |
Time step size e.g. 1/250 = 1 business day. |
Simulated values. tibble
Philippe Cote
simOUJ(nsims = 2, S0 = 5, mu = 5, theta = .5, sigma = 0.2, jump_prob = 0.05, jump_avesize = 3, jump_stdv = 0.05, T2M = 1, dt = 1 / 12)
simOUJ(nsims = 2, S0 = 5, mu = 5, theta = .5, sigma = 0.2, jump_prob = 0.05, jump_avesize = 3, jump_stdv = 0.05, T2M = 1, dt = 1 / 12)
Simulates a Ornstein–Uhlenbeck process with mu as a function of time
simOUt( nsims = 2, S0 = 0, mu = dplyr::tibble(t = 0:20, mr = c(rep(2, 7), rep(4, 14))), theta = 12, sigma = 0.2, T2M = 1, dt = 1/12 )
simOUt( nsims = 2, S0 = 0, mu = dplyr::tibble(t = 0:20, mr = c(rep(2, 7), rep(4, 14))), theta = 12, sigma = 0.2, T2M = 1, dt = 1/12 )
nsims |
number of simulations. Defaults to 2. |
S0 |
S at t=0. |
mu |
data frame of mean reversion level as a function of time. |
theta |
Mean reversion speed. |
sigma |
Standard deviation. |
T2M |
Maturity in years. |
dt |
Time step size e.g. 1/250 = 1 business day. |
Simulated values. tibble
Philippe Cote
mu = dplyr::tibble(t = 0:20,mr = c(rep(2,7),rep(4,14))) simOUt(nsims = 2, S0 = 5, mu = mu, theta = .5, sigma = 0.2, T2M = 1, dt = 1 / 12)
mu = dplyr::tibble(t = 0:20,mr = c(rep(2,7),rep(4,14))) simOUt(nsims = 2, S0 = 5, mu = mu, theta = .5, sigma = 0.2, T2M = 1, dt = 1 / 12)
Cash and futures
spot2futConvergence
spot2futConvergence
data frame
tibble
Morningstar, EIA
Forward Curve
spot2futCurve
spot2futCurve
data frame
tibble
Morningstar, EIA
Short Term Energy Outlook from the EIA.
steo
steo
plotly object
htmlwidget
eia
Traded equity prices and returns
stocks
stocks
list
list
Yahoo Finance
Commodity swap pricing from exchange settlement
swapCOM( futures = futs, futuresNames = c("CL0M", "CL0N"), pricingDates = c("2020-05-01", "2020-05-30"), contract = "cmewti", exchange = "nymex" )
swapCOM( futures = futs, futuresNames = c("CL0M", "CL0N"), pricingDates = c("2020-05-01", "2020-05-30"), contract = "cmewti", exchange = "nymex" )
futures |
Wide data frame of futures prices for the given swap pricing dates. |
futuresNames |
Tickers of relevant futures contracts. |
pricingDates |
Vector of start and end pricing dates. See example. |
contract |
Contract code in data(expiry_table). sort(unique(expiry_table$cmdty)) for options. |
exchange |
Exchange code in data(holidaysOil). Currently only "nymex" and "ice" supported. |
Data frame of histocial swap prices. tibble
Philippe Cote
## Not run: c <- paste0("CL0", c("M", "N", "Q")) futs <- getPrices( feed = "CME_NymexFutures_EOD", contracts = c, from = "2019-08-26", iuser = username, ipassword = password ) swapCOM( futures = futs, futuresNames = c("CL0M", "CL0N"), pricingDates = c("2020-05-01", "2020-05-30"), contract = "cmewti", exchange = "nymex" ) ## End(Not run)
## Not run: c <- paste0("CL0", c("M", "N", "Q")) futs <- getPrices( feed = "CME_NymexFutures_EOD", contracts = c, from = "2019-08-26", iuser = username, ipassword = password ) swapCOM( futures = futs, futuresNames = c("CL0M", "CL0N"), pricingDates = c("2020-05-01", "2020-05-30"), contract = "cmewti", exchange = "nymex" ) ## End(Not run)
Returns the percentage weight of the future in Calendar Month Average swaps
swapFutWeight( Month = "2020-09-01", contract = "cmewti", exchange = "nymex", output = "first.fut.weight" )
swapFutWeight( Month = "2020-09-01", contract = "cmewti", exchange = "nymex", output = "first.fut.weight" )
Month |
First calendar day of the month. |
contract |
Contract code in data(expiry_table). sort(unique(expiry_table$cmdty)) for options. |
exchange |
Exchange code in data(holidaysOil). Currently only "nymex" and "ice" supported. |
output |
Either "numDaysFut1", "numDaysFut2" or "first.fut.weight". |
Depending on output setting. numeric
If first.fut.weight, to compute swap 1 - first.fut.weight = % applied to 2nd line contract.
Philippe Cote
swapFutWeight( Month = "2020-09-01", contract = "cmewti", exchange = "nymex", output = "first.fut.weight" )
swapFutWeight( Month = "2020-09-01", contract = "cmewti", exchange = "nymex", output = "first.fut.weight" )
Returns dataframe required to price a WTI averaging instrument based on first line settlements.
swapInfo( date = "2023-08-24", feed = "CME_NymexFutures_EOD_continuous", ticker = "CL", contract = "cmewti", exchange = "nymex", iuser = "[email protected]", ipassword = "pass", output = "all" )
swapInfo( date = "2023-08-24", feed = "CME_NymexFutures_EOD_continuous", ticker = "CL", contract = "cmewti", exchange = "nymex", iuser = "[email protected]", ipassword = "pass", output = "all" )
date |
Character date as of which you want to extract daily settlement and forward values. |
feed |
Feeds for Morningstar getCurve() and getPrice(). |
ticker |
Nymex contract code. |
contract |
Contract code in data(expiry_table). sort(unique(expiry_table$cmdty)) for options. |
exchange |
Exchange code in data(holidaysOil). Defaults to "nymex". |
iuser |
Morningstar user name as character - sourced locally in examples. |
ipassword |
Morningstar user password as character - sourced locally in examples. |
output |
"chart" or "all". |
Plot or a list of data frame and plot if output = "all". htmlwidget
or list
Philippe Cote
## Not run: swapInfo( date = "2020-05-06", feed = "CME_NymexFutures_EOD_continuous", ticker = "CL", contract = "cmewti", exchange = "nymex", iuser = "[email protected]", ipassword = "pass", output = "all" ) ## End(Not run)
## Not run: swapInfo( date = "2020-05-06", feed = "CME_NymexFutures_EOD_continuous", ticker = "CL", contract = "cmewti", exchange = "nymex", iuser = "[email protected]", ipassword = "pass", output = "all" ) ## End(Not run)
Computes the mark to market of an IRS
swapIRS( trade.date = lubridate::today(), eff.date = lubridate::today() + 2, mat.date = lubridate::today() + 2 + lubridate::years(2), notional = 1e+06, PayRec = "Rec", fixed.rate = 0.05, float.curve = usSwapCurves, reset.freq = 3, disc.curve = usSwapCurves, convention = c("act", 360), bus.calendar = "NY", output = "price" )
swapIRS( trade.date = lubridate::today(), eff.date = lubridate::today() + 2, mat.date = lubridate::today() + 2 + lubridate::years(2), notional = 1e+06, PayRec = "Rec", fixed.rate = 0.05, float.curve = usSwapCurves, reset.freq = 3, disc.curve = usSwapCurves, convention = c("act", 360), bus.calendar = "NY", output = "price" )
trade.date |
Date object. Defaults to today(). |
eff.date |
Date object. Defaults to today() + 2 days. |
mat.date |
Date object. Defaults to today() + 2 years. |
notional |
Numeric value of notional. Defaults to 1,000,000. |
PayRec |
"Pay" or "Rec" fixed. |
fixed.rate |
Numeric fixed interest rate. Defaults to 0.05. |
float.curve |
List of interest rate curves. Defaults to data("usSwapCurves"). |
reset.freq |
Numeric where 1 = "monthly", 3 = quarterly, 6 = Semi annual 12 = yearly. |
disc.curve |
List of interest rate curves. Defaults to data("usSwapCurves"). |
convention |
Vector of convention e.g. c("act",360) c(30,360),... |
bus.calendar |
Banking day calendar. Not implemented. |
output |
"price" for swap price or "all" for price, cash flow data frame, duration. |
List of swap price, cash flow data frame, duration. list
Philippe Cote
data("usSwapCurves") swapIRS( trade.date = as.Date("2020-01-04"), eff.date = as.Date("2020-01-06"), mat.date = as.Date("2022-01-06"), notional = 1000000, PayRec = "Rec", fixed.rate = 0.05, float.curve = usSwapCurves, reset.freq = 3, disc.curve = usSwapCurves, convention = c("act", 360), bus.calendar = "NY", output = "all" )
data("usSwapCurves") swapIRS( trade.date = as.Date("2020-01-04"), eff.date = as.Date("2020-01-06"), mat.date = as.Date("2022-01-06"), notional = 1000000, PayRec = "Rec", fixed.rate = 0.05, float.curve = usSwapCurves, reset.freq = 3, disc.curve = usSwapCurves, convention = c("act", 360), bus.calendar = "NY", output = "all" )
Supports automated upload of EIA data through its API by categories. Data frame organized by Supply Demand categories and products.
tickers_eia
tickers_eia
data frame
tibble
Crude Trading Trade Cycles. Note that is uses NYMEX calendar (WIP)
tradeCycle
tradeCycle
data frame
tibble
Trading Hubs
tradeHubs
tradeHubs
data frame
tibble
Data set for explaining the various ways to monetize a market view.
tradeprocess
tradeprocess
data frame
tibble
Compute list of risk reward metrics
tradeStats(x, Rf = 0)
tradeStats(x, Rf = 0)
x |
Univariate xts object of returns OR dataframe with date and return variables. |
Rf |
Risk-free rate. |
List of risk/reward metrics. list
Philippe Cote
library(PerformanceAnalytics) tradeStats(x = stocks$spy, Rf = 0)
library(PerformanceAnalytics) tradeStats(x = stocks$spy, Rf = 0)
Based on dividend yield.
tradeStrategyDY(data, par1value = 50, par2value = 200)
tradeStrategyDY(data, par1value = 50, par2value = 200)
data |
Dataframe of OHLC data e.g. RTL::uso. |
par1value |
Value of first parameter e.g. short MA. |
par2value |
Value of second parameter e.g. long MA. |
Dataframe with indicators, signals, trades and profit and loss. tibble
Philippe Cote
tradeStrategyDY(data = RTL::stocks$ry, par1value = 50, par2value = 200)
tradeStrategyDY(data = RTL::stocks$ry, par1value = 50, par2value = 200)
Moving average crossover strategy
tradeStrategySMA(data = RTL::stocks$uso, par1value = 50, par2value = 200)
tradeStrategySMA(data = RTL::stocks$uso, par1value = 50, par2value = 200)
data |
Dataframe of OHLC data e.g. RTL::uso. |
par1value |
Value of first parameter e.g. short MA. |
par2value |
Value of second parameter e.g. long MA. |
Dataframe with indicators, signals, trades and profit and loss. tibble
Philippe Cote
tradeStrategySMA(data = RTL::stocks$uso, par1value = 50, par2value = 200)
tradeStrategySMA(data = RTL::stocks$uso, par1value = 50, par2value = 200)
USD IR curve input for RQuantlib::DiscountCurve
tsQuotes
tsQuotes
data frame
tibble
USD IR Discount, Forward and Zero curves from RQuantlib::DiscountCurve
usSwapCurves
usSwapCurves
List
list
Morningstar and FRED
USD IR Discount, Forward and Zero curves from RQuantlib::DiscountCurve - Parallel toy data set
usSwapCurvesPar
usSwapCurvesPar
data frame
tibble
WTI Crude futures
wtiSwap
wtiSwap
data frame
tibble
Morningstar