利用tushare获取金融数据并储存在Mysql中

发布于:2022-12-14 ⋅ 阅读:(806) ⋅ 点赞:(0)

 强烈推荐使用tushare金融数据包

Tushare数据有多种周期的金融数据,还有另类数据,指标数据等

用起来很方便

import tushare as ts

pro = ts.pro_api()
df = pro.daily(ts_code='000001.SZ', start_date='20180701', end_date='20180718')
#多个股票
#df = pro.daily(ts_code='000001.SZ,600000.SH', start_date='20180701', end_date='20180718')

获取结果:

 ts_code     trade_date  open  high   low  close  pre_close  change    pct_chg  vol        amount
0  000001.SZ   20180718  8.75  8.85  8.69   8.70       8.72   -0.02       -0.23   525152.77   460697.377
1  000001.SZ   20180717  8.74  8.75  8.66   8.72       8.73   -0.01       -0.11   375356.33   326396.994
2  000001.SZ   20180716  8.85  8.90  8.69   8.73       8.88   -0.15       -1.69   689845.58   603427.713
3  000001.SZ   20180713  8.92  8.94  8.82   8.88       8.88    0.00        0.00   603378.21   535401.175
4  000001.SZ   20180712  8.60  8.97  8.58   8.88       8.64    0.24        2.78  1140492.31  1008658.828
5  000001.SZ   20180711  8.76  8.83  8.68   8.78       8.98   -0.20       -2.23   851296.70   744765.824
6  000001.SZ   20180710  9.02  9.02  8.89   8.98       9.03   -0.05       -0.55   896862.02   803038.965
7  000001.SZ   20180709  8.69  9.03  8.68   9.03       8.66    0.37        4.27  1409954.60  1255007.609
8  000001.SZ   20180706  8.61  8.78  8.45   8.66       8.60    0.06        0.70   988282.69   852071.526
9  000001.SZ   20180705  8.62  8.73  8.55   8.60       8.61   -0.01       -0.12   835768.77   722169.579

如何储存在Mysql中呢? 

首先要在Mysql建立相应的表格:

1.库名:stock 表名:stock_all

字段名

字段类型

说明

state_dt

varchar2(45)

交易日

stock_code

varchar2(45)

股票代码

open

decimal(20,2)

开盘价

close

decimal(20,2)

收盘价

high

decimal(20,2)

最高价

low

decimal(20,2)

最低价

vol

int(20)

成交量

amount

decimal(20,2)

成交额

pre_close

decimal(20,2)

前日收盘价

amt_change

decimal(20,2)

涨跌额

pct_change

decimal(20,2)

涨跌幅

 Mysql代码如下: 

create table stock_all(
state_dt varchar(45),
stock_code varchar(45),
open decimal(20,2),
close decimal(20,2),
high decimal(20,2),
low decimal(20,2),
vol int(20),
amount decimal(20,2),
pre_close decimal(20,2),
amt_change decimal(20,2),
pct_change decimal(20,2)
)default charset=utf8;  

 把想要的数据储存到你的数据库里,以股票日线数据为例:

import datetime
import tushare as ts
import pymysql

if __name__ == '__main__':

    # 设置tushare pro的token并获取连接
    # ts.set_token('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx')
    pro = ts.pro_api()
    # 设定获取日线行情的初始日期和终止日期,其中终止日期设定为昨天。
    start_dt = '20100101'
    time_temp = datetime.datetime.now() - datetime.timedelta(days=1)
    end_dt = time_temp.strftime('%Y%m%d')
    # 建立数据库连接,剔除已入库的部分
    db = pymysql.connect(host='127.0.0.1', user='root', passwd='passwd', db='quanta', charset='utf8')#passwd是你数据库的密码,db是你要储存库的名字
    cursor = db.cursor()
    # 设定需要获取数据的股票池
    stock_pool = ['000001.SZ','000002.SZ']
     total = len(stock_pool)
    # 循环获取单个股票的日线行情
    for i in range(total):
        try:
            df = pro.daily(ts_code=stock_pool[i], start_date=start_dt, end_date=end_dt)
            # 打印进度
            print('Seq: ' + str(i + 1) + ' of ' + str(total) + '   Code: ' + str(stock_pool[i]))
            c_len = df.shape[0]  # 多少行数据,假设100行

        except Exception as aa:
            print(aa)
            print('No DATA Code: ' + str(i))
            continue
        for j in range(c_len):  # 100行数据
            resu0 = list(df.iloc[c_len - 1 - j])
            resu = []
            for k in range(len(resu0)):
                if str(resu0[k]) == 'nan':
                    resu.append(-1)
                else:
                    resu.append(resu0[k])
            state_dt = (datetime.datetime.strptime(resu[1], "%Y%m%d")).strftime('%Y-%m-%d')
            try:
                sql_insert = "insert into stock_all(state_dt,stock_code,open,close,high,low,vol,amount,pre_close,amt_change,pct_change) VALUES ('%s', '%s', '%.2f', '%.2f','%.2f','%.2f','%i','%.2f','%.2f','%.2f','%.2f')" % (
                    state_dt, str(resu[0]), float(resu[2]), float(resu[5]), float(resu[3]), float(resu[4]),
                    float(resu[9]),
                    float(resu[10]), float(resu[6]), float(resu[7]), float(resu[8]))
                cursor.execute(sql_insert)
                db.commit()
            except Exception as err:
                continue
    cursor.close()
    db.close()
    print('All Finished!')

 获取读取到的数据:

def get_stockdaily(stock_code, state_dt,front_time):
    df = pd.read_sql("SELECT * FROM quanta.stock_all where stock_code='% s' and state_dt<='%s' and state_dt>='%s'" % (stock_code, state_dt, front_time), con=db, index_col='state_dt', parse_dates=['state_dt'])[
        ['amount']]#拿到股票'open', 'close', 'low', 'high'.
    print(df.head(20))
    reture

其他表格不一一列举代码:

2.库名:stock 表名:my_capital

字段名

字段类型

说明

capital

decimal(20,2)

总资产

money_lock

decimal(20,2)

股票资产

money_rest

decimal(20,2)

现金资产

deal_action

varchar2(45)

交易动作

stock_code

varchar2(45)

股票代码

deal_price

decimal(20,2)

成交价

stock_vol

int(11)

成交量

profit

decimal(20,2)

收益额

profit_rate

decimal(20,2)

收益率

bz

varchar2(45)

备注

state_dt

varchar2(45)

交易日期

seq

int(11)

序号(用作表主键)

3.库名:stock 表名:my_stock_pool

字段名

字段类型

字段说明

stock_code

varchar2(45)

股票代码

buy_price

decimal(20,2)

买入价

hold_vol

int(11)

持仓量(单位:股)

hold_days

int(11)

持仓天数(只计算交易日)

4.库名:stock 表名:model_ev_resu

字段名

字段类型

说明

state_dt

varchar2(45)

评估日期

stock_code

varchar2(45)

股票代码

acc

decimal(20, 4)

查准率

recall

decimal(20, 4)

查全率

f1

decimal(20, 4)

f1分值

acc_neg

decimal(20, 4)

查准率(负样本)

bz

varchar2(45)

用于标注模型类别,比如svm、决策树等

predict

varchar2(45)

对评估日后一个交易日的预测值

5.库名:stock 表名:model_ev_mid

字段名

字段类型

说明

state_dt

varchar2(45)

回测日期

stock_code

varchar2(45)

股票代码

resu_predict

decimal(20, 2)

预测值

resu_real

decimal(20, 2)

真实值

 

本文含有隐藏内容,请 开通VIP 后查看