Exemplo n.º 1
0
def nse_stock_history_data(symbol, years):
    try:
        date_today = date(date.today().year,
                          date.today().month,
                          date.today().day)
        date_start = date(date.today().year - years,
                          date.today().month,
                          date.today().day)

        print("Collecting Stock Data", "-" * 80)
        print("date and time: ", datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
        history = get_history(symbol=symbol.upper(),
                              start=date_start,
                              end=date_today)
        print("date and time: ", datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
        print("Stock Data Collected", "-" * 80)

        data = []
        for i in range(len(history.Close.values)):
            stock_price = {
                "date": history.Close.index.values[i].strftime("%m-%d-%Y"),
                "price": history.Close.values[i],
            }
            data.append(stock_price)
        del history

        return Response(mimetype="application/json",
                        response=json.dumps(data),
                        status=200)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)
Exemplo n.º 2
0
def sign_in():
    try:
        '''
        data = {
            "email": "*****@*****.**",
            "password": "******"
        }
        '''
        data = request.json
        if data:
            return user_sign_in(data)
        else:
            return Response(
                mimetype="application/json",
                response=json.dumps({'error': "No Json object recieved"}),
                status=400
            )
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(
            mimetype="application/json",
            response=json.dumps({'error': error_msg}),
            status=400
        ) 
Exemplo n.º 3
0
def get_current_price_of_all_stocks(page):
    try:
        stocks = Stock.query.all()
        data = []
        i = page * 20
        n = 20
        while (n and i < len(stocks)):
            stock = stocks[i]
            symbol = stock.symbol
            price = get_current_stock_price(stock)
            if (price == -1):
                i += 1
                continue
            data.append({
                'symbol': symbol,
                'company': stock.company_name,
                'price': price
            })
            i += 1
            n -= 1
        return Response(mimetype="application/json",
                        response=json.dumps(data),
                        status=200)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)
Exemplo n.º 4
0
def nyse_stock_current_data(symbol):
    try:
        # date_today = "{}-{}-{}".format(date.today().year, date.today().month, date.today().day)
        # date_last_month = "{}-{}-{}".format(date.today().year, date.today().month-1, date.today().day)
        # if(date.today().month==1):
        #     date_last_month = "{}-{}-{}".format(date.today().year-1, 12, date.today().day)
        print("Collecting Current Stock Data", "-" * 80)
        print("date and time: ", datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
        stock = Stock.query.filter_by(symbol=symbol.upper()).first()
        # stock = yf.download(symbol.upper(),date_last_month,date_today)
        stock_price = get_current_stock_price(stock)
        print("date and time: ", datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
        print("Current Stock Data Collected", "-" * 80)
        stock_price = {
            # "date": "{}-{}-{}".format(date.today().day, date.today().month, date.today().year),
            "price": stock_price,
            "company": stock.company_name,
            "symbol": symbol
        }
        return Response(mimetype="application/json",
                        response=json.dumps(stock_price),
                        status=200)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)
Exemplo n.º 5
0
def nse_stock_current_data(symbol):
    try:
        nse = Nse()

        print("Collecting Current Stock Data", "-" * 80)
        print("date and time: ", datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
        stock = nse.get_quote(symbol)
        print("date and time: ", datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
        print("Current Stock Data Collected", "-" * 80)

        stock_price = {
            "date":
            "{}-{}-{}".format(date.today().day,
                              date.today().month,
                              date.today().year),
            "price":
            stock['lastPrice'],
        }
        return Response(mimetype="application/json",
                        response=json.dumps(stock_price),
                        status=200)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)
Exemplo n.º 6
0
def email_verification(token):
    try:
        return user_email_verification(token)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(
            mimetype="application/json",
            response=json.dumps({'error': error_msg}),
            status=400
        ) 
Exemplo n.º 7
0
def user_stock_details():
    try:
        return get_user_stock_detials()
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(
            mimetype="application/json",
            response=json.dumps({'error': error_msg}),
            status=400
        ) 
Exemplo n.º 8
0
def user_sign_up(data):
    try:
        if User.username_exists(data["username"]):
            return Response(mimetype="application/json",
                            response=json.dumps(
                                {'error': "Username already exists"}),
                            status=403)
        if User.email_exists(data["email"]):
            return Response(mimetype="application/json",
                            response=json.dumps(
                                {'error': "email already exists"}),
                            status=403)
        password_hash = User.generate_hash_password(data["password"])
        new_user = User(username=data["username"],
                        name=data["name"],
                        email=data["email"],
                        password=password_hash)
        new_user.save()

        # # Now we'll send the email confirmation link
        # subject = "Confirm your email"

        # token = ts.dumps(self.email, salt='email-confirm-key')

        # confirm_url = url_for(
        #     'confirm_email',
        #     token=token,
        #     _external=True)

        # html = render_template(
        #     'email/activate.html',
        #     confirm_url=confirm_url)

        # # We'll assume that send_email has been defined in myapp/util.py
        # send_email(user.email, subject, html)

        return Response(mimetype="application/json",
                        response=json.dumps(
                            {'success': "User created successfully"}),
                        status=201)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)
Exemplo n.º 9
0
def user_email_verification(token):
    try:
        email = ts.loads(token, salt="email-confirm-key", max_age=86400)
        user = User.query.filter_by(email=email).first()
        if user:
            user.email_verified = True
            db.session.commit()
            return  # ask arvind what all data does he require after verification
        else:
            return Response(mimetype="application/json",
                            response=json.dumps({'error': 'User not found'}),
                            status=404)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)
