Exemplo n.º 1
0
 def fetch_returns():
     if request.method == 'GET':
         portfolio_list = Portfolio.fetch_all()
         sum = 0
         for portfolio in portfolio_list:
             sum = sum + ((100-portfolio.avg_buy_price)*portfolio.shares)
         response = jsonify({'Cumulative Returns': sum})
         response.status_code = 200
         return response
Exemplo n.º 2
0
def create():
    form = CreatePortfolioForm()
    if form.validate_on_submit():
        portf = Portfolio(user=current_user, name=form.name.data)
        db.session.add(portf)
        db.session.commit()
        flash("Successfully created new portfolio!", "success")
        return redirect(url_for("portfolio.get", id=portf.id))
    return render_template("form.html",
                           form=QuickForm(form),
                           title="New Portfolio")
Exemplo n.º 3
0
    def sellStock(self, symbol, subreddit, permalink):

        # Same as above, but with Sell
        price = self.getStockPrice(symbol)
        if not price:
            return False
        if not self.isfloat(price):
            price = float(price.replace(",", ""))
        with app.app_context():
            Trades.Sell(symbol, price, permalink)
            Portfolio.Sell(symbol, "wallstreetbets")
        print("Sold " + symbol + " for " + str(price))
Exemplo n.º 4
0
def create_portfolio():
    form = PortfolioForm()
    if form.validate_on_submit():

        new_portfolio = Portfolio(
            name=form.name.data,
            p_type=form.portfolio_type.data,
            owner_id=current_user.id,

            # Filters - include stock markets
            include_nyse=form.include_nyse.data,
            include_nasdaq=form.include_nasdaq.data,
            include_nyse_arca=form.include_nyse_arca.data,
            include_nyse_american=form.include_nyse_american.data,

            # Filters - exclude sectors
            exclude_communications=form.exclude_communications.data,
            exclude_energy_minerals=form.exclude_energy_minerals.data,
            exclude_non_energy_minerals=form.exclude_non_energy_minerals.data,
            exclude_health_technology=form.exclude_health_technology.data,
            exclude_health_services=form.exclude_health_services.data,
            exclude_utilities=form.exclude_utilities.data,
            exclude_distribution_services=form.exclude_distribution_services.
            data,
            exclude_finance=form.exclude_finance.data,
            exclude_process_industries=form.exclude_process_industries.data,
            exclude_producer_manufacturing=form.exclude_producer_manufacturing.
            data,
            exclude_commercial_services=form.exclude_commercial_services.data,
            exclude_industrial_services=form.exclude_industrial_services.data,
            exclude_transportation=form.exclude_transportation.data,
            exclude_consumer_durables=form.exclude_consumer_durables.data,
            exclude_consumer_non_durables=form.exclude_consumer_non_durables.
            data,
            exclude_retail_trade=form.exclude_retail_trade.data,
            exclude_electronic_technology=form.exclude_electronic_technology.
            data,
            exclude_technology_services=form.exclude_technology_services.data,

            # ESG category (from our AI)
            # Will be lowest possible risk category (1 - low, 2 - medium, 3- high, 4 - all - include extreme risk)
            esg_risk_category=form.esg_risk_category.data

            # Oher stuff..
        )
        db.session.add(new_portfolio)
        db.session.commit()
        flash('Congratulations, you have created a portfolio')
        return redirect(url_for('dashboard'))
    return render_template('portfolio_build.html',
                           title='Portfolio Wizard',
                           form=form)
Exemplo n.º 5
0
 def return_portfolio():
     if request.method == 'GET':
         portfolio_list = Portfolio.fetch_all()
         results = []
         for portfolio in portfolio_list:
             obj = {
                 'ticker_symbol': portfolio.ticker_symbol,
                 'avg_buy_price': portfolio.avg_buy_price,
                 'shares': portfolio.shares
             }
             results.append(obj)
         response = jsonify(results)
         response.status_code = 200
         return response
Exemplo n.º 6
0
def portfolio():
    portfolioForm = PortfolioForm()
    portfolios = Portfolio.query.all()
    if request.method == 'POST':
        admin_portfolio = Portfolio(
            p_title=portfolioForm.p_title.data,
            p_icon=portfolioForm.p_icon.data,
            data_modal=portfolioForm.data_modal.data,
            portfoliocategory_name=portfolioForm.portfoliocategory_name.data,
            portfolioimages_name=portfolioForm.portfolioimages_name.data)
        db.session.add(admin_portfolio)
        db.session.commit()
        return redirect('/admin/portfolio/')
    return render_template('admin/portfolio.html',
                           form=portfolioForm,
                           portfolios=portfolios)
