我正在构建一个股票跟踪应用程序,需要每分钟使用当前价格自动更新股票模型(从谷歌财经中提取)。我需要知道如何以更有效的方式做到这一点,因为有几千条记录,而我目前的方法非常缓慢且效率低下。
#models.py
class Stock(models.Model):
ticker = models.CharField(max_length=200)
current_price = models.DecimalField(max_digits=20, decimal_places=5)
下面的脚本每分钟通过一个 crontab 运行
#script set to run on a crontab
from takestock.stock_getter import get_quotes
from takestock.models import Stock
class Command(BaseCommand):
help = 'Gathers current stock prices from Google Finance using stock_getter script (imported) and updates all stocks in the database to reflect the current stock price.'
def get_stock_dict(self):
all_stocks = Stock.objects.all()
stock_names = []
for single_stock in all_stocks:
stock_names.append(str(single_stock.ticker))
stock_values = get_quotes(stock_names) #a list of values which corresponds to the list of names
stock_dict = dict(zip(stock_names, stock_values)) #stock tickers and stock values zipped into dict (see below)
return stock_dict
#stock_dict looks like: {'GOOG': '73.84', 'AAPL': '520.34'}
def handle(self, *args, **options):
stock_dict = self.get_stock_dict()
for ticker, value in stock_dict.items():
stock_obj = Stock.objects.get(ticker=ticker)
stock_obj.current_price = value
stock_obj.save()
这种方法有效,但速度很慢,我想它是数据库密集型的。有没有更好的方法可以做到这一点?谢谢。