从tushare获取融资融券明细

#coding ='gbk'
import time
import datetime
import MySQLdb
import tushare as ts
from sqlalchemy import create_engine

pro = ts.pro_api('3f3b7e415ab8d5e2d139662b8f70dc1113defb8038b3f4daedfd7152')
engine = create_engine('mysql://root:[email protected]/test3?charset=utf8')
begin_day = '20200102'
end_day = '20200203'
default_num = 3

if begin_day == end_day and begin_day == '':
    n = 0
    c = 0
    while n < default_num:
        str = time.strftime("%Y%m%d", time.localtime(time.time() - 24*60*60*n))
        print(str)
        df = pro.margin_detail(trade_date=str)
        if df.shape[0] > 0:
            try:
                df["ts_code"] = df["ts_code"].map(lambda x: x[:-3])
                df.to_sql('margin_detail', engine, if_exists='append', index=False)
            except:
                print(str, "to_sql faile")
            c += 1
        n += 1
else:
    begin = time.mktime(time.strptime(begin_day, "%Y%m%d"))
    end = time.mktime(time.strptime(end_day, "%Y%m%d"))
    sql_table = []
    while begin <= end:
        str = time.strftime("%Y%m%d", time.localtime(begin))
        print(str)
        begin = begin + 24*60*60
        df = pro.margin_detail(trade_date=str)
        if df.shape[0] > 0:
            try:
                df["ts_code"] = df["ts_code"].map(lambda x: x[:-3])
                df.to_sql('margin_detail', engine, if_exists='append', index=False)
            except:
                print(str, "to_sql faile")

 

你可能感兴趣的:(金融)