'Finding a specific element in a matrix with set parameters
I created a code for financial options and there is one last thing missing to finish it. I want my code to find the implied volatility for a specific option. My code asks the user to input the stock's ticker, date to maturity, strike price, and if the option is a call or a put.
Here is what I would like it to do:
- Based on whether it is a call or a put, look for the suitable matrix that is given in the terminal.
- Extract the implied volatility value conditional to the strike price (I can already handle the date and ticker in the options.get_options_chain function) the user inputted
- Return the implied volatility
How should I go about this? I looked at many modules (pandas, pandas-DataReader, basic Python functions, NumPy, sys, etc.) and their documentation, and nothing seems to fit what I want. Here is an example of the output that I am getting from the data that I want.
from yahoo_fin import options
chain = options.get_options_chain("nflx", "2022-06-10")
print(chain)
$ python implied
{'calls': Contract Name Last Trade Date Strike Last Price Bid Ask Change % Change Volume Open Interest Implied Volatility
0 NFLX220610C00120000 2022-05-04 12:27PM EDT 120.0 75.50 46.50 49.60 0.00 - - 0 87.26%
1 NFLX220610C00130000 2022-05-09 10:25AM EDT 130.0 50.05 0.00 0.00 0.00 - - 0 0.00%
2 NFLX220610C00135000 2022-05-05 1:50PM EDT 135.0 55.75 34.50 35.60 0.00 - - 1 81.37%
3 NFLX220610C00145000 2022-05-10 10:04AM EDT 145.0 36.77 0.00 0.00 0.00 - - 0 0.00%
'puts': Contract Name Last Trade Date Strike Last Price Bid Ask Change % Change Volume Open Interest Implied Volatility
0 NFLX220610P00100000 2022-05-11 3:59PM EDT 100.0 0.59 0.56 0.66 0.19 +47.50% 83 59 100.05%
1 NFLX220610P00105000 2022-05-11 11:43AM EDT 105.0 0.40 0.71 0.86 -0.20 -33.33% 2 1 96.48%
2 NFLX220610P00110000 2022-05-11 3:22PM EDT 110.0 0.97 0.96 1.10 0.38 +64.41% 35 6 93.51%
Solution 1:[1]
The result set you get is a dict with the keys calls
or puts
and a pd.DataFrame
as a value.
Access the dict first, then select the required data in the DataFrame by selecting the strike
(right row) and Implied Volatility
(right column).
With iloc[0]
you will get the first element within the pd.Series
.
from yahoo_fin import options
import pandas as pd
# set basic parameters e. g., maturity, option type
option_type = 'calls'
strike = 180.0
last_trade_date = '2022-05-10'
chain = options.get_options_chain("nflx", "2022-06-10")
print(chain)
df = pd.DataFrame(chain.get(option_type))
vola = df[df['Strike'] == strike]['Implied Volatility'].iloc[0]
Output:
3.13%
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | KarelZe |