Search code examples
pythonpandasdataframeyfinance

Data appears when printed but doesn't show up in dataframe


#! /usr/lib/python3

import yfinance as yf
import pandas as pd

pd.set_option('display.max_rows', None, 'display.max_columns', None)

# Request stock data from yfinance
ticker = yf.Ticker('AAPL')

# Get all option expiration dates in the form of a list
xdates = ticker.options

# Go through the list of expiry dates one by one
for xdate in xdates:
    # Get option chain info for that xdate
    option = ticker.option_chain(xdate)
    # print out this value, get back 15 columns and 63 rows of information
    print(option)
    # Put that same data in dataframe
    df = pd.DataFrame(data = option)
    # Show dataframe
    print(df)
    

Expected: df will show a DataFrame containing the same information that is shown when running print(option), i.e. 15 columns and 63 rows of data, or at least some part of them

Actual:

  • df shows only two columns with no information
  • df.shape results in (2,1)
  • print(df.columns.tolist()) results in [0]

Since the desired info appears when you print it, I'm confused as to why it's not appearing in the dataframe.


Solution

  • The data of option_chain for specific expiration date is avaialable in calls property of the object as dataframe. You don't have to create a new dataframe.

    ticker = yf.Ticker('AAPL')
    xdates = ticker.options
    option = ticker.option_chain(xdates[0])
    option.calls # DataFrame 
    

    GitHub - yfinance