diff --git a/AI-InvestiBot/models.py b/AI-InvestiBot/models.py index ee2ca7e..858eb00 100644 --- a/AI-InvestiBot/models.py +++ b/AI-InvestiBot/models.py @@ -78,10 +78,10 @@ class BaseModel: information_keys (List[str]): The information keys that describe what the model uses """ - def __init__(self, start_date: str = None, + def __init__(self, start_date: Optional[Union[date, str]] = None, end_date: Optional[Union[date, str]] = None, - stock_symbol: Optional[Union[date, str]] = "AAPL", - num_days: int = None, + stock_symbol: str = "AAPL", + num_days: Optional[int] = None, information_keys: List[str]=["Close"]) -> None: if num_days is None: with open(f'Stocks/{stock_symbol}/dynamic_tuning.json', 'r') as file: @@ -154,7 +154,6 @@ def train(self, epochs: int=1000, stock_symbol = self.stock_symbol information_keys = self.information_keys num_days = self.num_days - print(start_date, end_date) #_________________ GET Data______________________# _, data, self.scaler_data = get_relavant_values( @@ -240,28 +239,6 @@ def save(self, transfer_learning: bool=False, name: Optional[str]=None) -> None: with open(f"Stocks/{self.stock_symbol}/min_max_data.json", "w") as json_file: json.dump(self.scaler_data, json_file) - @staticmethod - def plot(data): - """Plots any np.array that you give in""" - days_train = [i for i in range(data.shape[0])] - data = data[:, 0] - # Plot the actual and predicted prices - plt.figure(figsize=(18, 6)) - - predicted_test = plt.plot(days_train, data, label='Predicted Test') - plt.title(f'TITLE') - plt.xlabel("X") - plt.ylabel("Y") - - import matplotlib.ticker as ticker - plt.gca().xaxis.set_major_locator(ticker.MaxNLocator(7)) - - plt.legend( - [predicted_test[0]],#[real_data, actual_test[0], actual_train], - ['Data']#['Real Data', 'Actual Test', 'Actual Train'] - ) - plt.show() - @staticmethod def is_homogeneous(arr) -> bool: """Checks if any of the models indicators are missing""" @@ -269,7 +246,7 @@ def is_homogeneous(arr) -> bool: def test(self, time_shift: int=0, show_graph: bool=False, title: str="Stock Price Prediction", x_label: str='', y_label: str='Price' - ) -> None: + ) -> Tuple[float, float, float, float, bool]: """ A method for testing purposes. @@ -670,10 +647,7 @@ def predict(self, info: Optional[np.ndarray] = None) -> np.ndarray: class PriceModel(BaseModel): """ - This is the base class for all the models. It handles the actual training, saving, - loading, predicting, etc. Setting the `information_keys` allows us to describe what - the model uses. The information keys themselves are retrieved from a json format - that was created by getInfo.py. + This is the model to predict the price. It is not very good. Use the other one Args: start_date (str): The start date of the training data @@ -852,8 +826,6 @@ def update_cached_offline(self) -> None: scaled_data[0] = scaled_window self.cached = scaled_data - #self.plot(self.cached[0][0]) - def profit(self, pred, prev): return pred diff --git a/AI-InvestiBot/test.py b/AI-InvestiBot/test.py index 0209c76..ea7ea97 100644 --- a/AI-InvestiBot/test.py +++ b/AI-InvestiBot/test.py @@ -1,14 +1,10 @@ from models import * -from datetime import datetime, date -from dateutil.relativedelta import relativedelta -import json - from pandas_market_calendars import get_calendar import pandas as pd import numpy as np -from trading_funcs import create_sequences, get_relavant_values +from trading_funcs import create_sequences, get_relavant_values, plot from typing import List @@ -46,7 +42,7 @@ def test_indepth(models: List[BaseModel], hold_stocks=False): temp_test, expected = model.process_x_y_total(temp, temp2, model.num_days, 0) print(temp_test.shape) for t in temp_test: - model.plot(t[:, 0]) + plot(t[:, 0]) processed_data.append(temp_test) percent_made = 1 bought_at = [] diff --git a/AI-InvestiBot/trading_funcs.py b/AI-InvestiBot/trading_funcs.py index 4aea0eb..1c9de99 100644 --- a/AI-InvestiBot/trading_funcs.py +++ b/AI-InvestiBot/trading_funcs.py @@ -26,6 +26,7 @@ import numpy as np import pandas as pd +import matplotlib.pyplot as plt __all__ = ( 'non_daily', @@ -42,7 +43,8 @@ 'supertrends', 'kumo_cloud', 'is_floats', - 'calculate_percentage_movement_together' + 'calculate_percentage_movement_together', + 'plot' ) @@ -491,3 +493,27 @@ def calculate_percentage_movement_together(list1: Iterable, list2: Iterable) -> percentage = (count_same_direction / (total - 1)) * 100 percentage2 = (count_same_space / (total - 1)) * 100 return percentage, percentage2 + +def plot(data): + """ + Plots any np.array that you give in + Purely for testing + """ + days_train = [i for i in range(data.shape[0])] + data = data[:, 0] + # Plot the actual and predicted prices + plt.figure(figsize=(18, 6)) + + predicted_test = plt.plot(days_train, data, label='Predicted Test') + plt.title(f'TITLE') + plt.xlabel("X") + plt.ylabel("Y") + + import matplotlib.ticker as ticker + plt.gca().xaxis.set_major_locator(ticker.MaxNLocator(7)) + + plt.legend( + [predicted_test[0]], + ['Data'] + ) + plt.show() diff --git a/README.md b/README.md index 2cce6e7..83b2725 100644 --- a/README.md +++ b/README.md @@ -76,26 +76,15 @@ P.S: Remember to change the api and secret key in secrets.config. The project retrieves and caches information in the following manner: - The `get_info.py` file processes all data obtained from yfinance. -- The information is stored as a dictionary in a JSON file. -- The `information_keys` feature retrieves values from each key in the JSON. - -## Unique Indicators in Models - -The models in this project incorporate unique indicators as follows: - -- Models utilize the `information_keys` attribute. -- These keys correspond to the names of indicators created from `get_info.py`. -- The model retrieves a dictionary from the JSON file and extracts the list associated with the key. -- Features in the form of NumPy arrays are then fed into the Sequential model. -- Use different Features by inputing a list of information_keys into either `PriceModel` or `PercentageModel` +- The information is stored as a dictionary in a JSON file, according to indicator. +- The `information_keys` feature retrieves values from each key(indicator) in the JSON. ## Stock Bot Functionality The stock bot operates based on the following principles: - - -- The AI is implemented into the childclasses of `BaseModel`. + - Base Model: This is the parent class for all other models and has no data of its own unless specified. Holds functionality for bot NOT AI. +- The AI is implemented into the childclasses of `BaseModel`. - Price Model: This is the base child class that uses data scaled btw high and low of company data and outputs the predicted price - Percentage Model: This is the base child class that uses data scaled btw high and low of a window of data(the past num days) and outputs the predicted % change in price - Training, testing, saving, and loading are handled by separate functions(Ensuring quality code). @@ -108,9 +97,6 @@ The stock bot operates based on the following principles: - Utilizes data from yfinance. - Once 280 days of past data are obtained, the oldest day is removed, and a new day is added at the end. - In this case, `model.cached_info` is always a pandas DataFrame or None. - -## How the Bot Runs - - The bot identifies the most promising stocks. - It utilizes your available funds, following the rules set by the `ResourceManager` class. - Stocks are held if their performance exceeds a certain threshold (`MAX_HOLD_INDEX`). @@ -122,7 +108,7 @@ The stock bot operates based on the following principles: ## Earnings Processing -The project processes earnings in the following manner: +The project processes earnings in the following manner becuase it is not daily data: - All earnings are obtained and separated into two lists: dates and the difference between actual and estimated values. - During runtime, earnings outside of a specific range are removed. @@ -142,6 +128,8 @@ This project offers various models to choose from, including: - Price Model: This is the base class that uses data scaled btw high and low of company data and outputs the predicted price - Percentage Model: This is the base class that uses data scaled btw high and low of the window data and outputs the predicted % change in price +## For Percentage Model(Price model is not accurate) + - Day Trade Model: - Directional Test: 97.88732394366197 - Spatial Test: 95.07042253521126 diff --git a/requirements.txt b/requirements.txt index 82f6359..0d32769 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,5 +1,5 @@ numpy==1.24.3 -matplotlib==3.7.1 +matplotlib==3.7.4 pandas==2.0.1 pandas_market_calendars==4.1.4 yfinance==0.2.18