Skip to content

Instantly share code, notes, and snippets.

@dvliman
Last active July 27, 2025 15:50
Show Gist options
  • Save dvliman/90e5ea1f35a745bc11d479e788d72073 to your computer and use it in GitHub Desktop.
Save dvliman/90e5ea1f35a745bc11d479e788d72073 to your computer and use it in GitHub Desktop.
(weekly-csp
(->> (accounts)
first
:securitiesAccount
:currentBalances
:buyingPowerNonMarginableTrade)
["HOOD" "COIN" "TSM"])
{:high ["HOOD" 104.85 105.0 4.97 2 1416],
:low ["HOOD" 104.85 104.0 4.45 2 1277],
:pairs (["HOOD" 104.85 104.0 4.45 2 1277]
["HOOD" 104.85 105.0 4.97 2 1416]
["COIN" 391.66 390.0 14.28 0 1085]
["COIN" 391.66 392.5 15.63 0 1187]
["TSM" 245.6 245.0 3.68 1 448]
["TSM" 245.6 247.5 4.97 1 596])}
(defn accounts []
(format-response
(http/get
(str schwab-base-url "trader/v1/accounts")
{:headers {"Authorization" (str "Bearer " (:access_token @tokens))}
:throw-exceptions false
:as :json})))
(defn chains [symbol opts]
(format-response
(http/get
(str schwab-base-url "marketdata/v1/chains?"
(codec/form-encode
(into {:symbol symbol} (remove (comp nil? val) opts))))
{:headers {"Authorization" (str "Bearer " (:access_token @tokens))}
:throw-exceptions false
:as :json})))
(defn csp [symbol]
(->>
(chains symbol {:fromDate (next-friday)
:toDate (next-friday)
:contractType "PUT"
:strikeCount 2})
((juxt
:symbol
:underlyingPrice
(comp
(partial map #(select-keys % [:strikePrice :mark]))
(partial map first)
vals
first
vals
:putExpDateMap)))))
(defn weekly-csp [balance symbols]
(let [pairs
(->> symbols
(map csp)
(mapcat
(fn [[symbol underlying rows]]
(map (fn [{:keys [strikePrice mark]}]
[symbol
underlying
strikePrice
mark
(int (/ balance (* strikePrice 100))) ;; shares
(int (* (int (/ balance strikePrice)) mark)) ;; profit $
])rows))))
lows (->> pairs (map-indexed vector) (filter (fn [[i _]] (even? i))) (map second))
highs (->> pairs (map-indexed vector) (filter (fn [[i _]] (odd? i))) (map second))
best-profit (fn [rows]
(apply max-key #(nth % 5) rows))]
{:low (best-profit lows)
:high (best-profit highs)
:pairs pairs}))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment