Python tushare stock data acquisition and local storage (optimized version)

Foreword:
A few days after the last release of "python tushare stock data acquisition and local storage", I found that the locally stored data table still lacks some important indicator data, such as PE, total market value, circulating market value, etc., so I decided to Write an article to supplement the code, if you think you can give a quality triple, give some motivation to continue to update the article, thank you. Haha, it's also a bit verbose, the code is given below.

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()就是pycharm输出控制显示的设置
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_basic = pro.stock_basic()

		# 先获得所有股票的行情数据
		df_daily = pro.daily(trade_date=date)

		#获取每日指标
		df_daily_basic = pro.daily_basic(ts_code='', trade_date=date,
										 fields='ts_code, turnover_rate, turnover_rate_f, volume_ratio, pe, '
												'pe_ttm, pb, ps, ps_ttm, dv_ratio, dv_ttm, total_share, float_share, '
												'free_share, total_mv, circ_mv ')
		#基本数据跟行情数据合并,再跟每日指标数据合并生成一个csv数据文件
		#on='ts_code'以ts_code为索引,合并数据,how='outer',取并集
		df_first = pd.merge(left=df_basic, right=df_daily, on='ts_code', how='outer')
		df_all = pd.merge(left=df_first, right=df_daily_basic, 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')

The indicator value after adding the code. For specific indicators in English, please refer to tushare official text API
Insert picture description here
tushare registration link: link:
PS: It is recommended for beginners (hahaha, I am also a novice beginner) when reading this article , please read my previous release Code, first understand the logical sequence of the previous code, and then look at this article to see what changes are made, which will be a bit helpful for learning. (Here is a special thanks to the enlightenment of the teacher "Dao Ke Te Lu" sharing the code)

Guess you like

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