예제 #1
0
def sell():
    userInfo = UserInfo()[0]
    if request.method == "GET":
        stock_list = db.execute("SELECT symbol FROM :username", username=userInfo['username'])
        if len(stock_list) < 1:
            return render_template("trade/sell.html")
        else:
            return render_template("trade/sell.html", stock_list=stock_list)
    else:
        stock = request.form.get("symbol")
        number = request.form.get("number")
        number_owned = db.execute("SELECT number FROM :username WHERE symbol=:symbol", username=userInfo['username'], symbol=stock)
        if not number or len(number_owned) == 0 or int(number) < 0:
            return apology("Invalid input")
        elif int(number) > number_owned[0]['number']:
            return apology("You do not own " + number + " stocks")
        number = int(number)
        quote = lookup(stock)
        cash = quote['price'] * number
        remaining = number_owned[0]['number'] - number
        if remaining != 0:
            db.execute("UPDATE :username SET number=:remaining WHERE symbol=:symbol", username=userInfo['username'], remaining=remaining, symbol=stock)
        else:
            db.execute("DELETE FROM :username WHERE symbol=:symbol", username=userInfo['username'], symbol=stock)
        db.execute("UPDATE users SET cash=:total WHERE username=:username", username=userInfo['username'], total=(cash+userInfo['cash']))
        db.execute("INSERT INTO :tablename ('symbol','number', 'price', 'nature') VALUES (:symbol, :number, :price, 's')", tablename=(userInfo['username'] + "History"), symbol=stock, number=number, price=quote['price'])
        return redirect("/")
예제 #2
0
def buy():
    userInfo = UserInfo()[0]
    if request.method == "GET":
        return render_template("trade/buy.html")
    else:
        symbol = request.form.get("symbol").upper()
        number = request.form.get("number")
        if not symbol or not number or int(number)<1:
            return apology("Invalid input")
        number = int(number)
        quote = lookup(symbol)
        if quote != None:
            cost = float(number) * quote["price"]
            cash = db.execute("SELECT cash FROM users WHERE id = :id", id = userInfo["id"])[0]
            if cost > cash['cash']:
                return apology("You do not have enough cash")
            else:
                db.execute("UPDATE users SET cash = :remaining WHERE id = :id", remaining = cash['cash'] - cost, id = userInfo["id"])
                stockExists = db.execute("SELECT number FROM :username WHERE symbol=:symbol", username=userInfo['username'], symbol=symbol)
                if len(stockExists) == 0:
                    db.execute("INSERT INTO :username ('symbol', 'number') VALUES (:symbol, :number)", username=userInfo['username'], symbol = symbol, number = float(number))
                else:
                    db.execute("UPDATE :username SET number = :number WHERE symbol = :symbol", username=userInfo['username'], number = (number + int(stockExists[0]['number'])), symbol = symbol)
                db.execute("INSERT INTO :tablename ('symbol','number', 'price', 'nature') VALUES (:symbol, :number, :price, 'b')", tablename=(userInfo['username'] + "History"), symbol=symbol, number=number, price=quote['price'])
        else:
            return apology(symbol + " is an invalid symbol")
        return redirect("/")
예제 #3
0
파일: home.py 프로젝트: shridpant/stockie
def index():
    userInfo = UserInfo()[0]
    # Get Relevant Information
    stocks = db.execute("SELECT * FROM :username",
                        username=userInfo['username'])
    price = {}
    wealth = userInfo['cash']
    for stock in stocks:
        price[stock["symbol"]] = lookup(stock["symbol"])['price']
        wealth += price[stock["symbol"]] * stock["number"]
    db.execute("UPDATE users SET wealth = :wealth WHERE id = :id",
               wealth=wealth,
               id=session["user_id"])
    cash = "{:.2f}".format(userInfo['cash'])
    wealth = "{:.2f}".format(wealth)
    # GET Request Handling
    if request.method == "GET":
        if not stocks:
            return render_template("index.html",
                                   method="GET",
                                   cash=cash,
                                   wealth=wealth)
        else:
            return render_template("index.html",
                                   method="GET",
                                   stocks=stocks,
                                   price=price,
                                   cash=cash,
                                   wealth=wealth)
    # POST Reuqest Handling
    else:
        symbol = request.form.get("symbol")
        if not symbol:
            return apology("You must provide a symbol")
        quote = lookup(symbol)
        if quote != None:
            if not stocks:
                return render_template("index.html",
                                       method="POST",
                                       cash=cash,
                                       wealth=wealth,
                                       quote=quote)
            else:
                return render_template("index.html",
                                       method="POST",
                                       stocks=stocks,
                                       price=price,
                                       cash=cash,
                                       wealth=wealth,
                                       quote=quote)
        else:
            return apology(symbol + " is an invalid symbol")
예제 #4
0
파일: home.py 프로젝트: shridpant/stockie
def login():
    session.clear()
    # POST Request Handling
    if request.method == "POST":
        if not request.form.get("username"):
            return apology("You must provide username", 403)
        elif not request.form.get("password"):
            return apology("You must provide password", 403)
        accountExists = db.execute(
            "SELECT * FROM users WHERE username = :username",
            username=request.form.get("username"))
        if len(accountExists) != 1 or not check_password_hash(
                accountExists[0]["hash"], request.form.get("password")):
            return apology("Invalid username and/or password", 403)
        session["user_id"] = accountExists[0]["id"]
        return redirect("/")
    # GET Request Handling
    else:
        return render_template("auth/login.html")
