Ejemplo n.º 1
0
def main():
    path_example = "../examples"
    """example 1"""
    df = read_dataframe(path_examples=path_example, data_idx=4)
    model, future, forecasted = forecast(
        df, periods=1096,
        showflag=True)  # uncertainty intervals seem way too wide

    df.loc[(df['ds'] > '2010-01-01') & (df['ds'] < '2011-01-01'), 'y'] = None
    model_removed = Prophet().fit(df)
    fig = model_removed.plot(
        model_removed.predict(future)
    )  # model with missing data. prediction of whole data with future.
    fig.set_figheight(18)
    fig.set_figwidth(9)
    plt.title('prediction (model with missing data)')
    plt.show()
    """example 2"""
    df2 = read_dataframe(path_examples=path_example, data_idx=5)
    model2, future2, forecasted2 = forecast(
        df2, periods=1096,
        showflag=True)  # extreme outlieres in June 2015 mess up estimate.

    df2.loc[(df2['ds'] > '2015-06-01') & (df2['ds'] < '2015-06-30'),
            'y'] = None
    model2_removed = Prophet().fit(df2)  # Same approach as previous example
    fig = model2_removed.plot(model2_removed.predict(future2))
    fig.set_figheight(18)
    fig.set_figwidth(9)
    plt.title('prediction2 (model with missing data)')
    plt.show()
Ejemplo n.º 2
0
def forecast(ctx, tickers, label_path, feature_path, freq, model, label,
             label_cache, lags, features, config_path, rolling, rolling_bars,
             forward_bars, predict_bars, train_periods, test_periods,
             minimum_train_bars, multiprocess, standardize_features):

    name = ctx.obj['name']
    output = ctx.obj['output']
    debug = ctx.obj['debug']

    fct.forecast(name, output, tickers, label_path, feature_path, freq, label,
                 label_cache, lags, features, model, train_periods,
                 test_periods, config_path, rolling, rolling_bars,
                 forward_bars, predict_bars, minimum_train_bars, debug,
                 is_multiprocess=multiprocess,
                 is_normalize=standardize_features)
Ejemplo n.º 3
0
def get_prediction():

    #format toDate
    #result = forecast("../rnn/24_checkpoint.keras", "../rnn/data.csv",
    #                  "2019-02-10 10:10:10")

    return jsonify(
        forecast("../rnn/24_checkpoint.keras", "../rnn/data.csv",
                 "2019-01-01 10:10:10"))
Ejemplo n.º 4
0
def base_projection(notif_data, years_fwd):
    
    #if there are no 0's do a log transform to avoid negative projections
    if 0 not in notif_data:
        log_notif_data = [math.log(x) for x in notif_data]
        # find optimal alpha, beta
        alpha, beta, error = forecast.optimize_MASE(log_notif_data)
        # compute prediction
        prediction = forecast.forecast(log_notif_data, alpha, beta, years_fwd)
        prediction = [math.exp(x) for x in prediction]
    else:
        # find optimal alpha, beta
        alpha, beta, error = forecast.optimize_MASE(notif_data)
        # compute prediction
        prediction = forecast.forecast(notif_data, alpha, beta, years_fwd)
        # if negative values set them to 0
        prediction = [max(p, 0) for p in prediction]
    return prediction
Ejemplo n.º 5
0
def index():
	# upon user request, lets call the twitter api, and see if the last time
	# is the one in the db (last time not including 24 hour summaries)
	# if its in the db, return that row, otherwise, build out the predictions

	# on the other hand, lets make predictions as a cron job every 60 minutes,
	# and just simply return the latest row to the user
	forest = rforest.forest(train=False)
	frcast = forecast.forecast(forest.X_train.columns, forest.rf)
	return json.jsonify(frcast.df)
Ejemplo n.º 6
0
def labeller_predict():
    #times = time
    legend = "Labeller Values"
    l_data = labeller_data

    equipment_name = 'Labeller'
    forecast_time = int(request.form['input_forecast'])
    forecast_df = f.forecast(df, equipment_name, forecast_time)

    p_legend = "Predicted Values"
    p_time = forecast_df.index.tolist()
    p_labeller_data = forecast_df["Labeller Forecast"].tolist()

    return render_template("labeller.html",
                           values=l_data,
                           labels=p_time,
                           legend=legend,
                           tables=[forecast_df.to_html(classes='forecast_df')],
                           p_legend=p_legend,
                           p_labeller_data=p_labeller_data)
Ejemplo n.º 7
0
def nacelle_predict():
    #times = time
    legend = "Nacelle Position Values"
    n_data = nacelle_data
    feature_name = 'Nacelle Position'
    df1 = df.drop(['Ambient Air temp','GeneratorTemp'],axis=1)
    forecast_time = int(request.form['input_forecast'])
    forecast_df = f.forecast(df1, feature_name, forecast_time)
    print(forecast_df)
    n_legend = "Predicted Values"
    n_time = forecast_df.index.date.tolist()
    n_nacelle_data = forecast_df["Forecast"].tolist()
    
    forecast_df = forecast_df.reset_index()
    forecast_df = forecast_df.rename(columns={"index": "Timestamp"})
    return render_template("nacelle.html", 
                           values=n_data, 
                           labels=n_time, 
                           legend=legend, 
                           tables=[forecast_df.to_html(classes='forecast_df')],
                           n_legend=n_legend,
                           n_nacelle_data=n_nacelle_data)
