Skip to content

Instantly share code, notes, and snippets.

@nathanvy
Created October 18, 2024 20:59
Show Gist options
  • Save nathanvy/947bd837fff9770c22c00d38eb97415e to your computer and use it in GitHub Desktop.
Save nathanvy/947bd837fff9770c22c00d38eb97415e to your computer and use it in GitHub Desktop.
Sharpe Ratio and related calculations.
(defun mean (sequence)
(/ (reduce #'+ sequence) (length sequence)))
(defun variance (sequence)
(let ((m (mean sequence))
(n (length sequence)))
(/ (reduce #'+ (map 'vector (lambda (x) (expt (- x m) 2)) sequence))
(length sequence))))
(defun std-dev (sequence)
(sqrt (variance sequence)))
;; in which we assume RETURNS is a vector of double floats
(defun sharpe-ratio (returns &optional (rfree 0.02))
(when (zerop (length returns))
(return-from sharpe-ratio 0))
(let ((mean-return (mean returns))
(sd (std-dev returns)))
(when (zerop sd)
(return-from sharpe-ratio 0))
(/ (- mean-return rfree) sd)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment