def test_total_expected_earnings(self):
     position_1 = Position(stock=Stock('ticker', 'name', 20, 30),
                           quantity=2)
     position_2 = Position(stock=Stock('ticker', 'name', 20, 40),
                           quantity=2)
     portfolio = Portfolio(position_1, position_2)
     self.assertEqual(Decimal('1.5'), portfolio.total_expected_earnings)
예제 #2
0
파일: data_utils.py 프로젝트: LEVLLN/trades
def save_individual_trades(element_list, individual_code):
    for element in element_list:
        insider_trade = IndividualInsiderTrades()
        link = element[0]
        stock_code = link.replace('https://www.nasdaq.com/symbol/', '')
        stock_code = stock_code.replace('/insider-trades',
                                        '').strip(' \t\n\r').upper()
        print(stock_code)

        try:
            Stock().get_by_id(stock_code)
            print('success')
            insider_trade.company = stock_code
        except Exception:
            stock = Stock()
            stock_url = make_url('main', stock_code)
            stock_page = load_page(stock_url)
            stock_name = scrape_stock_name(stock_page)
            stock.name = stock_name
            stock.code = stock_code
            save_stock(stock)
            insider_trade.company = Stock().get_by_id(stock_code)

        insider_trade.insider = individual_code
        insider_trade.relation = element[2]
        trade_last_date = datetime.date(
            datetime.strptime(element[3], '%m/%d/%Y'))
        insider_trade.last_date = trade_last_date
        insider_trade.tran = element[5]
        insider_trade.owner_type = element[6]
        shares_traded = element[7].replace(',', '')
        if shares_traded == '':
            shares_traded = 0
        insider_trade.shares_traded = shares_traded
        last_price = element[8]
        if last_price == '':
            last_price = 0.0
        insider_trade.last_price = last_price
        shares_held = element[9].replace(',', '')
        if shares_held == '':
            shares_held = 0
        insider_trade.shares_held = shares_held
        try:
            insider_trade.save()
            logger.info(
                f'Trade object of {individual_code} on last date {element[3]} saved in db'
            )
        except Exception as exception:
            print(exception)
            logger.error(f'{individual_code} is allready exist: {exception}')
            db.rollback()
예제 #3
0
파일: api.py 프로젝트: kirilldolganov/music
def api_stock_insert():
    new_stock = request.get_json()
    stock = Stock(id=new_stock['id'], amount=new_stock['amount'])
    db.session.add(stock)
    db.session.commit()
    stock_json = {"id": stock.id, "amount": stock.amount}
    return jsonify(stock_json)
예제 #4
0
def test_booking_completed_url_gets_normalized():
    # Given

    product = Product()
    product.url = 'javascript:alert("plop")'

    offer = Offer()
    offer.id = 1
    offer.product = product

    stock = Stock()

    user = User()
    user.email = '*****@*****.**'

    booking = Booking()
    booking.token = 'ABCDEF'
    booking.stock = stock
    booking.stock.offer = offer
    booking.user = user

    # When
    completedUrl = booking.completedUrl

    # Then
    assert completedUrl == 'http://javascript:alert("plop")'
예제 #5
0
    def test_missing_stock_name_signup(self):
        """test missing stock name"""

        invalid_stock = Stock(stock_symbol="UNH")
        with self.assertRaises(exc.IntegrityError):
            db.session.add(invalid_stock)
            db.session.commit()
예제 #6
0
    def test_missing_stock_symbol_signup(self):
        """test midding stock symbol"""

        invalid_stock = Stock(stock_name="United Health Group")
        with self.assertRaises(exc.IntegrityError):
            db.session.add(invalid_stock)
            db.session.commit()
예제 #7
0
파일: finviz.py 프로젝트: beknazar/buffett
    def crawl(self, criteria, exchange):
        start = criteria.find('&c=')
        cols_count = len(criteria[start + 3:].split(','))

        entries = []
        page = 0
        page_count = 1
        tree = self.get_tree(self.homepage_url.format(criteria))

        page_nums = tree.xpath('//a[@class="screener-pages"]/text()')
        if len(page_nums) > 0:
            page_count = int(page_nums[-1])
        while True:
            page += 1
            self.info('Crawling page: {0}/{1}'.format(page, page_count))

            tickers = tree.xpath('//a[@class="screener-link-primary"]/text()')
            attrs = tree.xpath('//td[@class="screener-body-table-nw"]//text()')
            index = 0
            for i in range(len(tickers)):
                entry = {}
                for j in range(cols_count):
                    key = self.attr_map[j]
                    entry[key] = self.convert(key, attrs[i * cols_count + j])
                entry['exchange'] = exchange
                entries.append(Stock(**entry))
            next_el = tree.xpath('//a[contains(., "next")]')
            if len(next_el) > 0:
                criteria = next_el[0].attrib['href']
                tree = self.get_tree(self.homepage_url.format(criteria))
            else:
                break
        # Create stocks in bulk
        Stock.objects.bulk_create(entries)
예제 #8
0
def stock_crypto():
    if not g.user:
        flash("Access unauthorized.", "error")
        return redirect("/")
    form = TickerForm()
    user = g.user
    if form.validate_on_submit():
        symbol = form.ticker.data
        region = form.region.data
        data = search_stock(symbol, region)
        if data["type"] == "stock":
            if Stock.query.filter_by(ticker_symbol=symbol).first():
                stock = Stock.query.filter_by(ticker_symbol=symbol).first()
                return render_template('stock-profile.html',
                                       data=data,
                                       user=user,
                                       stock_data=data,
                                       stock=stock)
            else:
                stock = Stock(stock_name=data["name"],
                              ticker_symbol=data["symbol"],
                              region=region,
                              which_type=data["type"],
                              stock_price=data["price"])
                db.session.add(stock)
                db.session.commit()
                return render_template('stock-profile.html',
                                       data=data,
                                       user=user,
                                       stock_data=data,
                                       stock=stock)
        elif data["type"] == "crypto":
            if Cryptocurrency.query.filter_by(ticker_symbol=symbol).first():
                crypto = Cryptocurrency.query.filter_by(
                    ticker_symbol=symbol).first()
                return render_template('stock-profile.html',
                                       data=data,
                                       user=user,
                                       crypto_data=data,
                                       crypto=crypto)
            else:
                crypto = Cryptocurrency(crypto_name=data["name"],
                                        ticker_symbol=data["symbol"],
                                        region=region,
                                        which_type=data["type"],
                                        crypto_price=data["price"])
                db.session.add(crypto)
                db.session.commit()
                return render_template('stock-profile.html',
                                       data=data,
                                       user=user,
                                       crypto_data=data,
                                       crypto=crypto)
        elif data["type"] == "not found":
            flash(
                "Please insert correct ticker symbol for stocks and cryptocurrencies only!",
                "error")
            return redirect(f'/users/{user.username}')
    else:
        return redirect(f'/users/{user.username}')
예제 #9
0
    def setUp(self):
        print("*********first***********")
        User_stock.query.delete()
        User.query.delete()
        Stock.query.delete()

        user = User.register(first_name="rahul",
                             last_name="kapoor",
                             username="******",
                             email="*****@*****.**",
                             password="******")
        db.session.add(user)
        db.session.commit()

        stock = Stock(stock_name="Facebook, Inc.",
                      ticker_symbol="fb",
                      region="US",
                      which_type="stock",
                      stock_price="306.1696")
        db.session.add(stock)
        db.session.commit()
        self.stock_id = stock.id
        self.type = stock.which_type
        self.name = stock.stock_name
        self.region = stock.region
        self.symbol = stock.ticker_symbol
        self.price = stock.stock_price
예제 #10
0
async def create_stock(stock_request: StockRequest,
                       background_tasks: BackgroundTasks,
                       db: Session = Depends(get_db)):
    """ Method to create stock
    """
    stock = Stock()
    stock.symbol = stock_request.symbol

    db.add(stock)
    db.commit()

    background_tasks.add_task(fetch_stock_data, stock.id)

    return {
        "code": "sucess",
        "message": f"stock {stock_request.symbol} created"
    }


# @app.get("/stock/")
# def get_stock():
#     db = SessionLocal()
#     stocks = db.query(Stock).all()
#     stocks_json = jsonable_encoder(stocks)
#     return {"my_stock": stocks_json}
예제 #11
0
def addStock(drugNum):
    # 判断用户是否登录
    user_id = session.get('user_id')
    if user_id:
        user = User.query.filter(User.id == user_id).first()
        if user:
            # 判断是否是POST
            if request.method == 'GET':
                drug = Drug.query.filter(Drug.num == drugNum).first()
                return render_template('addStock.html', drug=drug)
            else:
                id = request.form.get('id')
                num = request.form.get('num')
                name = request.form.get('name')
                type = request.form.get('type')
                count = request.form.get('count')
                # 原来库存量
                stockCount = request.form.get('stockCount')
                price = request.form.get('price')
                desc = request.form.get('desc')

                # 库存量增加
                Drug.query.filter(Drug.id == id).update(
                    {Drug.count: int(stockCount) + int(count)})
                stock = Stock(stockPrice=price,
                              stockCount=count,
                              stockMoney=int(count) * float(price),
                              drugId=id,
                              userId=user_id)
                db.session.add(stock)
                db.session.commit()

                return redirect(url_for('addStockHome'))
    return redirect(url_for('login'))
