import tushare as ts
import MySQLdb

from config import CONFIG_DB 
from config import CONFIG_TS

db = MySQLdb.connect(CONFIG_DB['host'], CONFIG_DB['user'], CONFIG_DB['password'], CONFIG_DB['database'], charset='utf8')
pro = ts.pro_api(CONFIG_TS['secret'])


def str2float( str ):
    try:
        val = float(str)
        if math.isinf(val) or math.isnan(val) :
            val = 0
        return val
    except Exception as e:
        return 0.0


df = pro.index_basic(**{
    "ts_code": "",
    "market": "",
    "publisher": "",
    "category": "",
    "name": "",
    "limit": "",
    "offset": ""
}, fields=[
    "ts_code",
    "name",
    "fullname",
    "market",
    "publisher",
    "index_type",
    "category",
    "base_date",
    "base_point",
    "list_date",
    "weight_rule",
    "desc",
    "exp_date"
])

cursor = db.cursor()
for row in df.itertuples():
    sql = "insert into t_ods_hs_indicator_list(ts_code, name, fullname, market, publisher, index_type, category, \
            base_date, base_point, list_date, weight_rule, ts_desc, exp_date) \
             values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %f, '%s', '%s', '%s', '%s') \
             on duplicate key update name= '%s', fullname= '%s', market='%s', publisher='%s', index_type='%s', \
             category='%s', base_date='%s', base_point=%f, list_date='%s', weight_rule='%s', ts_desc='%s', \
             exp_date='%s' " % \
             (getattr(row, 'ts_code'), getattr(row, 'name'), getattr(row, 'fullname'), getattr(row, 'market'),
             getattr(row, 'publisher'), getattr(row, 'index_type'), getattr(row, 'category'), getattr(row, 'base_date'),
             str2float(getattr(row, 'base_point')), getattr(row, 'list_date'), getattr(row, 'weight_rule'), 
             getattr(row, 'desc'), getattr(row, 'exp_date'), 
             getattr(row, 'name'), getattr(row, 'fullname'), getattr(row, 'market'),
             getattr(row, 'publisher'), getattr(row, 'index_type'), getattr(row, 'category'), getattr(row, 'base_date'),
             str2float(getattr(row, 'base_point')), getattr(row, 'list_date'), getattr(row, 'weight_rule'), 
             getattr(row, 'desc'), getattr(row, 'exp_date'), )
    try:
        cursor.execute(sql)
        db.commit()
    except Exception as ex:
        print (ex)
        db.rollback()
        break


db.close()



