Python tushare stock data acquisition and local storage

# Preface
always wanted to share and store data download tushare to the local hard drive as a quantitative analysis of the future, suffer from a rookie himself, after studying in the major forum for reluctantly write this function (special thanks here know almost "Swordsman special "Teacher Deer" shared the enlightenment of the code), I hope it can play a role in attracting suggestions and improvements from all the big guys. If you can, please give me a thumbs up. Your encouragement is my motivation to write the article and share it. On the code.

import tushare as ts
import pandas as pd
import time
import os

os.chdir('D:/all_trading_data/')  #保存的绝对路径
pro = ts.pro_api('要到tushare官网注册个账户然后将token复制到这里,可以的话请帮个忙用文章末我分享的链接注册,谢谢')

pd.set_option('expand_frame_repr', False)#True就是可以换行显示。设置成False的时候不允许换行
pd.set_option('display.max_columns', None)# 显示所有列
#pd.set_option('display.max_rows', None)# 显示所有行
pd.set_option('colheader_justify', 'centre')# 显示居中

#df_daily = pro.daily()  获取所有股票日行情信息
#df_basic = pro.stock_basic()  获取所有股票基本信息

def get_all_stockdata(st_date, ed_date):
    trade_d = pro.trade_cal(exchange='SSE', is_open='1', start_date=st_date, end_date=ed_date, fields='cal_date')

    for date in trade_d['cal_date'].values:
        # 先获得所有股票的行情数据
        df_daily = pro.daily(trade_date=date)

        # 再获取所有股票的基本信息
        df_basic = pro.stock_basic()

        #行情数据跟基本信息数据合并生成一个csv数据文件
        #on='ts_code'以ts_code为索引,合并数据,how='outer',取并集
        df_all = pd.merge(left=df_basic, right=df_daily, on='ts_code', how='outer')
        #删除symbol列数据,跟ts_code数据重复
        df_all = df_all.drop('symbol', axis=1)
        #强制转换成str字符串格式
        df_all['ts_code'] = df_all['ts_code'].astype(str)

        # 保存数据,不保存索引,如果index=True,则保存索引会多出一列
        df_all.to_csv(str(date) + '_ts.csv', index=False, encoding='gbk')
        print(df_all)
        print('%s is downloaded.' % (str(date)))
    return df_all
if __name__=="__main__":
	get_all_stockdata('20200101', '20200315')

Insert picture description here
Insert picture description here
Tushare registration link: link .

Guess you like

Origin blog.csdn.net/Wilburzzz/article/details/106500349