예제 #1
0
def import_data_yahoo(asset_class):
    """
    Imports Historical Data for Mentioned ETFs
    asset_class = mention the asset class for ETFs data import (str)
    options available = 'Fixed Income', 'REIT', 'Currencies', 'Commodities', 'World Equities', 'Sectoral'
    """
    #Import list of ETFs and Ticker Names
    etf_list = pd.read_excel('etf_names.xlsx',
                             header=0,
                             sheet_name=asset_class)
    etf_list = etf_list.sort_values(by='Ticker')

    #Build an empty df to store historical 1 year data
    df = pd.DataFrame(index=pd.bdate_range(start=one_yr, end=date.today()))
    df.index.name = 'Date'

    #download and merge all data
    df1 = Ticker(
        list(etf_list['Ticker']),
        asynchronous=True).history(start=date(date.today().year - 1,
                                              date.today().month,
                                              date.today().day))['adjclose']
    df1 = pd.DataFrame(df1).unstack().T.reset_index(0).drop('level_0', axis=1)
    df1.index.name = 'Date'
    df1.index = pd.to_datetime(df1.index)
    df = df.merge(df1, on='Date')
    #Forward fill for any missing days i.e. holidays
    df = df.ffill().dropna()
    df.index.name = 'Date'
    df.columns = list(etf_list[asset_class])
    return df
#                 volumes.append(volume)
# =============================================================================
# =============================================================================
#     # appending each temporary variable to their respective list
#     names.append(name)
#     dates.append(date)
#     highs.append(high)
#     closes.append(close)
#     opens.append(o)
#     lows.append(low)
#     volumes.append(volume)
# =============================================================================

# reformatting the datetime into date
all_hist.index = all_hist.index.set_levels([
    all_hist.index.levels[0],
    [pd.to_datetime(i).date() for i in all_hist.index.levels[1]]
])

# writing the final dataframe to excel
all_hist.to_excel(
    'F:\\Python\\ImpactofCoronaVirus_Stocks\\Stocks\\all_history.xlsx',
    merge_cells=False)

# =============================================================================
# # creating a dataframe from the lists
# stock_df = pd.DataFrame({'Name': names, 'Date': dates, 'Open': opens, 'Close': closes, 'High': highs, 'Low': lows, 'Volume': volumes})
#
# # writing the history dataframe into excel
# stock_df.to_excel('F:\\Python\\ImpactofCoronaVirus_Stocks\\Stocks\\all_history.xlsx', index=False)
# =============================================================================