Skip to content

luka443/ForexTradingApp

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

58 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

ForexTradingApp

Clone the Repository:

git clone https://github.com/yourusername/your-repo.git
cd your-repo

Install Dependencies:

pip install Flask yfinance matplotlib torch

Run the Application:

python app.py

The application will be accessible at http://127.0.0.1:5000/ in your web browser.

Usage

Homepage (/)
    Users can input a stock symbol using a form.
    The app provides stock information, including the current price, changes, and volume.
    Historical stock price plots for the last month and year are displayed.
    Predictions generated by the LSTM model for different time periods are shown.

Functions

train_model(ticker)
    Downloads and prepares stock data for the given stock symbol (ticker) using the download_and_strip_data and prepare_dataframe_for_lstm functions.
    Trains an LSTM model (model) using the prepared data.
    Saves the trained model to a file in the models directory with the format {ticker}_model.pth.
    Returns the trained model.

check_and_return_model(ticker)
    Checks if a trained model exists for the given stock symbol (ticker) in the models directory.
    If the model exists, loads and returns it; otherwise, trains a new model using train_model.
    Returns the trained or loaded model.

get_predicted_plots(model, ticker, period)
    Downloads and prepares stock data for the given stock symbol (ticker) and time period using the download_and_strip_data and prepare_dataframe_for_lstm functions.
    Prepares data for prediction using the prepering_for_prediction function.
    Generates and returns a plot of predicted stock prices using the predict_and_plot function.

get_prediction(model, ticker)
    Downloads and prepares stock data for the given stock symbol (ticker) using the download_and_strip_data and prepare_dataframe_for_lstm functions.
    Prepares data for prediction using the prepering_for_prediction function.
    Returns the predicted stock price for the next day.

get_current_price(ticker)
    Uses the yfinance library to fetch the current price of the given stock symbol (ticker).
    Returns the current stock price.

plot_stock_price(ticker_symbol, period)
    Uses the yfinance library to fetch historical stock data for the given stock symbol (ticker_symbol) and time period.
    Creates a plot of stock prices and saves it as a base64-encoded image.
    Returns the HTML code to display the plot.

get_stock_info(tickers)
    Fetches current stock information for a list of stock symbols (tickers) using the yfinance library.
    Returns a list of lists containing stock information (symbol, company name, current price, change in dollars, change in percentage, and volume).
    
download_and_strip_data(stock, period)

    Downloads historical stock price data using the yfinance library for the given stock symbol (stock) and time period (period).
    Saves the downloaded data as a CSV file and reads it back, extracting only the 'Date' and 'Close' columns.
    Returns the cleaned dataframe.

prepare_dataframe_for_lstm(df)

    Takes a dataframe (df) containing 'Date' and 'Close' columns.
    Creates lag features for the 'Close' column, representing past values.
    Drops rows with missing values and scales the dataframe using Min-Max scaling between -1 and 1.
    Returns the scaled numpy array and the scaler used.

preparing_and_splitting(shifted_df_as_np)

    Takes the scaled numpy array (shifted_df_as_np) returned from prepare_dataframe_for_lstm.
    Extracts features (X) and target variable (y).
    Flips the array along the time axis, reshapes it, and splits it into training and testing datasets (95:5 ratio).
    Reshapes the data into the required format for LSTM.
    Converts data to PyTorch tensors.
    Returns the preprocessed data for training and testing.

preparing_and_splitting2(shifted_df_as_np)

    Similar to preparing_and_splitting but only used for obtaining data for prediction.
    Reshapes the data into the required format for LSTM.
    Converts data to PyTorch tensors.
    Returns the preprocessed data for prediction.

preparing_for_prediction(shifted_df_as_np)

    Takes the scaled numpy array (shifted_df_as_np) returned from prepare_dataframe_for_lstm.
    Extracts features.
    Flips the array along the time axis, reshapes it, and converts it to a PyTorch tensor.
    Returns the preprocessed data for making predictions.


get_loaders(X_train, y_train, X_test, y_test)

    Takes the preprocessed training and testing data.
    Creates PyTorch data loaders using the TimeSeriesDataset class.
    Returns the training and testing data loaders.


train_one_epoch(model, train_loader, optimizer, loss_function, epoch)

    Trains the LSTM model for one epoch using the training data.
    Prints the average loss across batches during training.

validate_one_epoch(model, test_loader, loss_function)

    Validates the LSTM model using the testing data.
    Computes and returns the average loss across batches during validation.

train_and_validate(model, train_loader, test_loader)

    Combines training and validation processes for the LSTM model.
    Saves the trained model to a file after training.

save_model(model, name)

    Saves the PyTorch model to a file in the models directory.
    The file name is constructed using the provided name.

load_model(ticker)

    Loads a previously saved PyTorch model for a given stock symbol (ticker).
    Returns the loaded model.

predict_and_plot(model, X, y, scaler)

    Makes predictions using the trained LSTM model and plots the actual vs. predicted stock prices.
    Returns the base64-encoded image of the plot.

predict(model, X, scaler)

    Makes predictions using the trained LSTM model.
    Returns the predicted stock prices.

Routes

/ - Homepage (index function)
    Displays a form for entering a stock symbol.
    Shows stock information, historical stock price plots, and LSTM model predictions.
    Updates dynamically based on user input or default stock symbols.

External Libraries Used

Flask: Web application framework for Python.
yfinance: Fetches stock market data.
Matplotlib: Creates plots.
torch: PyTorch library for machine learning.

Test1:

Checks if the function correctly fetches data and processes it into a DataFrame, as well as generates a CSV file with the correct name.
Test categories:

Calling the function with valid data.
Verifying if the result is a DataFrame with the appropriate columns.
Checking if the CSV file has been created.
Test description:

The function is called with sample data (stock symbol and time period).
It is verified whether the result is a DataFrame.
It is checked whether the DataFrame contains the 'Date' and 'Close' columns.
It is confirmed whether the CSV file has been created in the appropriate location.
After the test, the CSV file is removed.

Test4:

Tests the save_model function from the model_trainer module.
The test checks whether the function correctly saves the model to a file on disk.
Test categories:

Creating a sample model.
Calling the function to save the model.
Verifying if the model file has been created on disk.
Test description:

A sample LSTM model with specified parameters is created.
The save_model function is called with the model and the model name.
It is verified whether the model file has been created in the appropriate location.
After the test, the model file is removed.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published