Exemplo n.º 10
0
def user_sign_in(data):
    try:
        # print("1-"*80)
        user = User.query.filter_by(email=data["email"]).first()
        # print(user)
        # print("5-"*80)
        # print(user.id)
        if not user:
            return Response(mimetype="application/json",
                            response=json.dumps(
                                {'error': 'User Does not exsists'}),
                            status=403)
        password_verified = user.check_hash_password(data["password"])
        # print("2-"*80)

        if password_verified:
            data = {"sucess": "signed in successflly"}
            # user.increment_sign_in_count()
            res = make_response(json.dumps(data))
            token = Auth.generate_token(user.id)
            print(token)
            # res.set_cookie(key="session", value=token, domain=".webboard.in", max_age=None, samesite='Strict', secure=True)
            res.set_cookie(key="token",
                           domain=".tradezi.co.in",
                           value=token,
                           max_age=None,
                           samesite='Strict',
                           secure=True)
            return res, 200, {'Content-Type': 'application/json'}
            # return res
        else:
            return Response(
                mimetype="application/json",
                response=json.dumps({
                    'error':
                    'There was an error with your e-mail/password combination'
                }),
                status=403)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)
Exemplo n.º 11
0
def nyse_stock_history_data(symbol, years):
    try:
        date_today = "{}-{}-{}".format(date.today().year,
                                       date.today().month,
                                       date.today().day)
        date_start = "{}-{}-{}".format(date.today().year - years,
                                       date.today().month,
                                       date.today().day)

        print("Collecting Stock Data", "-" * 80)
        print("date and time: ", datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
        history = yf.download(symbol.upper(), date_start, date_today)
        # data = yf.download(tickers='UBER', period='5d', interval='5m')
        print("date and time: ", datetime.now().strftime("%d/%m/%Y %H:%M:%S"))
        print("Stock Data Collected", "-" * 80)

        data = []
        for i in range(len(history.Close.values)):
            stock_price = {
                "date":
                pd.to_datetime(str(
                    history.Close.index.values[i])).strftime("%m-%d-%Y"),
                "close":
                history.Close.values[i],
                "open":
                history.Open.values[i],
                "high":
                history.High.values[i],
                "low":
                history.Low.values[i]
            }
            data.append(stock_price)
        del history

        return Response(mimetype="application/json",
                        response=json.dumps(data),
                        status=200)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)
Exemplo n.º 12
0
def user_details():
    try:
        if(request.method == 'POST'):
            data = request.json
            if data:
                return update_user_details(data)
            else:
                return Response(
                    mimetype="application/json",
                    response=json.dumps({'error': "No Json object recieved"}),
                    status=400
                )
        return get_user_details()
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(
            mimetype="application/json",
            response=json.dumps({'error': error_msg}),
            status=400
        ) 
