Exemple #1
0
def vix_momentum_bias(timeseries, date, votality_calculation_range,
                      observation_range):
    vix, vix_id = download_stock("^vix", date, 1, False)
    for i in range(len(vix) - 1 - votality_calculation_range, 0, -1):
        del vix[i]
    votality_rate = (vix[len(vix) - 1] - vix[0]) / len(vix)

    bias = 0.00  # smaller the better
    for i in range(timeseries.raw_size() - 1,
                   timeseries.raw_size() - observation_range, -1):
        if timeseries.raw_datapoint(timeseries.raw_size() -
                                    1) < timeseries.raw_datapoint(i):
            bias += 1
        else:
            bias -= 1
    # always be negative (positive momentum * negative = negative bias)
    # (negative momentum * negative = positive bias)
    bias *= -votality_rate
    return bias
Exemple #2
0
    def __init__(self, name, id):
        self.id = id
        self.name = name
        self.start_date = ""
        self.data = None
        self.close_price = 0
        self.percentage = 0.00
        self.shares = 0
        self.required_purchase_sales = 0.00
        self.percentage_diff = 0

        today = date.today()
        today = str(today)
        date_info = today.split("-")
        date_info[0] = str(int(date_info[0]) - 1)
        for i in range(len(date_info)):
            if i == len(date_info) - 1:
                self.start_date += date_info[i]
            else:
                self.start_date += date_info[i] + "-"

        self.data, _ = download_stock(self.id, self.start_date, 1, True)
        self.close_price = self.data[len(self.data) - 1]
Exemple #3
0
        bh_change_matrix.append(bh_change)
        for i in range(_range, _range - evaluate_range, -1):
            if stock[_range] > stock[i]:
                momentum += 1
        if momentum >= evaluate_range * 8 / 12:
            momentum = evaluate_range
        else:
            momentum = evaluate_range / 2
        stock_asset = int(total_asset * (momentum / evaluate_range))
        shares = int(stock_asset / stock[_range])
        stock_asset = shares * stock[_range]
        cash = total_asset - shares * stock[_range]
        previous_asset = total_asset
        print("Total = ", total_asset, " [ Stock = ", stock_asset, ", Cash = ",
              cash, "] --> Shares: ", shares, ", < CHANGE=", change, ">",
              "<BH Change = ", bh_change, ">", stock[_range])
    print("Final Profit = ", (total_asset - principal) * 100 / principal)
    print(stock[0])
    graph(change_matrix, 'red', 'momentum.jpg', False)
    graph(bh_change_matrix, 'blue', 'momentum.jpg', False)


# momentum 비중 높으면 --> 채권 비중을 주식 비중으로 이동
# momentum 비중 낮으면 --> 주식 비중을 채권 비중으로 이동

if __name__ == "__main__":
    csv, id = download_stock()
    stock = upload(csv, 5, True)
    momentum_investing(stock, 100000000, 8, 1)
    git_update()
Exemple #4
0
#!/usr/bin/env python3

from service import download_stock

while True:
    stock, id = download_stock()
Exemple #5
0
    # get date YYYY-MM-DD string 1 year before
    start_date = ""
    today = str(date.today())
    date_info = today.split("-")
    date_info[0] = str(int(date_info[0]) - 1)
    for i in range(len(date_info)):
        if i == len(date_info) - 1:
            start_date += date_info[i]
        else:
            start_date += date_info[i] + "-"

    print("Downloading/uploading historcial stock data from finance.yahoo.com....")
    # download historical data, get one time series from stock, get close price
    for id in stock_id_list:
        historical, id = download_stock(id, start_date, 1, False)
        timeseries, close_price = fetch_last_time_series(historical, QUARTER)
        dataset.append(timeseries)
        price.append(int(close_price))

    cash_balance = 100.0 - total_stock_balance
    adjustment_value = 0.3 # THIS VALUE COULD BE TUNED

    # run sequential prediction before rebalancing
    predictions = []
    print("Running prediction models... ")
    for i in range(len(dataset)):
        stock, prediction = sequential_prediction(model=stock_id_list[i].lower(), stock_id=stock_id_list[i].lower(), date=start_date, log=False, bias_type='REGRESSION', itr=10)
        if prediction == []: # meaning that no model exists
            predictions.append('NO MODEL')
        else:
