High / app.py
Saraay's picture
up
812b185 verified
Raw
History Blame Contribute Delete
34.2 kB
# -*- coding: utf-8 -*-
"""High.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1fuCvRJdvsG0unIYY6-RQ6zNjKwRxIAes
"""
from re import VERBOSE
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import r2_score
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
import tensorflow as tf
import random
class UBER:
def __init__(self, symbol='UBER', epochs=50, time_step=60, seed=42):
self.symbol = symbol
self.time_step = time_step
self.epochs = epochs
self.seed = seed
self.scaler = MinMaxScaler(feature_range=(0, 1))
self.model = None
self.data = None
self.dates = None
self.train_data = None
self.test_data = None
self.X_train = None
self.y_train = None
self.X_test = None
self.y_test = None
self.set_seed(seed)
def set_seed(self, seed):
np.random.seed(seed)
random.seed(seed)
tf.random.set_seed(seed)
def fetch_data(self):
stock = yf.Ticker(self.symbol)
historical_data = stock.history(period="max")
self.dates = historical_data.index
self.data = historical_data['Close'].values.reshape(-1, 1)
def preprocess_data(self):
scaled_data = self.scaler.fit_transform(self.data)
train_size = int(len(scaled_data) * 0.7)
self.train_data = scaled_data[:train_size]
self.test_data = scaled_data[train_size:]
self.X_train, self.y_train = self.create_dataset(self.train_data)
self.X_test, self.y_test = self.create_dataset(self.test_data)
self.X_train = self.X_train.reshape(self.X_train.shape[0], self.X_train.shape[1], 1)
self.X_test = self.X_test.reshape(self.X_test.shape[0], self.X_test.shape[1], 1)
def create_dataset(self, dataset):
X, Y = [], []
for i in range(len(dataset) - self.time_step - 1):
a = dataset[i:(i + self.time_step), 0]
X.append(a)
Y.append(dataset[i + self.time_step, 0])
return np.array(X), np.array(Y)
def build_model(self):
self.model = Sequential()
self.model.add(LSTM(45, return_sequences=True, input_shape=(self.time_step, 1)))
self.model.add(Dropout(0.3))
self.model.add(LSTM(40, return_sequences=False))
self.model.add(Dropout(0.2))
self.model.add(Dense(25))
self.model.add(Dense(1))
self.model.compile(optimizer='adam', loss='mean_squared_error')
def train_model(self):
self.model.fit(self.X_train, self.y_train, batch_size=32, epochs=self.epochs)
def predict(self):
train_predict = self.model.predict(self.X_train)
test_predict = self.model.predict(self.X_test)
train_predict = self.scaler.inverse_transform(train_predict)
test_predict = self.scaler.inverse_transform(test_predict)
return train_predict, test_predict
def evaluate(self):
train_predict, test_predict = self.predict()
y_train_orig = self.scaler.inverse_transform(self.y_train.reshape(-1, 1))
y_test_orig = self.scaler.inverse_transform(self.y_test.reshape(-1, 1))
train_r2 = r2_score(y_train_orig, train_predict)
test_r2 = r2_score(y_test_orig, test_predict)
print(f"Train R2 Score: {train_r2}")
print(f"Test R2 Score: {test_r2}")
return train_r2, test_r2
def plot_predictions(self, train_predict, test_predict):
plt.figure(figsize=(14, 8))
plt.plot(self.dates, self.data, label='Actual CSCO Stock Price')
train_predict_plot = np.empty_like(self.data)
train_predict_plot[:, :] = np.nan
train_predict_plot[self.time_step:len(train_predict) + self.time_step, :] = train_predict
test_predict_plot = np.empty_like(self.data)
test_predict_plot[:, :] = np.nan
test_predict_plot[len(train_predict) + (self.time_step * 2) + 1:len(self.data) - 1, :] = test_predict
plt.plot(self.dates, train_predict_plot, label='Training Predictions')
plt.plot(self.dates, test_predict_plot, label='Testing Predictions')
plt.xlabel('Date')
plt.ylabel('CSCO Stock Price')
plt.legend()
plt.show()
def predict_future(self, days_ahead):
last_data = self.scaler.transform(self.data[-self.time_step:])
current_input = last_data.reshape((1, self.time_step, 1))
future_predictions = []
for _ in range(days_ahead):
predicted_price = self.model.predict(current_input)
future_predictions.append(predicted_price[0, 0])
current_input = np.append(current_input[:, 1:, :], predicted_price.reshape(1, 1, 1), axis=1)
future_predictions = self.scaler.inverse_transform(np.array(future_predictions).reshape(-1, 1))
print(future_predictions)
return future_predictions
# Create an instance of the uber class and run the methods
uber = UBER(epochs=50, seed=42
)
uber.fetch_data()
uber.preprocess_data()
uber.build_model()
uber.train_model()
from re import VERBOSE
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import r2_score
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
import tensorflow as tf
import random
class Equinix:
def __init__(self, symbol='EQIX', epochs=50, time_step=100, seed=42):
self.symbol = symbol
self.time_step = time_step
self.epochs = epochs
self.seed = seed
self.scaler = MinMaxScaler(feature_range=(0, 1))
self.model = None
self.data = None
self.dates = None
self.train_data = None
self.test_data = None
self.X_train = None
self.y_train = None
self.X_test = None
self.y_test = None
self.set_seed(seed)
def set_seed(self, seed):
np.random.seed(seed)
random.seed(seed)
tf.random.set_seed(seed)
def fetch_data(self):
stock = yf.Ticker(self.symbol)
historical_data = stock.history(period="max")
self.dates = historical_data.index
self.data = historical_data['Close'].values.reshape(-1, 1)
def preprocess_data(self):
scaled_data = self.scaler.fit_transform(self.data)
train_size = int(len(scaled_data) * 0.7)
self.train_data = scaled_data[:train_size]
self.test_data = scaled_data[train_size:]
self.X_train, self.y_train = self.create_dataset(self.train_data)
self.X_test, self.y_test = self.create_dataset(self.test_data)
self.X_train = self.X_train.reshape(self.X_train.shape[0], self.X_train.shape[1], 1)
self.X_test = self.X_test.reshape(self.X_test.shape[0], self.X_test.shape[1], 1)
def create_dataset(self, dataset):
X, Y = [], []
for i in range(len(dataset) - self.time_step - 1):
a = dataset[i:(i + self.time_step), 0]
X.append(a)
Y.append(dataset[i + self.time_step, 0])
return np.array(X), np.array(Y)
def build_model(self):
self.model = Sequential()
self.model.add(LSTM(40, return_sequences=True, input_shape=(self.time_step, 1)))
self.model.add(Dropout(0.2))
self.model.add(LSTM(40, return_sequences=False))
self.model.add(Dropout(0.3))
self.model.add(Dense(25))
self.model.add(Dense(1))
self.model.compile(optimizer='adam', loss='mean_squared_error')
def train_model(self):
self.model.fit(self.X_train, self.y_train, batch_size=32, epochs=self.epochs)
def predict(self):
train_predict = self.model.predict(self.X_train)
test_predict = self.model.predict(self.X_test)
train_predict = self.scaler.inverse_transform(train_predict)
test_predict = self.scaler.inverse_transform(test_predict)
return train_predict, test_predict
def evaluate(self):
train_predict, test_predict = self.predict()
y_train_orig = self.scaler.inverse_transform(self.y_train.reshape(-1, 1))
y_test_orig = self.scaler.inverse_transform(self.y_test.reshape(-1, 1))
train_r2 = r2_score(y_train_orig, train_predict)
test_r2 = r2_score(y_test_orig, test_predict)
print(f"Train R2 Score: {train_r2}")
print(f"Test R2 Score: {test_r2}")
return train_r2, test_r2
def plot_predictions(self, train_predict, test_predict):
plt.figure(figsize=(14, 8))
plt.plot(self.dates, self.data, label='Actual Equinix Stock Price')
train_predict_plot = np.empty_like(self.data)
train_predict_plot[:, :] = np.nan
train_predict_plot[self.time_step:len(train_predict) + self.time_step, :] = train_predict
test_predict_plot = np.empty_like(self.data)
test_predict_plot[:, :] = np.nan
test_predict_plot[len(train_predict) + (self.time_step * 2) + 1:len(self.data) - 1, :] = test_predict
plt.plot(self.dates, train_predict_plot, label='Training Predictions')
plt.plot(self.dates, test_predict_plot, label='Testing Predictions')
plt.xlabel('Date')
plt.ylabel('Equinix Stock Price')
plt.legend()
plt.show()
def predict_future(self, days_ahead):
last_data = self.scaler.transform(self.data[-self.time_step:])
current_input = last_data.reshape((1, self.time_step, 1))
future_predictions = []
for _ in range(days_ahead):
predicted_price = self.model.predict(current_input)
future_predictions.append(predicted_price[0, 0])
current_input = np.append(current_input[:, 1:, :], predicted_price.reshape(1, 1, 1), axis=1)
future_predictions = self.scaler.inverse_transform(np.array(future_predictions).reshape(-1, 1))
print(future_predictions)
return future_predictions
# Create an instance of the dash class and run the methods
eq = Equinix(epochs=1, seed=42 )
eq.fetch_data()
eq.preprocess_data()
eq.build_model()
eq.train_model()
from re import VERBOSE
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import r2_score
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
import tensorflow as tf
import random
class Ubiquiti:
def __init__(self, symbol='UI', epochs=50, time_step=100, seed=42):
self.symbol = symbol
self.time_step = time_step
self.epochs = epochs
self.seed = seed
self.scaler = MinMaxScaler(feature_range=(0, 1))
self.model = None
self.data = None
self.dates = None
self.train_data = None
self.test_data = None
self.X_train = None
self.y_train = None
self.X_test = None
self.y_test = None
self.set_seed(seed)
def set_seed(self, seed):
np.random.seed(seed)
random.seed(seed)
tf.random.set_seed(seed)
def fetch_data(self):
stock = yf.Ticker(self.symbol)
historical_data = stock.history(period="max")
self.dates = historical_data.index
self.data = historical_data['Close'].values.reshape(-1, 1)
def preprocess_data(self):
scaled_data = self.scaler.fit_transform(self.data)
train_size = int(len(scaled_data) * 0.7)
self.train_data = scaled_data[:train_size]
self.test_data = scaled_data[train_size:]
self.X_train, self.y_train = self.create_dataset(self.train_data)
self.X_test, self.y_test = self.create_dataset(self.test_data)
self.X_train = self.X_train.reshape(self.X_train.shape[0], self.X_train.shape[1], 1)
self.X_test = self.X_test.reshape(self.X_test.shape[0], self.X_test.shape[1], 1)
def create_dataset(self, dataset):
X, Y = [], []
for i in range(len(dataset) - self.time_step - 1):
a = dataset[i:(i + self.time_step), 0]
X.append(a)
Y.append(dataset[i + self.time_step, 0])
return np.array(X), np.array(Y)
def build_model(self):
self.model = Sequential()
self.model.add(LSTM(40, return_sequences=True, input_shape=(self.time_step, 1)))
self.model.add(Dropout(0.2))
self.model.add(LSTM(40, return_sequences=False))
self.model.add(Dropout(0.3))
self.model.add(Dense(25))
self.model.add(Dense(1))
self.model.compile(optimizer='adam', loss='mean_squared_error')
def train_model(self):
self.model.fit(self.X_train, self.y_train, batch_size=32, epochs=self.epochs)
def predict(self):
train_predict = self.model.predict(self.X_train)
test_predict = self.model.predict(self.X_test)
train_predict = self.scaler.inverse_transform(train_predict)
test_predict = self.scaler.inverse_transform(test_predict)
return train_predict, test_predict
def evaluate(self):
train_predict, test_predict = self.predict()
y_train_orig = self.scaler.inverse_transform(self.y_train.reshape(-1, 1))
y_test_orig = self.scaler.inverse_transform(self.y_test.reshape(-1, 1))
train_r2 = r2_score(y_train_orig, train_predict)
test_r2 = r2_score(y_test_orig, test_predict)
print(f"Train R2 Score: {train_r2}")
print(f"Test R2 Score: {test_r2}")
return train_r2, test_r2
def plot_predictions(self, train_predict, test_predict):
plt.figure(figsize=(14, 8))
plt.plot(self.dates, self.data, label='Actual Ubiquiti Stock Price')
train_predict_plot = np.empty_like(self.data)
train_predict_plot[:, :] = np.nan
train_predict_plot[self.time_step:len(train_predict) + self.time_step, :] = train_predict
test_predict_plot = np.empty_like(self.data)
test_predict_plot[:, :] = np.nan
test_predict_plot[len(train_predict) + (self.time_step * 2) + 1:len(self.data) - 1, :] = test_predict
plt.plot(self.dates, train_predict_plot, label='Training Predictions')
plt.plot(self.dates, test_predict_plot, label='Testing Predictions')
plt.xlabel('Date')
plt.ylabel('Ubiquiti Stock Price')
plt.legend()
plt.show()
def predict_future(self, days_ahead):
last_data = self.scaler.transform(self.data[-self.time_step:])
current_input = last_data.reshape((1, self.time_step, 1))
future_predictions = []
for _ in range(days_ahead):
predicted_price = self.model.predict(current_input)
future_predictions.append(predicted_price[0, 0])
current_input = np.append(current_input[:, 1:, :], predicted_price.reshape(1, 1, 1), axis=1)
future_predictions = self.scaler.inverse_transform(np.array(future_predictions).reshape(-1, 1))
print(future_predictions)
return future_predictions
# Create an instance of the dash class and run the methods
ub = Ubiquiti(epochs=1, seed=42 )
ub.fetch_data()
ub.preprocess_data()
ub.build_model()
ub.train_model()
from re import VERBOSE
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import r2_score
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
import tensorflow as tf
import random
class SFL:
def __init__(self, symbol='SFL', epochs=50, time_step=60, seed=42):
self.symbol = symbol
self.time_step = time_step
self.epochs = epochs
self.seed = seed
self.scaler = MinMaxScaler(feature_range=(0, 1))
self.model = None
self.data = None
self.dates = None
self.train_data = None
self.test_data = None
self.X_train = None
self.y_train = None
self.X_test = None
self.y_test = None
self.set_seed(seed)
def set_seed(self, seed):
np.random.seed(seed)
random.seed(seed)
tf.random.set_seed(seed)
def fetch_data(self):
stock = yf.Ticker(self.symbol)
historical_data = stock.history(period="max")
self.dates = historical_data.index
self.data = historical_data['Close'].values.reshape(-1, 1)
def preprocess_data(self):
scaled_data = self.scaler.fit_transform(self.data)
train_size = int(len(scaled_data) * 0.7)
self.train_data = scaled_data[:train_size]
self.test_data = scaled_data[train_size:]
self.X_train, self.y_train = self.create_dataset(self.train_data)
self.X_test, self.y_test = self.create_dataset(self.test_data)
self.X_train = self.X_train.reshape(self.X_train.shape[0], self.X_train.shape[1], 1)
self.X_test = self.X_test.reshape(self.X_test.shape[0], self.X_test.shape[1], 1)
def create_dataset(self, dataset):
X, Y = [], []
for i in range(len(dataset) - self.time_step - 1):
a = dataset[i:(i + self.time_step), 0]
X.append(a)
Y.append(dataset[i + self.time_step, 0])
return np.array(X), np.array(Y)
def build_model(self):
self.model = Sequential()
self.model.add(LSTM(40, return_sequences=True, input_shape=(self.time_step, 1)))
self.model.add(Dropout(0.2))
self.model.add(LSTM(40, return_sequences=False))
self.model.add(Dropout(0.3))
self.model.add(Dense(25))
self.model.add(Dense(1))
self.model.compile(optimizer='adam', loss='mean_squared_error')
def train_model(self):
self.model.fit(self.X_train, self.y_train, batch_size=32, epochs=self.epochs)
def predict(self):
train_predict = self.model.predict(self.X_train)
test_predict = self.model.predict(self.X_test)
train_predict = self.scaler.inverse_transform(train_predict)
test_predict = self.scaler.inverse_transform(test_predict)
return train_predict, test_predict
def evaluate(self):
train_predict, test_predict = self.predict()
y_train_orig = self.scaler.inverse_transform(self.y_train.reshape(-1, 1))
y_test_orig = self.scaler.inverse_transform(self.y_test.reshape(-1, 1))
train_r2 = r2_score(y_train_orig, train_predict)
test_r2 = r2_score(y_test_orig, test_predict)
print(f"Train R2 Score: {train_r2}")
print(f"Test R2 Score: {test_r2}")
return train_r2, test_r2
def plot_predictions(self, train_predict, test_predict):
plt.figure(figsize=(14, 8))
plt.plot(self.dates, self.data, label='Actual SFL Corporation Stock Price')
train_predict_plot = np.empty_like(self.data)
train_predict_plot[:, :] = np.nan
train_predict_plot[self.time_step:len(train_predict) + self.time_step, :] = train_predict
test_predict_plot = np.empty_like(self.data)
test_predict_plot[:, :] = np.nan
test_predict_plot[len(train_predict) + (self.time_step * 2) + 1:len(self.data) - 1, :] = test_predict
plt.plot(self.dates, train_predict_plot, label='Training Predictions')
plt.plot(self.dates, test_predict_plot, label='Testing Predictions')
plt.xlabel('Date')
plt.ylabel('SFL Corporation Stock Price')
plt.legend()
plt.show()
def predict_future(self, days_ahead):
last_data = self.scaler.transform(self.data[-self.time_step:])
current_input = last_data.reshape((1, self.time_step, 1))
future_predictions = []
for _ in range(days_ahead):
predicted_price = self.model.predict(current_input)
future_predictions.append(predicted_price[0, 0])
current_input = np.append(current_input[:, 1:, :], predicted_price.reshape(1, 1, 1), axis=1)
future_predictions = self.scaler.inverse_transform(np.array(future_predictions).reshape(-1, 1))
print(future_predictions)
return future_predictions
# Create an instance of the dash class and run the methods
sfl = SFL(epochs=1, seed=42 )
sfl.fetch_data()
sfl.preprocess_data()
sfl.build_model()
sfl.train_model()
from re import VERBOSE
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import r2_score
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
import tensorflow as tf
import random
class ELA :
def __init__(self, symbol='ELA', epochs=50, time_step=100, seed=42):
self.symbol = symbol
self.time_step = time_step
self.epochs = epochs
self.seed = seed
self.scaler = MinMaxScaler(feature_range=(0, 1))
self.model = None
self.data = None
self.dates = None
self.train_data = None
self.test_data = None
self.X_train = None
self.y_train = None
self.X_test = None
self.y_test = None
self.set_seed(seed)
def set_seed(self, seed):
np.random.seed(seed)
random.seed(seed)
tf.random.set_seed(seed)
def fetch_data(self):
stock = yf.Ticker(self.symbol)
historical_data = stock.history(period="max")
self.dates = historical_data.index
self.data = historical_data['Close'].values.reshape(-1, 1)
def preprocess_data(self):
scaled_data = self.scaler.fit_transform(self.data)
train_size = int(len(scaled_data) * 0.7)
self.train_data = scaled_data[:train_size]
self.test_data = scaled_data[train_size:]
self.X_train, self.y_train = self.create_dataset(self.train_data)
self.X_test, self.y_test = self.create_dataset(self.test_data)
self.X_train = self.X_train.reshape(self.X_train.shape[0], self.X_train.shape[1], 1)
self.X_test = self.X_test.reshape(self.X_test.shape[0], self.X_test.shape[1], 1)
def create_dataset(self, dataset):
X, Y = [], []
for i in range(len(dataset) - self.time_step - 1):
a = dataset[i:(i + self.time_step), 0]
X.append(a)
Y.append(dataset[i + self.time_step, 0])
return np.array(X), np.array(Y)
def build_model(self):
self.model = Sequential()
self.model.add(LSTM(40, return_sequences=True, input_shape=(self.time_step, 1)))
self.model.add(Dropout(0.3))
self.model.add(LSTM(40, return_sequences=False))
self.model.add(Dropout(0.3))
self.model.add(Dense(25))
self.model.add(Dense(1))
self.model.compile(optimizer='adam', loss='mean_squared_error')
def train_model(self):
self.model.fit(self.X_train, self.y_train, batch_size=32, epochs=self.epochs)
def predict(self):
train_predict = self.model.predict(self.X_train)
test_predict = self.model.predict(self.X_test)
train_predict = self.scaler.inverse_transform(train_predict)
test_predict = self.scaler.inverse_transform(test_predict)
return train_predict, test_predict
def evaluate(self):
train_predict, test_predict = self.predict()
y_train_orig = self.scaler.inverse_transform(self.y_train.reshape(-1, 1))
y_test_orig = self.scaler.inverse_transform(self.y_test.reshape(-1, 1))
train_r2 = r2_score(y_train_orig, train_predict)
test_r2 = r2_score(y_test_orig, test_predict)
print(f"Train R2 Score: {train_r2}")
print(f"Test R2 Score: {test_r2}")
return train_r2, test_r2
def plot_predictions(self, train_predict, test_predict):
plt.figure(figsize=(14, 8))
plt.plot(self.dates, self.data, label='Actual Envela Corporation Stock Price')
train_predict_plot = np.empty_like(self.data)
train_predict_plot[:, :] = np.nan
train_predict_plot[self.time_step:len(train_predict) + self.time_step, :] = train_predict
test_predict_plot = np.empty_like(self.data)
test_predict_plot[:, :] = np.nan
test_predict_plot[len(train_predict) + (self.time_step * 2) + 1:len(self.data) - 1, :] = test_predict
plt.plot(self.dates, train_predict_plot, label='Training Predictions')
plt.plot(self.dates, test_predict_plot, label='Testing Predictions')
plt.xlabel('Date')
plt.ylabel('Envela Corporation Stock Price')
plt.legend()
plt.show()
def predict_future(self, days_ahead):
last_data = self.scaler.transform(self.data[-self.time_step:])
current_input = last_data.reshape((1, self.time_step, 1))
future_predictions = []
for _ in range(days_ahead):
predicted_price = self.model.predict(current_input)
future_predictions.append(predicted_price[0, 0])
current_input = np.append(current_input[:, 1:, :], predicted_price.reshape(1, 1, 1), axis=1)
future_predictions = self.scaler.inverse_transform(np.array(future_predictions).reshape(-1, 1))
print(future_predictions)
return future_predictions
# Create an instance of the dash class and run the methods
ela = ELA (epochs=1, seed=42 )
ela.fetch_data()
ela.preprocess_data()
ela.build_model()
ela.train_model()
import matplotlib.pyplot as plt
import gradio as gr
from datetime import datetime
def date_to_days(date_str):
try:
target_date = datetime.strptime(date_str, '%Y-%m-%d')
except ValueError:
return None, "Date format should be YYYY-MM-DD"
current_date = datetime.now()
return (target_date - current_date).days + 1, None
def compare_models(date, money):
input_data, error = date_to_days(date)
if error:
return None, error
if input_data <= 0:
return None, "The date must be in the future."
uber_prediction = uber.predict_future(input_data)
eq_prediction = eq.predict_future(input_data)
ub_prediction = ub.predict_future(input_data)
sfl_prediction = sfl.predict_future(input_data)
ela_prediction = ela.predict_future(input_data)
uber_current = uber.predict_future(1)
eq_current =eq.predict_future(1)
ub_current = ub.predict_future(1)
sfl_current =sfl.predict_future(1)
ela_current = ela.predict_future(1)
available = []
if uber_current[-1][0] <= money:
available.append("Uber")
if eq_current[-1][0] <= money:
available.append("Equinix")
if ub_current[-1][0] <= money:
available.append("Ubiquiti")
if sfl_current[-1][0] <= money:
available.append("SFL Corporation")
if ela_current[-1][0] <= money:
available.append("Envela Corporation")
predictions = {}
av=[]
if "Uber" in available :
uber_stocks = money / uber_current[-1][0]
if (uber_prediction[-1][0] - uber_current[-1][0]) * uber_stocks >0 :
predictions["Uber"] = (uber_prediction[-1][0] - uber_current[-1][0]) * uber_stocks
av.append("Uber")
if "Equinix" in available :
eq_stocks = money / eq_current[-1][0]
if (eq_prediction[-1][0] - eq_current[-1][0]) * eq_stocks >0 :
av.append("Equinix")
predictions["Equinix"] = (eq_prediction[-1][0] - eq_current[-1][0]) * eq_stocks
if "Ubiquiti" in available :
ub_stocks = money / ub_current[-1][0]
if (ub_prediction[-1][0] - ub_current[-1][0]) * ub_stocks >0 :
av.append("Ubiquiti")
predictions["Ubiquiti"] = (ub_prediction[-1][0] - ub_current[-1][0]) * ub_stocks
if "SFL Corporation" in available :
sfl_stocks = money / sfl_current[-1][0]
if (sfl_prediction[-1][0] - sfl_current[-1][0]) * sfl_stocks >0 :
av.append("SFL Corporation")
predictions["SFL Corporation"] = (sfl_prediction[-1][0] - sfl_current[-1][0]) * sfl_stocks
if "Envela Corporation" in available :
ela_stocks = money / ela_current[-1][0]
if (ela_prediction[-1][0] - ela_current[-1][0]) * ela_stocks >0 :
av.append("Envela Corporation")
predictions["Envela Corporation"] = (ela_prediction[-1][0] - ela_current[-1][0]) * ela_stocks
pr = {
"Uber":"Industry: Transportation Technology \nHeadquarters: San Francisco, California, USA \nFounded: 2009 \nKey Products: Ride-hailing, Uber Eats (food delivery), Uber Freight, micro-mobility solutions (electric bikes and scooters), and autonomous vehicle technology. \nOverview: Uber Technologies, Inc. is a global transportation and mobility company known for revolutionizing the ride-hailing industry. It connects passengers with drivers through a mobile app, offering convenient and reliable transportation services. Uber has expanded its offerings to include food delivery, freight transportation, and micro-mobility solutions.",
"Equinix":"Industry: Data Centers and Colocation \nHeadquarters: Redwood City, California, USA \nFounded: 1998 \nKey Products: Data center services, interconnection solutions, hybrid cloud infrastructure, and colocation. \nOverview: Equinix, Inc. is a leading provider of data center and interconnection services, operating a global network of interconnected data centers. Equinix helps businesses securely house their IT infrastructure and connect with partners and customers, offering robust and scalable solutions for digital transformation and cloud adoption.",
"Ubiquiti":"Industry: Networking Technology \nHeadquarters: New York, New York, USA \nFounded: 2005 \nKey Products/Services: Wireless networking products, wired networking products, UniFi (Wi-Fi systems), EdgeMax (routers and switches), airMAX (wireless communication), and AmpliFi (home Wi-Fi systems). \nOverview: is known for its high-performance networking products that cater to both enterprises and consumers. With a focus on wireless and wired networking solutions, Ubiquiti offers innovative and cost-effective products, including Wi-Fi access points, routers, and switches, as well as advanced network management software.",
"SFL Corporation":"Industry:Shipping and Maritime \nHeadquarters: Hamilton, Bermuda \nFounded: 2003 \nKey Products/Services: Ownership and chartering of vessels, including tankers, bulk carriers, container ships, and offshore assets. \nOverview: SFL Corporation Ltd. is an international ship owning and chartering company with a diverse fleet of vessels. The company focuses on securing long-term charters with reputable counterparties, ensuring stable revenue streams. SFL Corporation's diversified fleet and strategic partnerships position it as a significant player in the global shipping industry.",
"Envela Corporation":"Industry: Precious Metals, Retail, and Recycling \nHeadquarters: Dallas, Texas, USA \nFounded: 1965 \nKey Products/Services: Buying and selling precious metals, jewelry, rare coins, watches, electronic device recycling, and retail operations. \nOverview: Envela Corporation is a diversified holding company engaged in the precious metals, retail, and recycling sectors. Through its subsidiaries, Envela buys, sells, and trades precious metals and operates retail locations for jewelry and rare items. The company also focuses on electronic device recycling, promoting environmental sustainability and resource management.",
}
best_stock=None
best_prediction=None
if not available:
return None, "There are no available stocks, you need to increase your budget to start your $park."
if not predictions:
return None, f"The current options are not ideal for investment. We recommend using the \"Saving\" section at this time."
seed_value = hash((date, money))
random.seed(seed_value)
best_stock = random.choice(av)
best_profit = predictions[best_stock]
best_prediction = f"Best stock company is {best_stock} with profit approximately {best_profit:.2f} $ and your total money is {best_profit + money:.2f} $\n{pr[best_stock]}"
return best_stock, best_prediction
def plot_for_user(stock_name, future_days):
stock = None
if stock_name == "Uber":
stock = uber
elif stock_name == "Equinix":
stock = eq
elif stock_name == "Ubiquiti":
stock = ub
elif stock_name == "SFL Corporation":
stock = sfl
elif stock_name == "Envela Corporation":
stock = ela
plt.figure(figsize=(12, 8))
plt.plot(stock.dates, stock.data )
plt.xlabel('Date')
plt.ylabel(f'{stock_name} company Stock Price')
plt.legend()
return plt.gcf()
def combined_function(date, money):
img = plt.imread('haga.jpeg')
plt.imshow(img)
plt.axis('off')
im = plt.gcf()
plt.close(im)
if money <= 0:
return "Budget must be greater than 0", im
best_stock, best_prediction = compare_models(date, money)
if best_stock:
plot = plot_for_user(best_stock,date)
return best_prediction, plot
else:
return best_prediction, im
with gr.Blocks() as demo:
gr.Markdown("""*<span style="color: green; font-style: normal;">Welcome to Investment Prediction page 💰</span>*\n
Enter the date and the amount you intend to invest.""")
inp=[
gr.Textbox(label="Future Date", placeholder="Enter date in YYYY-MM-DD format", lines=1),
gr.Number(label="Budget ($)", value =1 , precision=2)
]
bt=gr.Button("sumbit")
out=[
gr.Textbox(label="Investment Prediction"),
gr.Plot()
]
bt.click(combined_function , inp , out)
gr.Markdown("""*you can visit this links for more informations about company stocks and to start your first $park*
https://www.mubashertrade.com/
https://thndr.app/?gad_source=1&gclid=CjwKCAjwp4m0BhBAEiwAsdc4aIjM1zvbewSMYH4d77o29joJv2JHylodhfZh22nfHZgS_-Tm3hWkHxoCtUwQAvD_BwE
""")
demo.launch(debug=True , share=True)