Exemplo n.º 7
0
    def buyStock(self, symbol, subreddit, permalink):

        # Get the price value from Google
        price = self.getStockPrice(symbol)

        # If the symbol isn't a real stock, just skip it
        if not price:
            return False

        # Turn a sting with comma into a real float
        if not self.isfloat(price):
            price = float(price.replace(",", ""))

        # call the Buy method for the trade history and portfolio models.
        with app.app_context():
            Trades.Buy(symbol, price, permalink)
            Portfolio.Buy(symbol, "wallstreetbets")
        print("Bought " + symbol + " for " + str(price))
Exemplo n.º 8
0
def debug_portfolios():
    try:
        data = helpers.ws_get_positions()
        portfolios = {}
        for key, entry in data.items():
            # POSITION HANDLING ---------------------------------------
            if entry["account_id"] not in portfolios.keys():
                port = Portfolio(entry["account_id"])
                portfolios.update({entry["account_id"]: port})
            else:
                port = portfolios[entry["account_id"]]
            port.positions.append(Stock(entry))
        portfolio_dicts = [p.to_dict() for k, p in portfolios.items()]
        response = jsonify(portfolio_dicts)
        response.headers.add('Access-Control-Allow-Origin', '*')
        return response
    except Exception as e:
        return Markup(str(e))
Exemplo n.º 9
0
def create_portfolio():
    if current_user.port:
        flash('You already have portfolio, delete it first', 'danger')
        return redirect(url_for('main.home'))
    form = PortfolioForm()
    if form.validate_on_submit():
        port = Portfolio(title=form.title.data,
                         author=current_user.username,
                         content=form.content.data,
                         about=form.about.data,
                         avg=form.avg.data,
                         school=form.school.data,
                         background_color=form.background_color.data,
                         font_color=form.font_color.data,
                         creator=current_user)
        db.session.add(port)
        db.session.commit()
        flash('Success', 'success')
        return redirect(url_for('port.portfolio'))
    return render_template('create_portfolio.html', form=form)
Exemplo n.º 10
0
 def sellAllLowQuantity(self):
     with app.app_context():
         Portfolio.sellAllLowQuantity()
Exemplo n.º 11
0
 def mapUser(self, userId):
     portfolio = Portfolio(userId=userId)
     portfolio.save()
