首页 新闻 搜索 专区 学院

PYTHON 同步代码改为异步

0
悬赏园豆:100 [待解决问题]

import numpy as np
import tushare as ts
import aiohttp
import asyncio
import time

codes = ['787819', '787317', '787317', '600320', '600191', '600191', '600967', '600765', '600238', '603650']

cvs_30 = []
start = time.time()

async def get_index(code):

all_data = ts.get_hist_data(code, start='2020-05-12', end='2020-12-28')
if all_data is None:

cv_30 = 0
# 加入相对应的列表
cvs_30.append(cv_30)

else:
data = all_data['close']
cv_30 = np.std(data.head(30)) / np.mean(data.head(30))

# 加入相对应的列表
cvs_30.append(cv_30 * 1000)

tasks = [asyncio.ensure_future(get_index(code)) for code in codes]

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(*tasks))
end = time.time()

print(end - start)

乡村小三的主页 乡村小三 | 初学一级 | 园豆:102
提问于:2020-12-30 22:47
< >
分享
所有回答(1)
0
import numpy as np
import tushare as ts
import asyncio
import time
# import tushare as t1

codes = ['787819', '787317', '787317', '600320', '600191', '600191', '600967', '600765', '600238', '603650']

cvs_30 = []
start = time.time()
async def get_hist_data(code):
    all_data = ts.get_hist_data(code, start='2020-05-12', end='2020-12-28')
    return all_data

async def cv_append(all_data):
    print(all_data)
    if all_data is None:
        cv_30 = 0
        # 加入相对应的列表
        cvs_30.append(cv_30)
    else:
        data = all_data['close']
        cv_30 = np.std(data.head(30)) / np.mean(data.head(30))

        # 加入相对应的列表
        cvs_30.append(cv_30 * 1000)

async def get_index(code):
    all_data = await get_hist_data(code)
    await cv_append(all_data)



tasks = [asyncio.ensure_future(get_index(code)) for code in codes]

loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(*tasks))
end = time.time()
print(end - start)
小小咸鱼YwY | 园豆:2547 (老鸟四级) | 2020-12-31 15:36

园豆我怎么给你,我第一次发帖。

支持(0) 反对(0) 乡村小三 | 园豆:102 (初学一级) | 2020-12-31 20:51

@乡村小三: 结贴就好了,不过这豆子都是浮云

支持(0) 反对(0) 小小咸鱼YwY | 园豆:2547 (老鸟四级) | 2021-01-04 09:22
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册