예제 #12
0
def stock_add(symbol):
    """
    Add Stock to Stocks table
    """

    if not g.user:
        flash("You need to be logged in for this!", "danger")
        return redirect("/")

    overview = get_company_overview(symbol)

    user = User.query.get(g.user.id)
    stock = Stock.query.filter_by(symbol=symbol).first()
    if stock is None:

        new_stock = Stock(symbol=overview["Symbol"],
                          name=overview["Name"],
                          assettype=overview["AssetType"],
                          exchange=overview["Exchange"],
                          industry=overview["Industry"],
                          weekhigh=overview["52WeekHigh"],
                          weeklow=overview["52WeekLow"])
        db.session.add(new_stock)
        db.session.commit()
        user.watchlist.append(new_stock)
        db.session.commit()
    else:
        user.watchlist.append(stock)
        db.session.commit()

    return redirect(f"/stocks/{symbol}")
예제 #13
0
def store_stock(stock, market):
    stock_model = Stock(market=market,
                        url=stock['url'],
                        name=stock['name'],
                        symbol=stock['symbol'])
    stock_model.save()

    print stock['name']
예제 #14
0
 def get(self):
     try:
         db.session.add(Stock('goog', 'vinit'))
         db.session.commit()
         s1 = Stock.query.filter_by(owner_user='******').first()
         return {'owner': s1.company_name}, 222
     except Exception as e:
         return {'server_error': str(e)}, 522
예제 #15
0
def BeginToTrade(request):
    RequestUser = request.user
    RequestGroup = RequestUser.group
    context={
        "form":SearchForm(),
        "sear":True
    }
    if request.method=="POST":
        Post = request.POST.dict()
        if Post.has_key("StockName"):
            StockName=str(Post["StockName"])
        else:
            StockName=""
        if Post.has_key("Volume"):
            Volume=Post["Volume"]
        else:
            Volume=0
        if Post.has_key("TransactionType"):
            TransactionType=Post["TransactionType"]
        else:
            TransactionType=None
        print Post

        context={
            "form":OrderForm(),
            "sear":False
            
            }
        
        stock = Stock.objects.filter(StockName=StockName)
        if len(stock)==0:
            print "123123"
            stock = Stock(StockName=StockName)
            stock.save()
            context["StockData"] = jsonpickle.encode(stock.Get_data())
        else:
             context["StockData"] = jsonpickle.encode(stock[0].Get_data())

        if Volume!="" and TransactionType != None:
            RequestUser.group.UpdateAcount()
            stockprice = stock[0].Get_Price()
            if TransactionType=="buy":
                if RequestUser.group.Cash >= stockprice*float(Volume):
                    RequestGroup.transaction_set.create(TransType = TransactionType,StockOfTrans = stock[0], Volume=Volume, PriceAtTrans=stock[0].Get_Price() )
                    context["mess"] = "Succesfully making transaction"
                else:
                    context["mess"] = "You don't have enough money"
            else:
                asset = RequestUser.group.AllAsset
                if asset[StockName] >= float(Volume):
                    RequestGroup.transaction_set.create(TransType = TransactionType,StockOfTrans = stock[0], Volume=Volume, PriceAtTrans=stock[0].Get_Price() )
                    context["mess"] = "Succesfully making transaction"
                else:
                    context["mess"] = "You don't have enough this stock to sell"
        
    return render(request, "BeginToTrade.html", context)
예제 #16
0
def get_market_stocks(client):
    payload = client.get_market_stocks().payload
    stocks_usd = [
        stock for stock in payload.instruments[:] if stock.currency == 'USD'
    ]
    stocks = {
        s.ticker: Stock(ticker=s.ticker, isin=s.isin)
        for s in stocks_usd
    }
    return stocks
예제 #17
0
    def setUp(self):
        """create test client, add sample data"""

        s = Stock(stock_symbol="AAPL", stock_name="Apple")
        p = Peer(lead_stock_symbol=s.stock_symbol, peer_stock_symbol='MSFT')
        p.id = 9876

        db.session.add_all([s, p])
        db.session.commit()
        self.p = p
예제 #18
0
def create_stock(stock_request: StockRequest,
                 background_tasks: BackgroundTasks,
                 db: Session = Depends(get_db)):
    stock = Stock()
    stock.symbol = stock_request.symbol

    db.add(stock)
    db.commit()

    background_tasks.add_task(fetch_stock_data, stock.id)
    return {"code": "success", "message": "stock created"}
