Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 5 additions & 33 deletions AI-InvestiBot/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -240,36 +239,14 @@ 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"""
return len(set(arr.dtype for arr in arr.flatten())) == 1

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.

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
8 changes: 2 additions & 6 deletions AI-InvestiBot/test.py
Original file line number Diff line number Diff line change
@@ -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


Expand Down Expand Up @@ -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 = []
Expand Down
28 changes: 27 additions & 1 deletion AI-InvestiBot/trading_funcs.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

__all__ = (
'non_daily',
Expand All @@ -42,7 +43,8 @@
'supertrends',
'kumo_cloud',
'is_floats',
'calculate_percentage_movement_together'
'calculate_percentage_movement_together',
'plot'
)


Expand Down Expand Up @@ -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()
26 changes: 7 additions & 19 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand All @@ -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`).
Expand All @@ -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.
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pandas==2.0.1
pandas_market_calendars==4.1.4
yfinance==0.2.18
tensorflow==2.13.0
scikit-learn==1.2.2
scikit-learn==1.3.2
bs4==0.0.1
boto3==1.26.152
alpaca_trade_api==3.0.2