Exemplo n.º 1
0
def main():
    form = InputForm()
    amr = request.args.get('amr')
    model = request.args.get('model')
    sent = None
    if form.validate_on_submit():
        sent = amrtotext.run(form.input_amr.data, form.input_amr.model)

    elif amr is not None:
        sent = amrtotext.run(amr, model)
        if sent is not None:
            app.logger.info('Input: ' + amr)
            link = "http://bollin.inf.ed.ac.uk:9020/amrtotext?model=" + model + "&amr=" + "+".join(
                [t for t in amr.split()])
            return jsonify(
                {
                    'sent': sent.replace("\n", "<br/>").replace(" ", "&nbsp;"),
                    'link': link
                },
                sort_keys=True,
                indent=4,
                separators=(',', ': '))
        else:
            return jsonify({
                'sent': 'ERROR',
                'link': ''
            },
                           sort_keys=True,
                           indent=4,
                           separators=(',', ': '))
Exemplo n.º 2
0
def input():
    form = InputForm()
    if form.validate_on_submit():
        character_name = {form.character_name.data}
        return redirect(url_for('output', character_name=character_name))

    return render_template('input.html', title='Enter Data', form=form)
Exemplo n.º 3
0
def index():
    form = InputForm()
    if form.validate_on_submit():
        session['session_id'] = unicode(uuid4())
        session['state'] = form.state.data
        session['age'] = form.age.data
        session['zipcode'] = form.zipcode.data
        session['health'] = form.health.data
        session['income'] = form.income.data
        session['hhsize'] = form.hhsize.data
        if session['income'] and session['hhsize']:
            caps = CalcAcaSubsidy(session['income'], session['hhsize'])
            if caps:
                session['premium_cap'] = int(caps[1])
            else:
                session['premium_cap'] = 0
        else:
            session['premium_cap'] = 0
        session['query_weights'] = get_weights(session['state'], str(session['health']))
        log_query(
            session_id = session['session_id'],
            state = session['state'],
            age = session['age'],
            zipcode = session['zipcode'],
            health = session['health']
        )
        return redirect(url_for('main.results'))
    return render_template('index.html', form=form)
Exemplo n.º 4
0
def submit():
    global resp
    form = InputForm()
    if form.validate_on_submit():
        resp = get_atis(form.icao)
        return redirect('/success', )
    return render_template('submit.html', form=form)
def input_item():
    form = InputForm()
    if form.validate_on_submit():
        filename = 'default.jpg'
        f = form.Item_icon.data
        if f:
            filename = secure_filename(f.filename)
            f.save(os.path.join('static\icons', filename))

        item = Item(Category=form.Category.data,
                    Item_Title=form.Item_Title.data,
                    Item_Description=form.Item_Description.data,
                    Item_Price=form.Item_Price.data,
                    image_file=url_for('static', filename='icons/' + filename))
        print(url_for('static', filename='icons/' + filename))
        print(item.image_file)
        db.session.add(item)
        db.session.commit()
        flash(
            f'you have added your last item with product id {item.id} successfully',
            'success')
        return redirect(url_for('home'))
    Errors = []
    fields = []
    if form.errors:
        fields = form.errors.keys()
        Errors = form.errors.values()
    return render_template('input_item.html', form=form, errors=Errors)
Exemplo n.º 6
0
def show_board():
    new_board = print_board()
    form=InputForm()
    if form.validate_on_submit():
        flash("you are validated")
    else:
        flash("ehhh...ehh!, form didn't go")
    return render_template("board.html", form=form, board_1=new_board[0], board_2=new_board[1], board_3=new_board[2])
Exemplo n.º 7
0
def index():
    """Страница "Главная" """
    form = InputForm()
    if form.validate_on_submit():
        message = form.message.data
        answer = request.form['req']
        return sent(message, answer)
    return render_template("main.html", title='Главная', form=form, warning='')
Exemplo n.º 8
0
def input():
    form = InputForm()
    if form.validate_on_submit():
      # generate_xls(form.name_of_app.data)
        generate_schema(form.destinations.data, form.tabs.data)
        
    return render_template('input.html',
        form = form)
Exemplo n.º 9
0
def hello():
    form = InputForm()
    if form.validate_on_submit():
        message = request.form["message"]
        name = request.form["name"]
        note = Note(message=message, name=name)
        note.add()
        #return redirect(url_for("success", message=message, name=name, lookupId = note.lookupId))
        return render_template("success.html", message=message, name=name, lookupId = note.lookupId)
    return render_template("index.html", form=form)
