Exemple #1
0
    def test_add_duplicate_to_exchange(self):
        stk = gbce.Stock()
        setattr(stk, "Stock Symbol", "7UP")
        setattr(stk, "Type", "Common")
        setattr(stk, "Par Value", 100)

        self.me.add_stock(stk)

        stk = gbce.Stock()
        setattr(stk, "Stock Symbol", "7UP")
        setattr(stk, "Type", "Common")
        setattr(stk, "Par Value", 100)

        self.assertRaises(RuntimeError, self.me.add_stock, stk)
Exemple #2
0
def create_person_stocks_db(db: Session, person: schemas.PersonCreate):
    stock_list = person.stocks
    print("stock_list : ", stock_list)
    print("type(stock_list) : ", type(stock_list))
    db_person = models.Person(name=person.name,
                              email=person.email,
                              created_on=datetime.now(),
                              updated_by=person.updated_by)
    db.add(db_person)
    db.commit()
    db.refresh(db_person)
    print("db_person : ", db_person)
    for stock in stock_list:
        print("stock : ", stock)
        print("type(stock) : ", type(stock))
        print("db_person.id : ", db_person.id)
        db_stock = models.Stock(stock_name=stock.stock_name,
                                buy_price=stock.buy_price,
                                sell_price=stock.sell_price,
                                charges=stock.charges,
                                created_on=datetime.now(),
                                updated_by=stock.updated_by,
                                person_id=db_person.id)
        print("db_stock : ", db_stock)
        print("type(db_stock) : ", type(db_stock))
        db.add(db_stock)
        db.commit()
        db.refresh(db_stock)
        print("db_person : ", db_person)
    return {"status": "success"}
Exemple #3
0
def add_stock(symbol: str, db: Session):
    new_stock = models.Stock()
    new_stock.symbol = symbol
    db.add(new_stock)
    db.commit()
    db.refresh(new_stock)
    return new_stock
Exemple #4
0
    def test_add_stock_to_exchange(self):
        stk = gbce.Stock()
        setattr(stk, "Stock Symbol", "7UP")
        setattr(stk, "Type", "Common")
        setattr(stk, "Par Value", 100)

        self.assertTrue(self.me.add_stock(stk))
Exemple #5
0
def update_stock_by_id(db: Session, symbol: str, amount: int, cost: float,
                       userID: int):
    stock = db.query(models.Stock).filter(
        models.Stock.userID == userID, models.Stock.symbol == symbol).first()
    if stock is None:
        db_stock = models.Stock(symbol=symbol,
                                amount=amount,
                                cost=cost,
                                userID=userID)
        db.add(db_stock)
        db.commit()
    else:
        total_amount = stock.amount + amount
        total_cost = stock.cost + cost
        if (total_amount == 0):
            db.query(
                models.Stock).filter(models.Stock.userID == userID,
                                     models.Stock.symbol == symbol).delete()
        else:
            db.query(
                models.Stock).filter(models.Stock.userID == userID,
                                     models.Stock.symbol == symbol).update({
                                         models.Stock.amount:
                                         total_amount,
                                         models.Stock.cost:
                                         total_cost
                                     })
        db.commit()
Exemple #6
0
    def test_get_stock_not_ok(self):
        stk = gbce.Stock()
        setattr(stk, "Stock Symbol", "7UP")
        setattr(stk, "Type", "Common")
        setattr(stk, "Par Value", 100)
        self.me.add_stock(stk)

        self.assertIsNone(self.me.get_stock("FOO"))
Exemple #7
0
    def test_requirement_2_a_ii(self):
        """For a given stock, calculate the p/e ratio."""

        stk = gbce.Stock()
        setattr(stk, "Last Dividend", 23)

        for iter in range(100):
            price = choice(range(1, 1000))
            pe = stk.pe_ratio(price)
            self.assertEqual(price / getattr(stk, "Last Dividend", 1),
                             stk.pe_ratio(price))
