【发布时间】:2022-01-20 03:29:08
【问题描述】:
玩了 14 个小时(我是初学者)
从一个数据库表中提取数据以在 yahoo 上搜索该股票代码上的所有数据,然后“打算”上传它。
我最初将它作为 panda df 但得到“模棱两可的错误”,所以我现在再次将它作为 [] 。新错误。我绞尽脑汁:(但是,如果我把它留空,它确实有效。
from __future__ import print_function
import yfinance as yf
import pandas as pd
import datetime
import warnings
import MySQLdb as mdb
import requests
import numpy as np
import MySQLdb as mdb
import requests
# Obtain a database connection to the MySQL instance
con = mdb.connect("localhost","sec_user","","securities_master")
def obtain_list_of_db_tickers():
"""
Obtains a list of the ticker symbols in the database.
"""
with con:
cur = con.cursor()
cur.execute("SELECT id, ticker FROM symbol")
data = cur.fetchall()
print(data)
return [(d[0], d[1]) for d in data]
def get_daily_historic_data_yahoo(ticker):
blow = yf.download(ticker)
data = []
data.append(yf.download(ticker).reset_index())
return data
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 MySQL 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()
df = pd.DataFrame(data=daily_data[0])
df.insert(0, 'data_vendor_id', data_vendor_id)
df.insert(1, 'symbol_id', symbol_id)
df.insert(3, 'created_date', now)
df.insert(4, 'last_updated_date', now)
daily_data = []
daily_data.append(df)
#df = daily_data
# Amend the data to include the vendor ID and symbol ID
# Connect to the MySQL instance
db_host = 'localhost'
db_user = ''
db_pass = ''
db_name = 'securities_master'
con = mdb.connect("localhost", "sec_user", "", "securities_master"
# host=db_host, user=db_user, passwd=db_pass, db=db_name
)
try:
mdb.connect
# If connection is not successful
except:
print("Can't connect to database")
return 0
# If Connection Is Successful
print("Connected")
final_str = """INSERT INTO daily_price (data_vendor_id, symbol_id, price_date, created_date,
last_updated_date, open_price, high_price, low_price, close_price, volume, adj_close_price) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
with con:
cur = con.cursor()
cur.executemany(final_str, daily_data)
con.commit()
if __name__ == "__main__":
# This ignores the warnings regarding Data Truncation
# from the Yahoo precision to Decimal(19,4) datatypes
warnings.filterwarnings('ignore')
# Loop over the tickers and insert the daily historical
# data into the database
tickers = obtain_list_of_db_tickers()
lentickers = len(tickers)
for i, t in enumerate(tickers):
print(
"Adding data for %s: %s out of %s" %
(t[1], i+1, lentickers)
)
yf_data = get_daily_historic_data_yahoo(t[1])
insert_daily_data_into_db('1', t[0], yf_data)
print("Successfully added Yahoo Finance pricing data to DB.")
错误
Traceback (most recent call last):
File "/home/quant/price_retrieval.py", line 106, in <module>
insert_daily_data_into_db('1', t[0], yf_data)
File "/home/quant/price_retrieval.py", line 88, in insert_daily_data_into_db
cur.executemany(final_str, daily_data)
File "/home/quant/.local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 230, in executemany
return self._do_execute_many(
File "/home/quant/.local/lib/python3.8/site-packages/MySQLdb/cursors.py", line 255, in _do_execute_many
v = values % escape(next(args), conn)
TypeError: not enough arguments for format string
【问题讨论】:
-
正确@snakecharmerb。我确实有一个奇特的解决方案,但最终以简单和手动编码 %s 我可以确认 print(datadaily) 提供了 11 列,我什至尝试添加一列以查看是否有效。
-
所以如果我使用: print(len(df.columns)) 来检查。有 11 个。如果我 print(dailydata) 有 11 个。如果我在执行 many 中使用 Daily Data,错误是:TypeError: not enough arguments for format string
-
如果我使用 df 错误是: ValueError: DataFrame 的真值是不明确的。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。
-
写入 CSV 很有趣。第一列没有标题:,data_vendor_id,symbol_id,Date,created_date,last_updated_date,Open,High,Low,Close,Adj Close,Volume 0,1,5051,1970-01-02,2021-12-17 08 :29:17.962685,2021-12-17 08:29:17.962685,6.851562976837158,6.890625,6.84375,6.851562976837158,1.4377198219299316,72000
-
这能回答你的问题吗? stackoverflow.com/questions/29938613/…