TelegramAktienBot/api/app/blueprints/portfolio.py

56 lines
2.1 KiB
Python

__author__ = "Florian Kaiser"
__copyright__ = "Copyright 2022, Project Aktienbot"
__credits__ = ["Florian Kaiser", "Florian Kellermann", "Linus Eickhof", "Kevin Pauer"]
__license__ = "GPL 3.0"
__version__ = "1.0.1"
import os
from apiflask import APIBlueprint
from app.auth import auth
from app.db import database as db
from app.helper_functions import make_response, get_email_or_abort_401
from app.models import SharePrice
from app.schema import PortfolioResponseSchema
portfolio_blueprint = APIBlueprint('portfolio', __name__, url_prefix='/api')
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
@portfolio_blueprint.route('/portfolio', methods=['GET'])
@portfolio_blueprint.output(PortfolioResponseSchema(many=True), 200)
@portfolio_blueprint.auth_required(auth)
@portfolio_blueprint.doc(summary="Returns portfolio", description="Returns all shares of current user")
def get_portfolio():
email = get_email_or_abort_401()
return_portfolio = []
# Get all transactions of current user
transactions = db.session.execute("SELECT isin, comment, SUM(count), SUM(price), MAX(time) FROM `transactions` WHERE email = '" + email + "' GROUP BY isin, comment;").all()
# If there are no transactions, return empty portfolio
# Otherwise calculate portfolio
if transactions is not None:
for row in transactions:
if row[2] == 0:
continue
else:
data = {
"isin": row[0],
"comment": row[1],
"count": row[2],
# "calculated_price": row[3],
"last_transaction": row[4],
'current_price': 0
}
# Add current share value to portfolio
query_share_price = db.session.query(SharePrice).filter_by(isin=row[0]).order_by(SharePrice.date.desc()).first()
if query_share_price is not None:
data['current_price'] = query_share_price.as_dict()['price']
return_portfolio.append(data)
return make_response(return_portfolio, 200, "Successfully loaded symbols")