Skip to content

Instantly share code, notes, and snippets.

View pteetor's full-sized avatar

Paul Teetor pteetor

View GitHub Profile
@pteetor
pteetor / operators.R
Created July 1, 2022 20:39
Handy R operators
#'
#' Default value for `NULL`
#'
#' This infix function makes it easy to replace `NULL`s with a default
#' value. It's inspired by the way that Ruby's or operation (`||`)
#' works.
#'
#' @param x,y If `x` is NULL, will return `y`; otherwise returns `x`.
#' @export
#' @name op-null-default
@pteetor
pteetor / declare.R
Created July 1, 2022 20:28
Simple type checking for R parameters
#'
#' Type-check a function parameter
#'
#' Stops if variable type is wrong.
#'
#' \code{decl} is a simple, fast type checker,
#' and should be used when speed matters,
#' such as in low-level functions.
#' \code{declare} is more powerful and implements
#' a convenient syntax for richer types.
@pteetor
pteetor / fatal.R
Created July 1, 2022 11:53
R functions for reporting fatal errors
#' @export
fatal = function(..., sep = " ", caller = NULL) {
caller <- caller %||% as.list(sys.call(-1))[[1]]
msg <- paste0("[", caller, "] ", paste(..., sep = sep))
stop(msg, call. = FALSE)
}
#' @export
fatalIf = function(cond, ..., caller = NULL) {
if (cond) {
@pteetor
pteetor / barrier-breach-simulation.Rmd
Created June 10, 2022 16:55
Estimate barrier breach probabilities via simulation, coded into an RMarkdown document
---
title: "Barrier Breach Simulation"
author: "Paul Teetor"
date: "June 2022"
output: html_document
params:
annualVol: 0.20
annualDrift: 0.0
term: 30 # In days
startPrice: 100
@pteetor
pteetor / ar1-residuals.R
Created November 3, 2021 12:18
Demonstration of bootstrapping the residuals of an AR(1) time series model
#
# Demonstration of bootstrapping AR(1) residuals,
# using the AirPassergers data.
#
# This code performs a simple bootstrap, not a
# block bootstrap, because it assumes the model's residuals
# are independent. If your residuals exhibit autocorrelation,
# then a block bootstrap would be more appropriate.
# (However, if your residuals *do* show autocorrelation,
# then your time series model needs improvement.)
#
# One-factor model of spread using DLM package
#
# Model in discrete form:
#
# y[t] = a + b*s[t] + u[t]
# s[t] = c*s[t-1] + v[t]
#
# Model in matrix form:
#
@pteetor
pteetor / toyApp.R
Created November 20, 2015 14:01
Splitting an R application into modular parts
#
# This is a toy example of splitting an R application
# into three distinct parts:
#
# - Loading the data
# - Calculating the analytics
# - Rendering an RMarkdown document
#
# Note: The RMarkdown doc appears in a companion file, toyDoc.Rmd.
#