Tushare数据分析【高级】

1.快速开始

eg: 获取每日行情接口

import tushare as ts
import pandas

pro = ts.pro_api("your token")

daily = pro.daily(trade_date='20180810')

pandas.set_option('display.max_rows', 5)  # 总共显示5行
# pandas.set_option('display.max_rows', None) # 显示所有行
pandas.set_option('display.max_columns', None)  # 显示所有列
pandas.set_option('display.max_colwidth', 50)  # 每列的宽度

print(daily)

显示结果

 

2.获取数据并导入到MySQL

 
import tushare as ts
import pymysql
import re
import time

pro = ts.pro_api("your token ")
db = pymysql.connect("host", "user", "pass", "dbname")

cursor = db.cursor()

# 交易日历, is_open 表示开市,则获取当天的数据
cal = pro.trade_cal(exchange='', start_date='20181001', end_date='20200315')

for row in cal.iterrows():
    # 获取开市当时的行情
    if row[1]["is_open"] == 1:
        daily = pro.daily(trade_date=row[1]["cal_date"])
        for dayrow in daily.iterrows():
            # 用正则获取股票代码,不包含SZ这些
            ts_codes = re.findall(r"(\d+)", dayrow[1]["ts_code"])
            # 遍历获取的行情数据,并插入到数据库
            sql = "insert into backdata (ts_code, trade_date, open, high, low, close, pre_close, " \
                  "chg_quota, pct_chg, vol, amount, up_limit, down_limit) value ('%s', '%s', '%s', " \
                  "'%s', '%s', '%s', '%s', '%s', " \
                  "'%s', '%s', '%s', '%s', '%s')" % (
                      ts_codes[0], dayrow[1]["trade_date"], int(dayrow[1]["open"] * 100),
                      round(dayrow[1]["high"] * 100), int(dayrow[1]["low"] * 100), int(dayrow[1]["close"] * 100),
                      int(dayrow[1]["pre_close"] * 100),
                      dayrow[1]["change"], dayrow[1]["pct_chg"], dayrow[1]["vol"], int(dayrow[1]["amount"] * 1000),
                      round(dayrow[1]["pre_close"] * 110),
                      round(dayrow[1]["pre_close"] * 90))
            cursor.execute(sql)
            db.commit()
        time.sleep(1)
  • 6
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值