class Command(BaseCommand): def __init__(self): self.company_repo = CompanyRepo() def run(self): companies = self.company_repo.all() for company in companies: #try: print "Updating stock for : " + company.code c = get_current_stock_of_company(company.code, company=company)
class StockGetter(BaseCommand): """ To Update stock of the company to latest """ STOCK_API = "https://www.quandl.com/api/v3/datasets/{}/{}.json?api_key=xMH7BiBu6s24LHCizug3" def __init__(self): self.company_repo = CompanyRepo() self.stock_repo = StockRepo() self.count = 0 self.lock = allocate_lock() self.sleep_time = 1 # in seconds def run(self): companies = self.company_repo.all() complete = companies.count() for company in companies: start_new_thread(self.read_stock, (company, )) time.sleep(self.sleep_time) while self.count != complete: time.sleep(4) continue print "Companies synced successfully" def _extract_history(self, data): history = [] history_data = data['data'] if data['database_code'] == 'BSE': for d in history_data: history.append({ "date": d[0], "open": d[1], "high": d[2], "low": d[3], "close": d[4], "last": None, "totalTradeQuantity": None, "turnover": None, "wap": d[5], "noOfShares": d[6], "noOfTrades": d[7], "totalTurnover": d[8], "deliverableQuantity": d[9], "percentageDeliveryQtytoTradedQty": d[10], "spreadHtoL": d[11], "spreadCtoO": d[12], }) elif data['database_code'] == 'NSE': for d in history_data: history.append({ "date": d[0], "open": d[1], "high": d[2], "low": d[3], "last": d[4], "close": d[5], "totalTradeQuantity": d[6], "turnover": d[7], # in Lacs "wap": None, "noOfShares": None, "noOfTrades": None, "totalTurnover": None, "deliverableQuantity": None, "percentageDeliveryQtytoTradedQty": None, "spreadHtoL": None, "spreadCtoO": None, }) return history def read_stock(self, company): try: url = self.STOCK_API.format(company.stockExchangeCode, company.code) response = requests.get(url) if 'dataset' not in response.json(): print response.json() self.sleep_time = 2 time.sleep(2) self.read_stock(company) data = response.json()['dataset'] if (company.refreshedAt - helper.str_to_datetime(data['refreshed_at']).replace( tzinfo=None)) == timedelta(0): print company.stockExchangeCode, company.code, company.name, "Continuing" else: print company.stockExchangeCode, company.code, company.name, "Updating" company.refreshedAt = helper.str_to_datetime( data['refreshed_at']) company.oldestAvailableDate = helper.str_to_datetime( data['oldest_available_date']) company.newAvailableDate = helper.str_to_datetime( data['newest_available_date']) company.history = helper.str_to_datetime(data) company.save() except Exception as e: print "Error (" + company.code + "): " + e.__str__() pass self.lock.acquire() self.count += 1 self.lock.release()