Ejemplo n.º 8
0
def ambtmp_predict():
    #times = time
    legend = "Ambtemp Values"
    a_data = ambtmp_data
    print(df)
    feature_name = 'Ambient Air temp'
    df1 = df.drop(['GeneratorTemp','Nacelle Position'],axis=1)
    forecast_time = int(request.form['input_forecast'])
    forecast_df = f.forecast(df1, feature_name, forecast_time)
    print(forecast_df.head)
    a_legend = "Predicted Values"
    a_time = forecast_df.index.date.tolist()

    a_ambtmp_data = forecast_df["Forecast"].tolist()
    
    forecast_df = forecast_df.reset_index()
    forecast_df = forecast_df.rename(columns={"index": "Timestamp", "Ambient Air temp": "Amb Air temp" })
    return render_template("ambtemp.html", 
                           values=a_data, 
                           labels=a_time, 
                           legend=legend, 
                           tables=[forecast_df.to_html(classes='forecast_df')],
                           a_legend=a_legend,
                           a_ambtmp_data=a_ambtmp_data)
Ejemplo n.º 9
0
def weather_location(message):
    bot.send_message(
        message.chat.id,
        forecast.forecast(
            str(message.location.latitude) + "," +
            str(message.location.longitude)))
Ejemplo n.º 10
0
def weather_handle(message):
    bot.send_message(message.chat.id,
                     forecast.forecast(message.text.replace('Погода ', '')))
Ejemplo n.º 11
0
import forecast as wf
import json

result = wf.forecast(place = "Santa Fe, Provincia de Santa Fe" , time="13:03:00" , date="2021-02-23" , forecast="daily")
day = result['day']
night = result['night']

result = json.dumps(test1) 
Ejemplo n.º 12
0
import csv
from csv2md import csv2md
from forecast import forecast

out = "Current Elo ratings (includes preseason games):\n\n"
with open("aaf_elo.csv") as f:
	out += csv2md(list(csv.reader(f)),sort=lambda row: (0-float(row[1])))
	out+="\n\n"
out+="## Predictions\n"
with open("matchups.csv") as f:
	for row in csv.reader(f):
		winner, confidence = forecast(row[0],row[1])
		if winner==False:
			out+="Outcome unknown for {} vs. {}  \n".format(row[0],row[1])
		else:
			out+="{} **def.** {}  \n".format(winner,list(filter(lambda t: t!=winner,row))[0])
out=out.strip()+"\n"
with open("post.txt","w") as f:
	f.write(out)
Ejemplo n.º 13
0
import rforest
import forecast

forest = rforest.forest(train=False)
frcast = forecast.forecast(forest.X_train.columns, forest.rf)
Ejemplo n.º 14
0
def index():
    forest = rforest.forest(train=False)
    frcast = forecast.forecast(forest.X_train.columns, forest.rf)
    # return flask.json.jsonify({'predictions':frcast.df})
    return json.jsonify(frcast.df)
Ejemplo n.º 15
0
import csv, forecast

records = {k: [0, 0, 0] for k in forecast.league.team.keys()}

with open("season_known.csv") as f:
    n = csv.reader(f)
    next(n)
    for team in n:
        records[team[0]] = [int(x) for x in team[1:]]

with open("season.csv") as f:
    games = list(csv.reader(f))
CONFID = []
C = 1
for game in games:
    winner, confidence = forecast.forecast(game[0], game[1])
    if winner == False:
        print("{} and {} tie".format(*game), end=" ")
        records[game[0]][2] += 1
        records[game[1]][2] += 1
        forecast.league.match(forecast.league.team[game[0]],
                              forecast.league.team[game[1]], 0.5)
    elif winner == game[0]:
        print("{} def. {}".format(*game), end=" ")
        records[game[0]][0] += 1
        records[game[1]][1] += 1
        forecast.league.match(forecast.league.team[game[0]],
                              forecast.league.team[game[1]], 1)
    elif winner == game[1]:
        print("{1} def. {0}".format(*game), end=" ")
        records[game[0]][1] += 1
Ejemplo n.º 16
0
import forecast

team = input("Team?: ")
opponent = input("Opponent?: ")

winner, confidence = forecast.forecast(team, opponent)

if not winner:
    print("I expect a tie!")
elif winner == team:
    print("The {} are gonna blow the {}'s socks off!".format(team, opponent))
else:
    print("The {} are gonna blow the {}'s socks off!".format(opponent, team))

