Esempio n. 1
0
    def get(self):
        user = get_user()  # get user details from token
        portfolio_details = get_portfolio(user, "moving")
        portfolio_value_user = portfolio_value(user)

        file_basename = f'{portfolio_details["name"]}.xlsx'
        curr_dir = Path.cwd()
        file_path = curr_dir / "simvestr" / "resources"
        create_csv(
            file_path, file_basename, user, portfolio_details, portfolio_value_user
        )

        @after_this_request
        def download_file(response):
            response = make_response(
                send_from_directory(directory=file_path, filename=file_basename, as_attachment=True)
            )
            response.headers["X-UA-Compatible"] = "IE=Edge,chrome=1"
            response.headers["export"] = "portfolio"
            response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
            response.headers["Pragma"] = "no-cache"
            response.headers["Expires"] = "0"
            response.headers["Cache-Control"] = "public, max-age=0"
            return response

        return 200
Esempio n. 2
0
    def get(self):
        user = get_user()
        portfolio_id = user.portfolio.id

        # get the balances of all the portfolios
        balances_sorted = get_ordered_portfolios()

        # get the value of the users portfolio
        p = PortfolioPrice.query.filter(
            PortfolioPrice.portfolio_id == portfolio_id).order_by(
                PortfolioPrice.timestamp.desc()).first()
        my_value = p.close_balance + p.investment_value

        # find the position on the screen
        pos_screen = 1
        while balances_sorted[pos_screen - 1]["portfolio"] != portfolio_id:
            pos_screen += 1

        # find actual position in the leaderboard - maybe higher than displayed position if duplicate portfolio balances
        pos_actual = pos_screen
        while (pos_actual > 0) and (my_value == balances_sorted[pos_actual -
                                                                1]["value"]):
            pos_actual -= 1
        pos_actual += 1

        # add the ordinal suffix to the actual position
        suffix = ORDINAL_SUFFIXES[min(pos_actual % 10, 4)]
        if 11 <= (pos_actual % 100) <= 13:
            suffix = "th"
        return jsonify({
            "nominal": pos_screen,
            "ordinal": str(pos_actual) + suffix
        })
Esempio n. 3
0
 def get(self):
     user = get_user()
     args = portfolio_history_parser.parse_args()
     if args["number_of_days"] < 1:
         return abort(400, "Number of days must be a non zero positive integer")
     history = get_close_balance(user, **args)
     return history, 200
Esempio n. 4
0
 def get(self):
     user = get_user()
     args = simulate_parser.parse_args()
     if args["date_from"] and args["date_to"]:
         if args["date_from"] > args["date_to"]:
             return abort(400, "date_from must be a date at least 1 day before date_to. Check your inputs.")
         elif args["date_to"] - args["date_from"] < timedelta(days=1).total_seconds():
             return abort(400, "date_from must be a date at least 1 day before date_to. Check your inputs.")
     payload = simulate(user=user, **args)
     return {"simulation": payload}, 200
Esempio n. 5
0
    def put(self):
        user = get_user()

        # set cookie in browser
        token = auth.generate_token(user.email_id)

        @after_this_request
        def set_cookie_value(response):
            response.set_cookie("token", value=token, httponly=True)
            return response

        return 200
Esempio n. 6
0
    def delete(self, ):
        user = get_user()
        args = watchlist_parser.parse_args()
        symbol = args["symbol"].upper()

        # Run this to check if in the database or exists. Will add it if not already there
        get_details(symbol)

        if in_watchlist(symbol, user):
            items_to_remove = [
                item for item in user.watchlist.watchlist_items
                if item.stock_symbol == symbol
            ]
            user.watchlist.watchlist_items.remove(*items_to_remove)
            db.session.commit()
            return {"symbol": symbol}, 201
        else:
            return {"symbol": symbol}, 200
