Thought I'd share a project I just finished - 3D options plots with python

EDIT: functionality has been extended to run as a GUI in a web browser. This is great because now any plots that have been generated in a session will persist. Makes it easier to qualitatively compare different tickers, or see how one ticker evolves through time. Pretty cool stuff. I added a screen capture of it to the linked examples down below.

I've always thought there's gotta be a better way to 'see' what's going on in the option chain than just scrolling through a wall of numbers, so I wrote a python script that plots option chain information in a 3D space (code here).

This information includes:

  • price
  • volume
  • open interest
  • every greek in this table (minus dual delta & dual gamma)

When you run the code you'll be prompted for inputs in the console. The first prompt is to choose plotting mode or single option mode.

Single option mode

  • calculates standard greeks & IV of an option given the usual inputs
  • mostly a tool to cross check values with brokerage provided values

Plotting mode

  • you'll be prompted with a series of inputs
    • ticker symbol
    • which set of parameters to plot
      • standard set = price, volume, open interest, IV, delta, gamma, vega, theta
      • nonstandard set = rho, charm, veta, color, speed, vanna, vomma, zomma
    • which price to use
      • mid price or last traded price
    • which type of options to plot
      • puts, calls, or both
    • which moneyness to plot
      • ITM, OTM, or all options
    • risk-free rate
    • starting time to use in the time to expiration calculation
      • you can just tell it to use the current time, or specify a time (time to exp is calculated at the minute resolution btw)
      • example of when you might want to specify a time: it's Sunday, the prices will be from EOD Friday, so the time to exp should be calculated from the starting point of EOD Friday
  • option data is then pulled from Yahoo! Finance, and parameters are calculated & plotted in a series of 3D subplots

Here are some examples of what you will see when the plots are generated.

At the bottom of the examples you will see I've included a guide on how to run this for those who might not be familiar with programming.

