Python将股票数据保存到MySQL中

前文介绍了如何获取到股票数据并保存到Excel当中,相信大家已经学会了。但是,用Excel保存数据,数据量上还是不足,并且分析处理上还是不够便捷。所以我们今天以MySQL为例,介绍一下如何把股票数据保存到数据库中。

首先,创建数据表,SQL如下:

CREATE TABLE `stock` (
  `id` int NOT NULL,
  `code` varchar(255) NOT NULL COMMENT '代码',
  `name` varchar(255) NOT NULL COMMENT '名称',
  `price` float(11,2) DEFAULT NULL COMMENT '价格',
  `increase` float(11,2) DEFAULT NULL COMMENT '涨幅',
  `pe` float(11,2) DEFAULT NULL COMMENT '动态市盈率',
  `pb` float(11,2) DEFAULT NULL COMMENT '市净率',
  `total_value` float(11,2) DEFAULT NULL COMMENT '总市值(亿)',
  `currency_value` float(11,2) DEFAULT NULL COMMENT '流通市值(亿)',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='股票';

接下来,我们pymysql来编写插入数据方法,代码如下:

import pymysql

# 数据库连接
def db(sql):
    db = pymysql.connect(host='1.2.3.4', port=3306, user='root', password='root', db='data_center', charset='utf8')
    cursor = db.cursor()
    try:
        cursor.execute(sql)
        db.commit()
    except Exception as e:
        print(e)
        db.rollback()
    db.close()

最后,获取股票数据并插入到数据库中,完整代码如下:

import requests
import pymysql


# 数据库连接
def db(sql):
    db = pymysql.connect(host='1.2.3.4', port=3306, user='root', password='root', db='data_center', charset='utf8')
    cursor = db.cursor()
    try:
        cursor.execute(sql)
        db.commit()
    except Exception as e:
        print(e)
        db.rollback()
    db.close()


# 获取数据
def stock_get():
    url = 'http://27.push2.eastmoney.com/api/qt/clist/get'
    for i in range(1, 10):
        data = {
            'fields': 'f2,f3,f9,f12,f14,f20,f21,f23',
            'pz': 1000,  # 每页条数
            'pn': i,  # 页码
            'fs': 'm:0 t:6,m:0 t:80,m:1 t:2,m:1 t:23,m:0 t:81 s:2048'
        }
        response = requests.get(url, data)
        response_json = response.json()
        if response_json['data'] is None:  # 返回数据为空时停止循环
            break
        for j, k in response_json['data']['diff'].items():
            code = k['f12']  # 代码
            name = k['f14']  # 名称
            price = k['f2']  # 股价
            increase = k['f3']  # 涨幅
            pe = k['f9']  # 动态市盈率
            pb = k['f23']  # 市净率
            total_value = k['f20']  # 总市值
            currency_value = k['f21']  # 流通市值
            price = round(price / 100, 2)  # 价格转换为正确值(保留2位小数)
            increase = round(increase / 100, 2)  # 价格转换为正确值(保留2位小数)
            pe = round(pe / 100, 2)  # 市盈率转换为正确值(保留2位小数)
            pb = round(pb / 100, 2)  # 市净率转换为正确值(保留2位小数)
            total_value = round(total_value / 100000000, 2)  # 总市值转换为亿元(保留2位小数)
            currency_value = round(currency_value / 100000000, 2)  # 流通市值转换为亿元(保留2位小数)
            print('代码: %s, 名称: %s, 现价: %s, 涨幅: %s%%, 动态市盈率: %s, 市净率: %s, 总市值: %s亿, 流通市值: %s亿' % (code, name, price, increase, pe, pb, total_value, currency_value))
            # 执行SQL语句
            sql_insert = 'INSERT INTO `test_center`.`stock_new`(`id`, `code`, `name`, `price`, `increase`, `pe`, `pb`, `total_value`, `currency_value`) VALUES (%s, "%s", "%s", %s, %s, %s, %s, %s, %s);' % (int(code), code, name, price, increase, pe, pb, total_value, currency_value)
            db(sql_insert)


if __name__ == '__main__':
    stock_get()

数据插入完成之后,我们可以执行SQL(select * from stock_new order by id asc;)来查询结果,如图:

Python将股票数据保存到MySQL中

#股票财经# #股市分析# #财经# #股票# #A股#

发表评论
留言与评论(共有 0 条评论) “”
   
验证码:

相关文章

推荐文章