我正在尝试为熊猫数据框生成 1 行 1 行,但出现错误。数据框是一个股票价格数据,包括每日的开盘价、收盘价、最高价、最低价和成交量信息。
以下是我的代码。这个类将从 MySQL 数据库中获取数据
class HistoricMySQLDataHandler(DataHandler):
def __init__(self, events, symbol_list):
"""
Initialises the historic data handler by requesting
a list of symbols.
Parameters:
events - The Event Queue.
symbol_list - A list of symbol strings.
"""
self.events = events
self.symbol_list = symbol_list
self.symbol_data = {}
self.latest_symbol_data = {}
self.continue_backtest = True
self._connect_MySQL()
def _connect_MySQL(self): #get stock price for symbol s
db_host = 'localhost'
db_user = 'sec_user'
db_pass = 'XXX'
db_name = 'securities_master'
con = mdb.connect(db_host, db_user, db_pass, db_name)
for s in self.symbol_list:
sql="SELECT * FROM daily_price where symbol= s
self.symbol_data[s] = pd.read_sql(sql, con=con, index_col='price_date')"
def _get_new_bar(self, symbol):
"""
Returns the latest bar from the data feed as a tuple of
(sybmbol, datetime, open, low, high, close, volume).
"""
for row in self.symbol_data[symbol].itertuples():
yield tuple(symbol, datetime.datetime.strptime(row[0],'%Y-%m-%d %H:%M:%S'),
row[15], row[17], row[16], row[18],row[20])
def update_bars(self):
"""
Pushes the latest bar to the latest_symbol_data structure
for all symbols in the symbol list.
"""
for s in self.symbol_list:
try:
bar = self._get_new_bar(s).__next__()
except StopIteration:
self.continue_backtest = False
在主函数中:
# Declare the components with respective parameters
symbol_list=["GOOG"]
events=queue.Queue()
bars = HistoricMySQLDataHandler(events,symbol_list)
while True:
# Update the bars (specific backtest code, as opposed to live trading)
if bars.continue_backtest == True:
bars.update_bars()
else:
break
time.sleep(1)
数据示例:
symbol_data["GOOG"] =
price_date id exchange_id ticker instrument name ... high_price low_price close_price adj_close_price volume
2014-03-27 29 None GOOG stock Alphabet Inc Class C ... 568.0000 552.9200 558.46 558.46 13100
该update_bars
函数将调用_get_new_bar
移动到下一行(第二天价格)
我的目标是每天获取股票价格(迭代数据框的行),但self.symbol_data[s]
in_connect_MySQL
是数据框,而 in_get_new_bar
是生成器,因此我收到此错误
AttributeError:
'generator'
对象没有属性'itertuples'
有人有想法么?
我正在使用python 3.6。谢谢
self.symbol_data
is a dict
,symbol
是获取数据帧的字符串键。数据为股价数据。例如self.symbol_data["GOOG"]
,按日期返回一个带有谷歌每日股价信息索引的数据框,每行包括开盘价、最低价、最高价、收盘价和成交量。我的目标是每天使用yield
.
_connect_MySQL
将从数据库中获取数据在这个例子中,函数中的s = "GOOG"