说是第二个,其实在第一个之后,又学习了很多东西,学习python有几个重要的节点:
- python的数据类型十分丰富,其中的列表、集、字典都是此前我没有用过的,可以满足更高级的分析需求——数据类型是真实世界的模拟,高级的类型才更真实;
- 理解DataFrame的结构,和批量赋值的方法,刚开始转字典耗费生命,如今更喜欢用for in len()循环加iloc依此判断
- 循环是必不可少的语法
- 为了简化表达,开始定义函数,完美主义的解药。
第二个python是用来获得tushare中的期权数据,从而加以分析。使用了tushare的两个端口:获得期权合约,再依此获得每个合约的期权日线交易明细。
为了简化期权日线查询过程,定义了一个获得日线的函数:
def get_opt_daily(ts_code, exchange):
为了把结果导入数据库,定义了一个to_post的函数
def to_post(df,SQLTable, database):
因为端口每分钟只能读取150次,因此通过余数计算,每隔149次休息一分钟
if i%149==0: #计算余数,第一个0也等待了 time.sleep(60) print('have a sleep for 60 seconds')
我的程序如下:
import tushare as ts from sqlalchemy import create_engine import time import datetime exchange_list=['DCE','CZCE','SHFE','SSE'] # 大连、郑州、上海期货、上海证券 pro = ts.pro_api('fb***********') #我的密钥 SQLTable = 'F_opt_daily_1221new' #保存的数据库表 database = 'public' #数据库 def get_opt_daily(ts_code, exchange): df = pro.opt_daily(ts_code=ts_code, exchange=exchange) # print(' there are ',len(df),'rows in',ts_code) # print('demo', df.iloc[0:2]) #打印第一行和第二行 ,测试使用 to_post(df,SQLTable,database) print() def to_post(df,SQLTable, database): alchemyEngine = create_engine('postgresql+psycopg2://postgres:admin@127.0.0.1/' + database, pool_recycle=3600); postgreSQLConnection = alchemyEngine.connect(); print(" Opened database successfully") try: frame = df.to_sql(SQLTable, postgreSQLConnection, if_exists='append'); except ValueError as vx: print(vx) except Exception as ex: print(ex) else: print(len(df), " rows. %s has been created successfully." % SQLTable); finally: postgreSQLConnection.close(); i=0 for exchange in exchange_list: df = pro.opt_basic(exchange=exchange, fields='ts_code,name') for i in range(len(df)): print(i,df.iloc[i]['ts_code'],df.iloc[i]['name']) ts_code=df.iloc[i]['ts_code'] get_opt_daily(ts_code,exchange) if i%149==0: #计算余数,第一个0也等待了 time.sleep(60) print('have a sleep for 60 seconds') time.sleep(30) print(exchange,'had stored. waited 30 seconds ')
返回的结果保存在了我的postgresql数据库中,然后就可以使用Tableau分析。
后面用到了正则表达式拆分,可以参考另一篇文章:
Dec 21, 2019
喜乐君