Exemplo n.º 10
0
def input():
    form = InputForm()
    if form.validate_on_submit():
        response = requests.get(form.github_url.data)
        print(form.github_url.data)
        if response.status_code == 200:
            global soup
            soup = BeautifulSoup(response.text, 'html.parser')
            output_dict = total_issues()
            return render_template('output.html', output_dict=output_dict)
    return render_template('input.html', title='Input', form=form)
Exemplo n.º 11
0
def home():
    form = InputForm()
    if form.validate_on_submit():
        prediction = simulator.run_simulation([
            form.num_col.data, form.num_brit.data, form.general.data,
            form.offensive.data, form.allies.data
        ])
        print(prediction)
        flash(f'It looks like the {prediction} win this one!', 'info')
        # return redirect(url_for('home'))

    return render_template('index.html', form=form)
Exemplo n.º 12
0
def home():
    form = InputForm()
    prediction_message = Prediction_Message()
    if form.validate_on_submit():
        prediction_message.initial, prediction_message.pred1, prediction_message.pred2, prediction_message.pred3 = \
             predict(model, form.tweet.data, glove.get_glove_emb(), sequence_length=62, use_gpu=False)
        # if form.tweet.data == 'helloworld':
        #     flash('Entered correct input!', 'success')
        #     return redirect(url_for('home'))
        # else:
        #     flash('Invalid Tweet!', 'danger')
    return render_template('home.html', title='DeepFeels', form = form, prediction_message = prediction_message)
Exemplo n.º 13
0
def char_gen_form():
    form = InputForm()

    if form.validate_on_submit():
        random.seed(form.name_input.data)
        char_num = "%0.16d" % random.randint(0, 9999999999999999)
        char_dict = char_gen.main(form.name_input.data, char_num)

        return render_template("char-gen-result.html", form=form,
                               char_dict=char_dict)

    return render_template("char-gen-form.html", form=form)
Exemplo n.º 14
0
def hello():
    form = InputForm()
    if form.validate_on_submit():
        principle = int(request.form['principle'])
        interestRateYear = float(request.form['interestRateYear'])
        periodYears = int(request.form['periodYears'])
        flash('Thanks for the information!')
        # return periodYears and principle and interestRateYear
        # return test(principle, interestRateYear, periodYears)
        return ammortization(principle, interestRateYear, periodYears)
        # return redirect(url_for('schedule'))
    return render_template('home.html', title='Input', form=form)
Exemplo n.º 15
0
def show_board():
    new_board = print_board()
    form = InputForm()
    print "test"
    if form.validate_on_submit():
        flash("you are validated")
        print 'valid test'
    else:
        flash("ehhh...ehh!, form didn't go")
        print 'invalid test'
    return render_template("test.html", form=form, board_1=new_board[0], \
                                                    board_2=new_board[1], \
                                                    board_3=new_board[2])
Exemplo n.º 16
0
def main():
    form = InputForm(request.form)
    if form.validate_on_submit():
        contributors = [(form.name_1.data, form.val_1.data),
                        (form.name_2.data, form.val_2.data),
                        (form.name_3.data, form.val_3.data),
                        (form.name_4.data, form.val_4.data)]
        carrot_image = generate_image(contributors)
        return render_template('carrot.html',
                               form=form,
                               img_src=convert_pil_image(carrot_image))
    print(form.errors)
    return render_template('carrot.html', form=form, img_src=None)
Exemplo n.º 17
0
def show_board():
    new_board = print_board()
    form=InputForm()
    print "test"
    if form.validate_on_submit():
        flash("you are validated")
        print 'valid test'
    else:
        flash("ehhh...ehh!, form didn't go")
        print 'invalid test'
    return render_template("test.html", form=form, board_1=new_board[0], \
                                                    board_2=new_board[1], \
                                                    board_3=new_board[2])
Exemplo n.º 18
0
async def input():
    form = InputForm()
    if form.validate_on_submit():
        r_form = await request.form
        model_type = r_form['model_type']
        inp_text = r_form['input_text']
        div_factor = r_form['div_factor']
        return redirect(
            url_for('result',
                    model_type=model_type,
                    inp_text=inp_text,
                    div_factor=float(div_factor)))
    return await render_template('homepage.html', form=form)
