【发布时间】:2014-08-18 21:27:46
【问题描述】:
因此,我在 QuantState 找到了一个很棒的脚本,它对设置我自己的证券数据库和加载历史定价信息进行了很好的演练。但是,我并不想修改脚本,以便我可以每天运行它并添加最新的股票报价。
我将初始数据加载调整为仅下载 1 周的历史数据,但我在编写 SQL 语句以查看该行是否在添加之前已经存在时遇到了问题。谁能帮我解决这个问题。这是我目前所拥有的:
def insert_daily_data_into_db(data_vendor_id, symbol_id, daily_data):
"""Takes a list of tuples of daily data and adds it to the
database. Appends the vendor ID and symbol ID to the data.
daily_data: List of tuples of the OHLC data (with
adj_close and volume)"""
# Create the time now
now = datetime.datetime.utcnow()
# Amend the data to include the vendor ID and symbol ID
daily_data = [(data_vendor_id, symbol_id, d[0], now, now,
d[1], d[2], d[3], d[4], d[5], d[6]) for d in daily_data]
# Create the insert strings
column_str = """data_vendor_id, symbol_id, price_date, created_date,
last_updated_date, open_price, high_price, low_price,
close_price, volume, adj_close_price"""
insert_str = ("%s, " * 11)[:-2]
final_str = "INSERT INTO daily_price (%s) VALUES (%s) WHERE NOT EXISTS (SELECT 1 FROM daily_price WHERE symbol_id = symbol_id AND price_date = insert_str[2])" % (column_str, insert_str)
# Using the postgre connection, carry out an INSERT INTO for every symbol
with con:
cur = con.cursor()
cur.executemany(final_str, daily_data)
【问题讨论】:
标签: python sql postgresql stock