In a Research notebook I'm using the following code to fetch prices for numerous stocks:
tickers = ['LAMR','OUT','AIV','AVB','CPT','EQR','ESS','MAA','UDR','COR','CONE','DLR',
'EQIX','IRM','QTS','ALX','EPR','JBGS','VNO','WPC','PEAK',
'WELL','VTR','MPW','SNR','PLD','PSB','STAY','GLPI','HST',
'HT','IHT','MGP','PK','VICI','XHR','SUI','UMH','NLY','ANH',
'AI','ARE','BXP','BDN','OFC','CUZ','HPP','CLI','SLG','CXW',
'GEO','CBL','MAC''PEI','SPG','TCO','WPG','CUBE','EXR','LSI',
'PSA','BRX','CDR','FRT','KIM','RPT','REG','SITC','SKT','UBP','WRI',
'NNN','O','AMH','INVH','ACC','AMT','CCI','SBAC','PCH','RYN','WY']
symbols = [qb.AddEquity(ticker, Resolution.Daily).Symbol for ticker in tickers]
ef get_prices(symbols,months):
"""
generate a DataFrame with monthly stock prices.
The first and last entries are full months
"""
now = datetime.now()
history = qb.History(symbols, (now-timedelta(days=months*30)).replace(day=1), now.replace(day=1)-timedelta(days=1), Resolution.Daily).drop(['high','low','open','volume'],1)
history = history.unstack(level=0).resample('M').last().to_period('M').dropna(axis=1)
history.columns = history.columns.map(''.join).str.lstrip('close_')
history.columns = history.columns.str.split(' ').str[0]
del history.columns.name
del history.index.name
return history
prices = get_prices(symbols,50)
prices['WPG'].head()
On the last line, I get a
KeyError: 'WPG VQY4YY1HBASL'How come? It doesn't happen with any Dataframe not created by History. Am I missing something very basic?Thanks.
Adam W
I've come across some weird interactions occasionally with the DataFrame created by History as well in Research, for instance after changing column names, slicing it by the new names throws a KeyError.
I suggest keeping the keys/columns of the DataFrame as they are, then slicing by the full security ID:
# I've had issues directly changing column names like you are here. Try doing DataFrame manipulations # on a copy of it via .copy() or a slice of it instead. # history.columns = history.columns.map(''.join).str.lstrip('close_') # history.columns = history.columns.str.split(' ').str[0] del history.columns.name del history.index.name return history prices = get_prices(symbols,50) # prices['WPG'].head() prices.loc[:,qb.Symbol('WPG').ID].head() # For WPG security_IDs = [str(symbol.ID) for symbol in symbols] # Multiple columns prices.loc[:,security_IDs].head()
Â
Tal Davidson
The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by QuantConnect. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. QuantConnect makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances. All investments involve risk, including loss of principal. You should consult with an investment professional before making any investment decisions.
To unlock posting to the community forums please complete at least 30% of Boot Camp.
You can continue your Boot Camp training progress from the terminal. We hope to see you in the community soon!