1.背景
做量化交易的时候经常要用到股票的历史数据,例子中主要爬取每分钟'date','time''open','close','high','low','volume','money','avg'
这几个字段数据,爬取之后存入数据库。
2.例子
```csharp
# 连接聚宽
from jqdatasdk import *
auth('注册账户','注册密码') # 账号是申请时所填写的手机号;密码为聚宽官网登录密码
# 连接数据库测试
import pymysql
# 打开数据库
db = pymysql.connect(host="localhost",user="root",password="1234",db="stock")
# 使用cursor()方法获取操作游标
cur = db.cursor()
# 根据get_price接口获取每分钟数据
# get_price没有日期字段,要通过获得索引的方式来获得日期(date)和时间(time)
df = get_price('002326.XSHE', start_date='2021-09-01 00:00:00', end_date='2022-02-28 00:00:00', frequency='1m', fields=['open','close','high','low','volume','money','avg'])
# 先在mysql建表,然后将数据插入数据库
j=0
for i in df.index:
print(df.index[j].strftime('%Y-%m-%d'))
print(df.index[j].strftime('%X'))
sql = """INSERT INTO data_002326(date,time,open,close,high,low,volume,money,avg)
VALUES ('%s','%s','%s', '%s', '%s', '%s', '%s', '%s', '%s')""" % (df.index[j].strftime('%Y-%m-%d'),df.index[j].strftime('%X'),df.loc[i,'open'],df.loc[i,'close'],df.loc[i,'high'],df.loc[i,'low'],df.loc[i,'volume'],df.loc[i,'money'],df.loc[i,'avg'])
j=j+1
try:
cur.execute(sql)
#提交
db.commit()
except Exception as e:
#错误回滚
db.rollback()
结果:
# mysql建表
CREATE TABLE IF NOT EXISTS `data_600030`(
`id` INT UNSIGNED AUTO_INCREMENT,
`date` VARCHAR(100),
`time` VARCHAR(100) ,
`open` DECIMAL(10,2) ,
`close` DECIMAL(10,2) ,
`high` DECIMAL(10,2) ,
`low` DECIMAL(10,2) ,
`volume` DECIMAL(15,2) ,
`money` DECIMAL(15,2),
`avg` DECIMAL(10,2),
PRIMARY KEY ( `id` )
)ENGINE=INNODB DEFAULT CHARSET=utf8;