Here are the (easiest IMO) steps to run this code if you want to but don't know how:

  1. Download the Anaconda distribution (this is how you get python and the required packages)
  2. Open the Spyder development environment (Anaconda should install it by default -- if it doesn't then just install it from within Anaconda)
  3. Install the yfinance package. To do this, in the console just type in: "pip install yfinance" (without the quotes) and hit enter.
  4. Paste the code into the default 'temp' file (note - if you save the code, the file has to have a .py extension)
  5. Hit the green play button (or the F5 key)

This was mainly meant to be an educational project -- both from an options and programming perspective.

For example:

Even though Yahoo! provides implied volatility, I still calculate it manually using a bisection algorithm. I started with Newton-Raphson for speed, but as I found out, it's really hard to make it converge for every deep ITM option. Bisection is technically slower but always converges given that IV is between the two initial guesses. I also thought it would be a good idea to expose myself to the higher order greeks.

Since I'm used to creating more 'procedural' scripts, I wanted to get familiar with an 'object-oriented' programming style -- writing an 'option contract' class made things so much easier to handle. This was also good practice for handling a lot of data with complex layers. A next possible step would be making the graphs continuously update in real time, but that seems like more work that I don't want to do right now lol.

I tried to provide good commenting and docstrings, but let me know if something is wrong. This is mainly in reference to the descriptions I gave and the formulas for the higher order greeks -- can't really validate the numbers with a brokerage like I can for the standard greeks.

Edit: I should also add that if the yfinance package ever breaks, then this will stop working.

Edit 2: this post was also motivating and gave me the push to start working on this

Edit 3: should clarify not every single greek in the Wikipedia table is plotted, but every Greek has the formula entered into the option class, so the code can be modified to plot any of them

Edit 4: thanks for the awards

Edit 5: helpful comment for Mac users

Posted Jun 3, 2020, 4:00 AM UTC · edited

651131
CpntBrryCrnch•

This is the best post I've seen on this sub for some time.

88
BrononymousEngineerOP•

Thank you

29
StudioStudio•

Seconding this, this is some seriously good work!

6
BrononymousEngineerOP•

Thanks, I appreciate it

1

Cubing this. Kudos and great work.

2
robertovertical•

Super sticky this!

18
spidy33•

This is awesome man. I have never seen anything like this before

17
BrononymousEngineerOP•

Thanks, that's what initially motivated me -- not being able to find anything like this anywhere. Well I take that back, there was a post either here or in algotrading where somebody did the same sort of thing, and that got me thinking.

12
[deleted]•

[deleted]

1
BrononymousEngineerOP•

I think it was this one

5
tonyConc•

This is humbling in its simplicity & effectiveness (once you look at the finished product) vs. the worded promise. Very impressive work. Thank you for contributing this generously.

15
BrononymousEngineerOP•

My pleasure

8
tonyConc•

Most gracious.

I personally see countless uses for this (obviously as do you).

I trade options quite a bit. It's easy to imagine scenarios where the ‘project’ can either answer direct ad hoc queries, or constantly scan broad swaths of action for ideas.

2
BrononymousEngineerOP•

I agree, I'd think a lot of ideas could be generated by just examining areas of interest from a bird's eye view

3
chouhansolo•

Hey I asked this in another comment and I saw this comment now. Can you give sooner examples of how can this be used? I'm just wondering.

1
marvin182•

Very nice – you should put this on GitHub for additional visibility (and perhaps contributions from the OS community).

11
BrononymousEngineerOP•
2
[deleted]•

[deleted]

8
BrononymousEngineerOP•

Well now you have a starting point lol

6
eli_mintz•

Very nice, thanks for posting this.

I made some small changes to make it run as a web page and have a GUI using JustPy so it is still just one Python file.

You can find the code here

The only changes to your code are very minor ones in the `generate_plots` function and commenting out the call to `main()` .

The 50 lines at the end of the file create the web functionality. To see the website locally after you run the program, go to http://127.0.0.1:8000 in your browser.

You just need to install JustPy in addition to what you have to run. Full disclosure: I am the creator of JustPy and vixcentral.com

Feel free to use as you wish. I haven't tested extensively so there are probably bugs.

7
BrononymousEngineerOP•

Thanks! Wasn't expecting anyone to do something like this!

1
eli_mintz•

It took me a couple of hours and was fun to do. Thank you for posting your code.

2
BrononymousEngineerOP•

Glad to hear it, you're welcome

1
[deleted]•

[removed]

1
aram444•

I think there the interactive part is lost, when I execute the script I get plots but a 2nd terminal opens up with the name "Figure 1" and is not responding. On the web page I can see the plots but can't interact and move to rotate them nor can I scroll down.

1
eli_mintz•

Yes, on the web, you need to use a JavaScript library like Highcharts to make it interactive (see for example https://www.highcharts.com/demo/3d-scatter-draggable ). JustPy supports that but that would require a bigger rewrite. With matplotlib, JustPy converts the chart to SVG and puts it on the page so the interactivity is lost.

1
cyber_engineer•

Great job!!

5
BrononymousEngineerOP•

Thanks

1

Once in a while a post like this one comes along that restores my faith in selfless collaborative teamwork. Thank you very much !

5
BrononymousEngineerOP•

Thank you sir

1
revuimar•

Put it on GitHub great work. Reading through your code actually gave me a better idea how greeks work then anything I've ever read. Thank you!

5
BrononymousEngineerOP•

Thanks, I'm glad it helped you. See my other comment about github

1
0xbugsbunny•

This is awesome work man. Thanks for sharing it, and putting up the example plots.

Seems like a good next step might be to run these through different kinds of regression at a timescale of your choosing to see what trends you can pick out.

Not sure what your background on data science is, but if you're going to go that route, you probably want to standardize and detrend the data (Googling those should be enough to get you on the right track there).

As an aside, the visual of the 3D theta decay is super interesting, and something to keep in mind.

5
BrononymousEngineerOP•

Yeah I can picture something like that for IV...maybe normalize it by the ATM IV, make it a function of delta, and just play around with the data...of course this would probably need the ability to record data over time. Funny you mention detrending, time series analysis is the next area I want to explore (AR/I/MA, GARCH, etc...)

I agree, seeing the exponential shape of the cross section of theta across time is cool.

1

Does it reveal anything of particular interest?

4
BrononymousEngineerOP•

What initially popped out at me was how clustered volume and open interest are, at least for the few tickers I looked at. I was also surprised at how noisy ITM strikes are.

6
purple_ravioli•

What model did you use to calculate IV and Greeks?

4
BrononymousEngineerOP•

Plain Black Scholes

super late edit: bisection for IV, tried Newton-Raphson and didn't want to deal with convergence issues

4
Nahdudeurgood•

This is awesome. You should definitely work on other stuff like this.

4
BrononymousEngineerOP•

Thanks, and I definitely have lots of other ideas...too many to keep up with though

5
m00nturkey•

This is awesome I’m just starting to get into programming. Is the yfinance package the best way to model these as opposed to using API’s from ameritrade or Bloomberg and pull market data from them instead?

3
BrononymousEngineerOP•

You can do that too, and the data will be better, but it will be more work to actually get data from the brokerage APIs. From what I've read the steps to connect to TDA are notoriously confusing, and I think for IBKR you have to have TWS running. If I was actually going to pull data to trade on I'd get it from a brokerage. Yahoo works for this purpose because it's educational and you don't need API keys -- it's available for everyone.

4
Rocket089•

There are some great YT tutorials out there, and some posts on reddit, for getting ToS/TDA's api setup properly. The one YT channel that sticks out in my mind is "Sigma Coding." "Coding Fun" is another, but there are many with that username, in one form or another, but i dont want to give anyone free clicks so maybe prepend your search with "python + finance" or smg.

3
BrononymousEngineerOP•

Cool, yeah there was an updated guide posted to r/algotrading/ for TD recently. Maybe I'll check those channels out at some point.

1
m00nturkey•

Thats good to know thank you very much

2
ThroneTrader•

I was talking to some friends saying an options visualizer would be great as a way to spot trends and maybe catch unusual options activity. Your implementation looks really cool

3
BrononymousEngineerOP•

Thanks, and yup, spotting unusual activity was one of the first things I thought of.

1
bakaaaka•

This is heaven man (specially EU options). Why not put it on github (so that its open for contrinutions and improvements) ?

3
BrononymousEngineerOP•

Because I don't know how to use github lol. It's on my list of things to learn though.

1
krt_grmn•

This seems a pretty good course for learning git and version control... and it is from google

https://www.coursera.org/learn/introduction-git-github#instructors

3
BrononymousEngineerOP•

Thank you, I'll give it a look. I also saw this the other day, haven't watched it yet

3
0nlythebest•

Lmao im in college for software engineering. You can learn github in like a day.. its pretty easy. at least how it works and all. but this sounds like this is a tough project to do ( i didnt actually look at the code or run it so idk) . just blows my mind u can create these things but not know github haha. Good work tho man!

1
BrononymousEngineerOP•

Ha yeah if only you knew how bad it was before. When I first learned how to code in college we used matlab to solve engineering problems. We only ever did stuff like numerical integration and solving systems of differential equations, it was miserable.

In the final year we had a lab where the analysis required wind tunnel data to be read in from a text file. It was super confusing at the time and we had no idea that was even possible...to us it was just a calculator on steroids.

1
0nlythebest•

lol dam sounds wild. my entire last year was spent creating websites and android apps!

2
TheStoicInvestor•

Awesome graphs !

What kind of insights did you get from these visualizations ?

I've been trying to visualize options data as well (https://imgur.com/a/SUvdIh8), but so far I have not gained any meaningful insights. I think there is more value in building a dataset (e.g. by crawling option prices every day) and then use them for back-testing strategies.

2
BrononymousEngineerOP•

So far not a whole lot as a lot of brainpower was focused on actually coding it, I'm sure something might stand out as I play with it more.

That's a pretty cool visual, though I'm not quite sure what to make of it at first glance

1
TheStoicInvestor•

It shows how the option volume is spread across target prices. The higher the bubble, the bigger the option volume. I use it to visualize what the options market think will happen to the stock on a specific date.

2
BrononymousEngineerOP•

I see, that makes sense now. To your point about backtesting, I agree and think that is where the real insights would come from.

1
itssualgoodman•

Too good job, even I'm learning python and will refer to your code and learn more.
Does it help for Indian tickers as well?

2
BrononymousEngineerOP•

I'm not really sure what you mean. If the ticker is on yahoo finance and optionable then this can plot it.

2
itssualgoodman•

Will check yahoo finance, I might be doing it wrong I guess

1
TILnothingAMA•

This is pretty and all, but how is it useful? What can I do with it other than look at it?

2
BrononymousEngineerOP•

What can I do with it other than look at it?

Just seeing was the main purpose of this exercise. Looking at things from a new perspective can be super helpful in developing understanding and generating actionable ideas. If you have a deep understanding of what's going on, you won't need to memorize a cookbook recipe of steps with respect to a trading strategy, and you will understand why certain people run certain strategies, where they excel, and where they fall short...this is what I am trying to develop for myself.

I don't mean this to be a dig at you or others who have asked the same sort of question, but in my opinion, if you can only see as far as "what trade is this telling me I should make, or what strategy is this telling me to use?", then the point has been missed. I get it, those are fair questions, but that's not what this is about.

how is it useful?

Besides what I mentioned above, I see two main uses.

  1. Spotting areas of interest to explore more closely in the actual option chain
  2. Providing somewhat of a template for more specific uses, such as:
  • collecting your own options data
  • extending the code to perform more specific calculations in regard to something you want to know

I didn't write this code just to make a post -- I wanted to see what things looked like.

Edit: and I wanted to prove to myself I don't need to depend on a brokerage for anything other than placing trades and receiving a data stream

4