Exemple #8
0
    def test_requirement_2_a_iv(self):
        """For a given stock, calculate Volume Weighted Stock Price based on trades in past five minutes."""
        stk = gbce.Stock()

        satr = setattr  # shortcut
        satr(stk, "Stock Symbol", "GIN")
        satr(stk, "Type", "Preferred")
        satr(stk, "Fixed Dividend", 2)
        satr(stk, "Par Value", 100)
        self.Market.add_stock(stk)

        t = gbce.Trade()
        setattr(t, "Stock Symbol", "GIN")
        setattr(t, "Buy/Sell", 'Buy')
        setattr(t, "Quantity", 1000)
        setattr(t, "Price", 114)
        self.Market.add_trade(t)

        self.assertTrue(self.Market.get_stock("GIN").\
                        volume_weighted_stock_price(self.Market) > 0.0)
Exemple #9
0
    def test_requirement_2_a_iii(self):
        """For a given stock, record a trade, with timestamp, quantity, buy or sell indicator and price."""
        stk = gbce.Stock()

        satr = setattr  # shortcut
        satr(stk, "Stock Symbol", "GIN")
        satr(stk, "Type", "Preferred")
        satr(stk, "Fixed Dividend", 2)
        satr(stk, "Par Value", 100)

        self.Market.add_stock(stk)

        t = gbce.Trade()
        setattr(t, "Stock Symbol", "GIN")
        setattr(t, "Buy/Sell", 'Buy')
        setattr(t, "Quantity", 1000)
        setattr(t, "Price", 114)
        self.Market.add_trade(t)  # adds Timestamp

        self.assertTrue(len(self.Market.trades) > 0)

        # verify timestamp added ok
        self.assertIsNotNone(self.Market.trades[0].Timestamp)
Exemple #10
0
    def test_requirement_2_a_i(self):
        """For a given stock, calculate the dividend yield."""

        stk = gbce.Stock()

        satr = setattr  # shortcut

        # common
        satr(stk, "Stock Symbol", "POP")
        satr(stk, "Type", "Common")
        satr(stk, "Last Dividend", 8)

        dy = stk.dividend_yield(250)
        self.assertEqual(8 / 250, dy)

        # preferred
        satr(stk, "Stock Symbol", "GIN")
        satr(stk, "Type", "Preferred")
        satr(stk, "Fixed Dividend", 2)
        satr(stk, "Par Value", 100)

        dy = stk.dividend_yield(402)
        self.assertEqual(2 / 100 * 100 / 402, dy)
Exemple #11
0
    def test_requirement_2_b(self):
        """Calculate the GBCE All Share Index using teh geometric mean of the
        Volume Weighted Stock Price for all stocks."""

        for stock in SAMPLE_DATA:
            stk = gbce.Stock()
            setattr(stk, "Stock Symbol", stock[0])
            setattr(stk, "Type", stock[1])
            setattr(stk, "Last Dividend", stock[2])
            setattr(stk, "Fixed Dividend", stock[3])
            setattr(stk, "Par Value", stock[4])
            self.Market.add_stock(stk)

        for trade_no in range(1000):
            t = gbce.Trade()
            setattr(t, "Stock Symbol",
                    choice(list(map(lambda x: x[0], SAMPLE_DATA))))
            setattr(t, "Buy/Sell", choice(['Buy', 'Sell']))
            setattr(t, "Quantity", choice(list(range(100, 200))))
            setattr(t, "Price", choice(list(range(400, 475))))
            self.Market.add_trade(t)

        self.assertTrue(self.Market.all_share_index() > 400 and \
                        self.Market.all_share_index() < 475)
Exemple #12
0
def create_stock(db: Session, stock: schemas.StockDBIn):
    db_stock = models.Stock(**stock.dict())
    db.add(db_stock)
    db.commit()
    db.refresh(db_stock)
    return db_stock