Esempio n. 7
0
    def get(self):
        user = get_user()
        watch = user.watchlist
        port = user.portfolio

        for pp in PortfolioPrice.query.filter_by(portfolio_id=port.id).all():
            PortfolioPrice.query.filter_by(id=pp.id).delete()
        for tr in Transaction.query.filter_by(portfolio_id=port.id).all():
            Transaction.query.filter_by(id=tr.id).delete()

        User.query.filter_by(id=user.id).delete()
        Watchlist.query.filter_by(id=watch.id).delete()
        Portfolio.query.filter_by(id=port.id).delete()

        db.session.commit()
        Token.get(self)

        return 200
Esempio n. 8
0
    def post(self):
        args = watchlist_parser.parse_args()
        symbol = args["symbol"].upper()

        # Run this to check if in the database or exists. Will add it if not already there
        get_details(symbol)

        user = get_user()

        if not in_watchlist(symbol, user):
            watchlist_item = WatchlistItem(
                watchlist_id=user.watchlist.id,
                stock_symbol=symbol,
            )
            user.watchlist.watchlist_items.append(watchlist_item)
            db.session.add(watchlist_item)
            db.session.commit()
            return {"symbol": symbol}, 201
        else:
            return {"symbol": symbol}, 200
Esempio n. 9
0
 def get(self, ):
     user = get_user()
     data = get_transactions(user)
     return data, 200
Esempio n. 10
0
 def get(self):
     user = get_user()
     watchlist_list = get_watchlist(user)
     return watchlist_list, 200
Esempio n. 11
0
 def get(self, ):
     user = get_user()
     info = get_info(user)
     return info, 200
Esempio n. 12
0
 def get(self, ):
     user = get_user()
     data = get_user_details(user)
     return data, 200
Esempio n. 13
0
    def post(self):
        args = trade_parser.parse_args()
        symbol: str = args.get("symbol")
        quote = args.get("quote")
        trade_type = args.get("trade_type")
        quantity = args.get("quantity")
        symbol = symbol.upper()

        user = get_user()  # get user details from token

        variation, slippage = check_price(symbol, quote)
        if variation:
            return abort(
                416,
                "Current price has changed, can't commit this transaction")

        stock = Stock.query.filter_by(symbol=symbol).first()
        fee = 0

        if quantity < 1:
            return abort(
                400,
                f"Quantity should be an integer value greater than 0. Given {quantity}"
            )

        quantity = -quantity if trade_type == "sell" else quantity

        # --- Buy --- #
        if quantity > 0:  # check if user even has enough money to buy this stock quantity
            balance_adjustment = ((quote * quantity) + fee)
            if user.portfolio.balance - balance_adjustment < 0:
                return abort(417, "Insufficient funds")

            if stock not in user.portfolio.stocks:
                user.portfolio.stocks.append(stock)

        # --- Sell --- #
        elif quantity < 0:  # check if user owns this stock first, then the quantity he's
            check_stock = stock_balance(user, symbol)

            if not check_stock:
                return abort(417, "You currently don't own this stock")

            if check_stock[0] + quantity < 0:
                return abort(417, "Insufficient quantity of stock to sell")

            if check_stock[0] + quantity == 0:
                user.portfolio.stocks.remove(stock)

            balance_adjustment = (quote * quantity) + fee
        else:
            return abort(
                422,
                f"Invalid quantity. Quantity must be a non zero integer. Received {quantity}"
            )

        stock.last_quote = quote

        user.portfolio.balance -= balance_adjustment  # update user's balance after trade
        # --- Sell-ends --- #

        new_transaction = Transaction(
            portfolio_id=user.portfolio.id,
            symbol=symbol,
            quote=quote,
            quantity=quantity,
            fee=fee,
        )

        db.session.add(new_transaction)
        db.session.commit()

        return dict(
            symbol=symbol,
            quote=quote,
            quantity=quantity,
            trade_type=trade_type,
        ), 200
Esempio n. 14
0
 def get(self):
     user = get_user()
     args = portfolio_query_parser.parse_args()
     payload = get_portfolio(user, args["averagemode"])
     return payload, 200