Exemplo n.º 19
0
def index():
    cookie_secret = init_secret()
    cookie = Cookie()
    form = InputForm()
    pic = str(random.randint(1, 5)) + ".png"
    if form.validate_on_submit():
        data = form.name.data
        datas = {'name': data, 'pic': pic}
        flash('Guk guk, namaku {}!!!'.format(datas['name']))
        cookie_ = cookie.set_cookie(data, cookie_secret)
        response = redirect(url_for('index'))
        response.set_cookie('data', cookie_)
        return response
    data = cookie.get_cookie(cookie_secret)
    return render_template('index.html', form=form, pic=pic)
Exemplo n.º 20
0
def index(params = None):
	form = InputForm()
	user = g.user
	if form.validate_on_submit():
		return redirect(url_for('results'))
		# if form.queryType.data == "vin_query":
		# 	return redirect(url_for('results'))
		if form.queryType.data == "pop_query":
			form = PopForm()
			# return redirect(url_for('results'))
		# 	return render_template("index.html",
		# 		form = pop_form,
		# 		user = user)
	return render_template("index.html",
		form = form,
		user = user)
Exemplo n.º 21
0
def index():
	form = InputForm(request.form)
	# tags = []
	tags = set()
	empty = 1
	if form.validate_on_submit():
		for description in form.desList:
			fData = description.data['des']
			if fData and fData != 'None' and fData not in tags:
					empty = 0
					# tags.append(fData)
					tags.add(fData)
		if not empty:
			title, TagDic, score = ComputeMatch(tags)
			return render_template('index.html', results=[title, TagDic, score], form=form)
	return render_template('index.html', form=form)
Exemplo n.º 22
0
def main():
    form = InputForm()
    sent = request.args.get('sent')
    lang = request.args.get('lang')
    graph = None
    if form.validate_on_submit():
        if hasattr(form.input_sent, 'lang'):
            graph = parse_sent.run(form.input_sent.data, form.input_sent.lang)
        else:
            #compatability with older site
            graph = parse_sent.run(form.input_sent.data)

    elif sent is not None:
        if lang is None:
            lang = 'en'
        graph = parse_sent.run(sent, lang)
        if graph is not None:
            app.logger.info('Input: ' + sent)
            hash.update(str(time.time()))
            hash.update(sent)
            last = hash.hexdigest()
            AMRICA.disagree.run("# ::id 1\n" + graph, "tmp" + last + ".png")
            binpng = open("tmp" + last + ".png", "rb").read()
            os.remove("tmp" + last + ".png")
            link = "http://bollin.inf.ed.ac.uk:9010/amreager?lang=" + lang + "&sent=" + "+".join(
                [t for t in sent.split()])
            return jsonify(
                {
                    'graph': graph.replace("\n", "<br/>").replace(
                        " ", "&nbsp;"),
                    'png': base64.b64encode(binpng),
                    'link': link
                },
                sort_keys=True,
                indent=4,
                separators=(',', ': '))
        else:
            return jsonify({
                'graph': 'ERROR',
                'png': '',
                'link': ''
            },
                           sort_keys=True,
                           indent=4,
                           separators=(',', ': '))

    return render_template('sentence.html', form=form)
Exemplo n.º 23
0
def main2():
    form = InputForm()
    sent = request.args.get('sent')
    lang = request.args.get('lang')
    graph = None
    if form.validate_on_submit():
        if hasattr(form.input_sent, 'lang'):
            graph = parse_sent.run(form.input_sent.data, form.input_sent.lang)
        else:
            #compatability with older site
            graph = parse_sent.run(form.input_sent.data)

    elif sent is not None:
        if lang is None:
            lang = 'en'
        graph = parse_sent.run(sent, lang)
        if graph is not None:
            app.logger.info('Input: ' + sent)
            hash.update(str(time.time()))
            hash.update(sent)
            last = hash.hexdigest()
            AMRICA.disagree.run("# ::id 1\n" + graph, "tmp" + last + ".png")
            binpng = open("tmp" + last + ".png", "rb").read()
            os.remove("tmp" + last + ".png")
            link = "<span id ='link' style='height:150;width:162;background-color:pink'> http://bollin.inf.ed.ac.uk:9010?lang" + lang + "&sent=" + "+".join(
                [t for t in sent.split()]) + "</span>"
            return render_template(
                'sentence.html',
                form=form,
                graph=graph.replace("\n", "<br/>").replace(" ", "&nbsp;"),
                png="<img src=\"data:image/png;base64," +
                base64.b64encode(binpng) + "\">",
                link="<b>Link:</b> " + link +
                " <button onClick=\"ClipBoard();\">Copy to Clipboard</button>")
        else:
            return jsonify({
                'graph': 'ERROR',
                'png': '',
                'link': ''
            },
                           sort_keys=True,
                           indent=4,
                           separators=(',', ': '))
    return render_template('sentence.html', form=form)
