Search code examples
pythonpandasyahoo-finance

pandas from function / loop


I am importing stock data in python from yahoo.

import pandas as pd
import numpy as np
from pandas_datareader import data
from datetime import date
from datetime import timedelta

def Get_Historic_SP(ticker):
    end_date = date.today()
    start_end = end_date - timedelta(weeks=260)
    df = data.DataReader(ticker, data_source='yahoo',start=start_date, end=end_date)
    df.index = pd.to_datetime(df.index)
    df.reset_index().rename(columns={df.index.name:'Date'})
    return df['Close']

This works well. I would like to do this for multiple codes and create one dataframe with the companies in columns. Also each column to have ticker (comps) as the title.

I am using:

    comps = ['AVON.L', 'BYG.L']

example

    Date         AVON.L    BYG.L
    20/03/2019   193       980

Solution

  • Fixing your code as follows:

    import pandas as pd
    import numpy as np
    from pandas_datareader import data
    from datetime import date
    from datetime import timedelta
    
    def Get_Historic_SP(ticker, start_date):
        end_date = date.today()
        start_end = end_date - timedelta(weeks=260)
        df = data.DataReader(ticker, data_source='yahoo',start=start_date, end=end_date)
        df.index = pd.to_datetime(df.index)
        df.reset_index().rename(columns={df.index.name:'Date'})
        return df['Close']
    

    You can use the following code that first creates a dictionary and then converts it to a DataFrame:

    tickers = ['googl', 'aapl']
    
    ticker_dict = {}
    for ticker in tickers:
        ticker_dict[ticker] = Get_Historic_SP(ticker, date(2019,3,1))
    
    df = pd.DataFrame(ticker_dict)