Tushare库之日线行情
生活随笔
收集整理的這篇文章主要介紹了
Tushare库之日线行情
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
接口:daily
更新時間:交易日每天15點~16點之間
調取說明:每分鐘內最多調取200次,超過5000積分無限制
描述:獲取股票行情數據,或通過通用行情接口獲取數據,包含了前后復權數據.
輸入參數
| ts_code | str | N | 股票代碼(二選一) |
| trade_date | str | N | 交易日期(二選一) |
| start_date | str | N | 開始日期(YYYYMMDD) |
| end_date | str | N | 結束日期(YYYYMMDD) |
注:日期都填YYYYMMDD格式,比如20181010
輸出參數
| ts_code | str | 股票代碼 |
| trade_date | str | 交易日期 |
| open | float | 開盤價 |
| high | float | 最高價 |
| low | float | 最低價 |
| close | float | 收盤價 |
| pre_close | float | 昨收價 |
| change | float | 漲跌額 |
| pct_chg | float | 漲跌幅 (未復權,如果是復權請用 通用行情接口 ) |
| vol | float | 成交量 (手) |
| amount | float | 成交額 (千元) |
?
接口示例
pro = ts.pro_api()df = pro.daily(ts_code='000001.SZ', start_date='20180701', end_date='20180718')或者
df = pro.query('daily', ts_code='000001.SZ', start_date='20180701', end_date='20180718')也可以通過日期取歷史某一天的全部歷史
df = pro.daily(trade_date='20180810')數據樣例
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這個是股票分析最重要的接口,我經常將每日的行情下下來放到數據庫中(將代碼加入到定時任務,每天自動更新數據)。
效果圖:
代碼:
# -*- coding: utf-8 -*- """ Created on 2019年3月11日 23點06分 @author: fanbinglin """ #%%導入模塊 # from datetime import datetime,timedelta,time#時間處理函數 import time#時間處理函數 import pymysql #mysql操作庫 import pandas as pd import numpy as np import tushare as ts import sys import os #%%全局對象#生產環境mysql配置 mysqlSetting_server={'host':"ip",'port':3306,'user':"root", 'passwd':"**********", 'db':"Finance", 'charset':'utf8' } #本地 mysqlSetting_local={'host':"localhost",'port':3306,'user':"root", 'passwd':"***********", 'db':"Finance", 'charset':'utf8' }#執行sql語句 def exeSql(mysqlSetting,sql,mode = 0):# 打開數據庫連接db = pymysql.connect(host=mysqlSetting['host'], port=mysqlSetting['port'],user=mysqlSetting['user'], \passwd=mysqlSetting['passwd'], db=mysqlSetting['db'], charset=mysqlSetting['charset'] )# 使用cursor()方法獲取操作游標 cursor = db.cursor()if mode == 0:ret = 0try:cursor.execute(sql)ret = cursor.fetchall()print(ret)db.commit()except:db.rollback()# 關閉數據庫連接finally:db.close()return retelse:for line in sql:try:cursor.execute(line)except:cursor.rollback()# 關閉數據庫連接db.commit()db.close() #DataFrame對象落地數據庫 def df2sql(mysqlSetting,df,tableName):# 打開數據庫連接db = pymysql.connect(host=mysqlSetting['host'], port=mysqlSetting['port'],user=mysqlSetting['user'], \passwd=mysqlSetting['passwd'], db=mysqlSetting['db'], charset=mysqlSetting['charset'] )# 使用cursor()方法獲取操作游標 cursor = db.cursor() #添加操作的sql語句sqlInsert="REPLACE INTO "+tableName+" ("for _,column in enumerate(df.columns):if _<len(df.columns)-1:sqlInsert =sqlInsert+column+','else:sqlInsert =sqlInsert+column+') VALUES 'for index,row in df.iterrows():sqlInsertNew=sqlInsert+'('for i,column in enumerate(df.columns): if i<len(df.columns)-1:if pd.isnull(row[column]) or row[column] == 0:sqlInsertNew=sqlInsertNew+'NULL'+','else:sqlInsertNew=sqlInsertNew+'\''+str(row[column])+'\''+','#sqlInsertNew=sqlInsertNew+'\''+str(row[column])+'\''+','else:if pd.isnull(row[column]) or row[column] == 0:sqlInsertNew=sqlInsertNew+'NULL' else:sqlInsertNew=sqlInsertNew+'\''+str(row[column])+'\'' #sqlInsertNew=sqlInsertNew+'\''+str(row[column])+'\''sqlInsertNew=sqlInsertNew+');'#print(sqlInsertNew)cursor.execute(sqlInsertNew)db.commit()# 關閉數據庫連接db.close() def saveFile(filename,content,mode):try:#with open(filename,mode,encoding='utf-8') as f:#二進制文件不能保存為utf-8格式with open(filename,mode) as f:f.write(content)f.close()print('\t'+filename + "保存成功!")except:print('\t'+filename + "保存失敗!")f.close()def readFile(filename):try:with open(filename,"r",encoding='utf-8') as f:return f.read()except:return False if __name__ == '__main__':print(sys.argv)mode = 5 #0:(2,5)-all 1:自選股票 other:allinsertPara = 0if len(sys.argv) > 1:insertPara = int(sys.argv[1])ts.set_token('357f92fd3836f2d018d20b9b840897abb3e5c9a62e17895b413e05fe')today = time.strftime('%Y%m%d')pro = ts.pro_api()calendar = pro.query('trade_cal', start_date='20190101', end_date=today)trade_cal = calendar[calendar.is_open==1]df = pro.daily(trade_date=trade_cal.cal_date.values[-1]) #今天if not len(df):df = df = pro.daily(trade_date=trade_cal.cal_date.values[-2]) #如果今天沒數據,就請求上一個交易日df.rename(columns = {0:'ts_code',1:'ts_name',2:'trade_date',3:'ts_open',4:'ts_high',5:'ts_low',6:'ts_close',7:'pre_close',8:'ts_change',9:'pct_chg',10:'vol',11:'amount'},inplace = True)issueCode2IssueName = dict(pro.query('stock_basic', exchange='', list_status='L', fields='ts_code,name').values)if mode == 0:dfMask = list(df[(2 <df.open < 5)&(~df.ts_code.str.contains('^3'))].ts_code)start = '20190201'end = '20190529'elif mode == 1:# dfMask = ['600175.SH','600868.SH','000883.SZ','600425.SH','002145.SH','600869.SH','601991.SH']dfMask = ['600175.SH','600868.SH','000883.SZ']start = '19920101'end = '20150102'else:dfMask = list(df[(df.open < 18)&(~df.ts_code.str.contains('^3'))].ts_code)start = '20190522'end = '20190602'stockListDict = {k:v for k,v in issueCode2IssueName.items() if k in dfMask}createTableSql = r'create table IF NOT EXISTS myPrice(ts_code char(255),ts_name char(255),trade_date char(255),ts_open char(255),ts_high char(255),ts_low char(255),ts_close char(255),pre_close char(255),ts_change char(255),pct_chg char(255),vol char(255),amount char(255),PRIMARY KEY (ts_code,trade_date));'exeSql(mysqlSetting_local,createTableSql)end = '20190529'length = len(stockListDict)count = 1if insertPara == 0:#大量插入,按issuCode來請求,一般是第一次請求for issueCode,issueName in stockListDict.items():data = pro.query('daily',ts_code=issueCode,start_date = start,end_date = end)print("id = {id},name = {name},index = {index},totleLen = {length}".format(id = issueCode,name = issueName,index = count,length = length))data.rename(columns={'open':'ts_open','high':'ts_high','low':'ts_low','close':'ts_close','change':'ts_change'},inplace=True)data['ts_name'] = issueCode2IssueName[issueCode]df2sql(mysqlSetting_local,data,'myPrice')count += 1if insertPara == 1:#按交易日來,一般是用來增量增加for date in trade_cal.cal_date.values[-1:-5:-1]:data = pro.daily(trade_date=date)dfMask = list(df[(df.open < 18)&(~df.ts_code.str.contains('^3'))].ts_code)dataMask = data[data.ts_code.isin(dfMask)].ts_codestockListDict = {k:v for k,v in issueCode2IssueName.items() if k in dfMask}print("date = {}".format(date))dataInsert = data[data.ts_code.isin(stockListDict.keys())].copy()dataInsert.rename(columns={'open':'ts_open','high':'ts_high','low':'ts_low','close':'ts_close','change':'ts_change'},inplace=True)dataInsert['ts_name'] = dataInsert['ts_code'].map(lambda x:stockListDict[x])df2sql(mysqlSetting_local,dataInsert,'myPrice')saveTimte = time.strftime('%Y/%m/%d %H:%M:%S')saveFile(r'F:\Code\Python\python3.6.5\項目\金融數據\history\history.log',saveTimte + '\n','a+')這里的token是我的賬號生成的,如果你也想注冊,麻煩用 推薦 https://tushare.pro/register?reg=241422 鏈接。
這里需要提前在本地裝好Mysql數據庫并根據代碼建立好數據庫和數據表,如果不會裝數據庫請參看之前的博客文章。
數據庫代碼:
/* Navicat MySQL Data TransferSource Server : fbl Source Server Version : 80011 Source Host : localhost:3306 Source Database : financeTarget Server Type : MYSQL Target Server Version : 80011 File Encoding : 65001Date: 2019-08-01 23:18:12 */SET FOREIGN_KEY_CHECKS=0;-- ---------------------------- -- Table structure for myprice -- ---------------------------- DROP TABLE IF EXISTS `myprice`; CREATE TABLE `myprice` (`ts_code` char(255) NOT NULL,`ts_name` char(255) DEFAULT NULL,`trade_date` char(255) NOT NULL,`ts_open` char(255) DEFAULT NULL,`ts_high` char(255) DEFAULT NULL,`ts_low` char(255) DEFAULT NULL,`ts_close` char(255) DEFAULT NULL,`pre_close` char(255) DEFAULT NULL,`ts_change` char(255) DEFAULT NULL,`pct_chg` char(255) DEFAULT NULL,`vol` char(255) DEFAULT NULL,`amount` char(255) DEFAULT NULL,PRIMARY KEY (`ts_code`,`trade_date`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;?
喜歡折騰代碼的加群(群號:822286811)一起交流學習【python、VBA、Shell、Linux、dos、爬蟲、拆機、裝系統技術交流群】,點擊鏈接加入群聊【計算機技術交流】:https://jq.qq.com/?_wv=1027&k=5V7RB2c?
總結
以上是生活随笔為你收集整理的Tushare库之日线行情的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Moravec角点检测算子
- 下一篇: linux系统安装arcsde,Linu