print("Confidence:        {:.2%}".format(confidence))
Ejemplo n.º 17
0
def bare(test=False, dates=[], charts=False, verbose=False, useProphet=False):

    if test:
        uri = 'wss://test.deribit.com/ws/api/v2'
        print('===  TESTNET  ===')
    else:
        uri = 'wss://www.deribit.com/ws/api/v2'
        print('===  MAINNET  ===')

    handler = Handler(uri)

    instruments = getInstruments(handler)

    for d in dates:
        dd = d
        d = d.strftime('%-d%b%y').upper()
        print('===', d, '===')

        # all[d + '_CALL'] = []
        # all[d + '_PUT'] = []
        strikes = []

        s_results = []
        z_results = []

        for instr in instruments:
            if instr['instrument_name'] == "BTC-" + d + '-' + str(
                    int(instr['strike'])) + '-' + 'C':
                strikes.append(int(instr['strike']))

        strikes.sort(reverse=False)
        l = len(strikes)
        spot = getSpot(handler)

        print('=== Index:', spot, '===')

        if useProphet:
            print('=== Using Prophet... ===')
            yhat, upper, lower = forecast.forecast(dd,
                                                   showPlot=False,
                                                   histPeriodDays=750,
                                                   periodsAhead=1000)
            lowerBound = lower
            upperBound = upper

        else:
            print('=== Using Tolerance ± %.1f %%===' % (TOL * 100.0))
            lowerBound = (1 - TOL) * spot
            upperBound = (1 + TOL) * spot

        print('=== Lower Bound: %i' % (lowerBound), '===')
        print('=== Upper Bound: %i' % (upperBound), '===')

        # Put Vertical S (Bull)

        for j in range(l):
            s2 = strikes[j]
            bid2, bidAmt2, ask2, askAmt2 = getQuotes(handler, d, s2, 'P')

            if verbose: print(s2)

            if bid2 <= 0:
                if verbose: print('s2 price N.A')
                continue

            if (lowerBound <= s2):
                if verbose: print(s2)
                if verbose: print('Not in range')
                continue

            units = bidAmt2

            fee = FEE_RATE * spot * units
            optionPrice2 = bid2 * spot  #short put

            maxProfit = units * (optionPrice2) - fee

            boundary = s2 + FEE_RATE - optionPrice2

            unitProfit = maxProfit / units
            unitPercentGain = (unitProfit / spot) * 10 * 100

            if charts:
                INTERVAL = 5
                START = s2 - INTERVAL - 500
                END = s2 + INTERVAL + 500
                RANGE = range(START, END, INTERVAL)
                SPOT_PRICE_RANGE = pd.Series(RANGE)

                short = SP(s2, units, SPOT_PRICE_RANGE, bid2, spot)

            if maxProfit < 0:
                if verbose: print('100% Loss')
                continue

            if charts:
                title = 'BTC-' + d + '<br>' + '%.2f' % (spot)
                plotStuff(SPOT_PRICE_RANGE, [short],
                          total=None,
                          names=['Short Put'],
                          title=title)

            s_results.append([
                boundary, unitPercentGain, unitProfit, maxProfit, 'Sell Put',
                s2, bid2, units
            ])

        s_df = pd.DataFrame(s_results,
                            columns=[
                                'Profit if above', 'percent gain(%%)',
                                'unitProfit', 'maxProfit', 'Order 2 Type',
                                'Strike 2', 'Price 2', 'units'
                            ])

        s_df = s_df.sort_values(by=['Profit if above'])
        print(s_df)
        print()

        #region:Call Vertical Z (Bear)
        for i in range(l):
            s1 = strikes[i]
            bid1, bidAmt1, ask1, askAmt1 = getQuotes(handler, d, s1, 'C')
            if bid1 <= 0:
                if verbose: print('s1 price N.A')
                continue

            if (upperBound >= s1):
                if verbose: print(s1)
                if verbose: print('Not in range')
                continue

            units = bidAmt1

            fee = FEE_RATE * spot * units
            optionPrice1 = bid1 * spot  # short call

            maxProfit = units * (optionPrice1) - fee

            boundary = optionPrice1 - FEE_RATE + s1

            unitProfit = maxProfit / units
            unitPercentGain = (unitProfit / spot) * 10 * 100

            if charts:
                INTERVAL = 50
                START = s1 - INTERVAL - 10
                END = s1 + INTERVAL + 10
                RANGE = range(START, END, INTERVAL)
                SPOT_PRICE_RANGE = pd.Series(RANGE)

                short = SC(s1, units, SPOT_PRICE_RANGE, bid1, spot)

            if maxProfit < 0:
                if verbose: print('100% Loss')
                continue

            if charts:
                title = 'BTC-' + d + '<br>' + '%.2f' % (spot)
                plotStuff(SPOT_PRICE_RANGE, [short],
                          total=None,
                          names=['Short Call'],
                          title=title)

            z_results.append([
                boundary, unitPercentGain, unitProfit, maxProfit, 'Sell Call',
                s1, bid1, units
            ])

        z_df = pd.DataFrame(z_results,
                            columns=[
                                'Profit if below', 'percent gain(%%)',
                                'unitProfit', 'maxProfit', 'Order 1 Type',
                                'Strike 1', 'Price 1', 'units'
                            ])

        z_df = z_df.sort_values(by=['Profit if below'], ascending=False)
        print(z_df)
        print()