def test_company_str(self): """Tests the company string representation""" company = Company( index=11, company='ACME Inc' ) company.save() assert Company.objects.get(index=11).company == company.company
def test_company_model(company: Company): assert company.info assert str(company) == company.name assert company.last_dated_quotation assert not company.is_up_to_date company.save() assert len(CompanyInfo.objects.all()) == 1 assert len(Company.objects.all()) == 1
def import_companies(self): csv_file = self.read_file('importer/data/companies.csv') print('Importing Companies...') for row in csv_file: try: Company.objects.get(name=row[0]) print('Company', row[0], 'already registered.') except ObjectDoesNotExist: company = Company() company.name = row[0] company.save()
def setUp(self): super().setUp() self.client = Client(schema) # Populate the test collectiom with person data with open("core/tests/test_data/employees.json") as employee_json: employees = json.load(employee_json) for employee in employees: employee_obj = Person(**employee) employee_obj.save() # Populate the test collection with company data with open("core/tests/test_data/companies.json") as companies_json: companies = json.load(companies_json) for companies in companies: companies_obj = Company(**companies) companies_obj.save()
def import_companies(self): """ This method is used for read in parser file the fields referring a companies and create the objects of companies. """ csv_file = self.read_file('importer/data/companies.csv') print('Importing Companies...') for row in csv_file: try: Company.objects.get(name=row[0]) print('Company', row[0], 'already registered.') except ObjectDoesNotExist: company = Company() company.name = row[0] company.save()
def setUp(self): super().setUp() self.user_two = User.objects.create(username="******", email="*****@*****.**") self.company_two = Company.objects.create(user=self.user_two, name="Company 2") self.cb = Company.get_centralbank() self.sell = DynamicOrder.objects.create( order_by=self.cb, order_of=self.company, price=10, dynamic_value=1, limit=5, amount=1000, typ=Order.type_sell(), ) self.buy = DynamicOrder.objects.create( order_by=self.company, order_of=self.company_two, price=10, dynamic_value=1, limit=15, amount=1000, typ=Order.type_buy(), )
def setUp(self): super().setUp() Order.objects.create(typ=Order.type_sell(), order_by=Company.get_centralbank(), order_of=self.company, price=2, amount=100)
def test_sidebar(self): url = reverse("core:sidebar") rsp = self.client.get(url) cb = Company.get_centralbank() should_be = { "companies": [ { "name": self.company.name, "isin": self.company.isin, "id": self.company.id, "share_price": float(self.company.keyfigures.share_price), }, { "name": cb.name, "isin": cb.isin, "id": cb.id, "share_price": float(cb.keyfigures.share_price) }, ], "bond_rate": float(InterestRate.get_latest_rate()), "companies_count": Company.objects.count(), "buy_orders_count": Order.objects.filter(typ=Order.type_buy()).count(), "sell_orders_count": Order.objects.filter(typ=Order.type_sell()).count(), } self.assertDictEqual(should_be, rsp.json())
def build_company_from_dataclass(self, company_dc: CompanyDC) -> Company: return Company( name=company_dc.name, symbol=company_dc.symbol, info=self._company_info_factory.build_company_info( company_dc.info), )
def create_models_new_company(sender, instance, created, **kwargs): """ Signal to create models upon company creation """ if created: company = instance logger.info( f"Creating new objects for the new company {company}, cash: {company.cash}, shares: {company.shares}" ) assert company.shares >= 1_000 assert company.shares <= 1_000_000 with transaction.atomic(): time = timezone.now() Activity.objects.create(company_id=company.id) HistoryCompanyData.objects.create(company_id=company.id, start_shares=company.shares, joined=time) CompanyVolume.objects.create(company_id=company.id, day=time) if company.name != CENTRALBANK: DepotPosition.objects.create(depot_of=Company.get_centralbank(), company=company, amount=company.shares) book_value = company.cash share_price = company.cash / company.shares k = KeyFigures.objects.create( company_id=company.id, book_value=book_value, # On creation a company only has cash so ttoc equals the book value # for more explanation of the ttoc, please have a look at stats/models.py -> KeyFigures # and periodic_tasks/key_figures.py for the calculation. ttoc=book_value, share_price=share_price, ) PastKeyFigures.past_from_current_key_figure(k).save() # set isin _id = company.id # TODO: Extract to method isin = f"{company.country}{'0' * (6 - len(str(_id)))}{_id}" logger.info(f"Setting isin: id was {_id}, country: {company.country}. ISIN => {isin}") company.isin = isin company.save() if company.user: try: p = Profile.objects.get(user=company.user) except Profile.DoesNotExist: logger.error(f"Profile does not exist for {company.user.id}") return p.create_default_logo() p.save()
def handle(self, *args, **options): print('Deleting all existing records') Company.objects.all().delete() path = options['dataset'] keys = [f.name for f in Company._meta.fields] with open(path, mode='r', encoding='utf-8') as file_handler: for row in csv.DictReader(file_handler): filtered = {k: v for k, v in row.items() if k in keys} obj = Company(**filtered) obj.save() for ticker in self.extract_tickers(row): obj.tickers.create(code=ticker) print('{:,} objects created'.format(Company.objects.count()))
def validate_order_of_isin(self, value: str) -> str: """ Validate that the order_of isin is valid. It must be an existing company and not the same as the buying company. """ if value == self.company.isin: raise serializers.ValidationError( _("You cannot create an order for your own company!")) if not Company.objects.filter( id=Company.get_id_from_isin(value)).exists(): raise serializers.ValidationError( _("A company with the given isin does not exist")) if Company.get_centralbank().isin == value: raise serializers.ValidationError( _("You cannot place an order on the Centralbank")) return value
def company_delete(request, pk): item = get_object_or_404(Company, pk=pk) msg = DELETE_SUCCESS.format(item._meta.verbose_name, item) item.delete() if request.is_ajax(): return JsonResponse({"msg": msg, "type": TYPE_SUCCESS}, safe=True) else: messages.warning(request, msg, TITLE_SUCCESS) return redirect(Company.get_list_url())
def test_centralbank_exists(self): cb = Company.get_centralbank() self.assertIsNotNone(cb) self.assertTrue(cb.name, "Centralbank") # Test the signals got triggerd. On migrations signals are not triggered. # Must be called by hand self.assertTrue(Activity.objects.filter(company=cb).exists()) self.assertTrue(HistoryCompanyData.objects.filter(company=cb).exists()) self.assertTrue(CompanyVolume.objects.filter(company=cb).exists()) self.assertTrue(KeyFigures.objects.filter(company=cb).exists())
def update_cash_company(self, company: Company, cash): # ToDo: Update for private depot so private depot receives the money id_ = company.id if id_ not in self.companies_cash_update: company.cash = F("cash") + cash self.companies_cash_update[id_] = company else: company = self.companies_cash_update[id_] company.cash += cash self.companies_cash_update[id_] = company
def create(self, validated_data) -> Order: order_by_isin = self.company.isin order_of_isin = validated_data.get("order_of_isin") order_by_id = Company.get_id_from_isin(order_by_isin) order_of_id = Company.get_id_from_isin(order_of_isin) price = validated_data.get("price") amount = validated_data.get("amount") typ = validated_data.get("typ") order = Order.objects.create(order_by_id=order_by_id, order_of_id=order_of_id, amount=amount, price=price, typ=typ) check_orders_single_company.delay(order_of_id) return order
def setUp(self) -> None: self.cb = Company.get_centralbank() # Seems when all the tests are run together then signals get triggered # and the centralbank depot positions get created. Hence, we # delete all of them so DepotPosition.objects.filter(depot_of=self.cb).delete() # Test if the data has been loaded correctly self.assertEqual(5, User.objects.count()) self.assertEqual(6, Company.objects.count()) self.check_market()
def validate(self, data): company_id = Company.get_id_from_isin(data["company_isin"]) c = Company.objects.get(id=company_id) value = data["value"] if not c.enough_money(value): raise serializers.ValidationError({ "value": f"You do not have enough money to buy a {value} bond" }) return data
def render(self, data, accepted_media_type=None, renderer_context=None): kwargs = renderer_context.get("kwargs") isin = kwargs.get("isin") if isin and isinstance(data, dict): try: company = Company.objects.only("name").get( id=Company.get_id_from_isin(isin)) except Company.DoesNotExist: logger.info(f"Company with isin {isin} does not exist!") raise Http404 data["company_name"] = company.name return super().render(data, accepted_media_type, renderer_context)
def process_company(self, company_id, company_ipn, company_name): if not company_ipn and not company_name: return None if len(company_name) > 250: self.stderr.write( 'Company name {} is too long'.format(company_name)) return None company = None for k, v in [("pk", company_id), ("edrpou", company_ipn), ("name_uk", company_name)]: try: if v: company = Company.objects.get(**{k: v}) break except Company.DoesNotExist: pass if company is None: company = Company(state_company=True) # Set missing params if not company.name_uk: company.name_uk = company_name Ua2EnDictionary.objects.get_or_create(term=lookup_term(company_name)) if not company.edrpou: company.edrpou = company_ipn company.save() return company
def run(self): cb = Company.get_centralbank() depot = DepotPosition.objects.filter(depot_of=cb) active_orders = Order.objects.filter(typ=Order.type_sell(), order_by=cb).values_list( "order_of_id", flat=True) total_new_orders = 0 logger.info( f"Checking {depot.count()} depot positions of the centralbank") with transaction.atomic(): for position in depot.iterator(): # TODO Add this into the query so we do not have to check this again if position.company_id in active_orders: continue company = position.company # get 10% of the shares in the depot amount = position.amount * 0.1 if position.amount < company.shares * 0.1: amount = position.amount # The centralbank sell orders start always little bit over the last trade. # As it is a dynamic order and not a normal order # the price will dynamically fall every tick. # For more information please see the DynamicOrder model price = company.keyfigures.share_price * Decimal(1.5) dynamic_value = price * Decimal(0.01) # cannot bulk create because of multi inherited table DynamicOrder.objects.create( order_by=cb, order_of=company, amount=amount, price=price, limit=0.5, dynamic_value=dynamic_value, typ=Order.type_sell(), ) total_new_orders += 1 logger.info( f"A total of {total_new_orders} sell orders have been created by the centralbank" )
def validate(self, data): order_by_isin = self.company.isin order_of_isin = data.get("order_of_isin") self.validate_order_of_isin(order_of_isin) order_by_id = Company.get_id_from_isin(order_by_isin) order_of_id = Company.get_id_from_isin(order_of_isin) price = data.get("price") amount = data.get("amount") typ = data.get("typ") if typ == Order.type_sell(): self.validate_sell_order(amount, order_of_id) value = price * amount self.validate_enough_money(value=value) if Order.objects.filter(order_by_id=order_by_id).count() > 100: raise serializers.ValidationError( "You already have more than 100 orders!") return data
def create_bond(value, company_isin, runtime) -> Bond: """ Celery-Task for buying a bond. :param value: :param company_isin: :param runtime: :return: TODO: Actually not needed. Delete it! """ rate = InterestRate.calc_rate(value) company_id = Company.get_id_from_isin(company_isin) bond = Bond.objects.create(company_id=company_id, value=value, rate=rate, runtime=runtime) return bond
def read_data(self): user_ids = self.read_users() self.read_companies(user_ids) self._read_depot_positions(self.setup_path) self._read_orders(self.setup_path) DepotPosition.objects.filter( depot_of=Company.get_centralbank()).delete() # make sure that the total amount of shares of a company matches # the amount of shares distributed across depots in the market for c in Company.objects.all().exclude(name=CENTRALBANK): total_shares = c.shares total_depot_shares = DepotPosition.objects.filter( company=c).aggregate(s=Sum("amount")).get("s") msg = ( f"{c} does have {total_shares} shares and {total_depot_shares} where available on the market in depots" ) self.assertEqual(total_depot_shares, total_shares, msg)
def manage_company(request, company_id=None): if request.user.is_superuser: # Try to locate the object to use it as an instance and if not, create # new one to use it in a new form. # common_data = common_ticket_data() if company_id: actual_company = get_object_or_404(Company, pk=company_id) else: actual_company = Company() # POST mode if request.method == 'POST': form = CompanyForm(request.POST, request.FILES, instance=actual_company) if form.is_valid(): form.save() return redirect('company-list') else: # Non-POST mode, show only form = CompanyForm(instance=actual_company) return render(request, 'core/companies/create_edit_company.html', locals()) else: raise Http404
def create(self, validated_data): company_isin = validated_data.get("company_isin") value = validated_data.get("value") runtime = validated_data.get("runtime") rate = InterestRate.calc_rate(value) company_id = Company.get_id_from_isin(company_isin) with transaction.atomic(): # TODO: I think this can be replaced by simply writing: # c.cash = c.cash - value # as this inside in a transaction atomic block but I am not 100% sure # Need to check the docs Company.objects.filter(id=company_id).update(cash=F("cash") - value) bond = Bond.objects.create(company_id=company_id, value=value, rate=rate, runtime=runtime) return bond
def setUp(self): super().setUp() self.user_b = User.objects.create(username="******", password="******", email="*****@*****.**") self.company_b = Company.objects.create(name="Company-B", user=self.user_b) DepotPosition.objects.filter( depot_of=Company.get_centralbank()).delete() self.company_as_shareholder = DepotPosition.objects.create( company=self.company, depot_of=self.company_b, price_bought=1, amount=10000) self.user_company_private_depot = DepotPosition.objects.create( company=self.company, depot_of=self.company_b, price_bought=1, amount=10000, private_depot=True)
def setUp(self): self.user = User.objects.create(username="******", password="******", email="*****@*****.**") self.company = Company.objects.create(name="Company", user=self.user, cash=self.ONE_HUNDRED_THOUSAND) self.user_two = User.objects.create(username="******", password="******", email="*****@*****.**") self.centralbank = Company.get_centralbank()
def _deleting_company_keeps_trade(self, company: Company): Trade.create_trade_histories(company) company.delete() self.assertTrue(Trade.objects.filter(id=self.trade.id).exists())
def test_get_centralbank(self): c = Company.get_centralbank() self.assertEqual(c.name, CENTRALBANK)
def test_id_from_isin_can_hande_non_ints(self): self.assertEqual(Company.get_id_from_isin("abc"), -1) self.assertEqual(Company.get_id_from_isin("US0000001k"), -1)