SQLite将交易数据附加到现有数据库不起作用



我已经创建了我的第一个SQLite数据库。数据库中每个股票行情器都有一个表,其中包含Date、Open、High、Low、Close和Volume列。当第一次创建数据时,它运行良好。但随着时间的推移,新的数据是可用的,因为这是每天的股票行情信息。当试图附加新的时间序列数据时,会出现错误。

将OHLCV插入此股票行情机时出错ABT错误:UNIQUE约束失败:ABT日期

我知道有些条目的日期会重叠。我只需要加上遗漏的时间。

这是我的代码:

def insertData(db,tickers):
conn = sqlite3.connect(db)
c = conn.cursor()
for ticker in tickers:
try:
df = web.DataReader(ticker, 'alphavantage', start, end,api_key=AV_API_Key) #quandl stopped free data 2018
print(df)
except:
df = web.DataReader(ticker, 'yahoo', start, end) #if quandl doesn't have, try yahoo
print("===", ticker, "===")
print(df.tail(1))
for idx, val in df.iterrows():
try:
c.execute(
"INSERT INTO '{}' (Date, Open, High, Low, Close)"
"          VALUES(:Date, :Open, :High, :Low, :Close)".format(ticker),
{'Date':idx.strftime('%Y-%m-%d %H-%M-%S'),'Open':val['Open'],'High':val['High'],'Low':val['Low'],'Close':val['Close']})
except Error as e:
print("Error Inserting OHLCV to this ticker", ticker, "Err:", e)
print("Inserted", ticker)
conn.commit()
conn.close()

您已将Date作为主键,这意味着它的值对于所有行都必须是唯一的,但您正试图添加一个日期已存在的新行,因此出现错误。

DROP表(DROP TABLE XXX;(,并在不使用Date作为PK的情况下重新创建它-如果您想要PK,则添加AUTOINCREMENT列。

CREATE TABLE "XXX" (
"Id"    INTEGER NOT NULL,
"Date"  DATETIME NOT NULL,
"Open"  FLOAT,
"High"  FLOAT,
"Low"   FLOAT,
"Close" FLOAT,
PRIMARY KEY("Id" AUTOINCREMENT)
);

如果您希望Date针对查找进行优化,可以向其添加非唯一索引:

CREATE INDEX "IX_XXX_Date" ON "XXX" (
"Date"
);

在设计方面,99%的情况下,使用一个带有ticker-name列的表比每个ticker使用一个表要好。

最新更新