Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/hedge #1768

Merged
merged 34 commits into from
May 14, 2022
Merged

Feature/hedge #1768

merged 34 commits into from
May 14, 2022

Conversation

lepla
Copy link
Contributor

@lepla lepla commented May 5, 2022

Description

This feature is not quite intuitive, so in order for everyone to easily understand what this offers please read the article.
The hedge_model is based on @colin99d 's stocks/options/payoff menu.

My proposed feature is called 'hedge' and lives inside the stocks/options menu. It gives the user the opportunity to hedge their portfolio in order to neutralize its exposure to delta, gamma and vega. This means that whatever happens to the market, our investor will take profit (as long as it is volatile).

The user needs to firstly load a ticker (let's say tsla) and expiry date.
load tsla
exp 1

image

Then, after typing the command 'hedge', the user needs to pick their position option using the command 'pick'.
An example of this command is: pick long -s call -a 500 -p 900
(This indicates that the user's position is a Long position, with 500 calls in the strike price of $900)

image

Then, the user needs to add 2 options using the 'add' command. The reason for this is that in order to find the neutral exposure portfolio, we need to use linear algebra, and therefore we need 3 equations with 3 unknowns. (The 3 unknowns are delta, gamma and vega - the feature could be enhanced in the future to include more greeks).

We can check for all the available options for this expiry date:
list

Let's say we select Option A:
add 45

image

And Option B:
Add 47

imageimage

Right after we add the 2 options needed, the terminal automatically calculates the weight of the Options and the underlying asset that will lead to a delta, gamma and vega neutral exposure.

image

How has this been tested?

I have tried out many different combinations of options, expiry dates and positions (long calls, short puts etc.)
There is an issue that occurs in certain combinations which leads to a non invertible singular matrix error. (Unfortunately it happens quite often)

Checklist:

General Comments:

There are minor enhancements needed in the hedge_controller file, such as improve the help commands, some titles etc. , but first I would like its outputs to be validated and correct. After making sure it is correct, I will move on to the minor enhancements.

Others

  • I have performed a self-review of my own code.
  • I have commented my code, particularly in hard-to-understand areas.
  • My code passes all the checks pylint, flake8, black, ... To speed up development you should run pre-commit install.
  • New and existing unit tests pass locally with my changes. You can test this locally using pytest tests/....

@JerBouma JerBouma self-requested a review May 6, 2022 11:15
@DidierRLopes DidierRLopes requested a review from colin99d May 6, 2022 15:01
@DidierRLopes DidierRLopes added the feat M Medium T-Shirt size feature label May 6, 2022
@JerBouma
Copy link
Contributor

JerBouma commented May 9, 2022

Hi @lepla,

Thanks for the PR! I made some significant contributions to the menu fixing the errors received, making the code more robust and more intuitive. I have the following remarks:

  • I have noticed you are working a lot with lists e.g. when calling the delta, gamma and vega positions from the portfolio and each option. This hurts the readability greatly. I'd suggest to delve deeper into Dictionaries like how I used them, see code changes.
  • The code was missing docstrings and/or comments making it much harder to understand what was going on at each step.
  • The coding linters (e.g. Pylint and Black) did not pass. For future PRs, I'd suggest typing pre-commit install before committing.
  • Try to check whether the code actually works well when several options have been set. I have now limited this to just two.
  • Make more use of table functionality from Rich. I have converted all tables to this structure now but it should be relatively straightforward how to do this yourself via our guides.

There is a singular matrix error you receive because there are multiple answers. I haven't delved too deeply into this mathematical error and thus the code will warn the user about it. This also makes the menu experimental, I can not confidently say that the methods deployed are 100% correct.

See some screens/code below:
Screenshot 2022-05-09 at 12 49 19

2022 May 09, 07:25 (🦋) /stocks/options/ $ hedge
╭─────────────────────────────────────────────────────────────────────────────────────────────────────── Stocks - Options - Hedge ────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                                                                                         │
│ Ticker: MSFT                                                                                                                                                                                                                            │
│ Expiry: 2022-05-13                                                                                                                                                                                                                      │
│                                                                                                                                                                                                                                         │
│     pick          pick the underlying asset position                                                                                                                                                                                    │
│                                                                                                                                                                                                                                         │
│ Underlying Asset Position:                                                                                                                                                                                                              │
│                                                                                                                                                                                                                                         │
│     list          show the available strike prices for calls and puts                                                                                                                                                                   │
│     add           add an option to the list of options                                                                                                                                                                                  │
│     rmv           remove an option from the list of options                                                                                                                                                                             │
│     sop           show selected options and neutral portfolio weights                                                                                                                                                                   │
│                                                                                                                                                                                                                                         │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── OpenBB Terminal ─╯
2022 May 09, 07:25 (🦋) /stocks/options/hedge/ $ pick 200 Long Call
2022 May 09, 07:26 (🦋) /stocks/options/hedge/ $ add 20
┏━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┓
┃                    ┃ Positions ┃
┡━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━┩
│ Delta              │ 1.00      │
├────────────────────┼───────────┤
│ Gamma              │ 3477.05   │
├────────────────────┼───────────┤
│ Vega               │ 0.29      │
├────────────────────┼───────────┤
│ Implied Volatility │ 1.00e-05  │
├────────────────────┼───────────┤
│ Strike Price       │ 260.00    │
└────────────────────┴───────────┘

          Current Option Positions           
┏━━━━━━┳━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┓
┃ Type ┃ Hold ┃ Strike ┃ Implied Volatility ┃
┡━━━━━━╇━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━┩
│ Call │ Long │ 260.00 │ 1.00e-05           │
└──────┴──────┴────────┴────────────────────┘

2022 May 09, 07:26 (🦋) /stocks/options/hedge/ $ add 10
┏━━━━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━┓
┃                    ┃ Positions ┃
┡━━━━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━┩
│ Delta              │ 1.00      │
├────────────────────┼───────────┤
│ Gamma              │ 3477.05   │
├────────────────────┼───────────┤
│ Vega               │ 0.29      │
├────────────────────┼───────────┤
│ Implied Volatility │ 1.00e-05  │
├────────────────────┼───────────┤
│ Strike Price       │ 235.00    │
└────────────────────┴───────────┘

          Current Option Positions           
┏━━━━━━┳━━━━━━┳━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━┓
┃ Type ┃ Hold ┃ Strike ┃ Implied Volatility ┃
┡━━━━━━╇━━━━━━╇━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━┩
│ Call │ Long │ 260.00 │ 1.00e-05           │
├──────┼──────┼────────┼────────────────────┤
│ Call │ Long │ 235.00 │ 1.00e-05           │
└──────┴──────┴────────┴────────────────────┘
          Neutral Portfolio Weights          
┏━━━━━━━━━━━━━━━━━┳━━━━━━━━━━━━━━━━━━━━━━━━━┓
┃                 ┃ Positions               ┃
┡━━━━━━━━━━━━━━━━━╇━━━━━━━━━━━━━━━━━━━━━━━━━┩
│ Weight Option A │ 5180845893727149056.00  │
├─────────────────┼─────────────────────────┤
│ Weight Option B │ -5180845893727149056.00 │
├─────────────────┼─────────────────────────┤
│ Weight Shares   │ -1000.00                │
└─────────────────┴─────────────────────────┘


2022 May 09, 07:26 (🦋) /stocks/options/hedge/ $ ?
╭─────────────────────────────────────────────────────────────────────────────────────────────────────── Stocks - Options - Hedge ────────────────────────────────────────────────────────────────────────────────────────────────────────╮
│                                                                                                                                                                                                                                         │
│ Ticker: MSFT                                                                                                                                                                                                                            │
│ Expiry: 2022-05-13                                                                                                                                                                                                                      │
│                                                                                                                                                                                                                                         │
│     pick          pick the underlying asset position                                                                                                                                                                                    │
│                                                                                                                                                                                                                                         │
│ Underlying Asset Position: Long Call 1000 @ 200                                                                                                                                                                                         │
│                                                                                                                                                                                                                                         │
│     list          show the available strike prices for calls and puts                                                                                                                                                                   │
│     add           add an option to the list of options                                                                                                                                                                                  │
│     rmv           remove an option from the list of options                                                                                                                                                                             │
│     sop           show selected options and neutral portfolio weights                                                                                                                                                                   │
│                                                                                                                                                                                                                                         │
╰─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── OpenBB Terminal ─╯

@jmaslek
Copy link
Collaborator

jmaslek commented May 9, 2022

So let me know if this is too overboard, but in the case of multiple solutions, you could do some minimization technique. Maybe look for the mininum sum of absolute weights, constraining the greeks to be zero. Doing this would give you the solution of net zero greeks and having the purchase the lowest amount of instruments. Can be implemented using spicy.optimize.minimize()

@lepla
Copy link
Contributor Author

lepla commented May 10, 2022

So let me know if this is too overboard, but in the case of multiple solutions, you could do some minimization technique. Maybe look for the mininum sum of absolute weights, constraining the greeks to be zero. Doing this would give you the solution of net zero greeks and having the purchase the lowest amount of instruments. Can be implemented using spicy.optimize.minimize()

Thank you for the tips! For now, if there are multiple solutions, the command will yield the first feasible solution. Of course, this doesn't mean it will necessarily be the best one. After communicating with @JerBouma, we decided to keep this for now until the feature is monitored and proven to be worthy to many.

@JerBouma
Copy link
Contributor

Hi @lepla,

Looking good! I went ahead and tidied up the options menu as a whole a bit as well. I also got rid of the payoff menu as it is in essence the "dirty" version of your menu with a plot functionality. Therefore, added that plot functionality into your menu.

If tests pass I feel like we are all set to merge :)

@JerBouma JerBouma marked this pull request as ready for review May 10, 2022 20:34
@JerBouma
Copy link
Contributor

@colin99d Mind checking briefly and approving the PR if everything works for you? Given that Lepla took your payoff menu as a template which is now merged into the hedge menu that makes sense to me.

@colin99d
Copy link
Contributor

colin99d commented May 10, 2022

Great PR! I really like what people could do with this in the future. I found a small bug with the help menu that I fixed. Other than that here are my comments. Would love to hear from @JerBouma on whether he agrees.

  • This function lets the underlying asset be a call or put, but shouldn't the underlying asset be the stock?
    • Also, could the underlying be shorting the stock?
  • This function limits 2 options to be added. This is fine for you functionality but it definitely limits the plot functionality. Do you think we can allow more than two selections and then if there are more than two we can tell users only the first two are involved in the calculation.

@JerBouma
Copy link
Contributor

JerBouma commented May 11, 2022

I agree with @colin99d, it seems weird the underlying is an actual call or put option as your intention is not to hedge an option right? Instead, you want to hedge the underlying (stock). Could you elaborate on this? For example, I have the feeling that Short Call == Long Call and Short Put == Long Put looking at the results. This also becomes clear in the code, you have self.side and self.underlying and only self.side is actually used. I propose the following:

  • Change the code so it only uses self.side. Be way you also change this in call_plot that still relies on self.underlying.
  • Make the underlying easier to understand, e.g. it should have a delta of 1. Is this actually what is going on? We currently do calculate the delta.
  • Change the underlying text to represent the underlying instead of an option (unless this is intentional).

I think it is fine to keep it at 2 options for now for the plot functionality. You can quite quickly switch between options anyways right?

@lepla
Copy link
Contributor Author

lepla commented May 11, 2022

My solution as mentioned in the PR is influenced by the article. From that, I would like to point out two parts:

The first thing to realize is that to neutralize exposure to greeks we are going to need offsetting positions in other options. There are three greeks to neutralize, so we need three options to create three equations of greeks and weights with three unknowns (the weights in the other tradable options). However, the trick here is realizing that the partial derivative of the underlying asset with respect to itself is just 1, this means the underlying asset has a delta of 1 and all other greek values are 0. This means we can construct a portfolio of two tradable options, find appropriate weights to neutralize the greeks, then take an offsetting position in the underlying asset — effectively neutralizing exposure to all three greeks.

The fact that the underlying asset’s delta is 1 is not actually used anywhere, except for the fact that it changes the amount of equations we need (from 3 to 2). In his example, the portfolio is a short call option position, for which he needs to buy shares of the underlying asset in order to hedge his position.
This is what my initial solution did. The first element of the neutral matrix would be the amount of underlying asset shares needed to be bought/sold.

Just like the summary of the article example:
After multiplying our new options positions by the original greeks we find that our net delta position is -46. This means by purchasing 46 shares of the underlying asset (NVDA) we will have a delta, gamma, and vega neutral portfolio. This means the value of our option portfolio will not change when there are changes in the underlying asset price, underlying asset volatility, or the speed in which the underlying asset price changes.

@JerBouma
Copy link
Contributor

Hi @lepla,

So while I can agree with that, I have a feeling there is still something off with how Short and Long Puts and Calls are taken into account as they seem to be netting the same position every time. To some degree this makes sense to me, if you move 10 steps forward or 10 steps backwards, it should be the same number to return to the starting position. However, I'd expect a sign change. Does this make sense?

@lepla
Copy link
Contributor Author

lepla commented May 11, 2022

Hi @lepla,

So while I can agree with that, I have a feeling there is still something off with how Short and Long Puts and Calls are taken into account as they seem to be netting the same position every time. To some degree this makes sense to me, if you move 10 steps forward or 10 steps backwards, it should be the same number to return to the starting position. However, I'd expect a sign change. Does this make sense?

Yes it totally does and I do agree as well. Not exactly sure how the code should be manipulated for this.

@DidierRLopes DidierRLopes merged commit 54a1b6f into OpenBB-finance:main May 14, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
feat M Medium T-Shirt size feature
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants