Skip to content

Instantly share code, notes, and snippets.

@crapher
Created February 18, 2020 01:21
Show Gist options
  • Save crapher/4515259bd4c0f613bf7008376544c5af to your computer and use it in GitHub Desktop.
Save crapher/4515259bd4c0f613bf7008376544c5af to your computer and use it in GitHub Desktop.
All available long butterfly put spreads
import yfinance as yf
import math
stock = yf.Ticker("MSFT") # Get ticker
expiration = stock.options[0] # Get next expiration date
opt = stock.option_chain(expiration) # Get the option chain
options = opt.puts # Get options
for idx_body, body in options.iterrows(): # Iterate over all options
left_wings = options[options['strike'] < body['strike']] # Get left wings
right_wings = options[options['strike'] > body['strike']] # Get right wings
for idx_left, left in left_wings.iterrows(): # Iterate over left wings
for idx_right, right in right_wings.iterrows(): # Iterate over right wings
left_count = round(right['strike'] - body['strike'], 2) * 1000 # Left raw wing count
right_count = round(body['strike'] - left['strike'], 2) * 1000 # Right raw wing count
body_count = round(left_count + right_count, 2) # Body raw count
if (left_count == int(left_count) and right_count == int(right_count) and body_count == int(body_count)): # If there is a integer number of contracts try to minimize the quantity
gcd = math.gcd(math.gcd(int(left_count), int(body_count)), int(right_count)) # Greated Common Divisor between the number of contracts
left_count /= gcd
right_count /= gcd
body_count /= gcd
if left_count <= 10 and body_count <= 10 and right_count <= 10: # Filter all the butterflies with less than 10 contracts
print("Buy %d Contract (Strike %.2f) - Sell %d Contract (Strike %.2f) - Buy %d Contract (Strike %.2f)" %
(left_count, left['strike'], body_count, body['strike'], right_count, right['strike']))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment