使用如下代码从TuShare下载沪深300每只股票的历史成交记录并按股票、日期保存到本地。主要是为了以后查询方便快速。

#-*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import tushare as ts
import datetime
import time
import tushare as ts
import os data_dir = '/home/vnpy/share/' #下载数据的存放路径 #ts.get_sz50s() #获取上证50成份股 返回值为DataFrame:code股票代码 name股票名称 #cal_dates = ts.trade_cal() #返回交易所日历,类型为DataFrame, calendarDate isOpen
cal_dates = pd.read_csv(data_dir+'trade_cal.csv') #本地实现判断市场开市函数
#@date: str类型日期 eg.'2017-11-23'
def is_open_day(date):
if date in cal_dates['calendarDate'].values:
return cal_dates[cal_dates['calendarDate']==date].iat[0,2]==1
return False #从TuShare获取tick data数据并保存到本地
#@symbol: str类型股票代码 eg.600030
#@date: date类型日期
def get_save_tick_data(symbol, date):
global sleep_time,data_dir
res=True
sleep_time=2
str_date=str(date)
dir=data_dir+symbol+'/'+str(date.year)+'/'+str(date.month)
file=dir+'/'+symbol+'_'+str_date+'.csv'
if is_open_day(str_date):
if not os.path.exists(dir):
os.makedirs(dir)
if not os.path.exists(file):
try:
d=ts.get_tick_data(symbol,str_date,pause=0.1)
except IOError, msg:
print str(msg).decode('UTF-8')
sleep_time=min(sleep_time*2, 128)#每次下载失败后sleep_time翻倍,但是最大128s
print 'Get tick data error: symbol: '+ symbol + ', date: '+str_date+', sleep time is: '+str(sleep_time)
return res
else:
d.to_csv(file)
#hdf5_file=pd.HDFStore(file, 'w',complevel=4, complib='blosc')
#hdf5_file['data']=d
#hdf5_file.close()
sleep_time=max(sleep_time/2, 2) #每次成功下载后sleep_time变为一半,但是至少2s
print "Successfully download and save file: "+file+', sleep time is: '+str(sleep_time)
return res
else:
print "Data already downloaded before, skip " + file
res=False
return res #获取从起始日期到截止日期中间的的所有日期,前后都是封闭区间
def get_date_list(begin_date, end_date):
date_list = []
while begin_date <= end_date:
#date_str = str(begin_date)
date_list.append(begin_date)
begin_date += datetime.timedelta(days=1)
return date_list #获取感兴趣的所有股票信息,这里获取沪深全部股票
def get_all_stock_id():
#stock_info=ts.get_hs300s()
stock_info = pd.read_csv(data_dir+'stock_basics.csv')
return stock_info['code'].values # 补全股票代码(6位股票代码)
# input: int or string
# output: string
def getSixDigitalStockCode(code):
strZero = ''
for i in range(len(str(code)), 6):
strZero += '0'
return strZero + str(code) #从TuShare下载感兴趣的所有股票的历史成交数据,并保存到本地HDF5压缩文件
#dates=get_date_list(datetime.date(2017,11,6), datetime.date(2017,11,12))
dates=get_date_list(datetime.date(2018,1,1), datetime.date(2018,7,9))
stocks=get_all_stock_id()
for stock in stocks:
for date in dates:
if get_save_tick_data(getSixDigitalStockCode(stock), date):
time.sleep(sleep_time)

  

因为TuShare并没有提供1分钟线的信息,所以需要根据下载到的每日成交信息生成1分钟线信息。

代码如下: 其实就是不用for和列,直接 newdf = df.resample ... 保存列头一致就好了

#-*- coding: utf-8 -*-
import pandas as pd
import datetime
import os #根据分笔成交数据生成1分钟线
def gen_min_line(symbol, date):
global data_dir
data_dir = '/home/vnpy/share/'
str_date=str(date)
dir=data_dir+symbol+'/'+str(date.year)+'/'+str(date.month)
tickfile=dir+'/'+symbol+'_'+str_date+'.csv'
minfile=dir+'/'+symbol+'_'+str_date+'_1m.csv'
print tickfile,minfile
if (os.path.exists(tickfile)) and (not os.path.exists(minfile)):
df=pd.read_csv(tickfile)
print "Successfully read tick file: "+tickfile
if df.shape[0]<10: #TuShare即便在停牌期间也会返回tick data,并且只有三行错误的数据,这里利用行数小于10把那些unexpected tickdata数据排除掉
print "No tick data read from tick file, skip generating 1min line"
return 0
df['time']=str_date+' '+df['time']
df['time']=pd.to_datetime(df['time'])
df=df.set_index('time')
price_df=df['price'].resample('1min').ohlc()
price_df=price_df.dropna()
vols=df['volume'].resample('1min').sum()
vols=vols.dropna()
vol_df=pd.DataFrame(vols,columns=['volume'])
amounts=df['amount'].resample('1min').sum()
amounts=amounts.dropna()
amount_df=pd.DataFrame(amounts,columns=['amount'])
newdf=price_df.merge(vol_df, left_index=True, right_index=True).merge(amount_df, left_index=True, right_index=True)
newdf.to_csv(minfile)
print "Successfully write to minute file: "+minfile dates=get_date_list(datetime.date(2018,1,1), datetime.date(2018,7,9))
stocks=get_all_stock_id()
for stock in stocks:
for date in dates:
gen_min_line(stock, date)

  

  refer to:https://blog.csdn.net/wqfhenanxc/article/details/78525730

使用TuShare下载历史逐笔成交数据并生成1分钟线的更多相关文章

  1. 下载历史版本App超详细教程

    有些时候我们需要下载旧版本的 App 进行研究或者其他用途,然而在 iOS 下,苹果的 App Store 里面默认只能下载最新版本的 App,对滴,就是这么任性,不服不行.然而在 Android 里 ...

  2. Python获取股票历史、实时数据与更新到数据库

    要做量化投资,数据是基础,正所谓"巧妇难为无米之炊" 在免费数据方面,各大网站的财经板块其实已提供相应的api,如新浪.雅虎.搜狐...可以通过urlopen相应格式的网址获取数据 ...

  3. 如何在Maven官网下载历史版本

    如何在Maven官网下载历史版本 历史版本一般会隔一段时间,便找不到,官网会及时显示的是最新版本.不多说,直接进入. https://archive.apache.org/dist/maven/bin ...

  4. 下载历史版本App

    文/timhbw(简书作者)原文链接:http://www.jianshu.com/p/edfed1b1822c著作权归作者所有,转载请联系作者获得授权,并标注“简书作者”. 1.软件准备 [必备]C ...

  5. 青花瓷运用->下载历史版本App

    1.软件准备 [必备]Charles4.0.1 下载密码: jfnk [不需要,配合Charles食用效果更佳]Paw2.3.1 下载密码: t3my 2.正式开始 2.1 打开Charles青花瓷 ...

  6. 利用PHP从淘宝采集评论和成交数据

    如果不想通过淘宝开放平台API获取数据,那么另外一个很好的办法就是采集了.一般来说,采集一个网页上的内容,只需要用CURL获取源代码,然后用正则表达式取出需要的内容就可以,不过如果这样载入一个淘宝的页 ...

  7. 搭建mysql5.626及如何去官网下载历史版本数据库

    MySQL官网下载历史版本 网上搜索MySQL官网 2 查询所有的归档文件   点击进入服务器列表   列表中默认只有Windows 版本的,可选择其它版本,但无法进行查询   查看网页元素   发现 ...

  8. Jenkins下载历史Build版本的归档文件

    /root/.jenkins/jobs/zgg-crm-pre/builds//com.zgg$crm/archive/com.zgg/crm/0.0.1/crm-0.0.1.war https:// ...

  9. 使用git下载源码及数据文件

    初学git,用来下载github上的数据和源代码,具体步骤如下. 1.百度搜索git并下载:本想从github直接下载安装,无奈国外服务器的下载速度太慢,建议国内的直接搜索下载完整安装版. 2.完成g ...

随机推荐

  1. winform窗体 小程序【移动窗体和阴影】

    窗体无边框设置后无法移动,引用API 使其获得功能 移动 //窗体移动API [DllImport("user32.dll")] public static extern bool ...

  2. IDEA@Data注释使用

    @Data注解主要是帮助解决Setter 和 Getter以及 toString这种重复的无脑工作 加入@Data注解可以直接帮助我们添加实体类相应的Setter 和 Getter以及 toStrin ...

  3. BestCoder Round #29——A--GTY's math problem(快速幂(对数法))、B--GTY's birthday gift(矩阵快速幂)

    GTY's math problem Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Other ...

  4. php命令行生成与读取配置文件

    接着之前的文章:php根据命令行参数生成配置文件 ghostinit.php <?php class ghostinit{ static $v = 'ghost version is 1.1'; ...

  5. js-ES6学习笔记-async函数

    1.async 函数是 Generator 函数的语法糖.前文有一个 Generator 函数,依次读取两个文件. var fs = require('fs'); var readFile = fun ...

  6. linux下将本地文件上传到github中?

    今天编写一份Python基础代码,经过Linux上传到github上,遇到点问题,已经解决 1.首先sudo su 进入root 用户 2.ls 检查出当前文件下有什么文件 3. cd 进入你将要上传 ...

  7. (1-2)line-height的各类属性值

    (1-2)line-height的各类属性值 首先来个疑问!没有问题印象不深嘛 一.line-height支持哪些属性值呢? 五只手指头就能数过来了咯. 比如normal, <number> ...

  8. AJAX删除事件与加载数据

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  9. ionic开发之Android可以很快打开主页,iOS要几分钟打开主页

    原来是gap://ready导致的csp问题,日志会有这样的提示 解决的办法就是在你的index.html添加gap:的csp配置 <meta http-equiv="Content- ...

  10. Android--将实体类转化成Json和Map的基类

    package com.newair.talk.base; import android.text.TextUtils; import com.google.gson.Gson; import jav ...