Exemplo n.º 13
0
def get_user_stock_detials():
    user_id = g.user['id']
    # user_id = 1
    try:
        trans = Transaction.query.filter_by(user_id=user_id)
        stocks_purchased = {}
        for tran in trans:
            stock = stocks_purchased.get(tran.stock_id, {})
            stock['cost'] = stock.get(
                'cost', 0) + (tran.num_of_stocks * tran.stock_price)
            stock['num'] = stock.get('num', 0) + tran.num_of_stocks
            stocks_purchased[tran.stock_id] = stock
        data = {"stocks": [], "invested": 0, "current": 0, "balance": 0}
        invested = 0
        current = 0
        for stock_id, val in stocks_purchased.items():
            stock = Stock.query.get(stock_id)
            price = get_current_stock_price(stock)
            invested += val['cost']
            current += price * val['num']
            profit = price * val['num'] - val['cost']
            data["stocks"].append({
                'symbol': stock.symbol,
                'company': stock.company_name,
                'price': price,
                'num_purchased': val['num'],
                'profit': profit
            })
        data["invested"] = invested
        data["current"] = current
        data["balance"] = current - invested
        return Response(mimetype="application/json",
                        response=json.dumps(data),
                        status=200)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)
Exemplo n.º 14
0
def get_user_details():
    user_id = g.user['id']
    # user_id = 1
    try:
        user = User.query.get(user_id)
        data = {
            "username": user.username,
            "name": user.name,
            "email": user.email,
            "funds": user.funds,
            "sign_in_count": user.sign_in_count,
            "created_on": user.get_created_on()
        }
        return Response(mimetype="application/json",
                        response=json.dumps(data),
                        status=200)
    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)
Exemplo n.º 15
0
def transaction(stock_symbol, stock_price, num_of_stocks, buy):
    # user_id = 1
    user_id = g.user['id']
    try:
        user = User.query.get(user_id)
        stock = Stock.stock_via_symbol(stock_symbol.upper())
        stock_id = stock.id
        if (buy):
            if ((num_of_stocks * stock_price) > user.funds):
                return Response(mimetype="application/json",
                                response=json.dumps({
                                    'error':
                                    "Not enough funds to buy stocks"
                                }),
                                status=403)
            funds = user.funds - (num_of_stocks * stock_price)
            user.funds = funds
            user.commit()
            new_transaction = Transaction(user_id=user_id,
                                          stock_id=stock_id,
                                          stock_price=stock_price,
                                          num_of_stocks=num_of_stocks)
            new_transaction.save()
        else:
            trans = Transaction.get_user_stock_trans(user_id, stock_id)
            num_stocks_holded = 0
            for tran in trans:
                # print(tran)
                num_stocks_holded += tran.num_of_stocks
            if (num_of_stocks > num_stocks_holded):
                return Response(mimetype="application/json",
                                response=json.dumps(
                                    {'error': "Not enough stocks to sell"}),
                                status=403)
            funds = user.funds + (num_of_stocks * stock_price)
            user.funds = funds
            user.commit()
            # print("%"*80)
            # print(num_of_stocks)
            for tran in trans:
                # print("%"*80)
                # print(tran.id)
                if (tran.num_of_stocks <= num_of_stocks):
                    num_of_stocks -= tran.num_of_stocks
                    db.session.delete(tran)
                    db.session.commit()
                else:
                    num = tran.num_of_stocks - num_of_stocks
                    # print("^^"*80)
                    # print(tran.num_of_stocks)
                    # print(num_of_stocks)
                    # print(num)
                    tran.num_of_stocks = num
                    tran.commit()
        return Response(mimetype="application/json",
                        response=json.dumps(
                            {'success': "Transaction successfully"}),
                        status=201)

    except Exception as e:
        error_msg = get_error_msg(e)
        logger.error(error_msg)
        return Response(mimetype="application/json",
                        response=json.dumps({'error': error_msg}),
                        status=400)