pandas 来自函数/循环

pandas from function / loop

我正在从雅虎 python 中导入库存数据。

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']

这很好用。我想为多个代码执行此操作,并在列中创建一个包含公司的数据框。此外,每一列都有代码 (comps) 作为标题。

我正在使用:

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

例子

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

按如下方式修复您的代码:

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']

您可以使用以下代码首先创建一个字典,然后将其转换为 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)