错误"'Timestamp' object has no attribute 'translate'"



最近,我开始进行股价分析,以优化我的投资组合。我从一个Excel文件和几个VBA宏开始。它运行得很好,但速度很慢。所以,我现在正试图在我的服务器上建立一个合适的"股价"数据库(基于这篇文章(。

在"股票价格"数据库中,有一个"每日价格"表,用于存储一些股票行情机的每日股价。为了更新"每日价格"表,每天都会启动一个python脚本,其中包括以下python/SQL语句。

df = pdr.get_data_yahoo(ticker, start_date)
for row in df.itertuples():
values = [YAHOO_VENDOR_ID, ticker_index[ticker]] + list(row)
cursor.execute("INSERT INTO daily_price (data_vendor_id, ticker_id, price_date, open_price, high_price, low_price, close_price, adj_close_price, volume) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", tuple(values))

不幸的是,"cursor.execute…"行返回以下错误:"AttributeError:"Timestamp"对象没有属性"translate">

"values"元组的输出为:[1,2,时间戳("2004-08-19 00:00:00"(,49.81328582763672,51.83570861816406,47.80083084106445,49.98265457515332,49.98226545715332,44871300]

根据我在另一篇类似文章中读到的内容,我检查了日期索引的类型,以确保它不是对象:

Print(df.index.dtype)

这将返回"datetime64[ns]",看起来不错。

最后,在数据库中,我尝试将数据类型从"Date"更改为"Datetime",但这并不能解决错误。

有人能分享一些关于如何解决这个错误的提示吗?

谨致问候,

编辑于2020年4月25日:最终解决方案

df = pdr.get_data_yahoo(ticker, start_date)
df = df.reset_index()
df.columns = ['price_date', 'open_price', 'high_price', 'low_price', 'close_price', 'adj_close_price', 'volume']
df['data_vendor_id'] = YAHOO_VENDOR_ID
df['ticker_id'] = ticker_index[ticker]
df = df[['data_vendor_id','ticker_id','price_date', 'open_price', 'high_price', 'low_price', 'close_price', 'adj_close_price', 'volume']]
df['price_date'] = df['price_date'].dt.strftime('%Y-%m-%d %H:%M:%S')
print(df)
cursor.executemany("INSERT INTO daily_price (data_vendor_id, ticker_id, price_date, open_price, high_price, low_price, close_price, adj_close_price, volume) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", df.to_numpy().tolist())

考虑将日期-时间列转换为时间的字符串表示,并使用DataFrame.to_numpy()而不是iterrows方法:

df = pdr.get_data_yahoo(ticker, start_date)
# ADD NEW COLUMNS
df["data_vendor_id"] = YAHOO_VENDOR_ID
df["ticker_id"] = ticker_index[ticker]]
# CONVERT DATE TO STRING TIME
df["DATE"] = df["DATE"].dt.strftime('%Y-%m-%d %H:%M:%S')

sql = '''INSERT INTO daily_price (data_vendor_id, ticker_id, price_date, 
open_price, high_price, low_price, 
close_price, adj_close_price, volume) 
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
'''
# LIST
cursor.executemany(sql, df.to_numpy().tolist())
conn.commit()

相关内容

最新更新