这段代码可以怎么优化呀
运行计算效率低得离谱,我也找不出问题在哪里
for i in range(0, (endtime - starttime).seconds + 1):
tradingtime = starttime + timedelta(seconds=i)
if str(tradingtime.time()) not in time1:
print(tradingtime)
try:
underlying_510300 = price_data['510300'].get_group(tradingtime).tail(1)['pre_close'].values
underlying_000300 = price_data['000300'].get_group(tradingtime).tail(1)['pre_close'].values
except Exception as e:
underlying_510300 = \
price.get_group('510300')[price.get_group('510300')['inserttime'].dt.time <= tradingtime.time()].tail(
1)['pre_close'].values
underlying_000300 = \
price.get_group('000300')[price.get_group('000300')['inserttime'].dt.time <= tradingtime.time()].tail(
1)['pre_close'].values
MKT_data = {}
for code in code_group:
try:
option_data = price_data[code].get_group(tradingtime).tail(1)
except Exception as e:
option_data = price.get_group(code)[
price.get_group(code)['inserttime'].dt.time <= tradingtime.time()].tail(1)
if INFO_group[code]['underlying'] == '510300':
option_data['underlying_price'] = underlying_510300
else:
option_data['underlying_price'] = underlying_000300
MKT_data[code] = option_data
参考gpt以及个人思路优化过程:
1.在每个循环中,都会根据时间戳来查询数据,可以将查询的结果缓存起来,以避免重复查询。
2.在异常处理中使用了两次查询,可以将两次查询合并成一次,以避免重复代码。
3.可以尝试使用并行化的方式来加速数据处理过程。
代码如下:
from concurrent.futures import ThreadPoolExecutor
def get_price_data(code, tradingtime, price_data, price):
try:
option_data = price_data[code].get_group(tradingtime).tail(1)
except Exception as e:
option_data = price.get_group(code)[
price.get_group(code)['inserttime'].dt.time <= tradingtime.time()].tail(1)
return option_data
def optimize_code(starttime, endtime, time1, price_data, price, code_group):
underlying_510300 = None
underlying_000300 = None
MKT_data = {}
pool = ThreadPoolExecutor(max_workers=8)
underlying_future_510300 = pool.submit(price_data['510300'].get_group, starttime)
underlying_future_000300 = pool.submit(price_data['000300'].get_group, starttime)
for i in range(0, (endtime - starttime).seconds + 1):
tradingtime = starttime + timedelta(seconds=i)
if str(tradingtime.time()) not in time1:
if underlying_510300 is None:
underlying_510300 = underlying_future_510300.result().tail(1)['pre_close'].values
underlying_000300 = underlying_future_000300.result().tail(1)['pre_close'].values
try:
option_data = price_data[code].get_group(tradingtime).tail(1)
except Exception as e:
option_data = price.get_group(code)[
price.get_group(code)['inserttime'].dt.time <= tradingtime.time()].tail(1)
if code not in MKT_data:
MKT_data[code] = {}
MKT_data[code]['option_data'] = option_data
if INFO_group[code]['underlying'] == '510300':
if underlying_510300 is not None:
MKT_data[code]['underlying_price'] = underlying_510300
else:
if underlying_000300 is not None:
MKT_data[code]['underlying_price'] = underlying_000300
return MKT_data
赶快去给你最爱的她试试吧!!!