Exemple #6
0
def sequential_prediction(model=None,
                          stock_id=None,
                          date=None,
                          graphing=True,
                          log=True,
                          add_bias=True,
                          bias_type='DEFAULT',
                          itr=5):
    if model == None:
        model = select_model()
        print("Model = [", model, "]\n")

    stock = None
    if stock_id == None or date == None:
        stock, id = download_stock()
    else:
        stock, id = download_stock(stock_id, date, 1, True)

    predictor = None
    model_exists = None
    prediction_matrix = []

    try:
        predictor = Model(model)
        model_exists = True
    except:
        model_exists = False

    if model_exists == True:
        timeseries, final_close = fetch_last_time_series(stock, QUARTER)

        bias = 0.00
        if add_bias == True:
            if bias_type == 'VIX':
                bias = vix_momentum_bias(timeseries, date, WEEK, MONTH)
            elif bias_type == 'REGRESSION':
                bias = regression_momentum_bias(timeseries, WEEK)
            else:  # no specific BIAS type inputted
                bias_mode = int(
                    input("Bias Type [0: Votality, 1: Regression] :: "))
                # compute bias using momentum calculations with VIX index
                if bias_mode == 1:
                    bias = regression_momentum_bias(timeseries, WEEK)
                else:
                    bias = vix_momentum_bias(timeseries, date, WEEK, MONTH)
        #print("BIAS = ", bias)

        for count in range(itr):
            trend = moving_average(timeseries, MONTH)
            matrix = sampling(trend, 0, 2, STANDARD_SAMPLING_RANGE)
            timeseries.set_sampled_matrix(matrix)
            timeseries.normalize_timeseries()

            prediction = 0.00
            result = predictor.predict(timeseries)
            for i in range(result.shape[0]):
                for j in range(result.shape[1]):
                    prediction = rescale(result[i][j], timeseries.minimum(),
                                         timeseries.maximum())
                    # apply the pre-calculated bias to the prediction results
                    prediction += bias
            prediction_matrix.append(prediction)
            raw = timeseries.raw_matrix()
            for i in range(0, len(raw)):
                raw[i] = rescale(raw[i], timeseries.minimum(),
                                 timeseries.maximum())
            del raw[0]
            raw.append(prediction)
            timeseries.set_raw_matrix(raw)
            count += 1

        if graphing == True:
            graph_title = "../Images/" + model + "_sequential_prediction_demo.png"
            graph(prediction_matrix, 'red', graph_title, False)
    return stock, prediction_matrix
Exemple #7
0
models = all_models()

download_date = ""
today = str(date.today())
date_info = today.split("-")
date_info[0] = str(int(date_info[0]) - 1)
for i in range(len(date_info)):
    if i == len(date_info) - 1:
        download_date += date_info[i]
    else:
        download_date += date_info[i] + "-"

if __name__ == "__main__":
    print("UPDATING ALL EXISTING MODELS:\n")
    for m in models:
        stock, id = download_stock(m, download_date, 1, False)
        if len(stock) <= QUARTER:
            print("Failed! [NOT ENOUGH DATA]")
        else:
            dataset = partition_time_series(stock, QUARTER, 35, False)
            for timeseries in dataset:
                matrix = moving_average(timeseries, MONTH)
                matrix = sampling(matrix, 0, 2, STANDARD_SAMPLING_RANGE)
                timeseries.set_sampled_matrix(matrix)
                timeseries.normalize_timeseries()
            predictor = model.Model(m)
            predictor.update(dataset, True, 10, 32, 0)
            print("Updated model for {0}!".format(m))
    git_update()