Exemplo n.º 24
0
def home():
    form = InputForm()
    if form.validate_on_submit():
        oneUnitProbPerRoll, expectedUnitsPerRoll, oneUnitProbTotalGold, expectedUnitsTotalGold = calculate(
            form.level.data, form.unitCost.data, form.unitsSameCostGone.data,
            form.unitsGone.data, form.gold.data)
        flash(
            f'One Unit Probability Per Roll:  {"{:.2%}".format(oneUnitProbPerRoll)}'
        )
        flash(
            f'Expected Units Per Roll: {"{:.03f}".format(expectedUnitsPerRoll)}'
        )
        flash(
            f'One Unit Probability - Total Gold: {"{:.2%}".format(oneUnitProbTotalGold)}'
        )
        flash(
            f'Expected Units - Total Gold: {"{:.03f}".format(expectedUnitsTotalGold)}'
        )
        #return render_template('home.html', form=form)
    return render_template('home.html', form=form)
Exemplo n.º 25
0
def home():
    form = InputForm()
    if form.validate_on_submit():
        roll = form.rollno.data
        points = form.points.data
        if roll in roll_list:
            s = np.random.weibull(0.5, points)
            df = pd.DataFrame({'Values': s})
            df.index.name = 'Index'
            csv = df.to_csv()
            timestr = time.strftime("%m-%d@%H.%M.%S")
            filename = f'data_{roll}_{timestr}'
            return Response(csv,
                            mimetype="text/csv",
                            headers={
                                "Content-disposition":
                                "attachment; filename=%s.csv" % filename
                            })
        else:
            return redirect(url_for('home'))
    return render_template('home.html', title='EE765', form=form)
Exemplo n.º 26
0
def bkapp_page():
    form = InputForm()
    if form.validate_on_submit():
        roll = form.rollno.data
        points = form.points.data
        if roll in roll_list:
            s = np.random.weibull(0.5, points)
            df = pd.DataFrame({'Values': s})
            df.index.name = 'Index'
            csv = df.to_csv()
            return Response(csv,
                            mimetype="text/csv",
                            headers={
                                "Content-disposition":
                                "attachment; filename=dwnld_csv.csv"
                            })
        else:
            return redirect(url_for('bkapp_page'))
    script = server_document('http://localhost:5006/bkapp')
    return render_template("home.html",
                           title='EE765',
                           form=form,
                           script=script)
Exemplo n.º 27
0
def start():
    mlr_form = InputForm()
    automl_form = LongForm()

    #display predictions from automl model
    if automl_form.validate_on_submit():
        prediction = automl_model.predict([
            automl_form.volume.data, automl_form.rsi.data,
            automl_form.sma.data, automl_form.macd.data, automl_form.rmb.data,
            automl_form.rlb.data, automl_form.rub.data
        ])
        print(prediction)
        flash(str(prediction))

    #display mlr model summary
    elif mlr_form.validate_on_submit():
        info = utils.get_model_summary(
            utils.get_clean_input_data(str(mlr_form.stock.data)))
        summary = info[0]
        results = info[1]
        R2 = results.rsquared
        SSR = results.ssr
        p = results.pvalues
        nobs = results.nobs
        flash(Markup("<h6>Model Summary: </h6>"))
        flash(Markup("<p><b>Number of observations:</b> " + str(nobs) +
                     "</p>"))
        flash(Markup("<p><b>R^2 value:</b> " + str(R2) + "</p>"))
        flash(
            Markup("<p><b>Sum of the squared residuals:</b> " + str(SSR) +
                   "</p>"))
        flash(Markup("<h6>Statistics for each independent variable: </h6>"))
        flash(Markup(str(summary.tables[1].as_html())))

    return render_template('home.html',
                           mlr_form=mlr_form,
                           automl_form=automl_form)