Exemple #13
0
def update_pog(session, company_id, store_id, device_id, df, operation=False):
    company_pkey = session.query(
        models.Company.company_pkey).filter_by(company_id=company_id).first()
    assert company_pkey, f'company_id: {company_id}, 해당 정보가 존재하지 않습니다.'
    company_pkey = company_pkey.company_pkey

    store_pkey = session.query(models.Store.store_pkey).filter_by(
        company_pkey=company_pkey, store_id=store_id).first()
    assert store_pkey, f'company_id: {company_id}, store_id: {store_id}, 해당 정보가 존재하지 않습니다.'
    store_pkey = store_pkey.store_pkey

    try:
        # insert device
        device = session.query(models.Device).filter_by(store_pkey=store_pkey,
                                                        device_id=device_id)
        if device.first() is None:
            print(
                f'company_id: {company_id}, store_id: {store_id}, device_id: {device_id}, 해당 정보가 존재하지 않습니다.'
            )
            print(
                f'company_id: {company_id}, store_id: {store_id}, device_id: {device_id}, 해당 정보를 추가합니다.'
            )
            if device_id[0] == 's':
                device_install_type = 'S'
            elif device_id[0] == 'w':
                device_install_type = 'W'
            else:
                raise ValueError('device_id의 첫 글자는 "s" 또는 "w" 이어야 합니다.')
            session.add(
                models.Device(device_id=device_id,
                              store_pkey=store_pkey,
                              device_install_type=device_install_type,
                              operation=operation))
            # session.commit()

        # get device_pkey
        device_pkey = device.first().device_pkey

        # insert model
        model_pkeys = []
        change = False
        for d in df[['model_name', 'model_address']].itertuples():
            model = session.query(
                models.Model).filter_by(model_name=d.model_name).first()
            if model is None:
                print(f'model {d.model_name} 이 존재하지 않습니다. model 정보를 추가합니다.')
                model = models.Model(model_name=d.model_name,
                                     model_address=None if np.isnan(
                                         d.model_address) else d.model_address)
                session.add(model)
                change = True
            model_pkeys.append(model.model_pkey)
        df['model_pkey'] = model_pkeys

        # insert or update shelves
        for shelf_floor in set(df.shelf_floor):
            shelf = session.query(models.Shelf).filter_by(
                device_pkey=device_pkey, shelf_floor=shelf_floor)
            sub_df = df[df['shelf_floor'] == shelf_floor]
            model_pkey = sub_df['model_pkey'].iloc[0]
            if shelf.first() is None:
                print('shelf_floor가 존재하지 않습니다. shelf 정보를 추가합니다.')
                session.add(
                    models.Shelf(device_pkey=int(device_pkey),
                                 shelf_floor=int(shelf_floor),
                                 model_pkey=int(model_pkey)))
            else:
                if shelf.first().model_pkey != model_pkey:
                    print(
                        f'경고! shelf_floor: {shelf_floor} 자리의 model_pkey가 {shelf.first().model_pkey} 에서 {model_pkey} 로 변경됩니다.'
                    )
                    shelf.update({'model_pkey': int(model_pkey)})

        # get shelf_pkeys
        shelf_pkeys = []
        df2 = df.drop(['loadcell_column'], axis=1).drop_duplicates()
        for d in df2.itertuples():
            shelf_pkey = session.query(models.Shelf.shelf_pkey)\
                .select_from(models.Shelf)\
                .join(models.Device, models.Device.device_pkey == models.Shelf.device_pkey)\
                .filter(models.Device.store_pkey == store_pkey,
                        models.Device.device_id == device_id,
                        models.Shelf.shelf_floor == d.shelf_floor)\
                .first().shelf_pkey
            shelf_pkeys.append(shelf_pkey)

        # cells
        for d, shelf_pkey in zip(df2.itertuples(), shelf_pkeys):
            try:
                # get design_pkey
                design_pkey = session.query(
                    models.Design.design_pkey).filter_by(
                        design_infer_label=d.design_infer_label).all(
                        )[-1].design_pkey
            except IndexError as index_error:
                print(f'goods_id({d.goods_id})에 해당하는 데이터가 존재하지 않습니다.')
                raise index_error

            # get cells
            cell = session.query(models.Cell).filter_by(
                shelf_pkey=shelf_pkey, cell_column=d.cell_column)
            if cell.first() is None:
                # if the cell isn't exist, insert the cell
                print(
                    f'floor: {d.shelf_floor}, column: {d.cell_column} 에 해당하는 데이터가 존재하지 않습니다. 해당 cell을 추가합니다.'
                )
                session.add(
                    models.Cell(shelf_pkey=int(shelf_pkey),
                                design_pkey_master=int(design_pkey),
                                cell_column=int(d.cell_column),
                                stock_count_max=int(d.stock_count_max),
                                stock_count_low_alert_limit=None
                                if np.isnan(d.stock_count_low_alert_limit) else
                                int(d.stock_count_low_alert_limit),
                                inference_mode=d.inference_mode,
                                load_cell_mode=d.load_cell_mode))
            else:
                # else, update the cell
                cell.update({
                    'design_pkey_master':
                    int(design_pkey),
                    'stock_count_max':
                    int(d.stock_count_max),
                    'stock_count_low_alert_limit':
                    None if np.isnan(d.stock_count_low_alert_limit) else int(
                        d.stock_count_low_alert_limit),
                    'inference_mode':
                    d.inference_mode,
                    'load_cell_mode':
                    d.load_cell_mode
                })

            # insert init stock
            stock = session.query(
                models.Stock).filter_by(cell_pkey=cell.first().cell_pkey)
            if stock.first() is None:
                print(
                    f'stock 추가 (floor: {d.shelf_floor}, column: {d.cell_column}, goods_id: {d.goods_id}, stock_count: 0'
                )
                session.add(
                    models.Stock(cell_pkey=cell.first().cell_pkey,
                                 design_pkey=int(design_pkey),
                                 stock_count=0))

        # insert (or update) loadcell
        for d in df.itertuples():
            shelf_pkey = session.query(models.Shelf.shelf_pkey)\
                .select_from(models.Shelf)\
                .join(models.Device, models.Device.device_pkey == models.Shelf.device_pkey)\
                .filter(models.Device.store_pkey == store_pkey,
                        models.Device.device_id == device_id,
                        models.Shelf.shelf_floor == d.shelf_floor)\
                .first().shelf_pkey

            cell_pkey = session.query(models.Cell.cell_pkey).filter_by(
                shelf_pkey=shelf_pkey,
                cell_column=d.cell_column).first().cell_pkey

            # get loadcells
            loadcells = session.query(models.Loadcell).filter_by(
                shelf_pkey=shelf_pkey,
                loadcell_column=d.loadcell_column).first()

            if loadcells is None:
                # insert loadcell
                session.add(
                    models.Loadcell(shelf_pkey=int(shelf_pkey),
                                    cell_pkey=int(cell_pkey),
                                    loadcell_column=d.loadcell_column))
            else:
                # update loadcell
                loadcells.cell_pkey = cell_pkey

        session.commit()

    except Exception as e:
        session.rollback()
        raise e

    finally:
        session.close()
Exemple #14
0
 def _get_stock(self):
     stk = gbce.Stock()
     setattr(stk, "Stock Symbol", "7UP")
     setattr(stk, "Type", "Common")
     setattr(stk, "Par Value", 100)
     return stk
Exemple #15
0
 def test_add_blank_stock_to_exchange(self):
     stk = gbce.Stock()
     self.assertRaises(RuntimeError, self.me.add_stock, stk)
Exemple #16
0
 def setUp(self):
     self.me = gbce.Stock()