获取数据
- 获取股票信息
- 获取股票历史数据
1、获取股票信息
1.1、导入对应工具包
import tushare as ts
import pandas as pd
from pymongo import MongoClient
1.2、创建数据连接
con = MongoClient() ##连接客户端
1.3、获取股票列表信息
def get_data():
"""
获取取股票列表信息
:return:
"""
pro = ts.pro_api(token="bf4f8943b3cee8eb1ef51f3aed050a216d1f990c059e731f174d45df")
# 查询当前所有正常上市交易的股票列表
data = pro.stock_basic(exchange='', list_status='L', fields='ts_code,symbol,name,area,industry,list_date')
return data
1.4、写入MongoDB数据库
def write_data():
"""
将数据写入到MongoDB数据库
:return:
"""
database = con.StockCode ##创建数据库
set_post = database.Codedata ##创建集合
# 写入数据
data = get_data()
for i in range(0, len(data)):
u = dict(ts_code=data.iloc[i, 0], symbol=data.iloc[i, 1], name=data.iloc[i, 2], area=data.iloc[i, 3],
industry=data.iloc[i, 4], list_date=data.iloc[i, 5])
set_post.insert_one(u)
1.5、导入数据
def read_data():
"""
读取数据
:return:
"""
db = con['StockCode']
cursor = db['Codedata']
print(cursor)
# Expand the cursor and construct the DataFrame
df = pd.DataFrame(list(cursor.find()))
# Delete the _id
del data['_id']
return data
2、获取股票历史数据
2.1、国内数据(tushare)
通过tushare模块可以比较方便的获取国内大盘历史数据
import tushare as ts
1、常用获取数据函数
# 获取k线数据
ts.get_k_data(
['code=None', "start=''", "end=''", "ktype='D'", "autype='qfq'", 'index=False', 'retry_count=3', 'pause=0.001'],
)
# 获取个股历史交易记录
ts.get_hist_data(
['code=None', 'start=None', 'end=None', "ktype='D'", 'retry_count=3', 'pause=0.001'],
)
# 一次性获取最近一个日交易日所有股票的交易数据
ts.get_today_all()
# 获取历史复权数据
ts.get_h_data(
['code', 'start=None', 'end=None', "autype='qfq'", 'index=False', 'retry_count=3', 'pause=0.001', 'drop_factor=True'],
)
2、k线数据获取
ts.get_k_data('600398',start='2017-01-01',end='2019-01-01')
date | open | close | high | low | volume | code | |
---|---|---|---|---|---|---|---|
0 | 2017-01-03 | 9.917 | 9.908 | 9.954 | 9.862 | 41421.0 | 600398 |
1 | 2017-01-04 | 9.917 | 9.936 | 9.954 | 9.844 | 49584.0 | 600398 |
2 | 2017-01-05 | 9.936 | 9.982 | 10.028 | 9.844 | 89972.0 | 600398 |
3 | 2017-01-06 | 9.963 | 9.917 | 9.963 | 9.899 | 23910.0 | 600398 |
4 | 2017-01-09 | 9.936 | 9.899 | 9.945 | 9.862 | 59268.0 | 600398 |
… | … | … | … | … | … | … | … |
477 | 2018-12-24 | 8.550 | 8.600 | 8.670 | 8.510 | 66169.0 | 600398 |
478 | 2018-12-25 | 8.510 | 8.460 | 8.540 | 8.210 | 87789.0 | 600398 |
479 | 2018-12-26 | 8.410 | 8.480 | 8.560 | 8.400 | 46486.0 | 600398 |
480 | 2018-12-27 | 8.600 | 8.490 | 8.650 | 8.410 | 121024.0 | 600398 |
481 | 2018-12-28 | 8.510 | 8.480 | 8.570 | 8.320 | 92863.0 | 600398 |
482 rows × 7 columns