Exemplo n.º 28
0
def team():
    form = InputForm()
    global catcher
    catcher = 'empty'
    global firstb
    firstb = 'empty'
    global secondb
    secondb = 'empty'
    global thirdb
    thirdb = 'empty'
    global ss
    ss = 'empty'
    global outfieldone
    outfieldone = 'empty'
    global outfieldtwo
    outfieldtwo = 'empty'
    global outfieldthree
    outfieldthree = 'empty'
    global utilone
    utilone = 'empty'
    global utiltwo
    utiltwo = 'empty'
    global benchone
    benchone = 'empty'
    global benchtwo
    benchtwo = 'empty'
    global benchthree
    benchthree = 'empty'

    listofcatchers = []
    listoffbasemen = []
    listofsbasemen = []
    listofss = []
    listoftbasemen = []
    listofoutfielders = []
    if form.validate_on_submit():
        stringofcatchers = form.catchernames.data
        numberofcatchers = stringofcatchers.count(',')+1
        listofcatchers = stringofcatchers.split(', ')
        try:
            catchersratingslist = getratingslist(listofcatchers, numberofcatchers)
        except:
            return redirect('/inputerror')
        catchersmaxindex = returnbestone(catchersratingslist, numberofcatchers)
        catcher = listofcatchers[catchersmaxindex]
        
        stringoffbasemen = form.firstbnames.data
        numberoffbasemen = stringoffbasemen.count(',')+1
        listoffbasemen = stringoffbasemen.split(', ')
        try:
            fbasemenratingslist = getratingslist(listoffbasemen, numberoffbasemen)
        except:
            return redirect('/inputerror')
        fbasemenmaxindex = returnbestone(fbasemenratingslist, numberoffbasemen)
        firstb = listoffbasemen[fbasemenmaxindex]
        
        stringofsbasemen = form.secondbnames.data
        numberofsbasemen = stringofsbasemen.count(',')+1
        listofsbasemen = stringofsbasemen.split(', ')
        try:
            sbasemenratingslist = getratingslist(listofsbasemen, numberofsbasemen)
        except:
            return redirect('/inputerror')
        sbasemenmaxindex = returnbestone(fbasemenratingslist, numberofsbasemen)
        secondb = listofsbasemen[sbasemenmaxindex]

        stringofss = form.ssnames.data
        numberofss = stringofss.count(',')+1
        listofss = stringofss.split(', ')
        try:
            ssratingslist = getratingslist(listofss, numberofss)
        except:
            return redirect('/inputerror')
        ssmaxindex = returnbestone(ssratingslist, numberofss)
        ss = listofss[ssmaxindex]

        stringoftbasemen = form.thirdbnames.data
        numberoftbasemen = stringoftbasemen.count(',')+1
        listoftbasemen = stringoftbasemen.split(', ')
        try:
            tbasemenratingslist = getratingslist(listoftbasemen, numberoftbasemen)
        except:
            return redirect('/inputerror')
        tbasemenmaxindex = returnbestone(tbasemenratingslist, numberoftbasemen)
        thirdb = listoftbasemen[tbasemenmaxindex]

        stringofoutfielders = form.outfieldnames.data
        numberofoutfielders = stringofoutfielders.count(',')+1
        if numberofoutfielders < 3:
            return redirect('/inputerror')        
        listofoutfielders = stringofoutfielders.split(', ')
        try:
            outfieldersratingslist = getratingslist(listofoutfielders, numberofoutfielders)
        except:
            return redirect('/inputerror')
        ofmaxindexone, ofmaxindextwo, ofmaxindexthree = returnbestthree(outfieldersratingslist, numberofoutfielders)
        outfieldone = listofoutfielders[ofmaxindexone]
        outfieldtwo = listofoutfielders[ofmaxindextwo]
        outfieldthree = listofoutfielders[ofmaxindexthree]

        total = numberofcatchers + numberoffbasemen + numberofsbasemen + numberofss + numberoftbasemen + numberofoutfielders
        if total < 10 or total > 13:
            return redirect('/inputerror')

        listoftherest = []
        ratingsoftherest = []
        posoftherest = []
        for c in range(0, numberofcatchers):
            if c != catchersmaxindex:
                listoftherest.append(listofcatchers[c])
                ratingsoftherest.append(catchersratingslist[c])
                posoftherest.append('C ')
        for c in range(0, numberoffbasemen):
            if c != fbasemenmaxindex:
                listoftherest.append(listoffbasemen[c])
                ratingsoftherest.append(fbasemenratingslist[c])
                posoftherest.append('1B')
        for c in range(0, numberofsbasemen):
            if c != sbasemenmaxindex:
                listoftherest.append(listofsbasemen[c])
                ratingsoftherest.append(sbasemenratingslist[c])
                posoftherest.append('2B')
        for c in range(0, numberofss):
            if c != ssmaxindex:
                listoftherest.append(listofss[c])
                ratingsoftherest.append(ssratingslist[c])
                posoftherest.append('SS')
        for c in range(0, numberoftbasemen):
            if c != tbasemenmaxindex:
                listoftherest.append(listoftbasemen[c])
                ratingsoftherest.append(tbasemenratingslist[c])
                posoftherest.append('3B')
        for c in range(0, numberofoutfielders):
            if (c != ofmaxindexone and c != ofmaxindextwo and c!=ofmaxindexthree):
                listoftherest.append(listofoutfielders[c])
                ratingsoftherest.append(outfieldersratingslist[c])
                posoftherest.append('OF')
 
        utilmaxindexone, utilmaxindextwo, restoftherestindices = returnbesttwo(ratingsoftherest)
        utilone = posoftherest[utilmaxindexone] + ': ' + listoftherest[utilmaxindexone]
        utiltwo = posoftherest[utilmaxindextwo] + ': ' + listoftherest[utilmaxindextwo]

        if len(restoftherestindices)==5:
            if restoftherestindices[2] is not None:
                benchone = posoftherest[restoftherestindices[2]] + ': ' + listoftherest[restoftherestindices[2]]
            if restoftherestindices[1] is not None:
                benchtwo = posoftherest[restoftherestindices[1]] + ': ' + listoftherest[restoftherestindices[1]]
            if restoftherestindices[0] is not None:
                benchthree = posoftherest[restoftherestindices[0]] + ': ' + listoftherest[restoftherestindices[0]]
        elif len(restoftherestindices)==4:
            if restoftherestindices[1] is not None:
                benchtwo = posoftherest[restoftherestindices[1]] + ': ' + listoftherest[restoftherestindices[1]]
            if restoftherestindices[0] is not None:
                benchthree = posoftherest[restoftherestindices[0]] + ': ' + listoftherest[restoftherestindices[0]]
        elif len(restoftherestindices)==3:
            if restoftherestindices[0] is not None:
                benchthree = posoftherest[restoftherestindices[0]] + ': ' + listoftherest[restoftherestindices[0]]
                
        return redirect('/lineup')

    return render_template('team.html', form=form)
