def stock_enter(request): """ Function to read the CSV files and enter the data to the database. The csv module is used for this purpose. The 'resources' folder is scanned for the CSV files. All the files found from there are listed in the terminal, and they are read and stored one by one. :return: HttpResponse containing a message saying either all entries have been added, or no CSV files found in the resources folder to add """ mypath = join(os.getcwd(), 'stock/resources') # path to the 'resources' folder print '\nLooking for .CSV files in %s' % mypath files = [ f for f in listdir(mypath) if isfile(join(mypath,f)) and f.endswith('.CSV') ] # list of CSV files found, if any if not files: # no CSV files present in the resources folder return HttpResponse('No ".CSV" files are placed in the resources folder. Could not add data.') # display error message else: # CSV files found print '\nThe following %s .CSV files have been found in %s -' % (len(files), mypath) for count, f in enumerate(files): print 'File (%s/%s): %s' %(count + 1, len(files), f) stock_list = Stock.objects.all() for filename in files: # iterating through the list of CSV filenames found # calculating the date by reading the filename (present in ddmmyy format by default) day, month, year = filename.split('.CSV')[0][2:4], filename.split('.CSV')[0][4:6], filename.split('.CSV')[0][6:] if len(year) == 2: year = '20' + year # if year is of 2 digits, add '20' to its beginning print '\nEntering data from file (%s/%s) %s' % (files.index(filename) + 1, len(files), filename) with open(join(mypath, filename)) as csvfile: # open the file spamreader = csv.reader(csvfile, delimiter=',', quotechar='|') # read the contents for count, row in enumerate(spamreader): row_entry_list = ', '.join(row).split(', ') # list of all the elements in the current row separated by comma if count > 0: # the current row is not the field-name row # save the entry to database q = Stock(SC_CODE = row_entry_list[0], SC_NAME = row_entry_list[1], SC_GROUP = row_entry_list[2], SC_TYPE = row_entry_list[3], OPEN = float(row_entry_list[4]), HIGH = float(row_entry_list[5]), LOW = float(row_entry_list[6]), CLOSE = float(row_entry_list[7]), LAST = float(row_entry_list[8]), PREVCLOSE = float(row_entry_list[9]), NO_TRADES = float(row_entry_list[10]), NO_OF_SHRS = float(row_entry_list[11]), NET_TURNOV = float(row_entry_list[12]), DATE = datetime.date(int(year), int(month), int(day))) q.save() print "Saving entry from file %s/%s with id %s, SC_NAME %s" % (files.index(filename) + 1, len(files), q.id, q.SC_NAME) return HttpResponse('All the entries have been successfully added. Call the "stock" method to view the current database.')
class YourTestClass(TestCase): def setUp(self): self.stock = Stock(stock_name='testStock', stock_price=2, stock_sold=0) self.stock.save() self.shareQuantity = 5 self.user = User(username='******', password='******') self.user.save() self.user = User.objects.get(username='******') self.userund = UserFund(user=self.user, fund=1000) Trading_Account.objects.create(user_id=self.user, trading_name='testTrade') self.trading = Trading_Account.objects.get(user_id=self.user) def testBuyShareOnFunds(self): self.user.userfund.fund -= self.stock.stock_price * self.shareQuantity self.assertTrue(self.user.userfund.fund, 10) def testBuySharesOnSharesAmount(self): shares = Shares(shares_amount=10) self.stock.stock_sold -= self.shareQuantity self.assertTrue(self.stock.stock_sold, 5) def testSellSharesOnStockSold(self): self.stock.stock_sold += self.shareQuantity self.assertTrue(self.stock.stock_sold, 5) def testSellSharesOnSharesAmount(self): shares = Shares(shares_amount=self.shareQuantity) self.stock.stock_sold += shares.shares_amount self.assertTrue(self.stock.stock_sold, 5)
def register(request): stock = Stock.objects.filter(symbol=request.POST['symbol']) if not stock: stock = Stock(symbol=request.POST['symbol'], name=request.POST['name']) stock.save() subprocess.Popen(['java', '-jar', '/Users/shijieru/Desktop/updateDB.jar']) return HttpResponseRedirect(reverse('index'))
def register(request): stock = Stock.objects.filter(symbol=request.POST['symbol']) if not stock: stock = Stock(symbol=request.POST['symbol'], name=request.POST['name']) stock.save() subprocess.Popen( ['java', '-jar', '/Users/shijieru/Desktop/updateDB.jar']) return HttpResponseRedirect(reverse('index'))
def get(self, request): stocks = ts.get_stock_basics() for code in stocks.index: print not Stock.objects.filter(code=code).exists() print Stock.objects.filter(code=code).exists() if not Stock.objects.filter(code=code).exists(): stock = Stock() stock.code = code stock.save() return HttpResponse(json.dumps({"status": "success"}), content_type="application/json")
def setUp(self): self.stock = Stock(stock_name='testStock', stock_price=2, stock_sold=0) self.stock.save() self.shareQuantity = 5 self.user = User(username='******', password='******') self.user.save() self.user = User.objects.get(username='******') self.userund = UserFund(user=self.user, fund=1000) Trading_Account.objects.create(user_id=self.user, trading_name='testTrade') self.trading = Trading_Account.objects.get(user_id=self.user)
def get_available(self, product, location, slabs=None): """ Args: product: object产品 location: object库位 slabs: questset板材 Returns:元祖,(件,数量) """ return Stock.get_available(product=product, location=location, slabs=slabs)
def handle(self, **options): print("[command.stock.update] start") stocks = apiCall("torn", "", "stocks,timestamp", randomKey()) for k, v in stocks["stocks"].items(): stock = Stock.objects.filter(tId=int(k)).first() if stock is None: stock = Stock.create(k, v, stocks["timestamp"]) else: stock.update(k, v, stocks["timestamp"]) stock.save() print("[command.stock.update] end")
def handle(self, **options): print(f"[CRON {logdate()}] START stocks") stocks = apiCall("torn", "", "stocks,timestamp", randomKey()) for k, v in stocks["stocks"].items(): stock = Stock.objects.filter(tId=int(k)).first() if stock is None: stock = Stock.create(k, v, stocks["timestamp"]) else: stock.update(k, v, stocks["timestamp"]) stock.save() print(f"[CRON {logdate()}] END")
def _create_stocks(self, cad, gbx, hkd, jpy, sek, start_date, usd): stocks = [ Stock(symbol='MIK', name='The Michaels Company', currency=usd), Stock(symbol='DEDI.ST', name='Dedicare AB', currency=sek), Stock(symbol='CARD.L', name='Card Factory', currency=gbx), Stock(symbol='MOMO', name='Momo', currency=usd), Stock(symbol='1997.T', name='Akatsuki Eazima', currency=jpy), Stock(symbol='3932.T', name='Akatsuki', currency=jpy), Stock(symbol='1830.HK', name='Perfect Shape', currency=hkd), Stock(symbol='DR.TO', name='Medical Facilities Corporation', currency=cad), Stock(symbol='NHTC', name='Natural Health Trends Corp.', currency=usd), Stock(symbol='SCS.L', name='SCS Group', currency=gbx), ] Stock.objects.bulk_create(stocks) stock_symbols = [stock.symbol for stock in stocks] call_command('fetch_historical_stock_data', *stock_symbols, '--force-update', '--start', start_date.strftime('%Y-%m-%d'))
def new(self, barcode=""): if len(barcode) == 0: barcode = self.scan() if self.getProduit(barcode) == None: name = raw_input("Entrez le nom du produit: ") price = raw_input("Entrez le prix: ") quantity = raw_input("Entrez la quantité: ") p = Product(barcode=barcode, name=name, price=price) p.save() s = Stock(produit=p, quantite=quantity) s.save() else: p = Product.objects.get(barcode=barcode) name = raw_input("Entrez le nouveau nom du produit: ") price = raw_input("Entrez le nouveau prix: ") quantity = raw_input("Entrez la quantitée supplémentaire: ") p.name = name p.price = price p.save() s = Stock.objects.get(produit=p) s.quantite += int(quantity) s.save()
def stock_detail(request, pk): #Retrieve, update or delete a code snippet. try: stock = Stock.objects.get(pk=pk) except Stock.DoesNotExist: return HttpResponse(status=404) if request.method == 'GET': serializer = StockSerializer(stock) return JSONResponse(serializer.data) elif request.method == 'PUT': data = JSONParser().parse(request) serializer = StockSerializer(stock, data=data) if serializer.is_valid(): serializer.save() return JSONResponse(serializer.data) return JSONResponse(serializer.errors, status=400) elif request.method == 'DELETE': Stock.delete() return HttpResponse(status=204)
def bookin_product_on_position(self): query_condition = Q( Q(product=self.product, lagerplatz__iexact=self.position.name, zustand=self.state) | (Q(ean_vollstaendig=self.product.ean, lagerplatz__iexact=self.position.name, zustand=self.state))) self.stock = Stock.objects.filter(query_condition).first() print(f"bbaba: {self.position.name} - {self.stock}") if self.stock is None: self.stock = Stock(ean_vollstaendig=self.product.ean, zustand=self.state, lagerplatz=self.position.name, product=self.product) print(f"GUTE FRAGE : {self.bookin_amount} - {self.stock.bestand}") print(f"bbaba2: {self.position.name} - {self.stock.lagerplatz}") if self.stock.bestand is not None: self.stock.bestand += self.bookin_amount else: self.stock.bestand = self.bookin_amount self.stock.save()
def rebook_stock_to_destination(self): rebook_amount = self.form.cleaned_data.get("amount") self.destination_stock = Stock.objects.filter( lagerplatz=self.position, sku_instance=self.stock.sku_instance) if self.destination_stock.count() > 0: self.destination_stock = self.destination_stock.first() else: self.destination_stock = None if self.destination_stock is None: self.destination_stock = Stock( lagerplatz=self.position, sku_instance=self.stock.sku_instance, sku=self.stock.sku_instance.sku) if self.destination_stock is not None: if self.destination_stock.bestand is None: self.destination_stock.bestand = rebook_amount else: self.destination_stock.bestand += rebook_amount self.destination_stock.save() self.pre_rebook_stock_to_destination( self.destination_stock, self.destination_stock.sku_instance, self.destination_stock.lagerplatz) if rebook_amount > 0: if self.stock.bestand - rebook_amount >= 0: self.destination_stock.save() if self.stock.bestand - rebook_amount == 0: self.stock.delete() else: self.stock.bestand -= rebook_amount self.stock.save()
def handle(self, **options): print("[command.stock.update] start") preference = Preference.objects.all()[0] key = preference.get_random_key()[1] stocks = apiCall("torn", "", "stocks,timestamp", key=key) for k, v in stocks["stocks"].items(): stock = Stock.objects.filter(tId=int(k)).first() if stock is None: stock = Stock.create(k, v, stocks["timestamp"]) else: stock.update(k, v, stocks["timestamp"]) stock.save() print("[command.stock.update] end")
def get_stock(request): context = {} result = ts.get_stock_basics() print(result.shape) #result = result.head(2) stock_json = result.to_json(orient='records', force_ascii=False) stock_list = json.loads(stock_json) stock_object_list = [] for i in stock_list: stock_object_list.append(Stock(i['name'], i['industry'], i['area'], i['pb'], i['pe'])) context['all'] = stock_object_list return render(request, 'stock.html', context)
def handle(self, *args, **options): yahoo = YahooApi() symbols = options['symbols'] force_update = options['force_update'] start_str = options['start'] end_str = options['end'] for symbol in symbols: try: stock = Stock.objects.get(symbol=symbol) except Stock.DoesNotExist as e: msg = f'No stock with symbol {symbol} exists' raise Stock.DoesNotExist(msg) from e start, end = self._get_start_and_end(start_str, end_str, force_update, stock) yahoo.fetch_historical_stock_data(stock, start, end)
def playground_view(request): stock_id = "2330" msg = '' # access stock from db stock = Stock().getNewestStock(stock_id) # get price change from stock try: # get full info of stock end_price = stock.end_price yesterday_end = stock.yesterday_end change = round(float(end_price) - float(yesterday_end), 2) except: msg += '錯誤:無法取得股票漲跌資訊\n' change = '' # get time try: # get current time in 'Asia/Taipei' current_time = datetime.now() except: msg += '錯誤:無法取得時間\n' current_time = '' return render( request, 'dailyGame/playground.html', { 'notif_num': Notification.objects.filter(n_to=request.user, is_read=False).count(), 'stock': stock, 'change': change, 'current_time': current_time, 'msg': msg })
def stock_view(request): msg = '' if request.method == 'GET' and 'stock_id' in request.GET: stock_id = request.GET['stock_id'] else: stock_id = None # access stock from db stock = Stock().getNewestStock(stock_id) # get price change from stock try: # get full info of stock end_price = stock.end_price yesterday_end = stock.yesterday_end change = round(float(end_price) - float(yesterday_end), 2) except: msg += '錯誤:無法取得股票漲跌資訊\n' change = '' # get time try: # get current time in 'Asia/Taipei' current_time = datetime.now() except: msg += '錯誤:無法取得時間\n' current_time = '' return render(request, 'trade/stock.html', { 'notif_num': Notification.objects.filter(n_to = request.user, is_read = False).count(), 'stock_id': stock_id, 'stock': stock, 'change': change, 'current_time': current_time, 'msg': msg })
def _get_stock(self, product, location, slabs=None, check_in=False): # 取得库存的记录 return Stock._get_stock(product, location, slabs, check_in=check_in)
def create(self, validated_data): stocks = [Stock(**item) for item in validated_data] return Stock.objects.bulk_create(stocks)
stock_code = pd.read_html( 'http://kind.krx.co.kr/corpgeneral/corpList.do?method=download', header=0)[0] stock_code.sort_values(['상장일'], ascending=True) stock_code = stock_code[['회사명', '종목코드']] stock_code = stock_code.rename(columns={'회사명': 'company', '종목코드': 'code'}) stock_code.code = stock_code.code.map('{:06d}'.format) # company = input() company = sys.argv[1] code = stock_code[stock_code.company == company].code.values[0].strip() url = 'http://finance.naver.com/item/sise.nhn?code={code}'.format(code=code) print(url) req_header = { 'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 11_0_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36' } res = requests.get(url, headers=req_header) print(res.status_code) soup = BeautifulSoup(res.text, 'html.parser') price = soup.select_one('div > p.no_today span.blind').get_text() url = url Stock(name=company, code=code, price=price, url=url).save()
class BookStockOnPositionBase(ABC, LoginRequiredMixin, View): __metaclass__ = ABCMeta template_name = "rebook/book_stock_on_position.html" def __init__(self, **kwargs): self.position = None self.stock = None self.destination_stock = None self.form = None super().__init__(**kwargs) @abstractmethod def pre_dispatch(self): pass def dispatch(self, request, *args, **kwargs): self.pre_dispatch() self.position = self.request.GET.get("position", "") or "" self.form = self.get_form() if self.position == "": return render(request, self.template_name, self.get_context()) if self.form.is_valid() is True: self.rebook_stock_to_destination() else: return render(request, self.template_name, self.get_context()) return super().dispatch(request, *args, **kwargs) def rebook_stock_to_destination(self): rebook_amount = self.form.cleaned_data.get("amount") self.destination_stock = Stock.objects.filter( lagerplatz=self.position, sku_instance=self.stock.sku_instance) if self.destination_stock.count() > 0: self.destination_stock = self.destination_stock.first() else: self.destination_stock = None if self.destination_stock is None: self.destination_stock = Stock( lagerplatz=self.position, sku_instance=self.stock.sku_instance, sku=self.stock.sku_instance.sku) if self.destination_stock is not None: if self.destination_stock.bestand is None: self.destination_stock.bestand = rebook_amount else: self.destination_stock.bestand += rebook_amount self.destination_stock.save() self.pre_rebook_stock_to_destination( self.destination_stock, self.destination_stock.sku_instance, self.destination_stock.lagerplatz) if rebook_amount > 0: if self.stock.bestand - rebook_amount >= 0: self.destination_stock.save() if self.stock.bestand - rebook_amount == 0: self.stock.delete() else: self.stock.bestand -= rebook_amount self.stock.save() def pre_rebook_stock_to_destination(self, destination_stock, destination_sku, destination_position): pass def get_form(self): if self.request.method == "POST": self.form = BookStockOnPositionForm(data=self.request.POST, stock=self.stock) else: self.form = BookStockOnPositionForm(stock=self.stock) return self.form def get(self, request, *args, **kwargs): context = self.get_context() return render(request, self.template_name, context) def get_context(self): return { "title": "Auf Position einbuchen", "stock": self.stock, "position": self.position, "form": self.form } def post(self, request, *args, **kwargs): return HttpResponseRedirect(reverse_lazy("stock:list"))
from xlrd import open_workbook wb = open_workbook('/home/ganesh/Downloads/kalpatru-1.xlsx') from stock.models import Stock for s in wb.sheets(): rows=s.nrows for row in range(1,rows): rowValues = [] col_value = [] for col in range(s.ncols): value = (s.cell(row,col).value) rowValues.append(value) print rowValues stkObj=Stock() stkObj.type=str(rowValues[0]) stkObj.company_Name=str(rowValues[0]) # stkObj.supply_Place=str(rowValues[1]) # stkObj.bill_No=str(rowValues[1]) # stkObj.bill_Date=str(rowValues[1]) # stkObj.bill_Rec_Date=str(rowValues[1]) # stkObj.bill_Amount=str(rowValues[1]) # stkObj.lr_No=str(rowValues[1]) # stkObj.lr_Date=str(rowValues[1]) # stkObj.cases=str(rowValues[1]) # stkObj.carriers_Name=str(rowValues[1]) # stkObj.permit_No=str(rowValues[1]) # stkObj.doc_Month=str(rowValues[1]) # stkObj.F_C_O=str(rowValues[1]) # stkObj.date=str(rowValues[1])
class BookProductInPosition(View): template_name = "online/refill_order/book_product_in_position.html" def __init__(self, **kwargs): super().__init__(**kwargs) self.product, self.state, self.position, self.form, self.refill_order = None, None, None, None, None self.bookin_amount, self.booked_in_amount, self.booked_out_amount = 0, 0, 0 self.stock = None def dispatch(self, request, *args, **kwargs): self.product = Product.objects.get(pk=self.kwargs.get("product_pk")) self.position = Position.objects.get(pk=self.kwargs.get("position_pk")) self.state = self.kwargs.get("state") self.form = self.get_form() self.refill_order = request.user.refillorder_set.filter( Q(Q(booked_out=None) | Q(booked_in=None)) & Q(user=self.request.user)).first() self.bookin_amount = self.get_bookin_amount() self.booked_in_amount = self.get_booked_in_amount() self.booked_out_amount = self.get_booked_out_amount() return super().dispatch(request, *args, **kwargs) def get(self, request, *args, **kwargs): return render(request, self.template_name, self.get_context()) def get_context(self): context = { "title": "Artikel in Lagerposition einbuchen", "product": self.product, "position": self.position, "form": self.form, "refill_order": self.refill_order, "state": self.state } return context def get_form(self): if self.request.method == "POST": return BookinForm(data=self.request.POST) else: return BookinForm() def post(self, request, *args, **kwargs): self.validate_booked_in_amount_is_greater_than_booked_out() self.validate_booked_in_amount_not_exceeding_outbooked_amount() if self.form.is_valid() is True: self.bookin_product_on_position() self.create_refill_order_inbook_stock() return HttpResponseRedirect( reverse_lazy("online:products_for_bookin")) else: return render(request, self.template_name, self.get_context()) def bookin_product_on_position(self): query_condition = Q( Q(product=self.product, lagerplatz__iexact=self.position.name, zustand=self.state) | (Q(ean_vollstaendig=self.product.ean, lagerplatz__iexact=self.position.name, zustand=self.state))) self.stock = Stock.objects.filter(query_condition).first() print(f"bbaba: {self.position.name} - {self.stock}") if self.stock is None: self.stock = Stock(ean_vollstaendig=self.product.ean, zustand=self.state, lagerplatz=self.position.name, product=self.product) print(f"GUTE FRAGE : {self.bookin_amount} - {self.stock.bestand}") print(f"bbaba2: {self.position.name} - {self.stock.lagerplatz}") if self.stock.bestand is not None: self.stock.bestand += self.bookin_amount else: self.stock.bestand = self.bookin_amount self.stock.save() def create_refill_order_inbook_stock(self): RefillOrderInbookStock.objects.create(refill_order=self.refill_order, product=self.product, amount=self.bookin_amount, position=self.position.name, booked_in=True, stock=self.stock, state=self.state) def get_bookin_amount(self): if self.form.is_valid() is True: self.bookin_amount = self.form.cleaned_data.get("bookin_amount") return self.bookin_amount def get_booked_in_amount(self): booked_in_sum = 0 for inbook_stock in self.refill_order.refillorderinbookstock_set.filter( product=self.product): booked_in_sum += inbook_stock.amount return booked_in_sum def get_booked_out_amount(self): booked_out_amount = 0 for outbook_stock in self.refill_order.refillorderoutbookstock_set.filter( product_mission__sku__product=self.product): booked_out_amount += outbook_stock.amount return booked_out_amount def validate_booked_in_amount_not_exceeding_outbooked_amount(self): booked_in_sum = self.get_booked_in_amount() if self.booked_out_amount - (self.booked_in_amount + self.bookin_amount) < 0: self.form.add_error( "bookin_amount", f"Sie dürfen maximal noch " f"{self.booked_out_amount-self.booked_in_amount}x den Artikel " f"einbuchen") def validate_booked_in_amount_is_greater_than_booked_out(self): self.booked_out_amount = self.get_booked_out_amount() if self.form.is_valid() is True: if self.bookin_amount + self.booked_in_amount > self.booked_out_amount: self.form.add_error( "bookin_amount", f"Sie dürfen nicht mehr einbuchen als ausgebucht wurde ") self.form.add_error( "bookin_amount", f"Sie haben den Artikel {self.booked_out_amount}x ausgebucht" )
def create_stock_data(): stock_list = business() for stock in stock_list: new_stock = Stock() new_stock.business = stock['business'] new_stock.code = stock['code'] new_stock.title = stock['title'] new_stock.graph_url() new_stock.stock_reset() new_stock.save()
def get_stock_model(row): stock = Stock() stock.symbol = row[0] stock.series = row[1] stock.open_stock = row[2] stock.high_value = row[3] stock.low_value = row[4] stock.close_value = row[5] stock.last_value = row[6] stock.prev_close_value = row[7] stock.ttr_dqty_value = row[8] stock.ttr_dval_value = row[9] stock.time_stamp = datetime.strptime(row[10], '%d-%b-%Y').date() stock.total_trades = row[11] stock.isin = row[12] return stock
def get_available(self, location=None): return Stock.get_available(product=self, location=location)