Exemplo n.º 12
0
    def trading():
        if request.method == 'GET':
            if request.args.get('ticker') != None:
                tradelist = Trades.fetch_all()
                results = []

                for trade in tradelist:
                    if(trade.ticker_symbol == request.args.get('ticker')):
                        obj = {
                            'id': trade.id,
                            'ticker_symbol': trade.ticker_symbol,
                            'price': trade.price,
                            'shares': trade.shares,
                            'type': trade.type
                        }
                        results.append(obj)
                response = jsonify(results)
                response.status_code = 200
                return response
            else:
                tradelist = Trades.fetch_all()
                results = []

                for trade in tradelist:
                    obj = {
                        'id': trade.id,
                        'ticker_symbol': trade.ticker_symbol,
                        'price': trade.price,
                        'shares': trade.shares,
                        'type': trade.type
                    }
                    results.append(obj)
                response = jsonify(results)
                response.status_code = 200
                return response
        elif request.method == 'PUT':
            id = str(request.data.get('id', ''))
            if not id:
                response = jsonify({'ERROR': 'ID field is required'})
                response.status_code = 400
                return response
            tradelist = Trades.query.filter_by(id=id).first()
            flag=0
            if not tradelist:
                flag=1

            if request.data.get('price') <= 0: 
                response = jsonify({'ERROR': 'Zero or Negative price not valid'})
                response.status_code = 400
                return response
            if request.data.get('shares') <=0:
                response = jsonify({'ERROR': 'Zero or Negative shares not valid'})
                response.status_code = 400
                return response
            if request.data.get('type') == 'SELL':
                check_portfolio = Portfolio.query.filter_by(
                    ticker_symbol=request.data.get('ticker_symbol')).first()
                if not check_portfolio or (check_portfolio.shares < request.data.get('shares')):
                    response = jsonify(
                        {'ERROR': 'Cannot sell when low/no shares available'})
                    response.status_code = 400
                    return response
            prev_shares = tradelist.shares
            if flag==1:
                tradelist=Trades(id,str(request.data.get('ticker_symbol')),request.data.get('price'), request.data.get('shares')
                ,str(request.data.get('type')))
            else :
                tradelist.id = id
                tradelist.ticker_symbol = str(request.data.get('ticker_symbol'))
                tradelist.price = request.data.get('price')
                tradelist.shares = request.data.get('shares')
                tradelist.type = str(request.data.get('type'))

            if Portfolio.query.filter_by(ticker_symbol=request.data.get('ticker_symbol', '')).first():
                if tradelist.type == 'BUY':
                    current_portfolio = Portfolio.query.filter_by(
                        ticker_symbol=request.data.get('ticker_symbol', '')).first()
                    total = current_portfolio.shares * current_portfolio.avg_buy_price
                    total = total + (tradelist.price * tradelist.shares)
                    total = total / (tradelist.shares +
                                     current_portfolio.shares)
                    current_portfolio.avg_buy_price = total
                    current_portfolio.shares = tradelist.shares-prev_shares + current_portfolio.shares
                    
                else:
                    current_portfolio = Portfolio.query.filter_by(
                        ticker_symbol=request.data.get('ticker_symbol', '')).first()
                    current_portfolio.shares = current_portfolio.shares - tradelist.shares + prev_shares

                current_portfolio.add_trade()
            else:
                portfolio = Portfolio(
                    tradelist.ticker_symbol, tradelist.price, tradelist.shares)
                portfolio.add_trade()

            tradelist.add_trade()
            if flag==1:
                response = jsonify({
                    'NOTE' : 'The Id provided does not exist so creating a new record as below',
                    'id': tradelist.id,
                    'ticker_symbol': tradelist.ticker_symbol,
                    'price': tradelist.price,
                    'shares': tradelist.shares,
                    'type': tradelist.type
                })
            else :
                response = jsonify({
                    'id': tradelist.id,
                    'ticker_symbol': tradelist.ticker_symbol,
                    'price': tradelist.price,
                    'shares': tradelist.shares,
                    'type': tradelist.type
                })
            response.status_code = 202
            return response
        elif request.method == 'POST':
            if request.data.get('id'):
                if Trades.query.filter_by(id=request.data.get('id', '')).first() and Trades.query.filter_by(ticker_symbol=request.data.get('ticker_symbol')).first():
                    response = jsonify({'ERROR': 'Record already exists'})
                    response.status_code = 200
                    return response
            if request.data.get('price') <= 0: 
                response = jsonify({'ERROR': 'Zero or Negative price not valid'})
                response.status_code = 400
                return response
            if request.data.get('shares') <=0:
                response = jsonify({'ERROR': 'Zero or Negative shares not valid'})
                response.status_code = 400
                return response
            if request.data.get('type') == 'SELL':
                check_portfolio = Portfolio.query.filter_by(
                    ticker_symbol=request.data.get('ticker_symbol')).first()
                if not check_portfolio or (check_portfolio.shares < request.data.get('shares')):
                    response = jsonify(
                        {'ERROR': 'Cannot sell when low/no shares available'})
                    response.status_code = 400
                    return response
            if request.data.get('id'):
                tradelist = Trades(request.data.get('id'), str(request.data.get('ticker_symbol')), request.data.get(
                    'price'), request.data.get('shares'), str(request.data.get('type')))
            else:
                tradelist = Trades(-1,str(request.data.get('ticker_symbol')), request.data.get(
                    'price'), request.data.get('shares'), str(request.data.get('type')))

            if Portfolio.query.filter_by(ticker_symbol=request.data.get('ticker_symbol')).first():
                if tradelist.type == 'BUY':
                    current_portfolio = Portfolio.query.filter_by(
                        ticker_symbol=request.data.get('ticker_symbol', '')).first()
                    total = current_portfolio.shares * current_portfolio.avg_buy_price
                    total = total + (tradelist.price * tradelist.shares)
                    total = total / (tradelist.shares +
                                     current_portfolio.shares)
                    current_portfolio.avg_buy_price = total
                    current_portfolio.shares = tradelist.shares + current_portfolio.shares
                else:
                    current_portfolio = Portfolio.query.filter_by(
                        ticker_symbol=request.data.get('ticker_symbol', '')).first()
                    current_portfolio.shares = current_portfolio.shares - tradelist.shares
                current_portfolio.add_trade()
            else:
                portfolio = Portfolio(
                    tradelist.ticker_symbol, tradelist.price, tradelist.shares)
                portfolio.add_trade()
            tradelist.add_trade()
            response = jsonify({
                'id': tradelist.id,
                'ticker_symbol': tradelist.ticker_symbol,
                'price': tradelist.price,
                'shares': tradelist.shares,
                'type': tradelist.type
            })
            response.status_code = 201

            return response
        else:
            response = jsonify({'ERROR': 'Illegal Operation'})
            response.status_code = 400
            return response