使用基于csv数据的nsetools并行获取股票价格

时间:2017-01-17 09:41:19

标签: python performance python-2.7 csv financial

import time
import argparse
import pandas as pd
from nsetools import Nse

nse = Nse()
t = time.time()
FILE_LOCATION = ''  # csv file, blank because path not relevant to others
df = pd.read_csv(FILE_LOCATION)

CSV文件内容:

Instrument,Qty,Avg buy price
APLAPOLLO,3,949.95
AVANTIFEED,6,554.55
BALAMINES,9,337.72
BALMLAWRIE,4,258.5
BANCOINDIA,15,217
DCMSHRIRAM,12,261.4
GHCL,12,267.2
GIPCL,27,101.95
JAMNAAUTO,15,182.1
JBCHEPHARM,15,344.85
KEI,24,143.95
KPRMILL,6,569.65
KRBL,9,312
MPHASIS,6,533.95
SHEMAROO,2,413.25

代码:

# using argparse to provide options for obtaining closePrice or buyPrice1
# of stocks
parser = argparse.ArgumentParser(description='Stock Quote fetcher')
parser.add_argument('-r', '--realtime', help='Obtain realtime stock\
                    quotes', action='store_true')
args = parser.parse_args()


def get_closing(stock):
    """Function to obtain closePrice or buyPrice1 of stocks"""
    if args.realtime:
        return nse.get_quote(stock)['buyPrice1']
    else:
        return nse.get_quote(stock)['closePrice']


# calculating current value of investment
current_value = sum(get_closing(row[0]) * row[1] for index, row in
                    df.iterrows())

print(current_value)
print("Completed in ", time.time() - t)

目前,使用生成器表达式顺序获取股票价格。这样做需要18-25秒来计算当前的投资价值。有没有办法并行计算这些价格并计算当前的投资价值?

1 个答案:

答案 0 :(得分:1)

我已经分配了存储库here,我一直在努力将nsetools API转换为基于DataFrame的方法,并使用线程来减少获取多个数据所需的时间引号。

截至今天v1.1.0的最新版本目前已实现所有这些功能。

但是,不保证python2兼容性。如果您想要求更多功能,请务必创建新问题。我将继续努力并不断更新回购。