예제 #19
0
def update_or_add_stock(equity, field, data):
    equity = equity.upper()
    existing_stock = db.session.query(Stock).filter(
        Stock.equity == equity).first()
    if existing_stock is None:
        if field == 'info':
            stock = Stock(equity=equity, info=data)
        elif field == 'history':
            stock = Stock(equity=equity, history=data)
        elif field == 'history_alpha':
            stock = Stock(equity=equity, history_alpha=data)
        db.session.add(stock)
    else:
        if field == 'info':
            existing_stock.info = data
        elif field == 'history':
            existing_stock.history = data
        elif field == 'history_alpha':
            existing_stock.history_alpha = data
    db.session.commit()
예제 #20
0
    def test_raises_resource_gone_error_if_is_used(self):
        # Given
        booking = Booking()
        booking.isUsed = True
        booking.stock = Stock()

        # When
        with pytest.raises(ResourceGoneError) as e:
            check_booking_is_usable(booking)
        assert e.value.errors['booking'] == [
            'Cette réservation a déjà été validée']
예제 #21
0
def create_stock_from_offer(offer, price=10, available=10, soft_deleted=False, booking_limit_datetime=None,
                            beginning_datetime=None, end_datetime=None):
    stock = Stock()
    stock.offer = offer
    stock.price = price
    stock.available = available
    stock.isSoftDeleted = soft_deleted
    stock.bookingLimitDatetime = booking_limit_datetime
    stock.beginningDatetime = beginning_datetime
    stock.endDatetime = end_datetime
    return stock
예제 #22
0
def add_stock():
    body = request.get_json()

    for ingreTemp in body:

        stock1 = Stock(id_profile=ingreTemp["id_profile"],
                       id_ingrediente=ingreTemp["id_ingrediente"],
                       quantity=ingreTemp["quantity"])
        db.session.add(stock1)
        db.session.commit()
    return "ok", 200
예제 #23
0
    def test_returns_humanized_ids_for_foreign_keys(self, app):
        # given
        user = create_user(postal_code=None, idx=12)
        booking = create_booking(user, Stock(), idx=13)
        booking.userId = user.id

        # when
        dict_result = as_dict(booking, includes=[])

        # then
        assert dict_result['userId'] == 'BQ'
예제 #24
0
    def test_validated_label_when_event_is_expired(self):
        # Given
        booking = Booking()
        booking.stock = Stock()
        booking.stock.beginningDatetime = datetime.utcnow() + timedelta(-1)

        # When
        statusLabel = booking.statusLabel

        # Then
        assert statusLabel == 'Validé'
예제 #25
0
    def test_is_countermak_validated_label_when_booking_is_used(self):
        # Given
        booking = Booking()
        booking.stock = Stock()
        booking.isUsed = True

        # When
        statusLabel = booking.statusLabel

        # Then
        assert statusLabel == 'Contremarque validée'
예제 #26
0
    def test_is_cancelled_label_when_booking_is_cancelled(self):
        # Given
        booking = Booking()
        booking.stock = Stock()
        booking.isCancelled = True

        # When
        statusLabel = booking.statusLabel

        # Then
        assert statusLabel == "Réservation annulée"
예제 #27
0
파일: dataproxy.py 프로젝트: tianyakun/yak
def get_all():
    try:
        df = pd.DataFrame(ts.get_today_all())
        j_datas = json.loads(df.to_json(orient='records'))
        stocks = []
        from models import Stock
        for j_data in j_datas:
            stocks.append(Stock(j_data))
        return stocks
    except IOError:
        pass
예제 #28
0
    def test_booking_on_thing_is_cancellable(self):
        # Given
        booking = Booking()
        booking.stock = Stock()
        booking.stock.offer = Offer()
        booking.stock.offer.product = create_product_with_thing_type()

        # When
        is_cancellable = booking.isUserCancellable

        # Then
        assert is_cancellable == True
예제 #29
0
def add_stock_for_user(db: Session, stock: StockCreate, email: str):
    stock.ticker = stock.ticker.upper()
    stock_obj = stockquotes.Stock(stock.ticker)
    current_price = stock_obj.current_price
    user_id = get_user_by_email(db, email).id
    db_stock = Stock(**stock.dict(),
                     user_id=user_id,
                     current_price=current_price)
    db.add(db_stock)
    db.commit()
    db.refresh(db_stock)
    return db_stock
예제 #30
0
    def test_does_not_raise_api_error_when_user_cancellation_and_event_in_more_than_72h(self):
        # Given
        booking = Booking()
        booking.isUsed = False
        booking.stock = Stock()
        booking.stock.beginningDatetime = datetime.utcnow() + timedelta(hours=73)

        # When
        check_output = check_booking_is_cancellable(booking, is_user_cancellation=False)

        # Then
        assert check_output is None