Exemplo n.º 29
0
Arquivo: app.py Projeto: RiB-/strategy
def index():
    #b20 = get_highest_returns()
    #b20ticks = b20.index
    last_update_query = cur.execute("""SELECT last_update FROM daily_price ORDER BY date desc LIMIT 1;""")
    last_update = (cur.fetchall())[0][0]
    
    # best_query = cur.execute("""SELECT ticker, ret FROM best_stocks \
    #                 WHERE date_added='%s' ORDER BY ret desc;""" % last_update)
    # best_sql = cur.fetchall()
    # best = [d for d in best_sql]
    
    best_crisis_query = cur.execute("""SELECT ticker, ret, ret_spy FROM best_crisis \
                    ORDER BY date_added desc, ret desc LIMIT 4;""" ) 
    best_crisis_sql = cur.fetchall()
    best_crisis = [b for b in best_crisis_sql]
    
    rec_query =  cur.execute("""SELECT ticker, date_recommended, type FROM recommended_trades \
                    ORDER BY date_recommended desc LIMIT 1;""")
    rec_sql = cur.fetchall()           
    notifications = [rec for rec in rec_sql]
    recommend = []
    for notif in notifications:
        if (notif[1].year == last_update.year) & (notif[1].month == last_update.month) & (notif[1].day == last_update.day):
            recommend.append(notif)
        
    #ev, rec_ev, rec_trans, rec_trans_p, prof_trans = fetch_events()

    form = InputForm(request.form)
    
    if form.validate_on_submit():
        stock = form.stock.data
        strategy = form.strategy.data
        email = form.email.data
        
        if email:
            insert = """INSERT INTO notifications (email) VALUES ('%s') """ % email
            cur.execute(insert)
            con.commit()
        kalman = kalman_stock([stock])
        if stock == "FB":
            startdate = dt.date(2012,05,18)
            enddate =dt.datetime.now()
        elif stock == "TRIP":
            startdate = dt.date(2011,12,21)
            enddate =dt.datetime.now()
        elif stock == "ABBV":
            startdate = dt.date(2013,01,01)
            enddate =dt.datetime.now()
        else: 
            startdate=dt.date(2008,01,01)
            enddate = dt.date(2009,05,01) 
  
        data_df = get_data(symbols=[stock], startdate=startdate, enddate=enddate)
        return_holding = (data_df.values[-1]-data_df.values[0])*100./data_df.values[0]
        dat = parseDFdata(data_df, stock)
    
        ev, rec_ev, rec_trans, rec_trans_p, prof_trans = fetch_events(symbols=[stock], startdate=startdate, enddate=enddate)  
        
        buy, sell = parseEvents(ev,data_df, stock)

        pos = [b[2] for b in rec_trans_p if b[2] > 0]
        if len(rec_trans_p):
            percent_correct_trans = len(pos)*100./float(len(rec_trans_p))
            last_trans = rec_trans_p[-1]
        else:
            percent_correct_trans = 0
        
        stats = analysis()
        return  render_template('results.html', stock=stock, n_events=len(ev), \
         stats=stats, strategy=strategy, kalman=kalman, percent_correct_trans=percent_correct_trans, \
             last_trans=last_trans, dat=dat, buy=buy, sell=sell, return_holding = return_holding, \
             startdate=startdate, enddate=enddate)
             
    return render_template('index.html', form=form,recommend=recommend, notifications=notifications, best_crisis = best_crisis)
Exemplo n.º 30
0
def input_form():
    # If user is authenticated, expose form
    if 'username' in session:
        print(session['username'])
        form = InputForm()
        if form.validate_on_submit():
            flash('Submission: multiplayer={}'.format(form.multiplayer.data))
            # Write to DynamoDB

            currentWeek = 10  # TEMPORARY ToDo: Pull this from current Week

            # Get teamID
            teamID = teams.get_item(
                Key={'username': session['username']})['Item']['teamID']

            # Check if existing entry not in play and submission not in play. ToDo - Error handling if no entry
            existing_multiplayer = multiplayer.get_item(
                Key={
                    'week': str(currentWeek),
                    'teamID': teamID
                })['Item']['multiplayer']

            if False == False:  #espn_stats.getPlayerLockStatus(existing_multiplayer) == False:
                if espn_stats.getPlayerLockStatus(
                        form.multiplayer.data) == False:  # Success
                    # ToDo - Check that player is on roster?
                    # Write new multiplayer - ToDo - error handling
                    multiplayer.put_item(
                        Item={
                            'week': currentWeek,
                            'teamID': teamID,
                            'multiplayer': form.multiplayer.data
                        })

                    # write multiplier
                    helpers.updateMultiplier(currentWeek=currentWeek,
                                             teamID=teamID,
                                             multiplier_db_table=multiplier)

                    application.logger.info(
                        "MULTIPLAYER UPDATE: SUCCESS. {user} / {entry}".format(
                            user=session['username'],
                            entry=form.multiplayer.data))

                    return render_template('submission_success.html',
                                           username=session['username'],
                                           time=datetime.datetime.now())
                else:
                    application.logger.info(
                        "MULTIPLAYER UPDATE: FAIL (Invalid Entry). {user} / {entry}"
                        .format(user=session['username'],
                                entry=form.multiplayer.data))

                    return render_template(
                        'submission_fail.html',
                        username=session['username'],
                        time=datetime.datetime.now(),
                        error='Multiplayer entry is not valid')
            else:
                application.logger.info(
                    "MULTIPLAYER UPDATE: FAIL (Existing Entry Locked). {user} / {entry}"
                    .format(user=session['username'],
                            entry=form.multiplayer.data))

                return render_template(
                    'submission_fail.html',
                    username=session['username'],
                    time=datetime.datetime.now(),
                    error='Existing multiplayer entry is already locked')

        return render_template(
            'input_form.html', form=form,
            username=session['username'])  # ToDo - Clean up this section

    else:  # Route to Cognito UI
        print('Not Authenticated')
        return redirect(url_for('authenticate'))