|
| 1 | +# # Systematic short put spread example |
| 2 | +# |
| 3 | +# This example shows a simple options strategy on synthetic SPY-like data. |
| 4 | +# The strategy sells one 30-delta put and buys a lower-strike put as protection, |
| 5 | +# holds the vertical spread to cash-settled expiry, and then repeats. |
| 6 | +# |
| 7 | +# The data is a static CSV pair: daily SPY-like underlying marks and a |
| 8 | +# ThetaData-style put option quote table with bid/ask/last/delta rows. The |
| 9 | +# important Fastback pieces are: |
| 10 | +# |
| 11 | +# - listed option instruments with strikes, expiries, rights, and multipliers |
| 12 | +# - `OptionUnderlyingUpdate` for one underlying/quote chain mark |
| 13 | +# - `MarkUpdate` for bid/ask/last option marks |
| 14 | +# - multi-leg fills with option premium cash settlement |
| 15 | +# - vertical spread margin relief and cash-settled expiry processing |
| 16 | + |
| 17 | +using Fastback |
| 18 | +using Dates |
| 19 | +using CSV |
| 20 | +using DataFrames |
| 21 | +using Statistics |
| 22 | + |
| 23 | +const START_CAPITAL = 100_000.0 |
| 24 | +const CONTRACTS = 3.0 |
| 25 | +const TARGET_DELTA = 0.30 |
| 26 | +const SPREAD_WIDTH = 10.0 |
| 27 | +const ENTRY_DTE = 30 |
| 28 | +const ENTRY_GAP = 21 |
| 29 | + |
| 30 | +data_dir = joinpath(@__DIR__, "data"); |
| 31 | +market = DataFrame(CSV.File(joinpath(data_dir, "options_spy_1d.csv"); dateformat="yyyy-mm-dd")); |
| 32 | +sort!(market, :dt); |
| 33 | +option_quotes = DataFrame(CSV.File(joinpath(data_dir, "options_spy_put_quotes_1d.csv"); dateformat="yyyy-mm-dd")); |
| 34 | +sort!(option_quotes, [:dt, :expiry, :strike]); |
| 35 | + |
| 36 | +quote_by_key = Dict( |
| 37 | + (row.dt, row.expiry, row.strike) => (bid=row.bid, ask=row.ask, last=row.last) |
| 38 | + for row in eachrow(option_quotes) |
| 39 | +); |
| 40 | + |
| 41 | +function option_symbol(expiry::Date, right::Char, strike::Real) |
| 42 | + Symbol("SPY_$(Dates.format(expiry, "yyyymmdd"))_$(right)$(Int(round(strike)))") |
| 43 | +end |
| 44 | + |
| 45 | +function spy_put(expiry::Date, strike::Real) |
| 46 | + option_instrument( |
| 47 | + option_symbol(expiry, 'P', strike), |
| 48 | + :SPY, |
| 49 | + :USD; |
| 50 | + strike=Float64(strike), |
| 51 | + expiry=expiry, |
| 52 | + right=OptionRight.Put, |
| 53 | + multiplier=100.0, |
| 54 | + time_type=Date, |
| 55 | + ) |
| 56 | +end |
| 57 | + |
| 58 | +## account: margin-enabled, with IBKR Pro Fixed option commissions |
| 59 | +acc = Account(; |
| 60 | + time_type=Date, |
| 61 | + funding=AccountFunding.Margined, |
| 62 | + base_currency=CashSpec(:USD), |
| 63 | + broker=IBKRProFixedBroker(; time_type=Date), |
| 64 | +) |
| 65 | +usd = cash_asset(acc, :USD) |
| 66 | +deposit!(acc, :USD, START_CAPITAL) |
| 67 | + |
| 68 | +## data collectors |
| 69 | +collect_equity, equity_data = periodic_collector(Float64, Day(1); time_type=Date) |
| 70 | +collect_drawdown, drawdown_data = drawdown_collector(DrawdownMode.Percentage, Day(1); time_type=Date) |
| 71 | + |
| 72 | +registered_options = Instrument{Date}[] |
| 73 | +open_legs = Instrument{Date}[] |
| 74 | +entries = DataFrame( |
| 75 | + entry_dt=Date[], |
| 76 | + expiry=Date[], |
| 77 | + short_strike=Float64[], |
| 78 | + long_strike=Float64[], |
| 79 | + credit=Float64[], |
| 80 | + margin_used=Float64[], |
| 81 | +) |
| 82 | + |
| 83 | +next_entry_idx = Ref(1) |
| 84 | + |
| 85 | +for i in eachindex(market.dt) |
| 86 | + dt = market.dt[i] |
| 87 | + spot = market.spot[i] |
| 88 | + |
| 89 | + ## Mark all live options and update the option chain's underlying price. |
| 90 | + marks = MarkUpdate[] |
| 91 | + for inst in registered_options |
| 92 | + is_expired(inst, dt) && continue |
| 93 | + q = quote_by_key[(dt, inst.spec.expiry, inst.spec.strike)] |
| 94 | + push!(marks, MarkUpdate(inst.index, q.bid, q.ask, q.last)) |
| 95 | + end |
| 96 | + |
| 97 | + process_step!( |
| 98 | + acc, |
| 99 | + dt; |
| 100 | + option_underlyings=[OptionUnderlyingUpdate(:SPY, :USD, spot)], |
| 101 | + marks=marks, |
| 102 | + expiries=true, |
| 103 | + ) |
| 104 | + |
| 105 | + filter!(inst -> get_position(acc, inst).quantity != 0.0, open_legs) |
| 106 | + |
| 107 | + ## Enter one 30 DTE put credit spread at a time. |
| 108 | + if isempty(open_legs) && i >= next_entry_idx[] && i + ENTRY_DTE <= nrow(market) |
| 109 | + expiry = market.dt[i + ENTRY_DTE] |
| 110 | + chain = option_quotes[(option_quotes.dt .== dt) .& (option_quotes.expiry .== expiry) .& (option_quotes.right .== "P"), :] |
| 111 | + short_idx = argmin(abs.(abs.(chain.delta) .- TARGET_DELTA)) |
| 112 | + short_quote = chain[short_idx, :] |
| 113 | + long_idx = argmin(abs.(chain.strike .- (short_quote.strike - SPREAD_WIDTH))) |
| 114 | + long_quote = chain[long_idx, :] |
| 115 | + short_strike = Float64(short_quote.strike) |
| 116 | + long_strike = Float64(long_quote.strike) |
| 117 | + |
| 118 | + long_put = register_instrument!(acc, spy_put(expiry, long_strike)) |
| 119 | + short_put = register_instrument!(acc, spy_put(expiry, short_strike)) |
| 120 | + push!(registered_options, long_put) |
| 121 | + push!(registered_options, short_put) |
| 122 | + |
| 123 | + ## Buy the protective leg first, then sell the higher-strike put. |
| 124 | + fill_order!( |
| 125 | + acc, |
| 126 | + Order(oid!(acc), long_put, dt, long_quote.ask, CONTRACTS); |
| 127 | + dt=dt, |
| 128 | + fill_price=long_quote.ask, |
| 129 | + bid=long_quote.bid, |
| 130 | + ask=long_quote.ask, |
| 131 | + last=long_quote.last, |
| 132 | + underlying_price=spot, |
| 133 | + ) |
| 134 | + fill_order!( |
| 135 | + acc, |
| 136 | + Order(oid!(acc), short_put, dt, short_quote.bid, -CONTRACTS); |
| 137 | + dt=dt, |
| 138 | + fill_price=short_quote.bid, |
| 139 | + bid=short_quote.bid, |
| 140 | + ask=short_quote.ask, |
| 141 | + last=short_quote.last, |
| 142 | + underlying_price=spot, |
| 143 | + ) |
| 144 | + |
| 145 | + credit = (short_quote.bid - long_quote.ask) * CONTRACTS * short_put.spec.multiplier |
| 146 | + push!(entries, ( |
| 147 | + entry_dt=dt, |
| 148 | + expiry=expiry, |
| 149 | + short_strike=short_strike, |
| 150 | + long_strike=long_strike, |
| 151 | + credit=credit, |
| 152 | + margin_used=init_margin_used(acc, usd), |
| 153 | + )) |
| 154 | + push!(open_legs, long_put) |
| 155 | + push!(open_legs, short_put) |
| 156 | + next_entry_idx[] = i + ENTRY_GAP |
| 157 | + end |
| 158 | + |
| 159 | + if should_collect(equity_data, dt) |
| 160 | + equity_value = equity(acc, usd) |
| 161 | + collect_equity(dt, equity_value) |
| 162 | + collect_drawdown(dt, equity_value) |
| 163 | + end |
| 164 | +end |
| 165 | + |
| 166 | +## account and strategy summary |
| 167 | +show(acc) |
| 168 | + |
| 169 | +println("Spreads opened: ", nrow(entries)) |
| 170 | +println("Final equity: \$", round(equity(acc, usd); digits=2)) |
| 171 | +println("Maximum spread margin used: \$", round(maximum(entries.margin_used); digits=2)) |
| 172 | +println("Average entry credit: \$", round(mean(entries.credit); digits=2)) |
| 173 | + |
| 174 | +#--------------------------------------------------------- |
| 175 | + |
| 176 | +# ### Trade log sample |
| 177 | + |
| 178 | +trades = DataFrame(trades_table(acc)); |
| 179 | +trades[1:min(10, nrow(trades)), [:trade_date, :symbol, :side, :fill_price, :fill_qty, :commission_settle, :cash_delta_settle, :reason]] |
| 180 | + |
| 181 | +#--------------------------------------------------------- |
| 182 | + |
| 183 | +# ### Spread entries |
| 184 | + |
| 185 | +entries |
| 186 | + |
| 187 | +#--------------------------------------------------------- |
| 188 | + |
| 189 | +# ### Underlying and implied volatility |
| 190 | + |
| 191 | +using Plots |
| 192 | + |
| 193 | +theme(:juno); |
| 194 | + |
| 195 | +plot( |
| 196 | + market.dt, |
| 197 | + market.spot; |
| 198 | + label="SPY synthetic", |
| 199 | + ylabel="underlying price", |
| 200 | + legend=:topleft, |
| 201 | + size=(800, 360), |
| 202 | +) |
| 203 | +plot!( |
| 204 | + twinx(), |
| 205 | + market.dt, |
| 206 | + market.iv; |
| 207 | + label="implied volatility proxy", |
| 208 | + color=:orange, |
| 209 | + ylabel="IV", |
| 210 | + legend=:topright, |
| 211 | +) |
| 212 | + |
| 213 | +#--------------------------------------------------------- |
| 214 | + |
| 215 | +# ### Account equity curve |
| 216 | + |
| 217 | +Fastback.plot_equity(equity_data; size=(800, 400)) |
| 218 | + |
| 219 | +#--------------------------------------------------------- |
| 220 | + |
| 221 | +# ### Account drawdown |
| 222 | + |
| 223 | +Fastback.plot_drawdown(drawdown_data; size=(800, 220)) |
| 224 | + |
| 225 | +#--------------------------------------------------------- |
| 226 | + |
| 227 | +# ### Summary performance table |
| 228 | + |
| 229 | +DataFrame(performance_summary_table(equity_data; periods_per_year=252)) |
0 commit comments