pythonpandasstockdatareader

Python - Pandas Dataframe - Stocks data - Adjusted Close attribute variable creation


I would like to create a variable to easily use the Adjusted Close price, which is simple for other single-worded attributes (like 'Close') but not that straightforward with Adjusted Close. How can I do the same thing I do here below with the column 'Close'?

    end = dt.datetime.now()
    start = end - dt.timedelta(weeks=104)
    stocks_list = ['COST', 'NIO', 'AMD']
    df = pdr.get_data_yahoo(stocks_list, start, end)
    Close = df.Close
    Close.head()
    

Solution

  • What you are referring to here is called Attribute Access in the documentation. Near the end of the section on Attribute access, there is the following warning:

    You can use this access only if the index element is a valid Python identifier, e.g. s.1 is not allowed. See here for an explanation of valid identifiers.

    From the linked documentation on what a valid identifier is:

    Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase letters A through Z, the underscore _ and, except for the first character, the digits 0 through 9.

    Adjusted Close is not a valid python identifier (due to the space), so it will not be accessible as an attribute of your dataframe. There are also some other exceptions in the same warning that are worth reading about.

    I would recommend an approach like BigBen suggests in the comments where you simply assign a local variable based on the column name as a string adjusted_close = df['Adjusted Close'].

    If you are dead set on using Attribute access, you can mangle your column's name so it becomes a valid python identifier, and then you can use attribute access. From your example, this can be done with:

    df.rename(columns = {"Adjusted Close" : "AdjustedClose"}, inplace = True)
    

    Once you do this, you can access the Adjusted Close with df.AdjustedClose. I don't really recommend this approach, but it's possible.