def main(): raw_tickers = input('Enter stocks separated by a comma: ') investment = int(input("Enter total investment to allocate: ")) stock_tickers = raw_tickers.split(", ") print(stock_tickers) listed_prices, returns, cov_mat, avg_rets = gd.get_stock_data( stock_tickers) section("Example returns") print(returns.head(10)) print("...") section("Average returns") print(avg_rets) section("Covariance matrix") print(cov_mat) section("Minimum variance portfolio (long only)") weights = pfopt.min_var_portfolio(cov_mat) print_portfolio_info(returns, avg_rets, weights) allocation = investment * weights print(allocation) # Define some target return, here the 70% quantile of the average returns target_ret = avg_rets.quantile(0.7) section("Markowitz portfolio (long only, target return: {:.5f})".format( target_ret)) weights = pfopt.markowitz_portfolio(cov_mat, avg_rets, target_ret) print_portfolio_info(returns, avg_rets, weights) allocation = investment * weights print(allocation)
def intrinsic_val_calculation(stock_ticker): global stock_eps_input, stock_growth_rate_input while True: try: print( Fore.RED + "Warning! The EPS must be positive to do this Intrinsic Value Calculation" + Style.RESET_ALL) stock_eps_input = float( input("\nWhat is " + stock_ticker + "'s EPS? ")) if stock_eps_input < 0: print( "Sorry! We can't calculate the intrinsic value with a negative EPS" ) stock_growth_rate_input = float( input("What is " + stock_ticker + "'s Growth Rate? ")) break except ValueError: print("The input must be numbers (Example: '25', '2.5', etc.)") pe_ratio = 7 corp_Bond_Yield = 4.4 aaa_Bond_Yield = 2.41 # Basic Graham Intrinsic Value # Source: https://www.youtube.com/channel/UCOi_Zu4asFEMKISIbL9yuUA graham_intrinsic = (stock_eps_input * (pe_ratio + stock_growth_rate_input) * corp_Bond_Yield) / aaa_Bond_Yield # Basic EPS Intrinsic Value # Source: https://www.youtube.com/channel/UCOi_Zu4asFEMKISIbL9yuUA index_num_years = list(range(0, 4)) pe_ratio = stock_growth_rate_input * 2 eps_prediction_list = [stock_eps_input] discount_rate = 0.1 for year in index_num_years: eps_prediction_list.append( (eps_prediction_list[year] * (1 + stock_growth_rate_input / 100))) stock_price_prediction_list = [0] * 5 stock_price_prediction_list[0] = eps_prediction_list[4] * pe_ratio index = list(range(1, 5)) for i in index: stock_price_prediction_list[i] = stock_price_prediction_list[i - 1] / ( 1 + discount_rate) stock_price_prediction_list.reverse() eps_intrinsic = stock_price_prediction_list[0] # Average of both intrinsic values stock_data = get_stock_data( stock_ticker ) # Can put it as a variable in the menu to avoid this step over and over intrinsic_value = (eps_intrinsic + graham_intrinsic) / 2 current_value = stock_data['Adj Close'][stock_data.shape[0] - 1] upside = ((intrinsic_value / current_value) - 1) * 100 return intrinsic_value, upside, current_value
def current_earnings(portfolio_data): stocks_tickers_owned_list = portfolio_data['Ticker'] stocks_purchase_price_owned = portfolio_data['Purchase_Price'] earnings_percentage_list = [] earnings_dollars_list = [] for ticker, shares, purchased_price in zip(stocks_tickers_owned_list, portfolio_data['Shares'], stocks_purchase_price_owned): stock_data = get_stock_data( ticker ) # Can put it as a variable in the menu to avoid this step over again current_value = stock_data['Adj Close'][stock_data.shape[0] - 1] earnings_percentage_list.append( ((current_value / purchased_price) - 1) * 100) earnings_dollars_list.append( (current_value - purchased_price) * shares) return earnings_percentage_list, earnings_dollars_list
def home_input(): continue_program = True print("\nHello Santiago,") while continue_program: print( "\nThis is your Virtual Stock Portfolio (VSP), where you can manage your stocks.\n" "You can:\n" "a) 'Current': See My Portfolio and current earnings.\n" "b) 'Edit': Change My Portfolio or Add a new stock.\n" "c) 'Explore': Check out and analyze a new stock.\n" "d) 'Exit': Stop the program.\n") intro_command_input = input("Enter the command: ") if intro_command_input == 'Current': myPortfolio = get_data.open_portfolio() # IDK WHY DOESN'T WORK print("\nmyPortfolio:") print(myPortfolio) earnings_percentage_list, earnings_dollars_list = current_command.current_earnings( myPortfolio) current_command.print_earnings(myPortfolio, earnings_percentage_list, earnings_dollars_list) in_depth_command = input( "\nDo you want to take a look at a specific stock? Yes or No? " ) current_continue = False if ((in_depth_command == 'No') or (in_depth_command == 'no')) else True while current_continue: stock_evaluating = input( "From MyPortfolio, Which stock do you want to take a look at? " ) print( "\nWith the stocks of My Portfolio, you can:\n" "a) 'Graphs': Get the current graph for the stock and the analytics graph\n" "b) 'Intrinsic': Calculate the intrinsic value\n" "c) 'Back': Go back\n") current_command_input = input("Enter the command: ") if current_command_input == 'Graphs': stock_data = get_data.get_stock_data( stock_evaluating ) # Can put it as a variable in the menu to avoid this step over and over current_command.stock_graph(stock_evaluating, stock_data) current_command.stock_graph_MACD(stock_evaluating, stock_data) elif current_command_input == 'Intrinsic': stock_intrinsic_val, stock_upside, current_value = current_command. \ intrinsic_val_calculation(stock_evaluating) print("\nIntrinsic Value Calculation:") print("Stock:", stock_evaluating) print("Current Value : $ {:.2f}".format(current_value)) print("Intrinsic Value: $ {:.2f}".format( stock_intrinsic_val)) print("Upside : % {:.2f}\n".format(stock_upside)) elif current_command_input == 'Back': break else: print("Please type the command correctly") current_repeat = input( "Do you want to check something else in 'Current'? 'Yes' or 'No': " ) current_continue = False if ( (current_repeat == 'No') or (current_repeat == 'no')) else True elif intro_command_input == 'Edit': edit_continue = True while edit_continue: print("For this section you can:\n" "a) 'Add': Add a new stock to your portfolio\n" "b) 'Delete': Delete a stock\n" "c) 'Back': Go back\n") edit_command_input = input("Enter the command: ") if edit_command_input == 'Add': edit_command.add_to_csv() elif edit_command_input == 'Delete': edit_command.delete_csv_row() elif edit_command_input == 'Back': break else: print("Please type the command correctly") edit_repeat = input( "Do you want to check something else in 'Edit'? 'Yes' or 'No'? " ) edit_continue = False if ((edit_repeat == 'No') or (edit_repeat == 'no')) else True elif intro_command_input == 'Explore': explore_continue = True while explore_continue: exploring_stock = input( "What stock ticker symbol you want to take a look at? ") print( "\nFor '", exploring_stock, "' you can:\n" "a) 'Graphs': Get the current graph for the stock and the analytics " "graph\n" "b) 'Intrinsic': Calculate the intrinsic value\n" "c) 'Back': Go back\n") explore_command_input = input("Enter the command: ") if explore_command_input == 'Graphs': explore_stock_data = get_data.get_stock_data( exploring_stock) current_command.stock_graph(exploring_stock, explore_stock_data) current_command.stock_graph_MACD(exploring_stock, explore_stock_data) elif explore_command_input == 'Intrinsic': explore_stock_intrinsic_val, explore_stock_upside, explore_current_value = current_command. \ intrinsic_val_calculation(exploring_stock) print("\nIntrinsic Value Calculation:") print("Stock:", exploring_stock) print("Current Value : $ {:.2f}".format( explore_current_value)) print("Intrinsic Value: $ {:.2f}".format( explore_stock_intrinsic_val)) print("Upside : % {:.2f}\n".format(explore_stock_upside)) elif explore_command_input == 'Back': break else: print("Please type the command correctly") explore_repeat = input( "Do you want to check something else in 'Explore'? 'Yes' or 'No'? " ) explore_continue = False if ( (explore_repeat == 'No') or (explore_repeat == 'no')) else True elif intro_command_input == 'Exit': break else: print("Please type the command correctly") is_repeat = input( "Do you want to check something else in the General Menu? 'Yes' or 'No'? " ) continue_program = False if ((is_repeat == 'No') or (is_repeat == 'no')) else True
def predict(ticker, pred_period=1): pred_values = [] json_file = open(model_dir + '/' + ticker + '/model.json', 'r') loaded_model_json = json_file.read() json_file.close() model = model_from_json(loaded_model_json) # load weights into new model model.load_weights(model_dir + '/' + ticker + "/model.h5") #print("Loaded model from disk") #model.summary() today = date.today() days = timedelta(80) period = today - days data = get_stock_data(ticker, start_date=period, end_date=today).reset_index(drop=True) clean_data = data.dropna() clean_data = clean_data.iloc[:-10] scaler = pickle.load(open(model_dir + '/' + ticker + "/scaler.pkl", "rb")) #print(data) for i in range(pred_period): req_data = clean_data.values if i == 0: pred_values.append({ "Open": req_data[-1, 0], "High": req_data[-1, 1], "Low": req_data[-1, 2], "Close": req_data[-1, 3], "Day": i }) scaled = scaler.transform(req_data) print() to_pred = scaled[-5:] to_pred = to_pred.reshape((1, 5, scaled.shape[1])) ######PREDICTION####### #print('before pred') pred = model.predict(to_pred) #print('after_pred') #print(pred) pred1 = np.zeros((to_pred.shape[0], 18)) pred1[:, :4] = pred[0] pred1 = np.around(scaler.inverse_transform(pred1), decimals=2) pred_values.append({ "Open": pred1[0, 0], "High": pred1[0, 1], "Low": pred1[0, 2], "Close": pred1[0, 3], "Day": i + 1 }) if pred_period > 1: data.loc[len(data)] = pred1[0] clean_data = calculate_indicators(data).dropna() #print(data) #print(data.loc[data.index.max()]) #new = new + timedelta(1) #print("The predicted value for the next trading day for " + ticker + " is : " + str(pred1[0,3])) return pred_values
plt.legend() #fig1 = plt.gcf() plt.savefig(ticker + '_' + type + "conv.jpg", transparent=False) plt.show() #print("tf.__version__ is", tf.__version__) #print("tf.keras.__version__ is:", tf.keras.__version__) #tfback._get_available_gpus = _get_available_gpus ticker = input("Please enter symbol: ") present_date = date.today() prev_date = date.today() - timedelta(days=5457) print(date(present_date.year, present_date.month, present_date.day)) get_stock_data(ticker, start_date=prev_date, end_date=present_date) dataset = pd.read_csv('stock_prices' + ticker + '.csv') scaler = MinMaxScaler(feature_range=(0, 1)) scaled = scaler.fit_transform(dataset.values) ##### TRAIN TEST SPLITTING ##### train_gen = TimeseriesGenerator(scaled, scaled[:, 3], start_index=0, end_index=int(len(scaled) * 0.8), length=3, batch_size=256) test_gen = TimeseriesGenerator(scaled, scaled[:, 3],
def train(ticker): #Initializing the Paths create_dir(model_dir + '/' + ticker) output = {} present_date = date.today() prev_date = date.today() - timedelta(days=5457) dataset = get_stock_data(ticker, start_date=prev_date, end_date=present_date, drop_na=True).reset_index(drop=True) dataset.to_csv(model_dir + '/' + ticker + '/' + str(ticker) + '.csv', index=False) scaler = MinMaxScaler(feature_range=(0, 1)) scaled = scaler.fit_transform(dataset.values) pickle.dump(scaler, open(model_dir + '/' + ticker + '/scaler.pkl', 'wb')) ##### TRAIN TEST SPLITTING ##### ''' train_gen = TimeseriesGenerator(scaled, scaled[:,0:4], start_index = 0, end_index = int(len(scaled) * 0.90), length = 1, batch_size = 256) test_gen = TimeseriesGenerator(scaled, scaled[:,0:4], start_index = int(len(scaled) * 0.90), end_index = int(len(scaled) - 1), length = 1, batch_size = 256) ''' train_gen = TimeseriesGenerator(scaled, scaled[:, :4], start_index=0, end_index=int(len(scaled) * 0.85), length=5, batch_size=16) test_gen = TimeseriesGenerator(scaled, scaled[:, :4], start_index=int(len(scaled) * 0.85), end_index=int(len(scaled) - 1), length=5, batch_size=16) ##### MODEL CREATION ###### ''' model = Sequential() model.add(Conv1D(18, kernel_size=3, activation='relu', padding = 'valid', strides=1, input_shape=(1,18), data_format='channels_first')) model.add(Conv1D(18, kernel_size=3, activation='relu', padding = 'valid', strides=1)) #model.add(MaxPooling1D(pool_size=2)) model.add(LSTM(100, activation = 'tanh', recurrent_activation = 'sigmoid', unroll = False, use_bias = True, recurrent_dropout = 0, return_sequences=True)) model.add(Dropout(0.4)) model.add(LSTM(100, activation = 'tanh', recurrent_activation = 'sigmoid', unroll = False, use_bias = True, recurrent_dropout = 0,return_sequences=True)) model.add(Dropout(0.4)) model.add(LSTM(100, activation = 'tanh', recurrent_activation = 'sigmoid', unroll = False, use_bias = True, recurrent_dropout = 0,return_sequences= True)) model.add(Dropout(0.2)) model.add(Flatten()) model.add(Dense(4, activation = 'linear')) adadelta = Adadelta(learning_rate=1.0, rho=0.95) model.compile(loss= 'mae', optimizer = adadelta, metrics=[tf.keras.metrics.MeanAbsolutePercentageError()]) #model.summary() ''' from tensorflow.keras.regularizers import l1 model = Sequential() model.add( Conv1D(18, kernel_size=3, activation='relu', padding='valid', strides=1, input_shape=(5, 18), data_format='channels_first')) model.add( Conv1D(18, kernel_size=4, activation='relu', padding='valid', strides=1)) #model.add(MaxPooling1D(pool_size=2)) model.add( LSTM(100, activation='tanh', recurrent_activation='sigmoid', unroll=False, use_bias=True, recurrent_dropout=0, return_sequences=True, kernel_regularizer=l1(0.001))) model.add(Dropout(0.4)) model.add( LSTM(50, activation='tanh', recurrent_activation='sigmoid', unroll=False, use_bias=True, recurrent_dropout=0, return_sequences=True, activity_regularizer=l1(0.001))) model.add(Dropout(0.4)) model.add( LSTM(25, activation='tanh', recurrent_activation='sigmoid', unroll=False, use_bias=True, recurrent_dropout=0, return_sequences=True, activity_regularizer=l1(0.001))) model.add(Dropout(0.2)) model.add(Flatten()) model.add(Dense(4, activation='linear')) adadelta = Adadelta(learning_rate=1.0, rho=0.95) model.compile(loss='mse', optimizer=adadelta, metrics=[tf.keras.metrics.RootMeanSquaredError()]) model.summary() ##### TRAINING ##### my_callbacks = [ #tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss', patience=4, factor=0.2, min_lr=0.001), tf.keras.callbacks.ModelCheckpoint( filepath=model_dir + "/" + ticker + "/model" + ".h5", save_weights_only=True, save_best_only=True, monitor="val_root_mean_squared_error", mode="min"), ] history = model.fit_generator(train_gen, epochs=300, verbose=0, shuffle=True, validation_data=test_gen, callbacks=my_callbacks) ##### PLOTTING LOSS ###### '''plt.plot(history.history['loss'], label='train') plt.plot(history.history['val_loss'], label='test') plt.legend() plt.show() score = model.evaluate_generator(test_gen, verbose = 1) print() print('Test loss:', score[0]) print('Test accuracy:', score[1]) print()''' ###### RESHAPE ACTUAL DATA ####### actual_train = reshape_actual(train_gen) predictions_train = model.predict_generator(train_gen, verbose=0) print(predictions_train) ##### RSME FOR TRAIN ##### rmse_train = math.sqrt( mean_squared_error(actual_train[:], predictions_train[:])) print(rmse_train) ###### TEST DATA ###### actual_test = reshape_actual(test_gen) predictions_test = model.predict_generator(test_gen, verbose=0) rmse_test = math.sqrt( mean_squared_error(actual_test[:], predictions_test[:])) print(rmse_test) output["Accuracy"] = { "Train": round(rmse_train * 100, 2), "Test": round(rmse_test * 100, 2) } ###### PLOT TEST ###### output["Train"] = plot_them_graphs(actual_train, predictions_train, "train", ticker, scaler) output["Test"] = plot_them_graphs(actual_test, predictions_test, "test", ticker, scaler) ##### SAVE IT!!!!!! ##### model_json = model.to_json() with open(model_dir + "/" + ticker + "/model" + ".json", "w") as json_file: json_file.write(model_json) #model.save_weights(model_dir + "/" + ticker + "/model" + ".h5") print("Saved model to disk") data = {"name": ticker, "date": present_date.strftime("%d-%b-%Y")} with open(model_dir + "/" + ticker + '/data.json', 'w') as outfile: json.dump(data, outfile) return output