Skip to content

Instantly share code, notes, and snippets.

@chunsj
Created January 14, 2021 05:52
Show Gist options
  • Save chunsj/043e151b8bd4d997768f52062c580717 to your computer and use it in GitHub Desktop.
Save chunsj/043e151b8bd4d997768f52062c580717 to your computer and use it in GitHub Desktop.
Computes weights to make similar amounts
(defun weighting/same (prices)
"returns integral weights to make similar amounts"
(labels ((dp (&rest args)
(let ((ns (mapcar #'round args)))
(if (> ($sum (mapcar (lambda (n) (if (<= n 0) 1 0)) ns)) 0)
most-positive-single-float
(let ((vals (mapcar (lambda (price n) (* n price)) prices ns)))
(loop :for v :in vals
:summing ($sum (mapcar (lambda (u) ($square (- u v))) vals))))))))
(multiple-value-bind (weights dp)
(th.pp::nelder-mead #'dp (loop :repeat ($count prices) :collect 1))
(values (mapcar #'round ($list weights)) (sqrt dp)))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment