Search code examples
pythondataframefinancestock

Historical stock prices for list of stocks in data frame


I am new to Python and I am struggling with getting historical stock prices for stocks in my data frame:

I have following data frame

Column New_ticker: MSGE, IT, NVST
Column Date: 2020-04-20, 2020-02-29,2019-12-18

I struggle to generate the historical stock price for each stock from the respective date to YTD, eg. stock price for MSGE from 2020-04-20 until today

Do you I need to create a separate data frame for each stock or can I put them altogether?

Many thanks for any hint.

import pandas as pd
import yfinance as yf
from yahoofinancials import YahooFinancials

assets=df['New_ticker'].tolist()
yahoo_financials=YahooFinancials(assets)
data=yahoo_financials.get_historical_price_data(start_date='2019-01-01',end_date='2020-08-30',time_interval='daily')
prices_df = pd.DataFrame({a: {x['formatted_date']: x['adjclose'] for x in data[a]['prices']} for a in assets})
prices_df

But getting no data when I call prices_df


Solution

  • This is the first time I've downloaded and used yfinance. You can get it with the following code. Another code was obtained using 'panda_datareader' using the 'Alpha Vantage' API, Alpha Vantage's API is mail-less It can be obtained with only pandas datareader

    # yfinance
    import yfinance as yf
    
    import datetime
    import pandas as pd
    
    ticker = ["MSGE", "IT", "NVST"]
    msge = "MSGE"
    now_ = datetime.datetime.today()
    
    start = datetime.datetime(2020, 4, 1)
    end = datetime.datetime(now_.year, now_.month, now_.day - 1)
    
    all_df = pd.DataFrame()
    for i in ticker:
        data = yf.download(i, start=start, end=end)
        data['symbol'] = i
        all_df = all_df.append(data)
    
    all_df.head()
        Open    High    Low Close   Adj Close   Volume  symbol
    Date                            
    2020-04-09  100.000000  100.000000  86.510002   88.510002   88.510002   1900    MSGE
    2020-04-13  85.000000   86.830002   80.250000   80.250000   80.250000   167400  MSGE
    2020-04-14  75.150002   77.559998   75.150002   75.190002   75.190002   5300    MSGE
    2020-04-15  72.150002   76.000000   72.150002   76.000000   76.000000   800 MSGE
    2020-04-16  76.000000   76.000000   74.599998   74.599998   74.599998   75300   MSGE
    
    import matplotlib.pyplot as plt
    # import matplotlib.dates as mdates
    
    fig = plt.figure(figsize=(8,4),dpi=144)
    ax = fig.add_subplot(111)
    
    msge = all_df[all_df['symbol'] == 'MSGE']
    it = all_df[all_df['symbol'] == 'IT']
    nvst = all_df[all_df['symbol'] == 'NVST']
    
    ax.plot(msge.index, msge['Adj Close'], color='g', lw=1.5, label='MSGE')
    ax.plot(it.index, it['Adj Close'], color='b', lw=1.5, label='IT')
    ax.plot(nvst.index, nvst['Adj Close'], color='orange', lw=1.5, label='NVST')
    
    plt.legend()
    plt.show()
    

    enter image description here

    # pandas_datareader and Alpha Vantage API
    import datetime
    import pandas as pd
    import pandas_datareader.data as web
    import mplfinance as mpf
    import matplotlib.pyplot as plt
    
    with open('./alpha_vantage_api_key.txt') as f:
        api_key = f.read()
    
    now_ = datetime.datetime.today()
    
    start = datetime.datetime(2019, 1, 1)
    end = datetime.datetime(now_.year, now_.month, now_.day - 1)
    symbol = 'MSGE'
    df = web.DataReader(symbol, 'av-daily', start, end, api_key=api_key)
    
    df.columns = ['Open', 'High', 'Low', 'Close', 'Volume']
    df.index = pd.to_datetime(df.index)
    
    df.head()
    Open    High    Low Close   Volume
    2020-04-09  100.00  100.00  86.51   88.51   1900
    2020-04-13  85.00   86.83   80.25   80.25   167421
    2020-04-14  75.15   77.56   75.15   75.19   5281
    2020-04-15  72.15   76.00   72.15   76.00   807
    2020-04-16  76.00   76.00   74.60   74.60   74999