예제 #5
0
def landing():
    db = SQL("sqlite:///src/finance.db")
    if request.method == "GET":
        return render_template("auth/register.html")
    elif request.method == "POST":
        username = request.form.get("username")
        password = request.form.get("password")
        confirm = request.form.get("confirm")
        # Ensure username was submitted
        if not username:
            return apology("You must provide a username")
        # Ensure password was submitted
        elif not password:
            return apology("You must provide a password")
        # Ensure the passwords match
        elif password != confirm:
            return apology("Your passwords do not match")
        # Insert the username and hash onto the SQL database
        try:
            tablename = username + "History"
            table_existence = db.execute(
                "SELECT name FROM sqlite_master WHERE type='table' AND name=:tablename;",
                tablename=tablename)
            if not table_existence:
                db.execute(
                    "INSERT INTO users (username, hash) VALUES (:username, :hash)",
                    username=username,
                    hash=generate_password_hash(password))
                db.execute(
                    "CREATE TABLE IF NOT EXISTS :username ('symbol' TEXT NOT NULL PRIMARY KEY, 'number' NUMERIC NOT NULL)",
                    username=username)
                db.execute(
                    "CREATE TABLE IF NOT EXISTS :tablename ('transaction' INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,'symbol' TEXT NOT NULL,'number' NUMERIC NOT NULL, 'price' NUMERIC NOT NULL, 'timestamp' DATETIME DEFAULT CURRENT_TIMESTAMP, 'nature' TEXT DEFAULT 'na')",
                    tablename=tablename)
                return redirect("/")
            else:
                return apology("Username already taken")
        # Check for error
        except Exception as inst:
            return apology(str(inst))
예제 #6
0
def target_profile(target_uname):
    userInfo = UserInfo()[0]
    if target_uname == userInfo['username']:
        return redirect("/profile/")
    match=db.execute("SELECT * FROM users WHERE username=:target_uname", target_uname=target_uname)
    if not match:
        return apology("User not found!", 404)
    dp = "static/dp/" + match[0]['username'] + "." + match[0]['dp']
    if not os.path.exists(dp):
        dp = "../../static/dp/"+"default.png"
    else:
        dp = "../../static/dp/" + match[0]['username'] + "." + match[0]['dp']
    return render_template("profiles/target_profile.html", dp=dp, user=match[0])
예제 #7
0
def landing(stock_symbol=None):
    # GET Request Handling
    if request.method == "GET":
        if stock_symbol != None:
            informationInsights = Information(stock_symbol)
            if informationInsights != None:
                open_df = informationInsights[1]["Open"].tolist()
                close_df = informationInsights[1]["Close"].tolist()
                high_df = informationInsights[1]["High"].tolist()
                low_df = informationInsights[1]["Low"].tolist()
                return render_template("insights/insights.html",
                                       method="POST",
                                       display="company",
                                       info=informationInsights,
                                       open=open_df,
                                       close=close_df,
                                       high=high_df,
                                       low=low_df)
            else:
                return apology("Not found", 404)
        else:
            return render_template("insights/insights.html", method="GET")
    # POST Request Handling
    else:
        search_phrase = request.form.get("phrase")
        stock_symbol = request.form.get("symbol")
        if stock_symbol:
            return redirect("/insights/" + stock_symbol)
        elif search_phrase:
            #TODO Better analysis methods
            try:
                # Connect to Twitter
                twitterAPI = twitter.init(keys)
                yfinanceInsights = PreInfo(search_phrase)
                if yfinanceInsights != None:
                    search_phrase = yfinanceInsights[0]["shortName"]
                tweetInsights = twitter.sentiment(twitterAPI, 7, search_phrase)
                newsInsights = newsapi(search_phrase)
                if len(tweetInsights) == 0 and len(newsInsights) == 0:
                    return render_template("insights/insights.html",
                                           method="POST",
                                           display="nlp",
                                           search_phrase=search_phrase,
                                           company=yfinanceInsights)
                elif len(tweetInsights) == 0:
                    return render_template("insights/insights.html",
                                           method="POST",
                                           display="nlp",
                                           news=newsInsights,
                                           search_phrase=search_phrase,
                                           company=yfinanceInsights)
                elif len(newsInsights) == 0:
                    return render_template("insights/insights.html",
                                           method="POST",
                                           display="nlp",
                                           tweets=tweetInsights,
                                           search_phrase=search_phrase,
                                           company=yfinanceInsights)
                else:
                    return render_template("insights/insights.html",
                                           method="POST",
                                           display="nlp",
                                           tweets=tweetInsights,
                                           news=newsInsights,
                                           company=yfinanceInsights)
            except Exception as inst:
                return apology(str(inst))
        else:
            return apology("Unknown error")
예제 #8
0
def errorhandler(e):
    if not isinstance(e, HTTPException):
        e = InternalServerError()
    return apology(e.name, e.code)