Skip to content

carlosaadames/EWMA-Example

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

41 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Stock Dashboard

Stock Image

Deployment: https://stocks-dashboard-qz33.onrender.com/

Phase 1: Requirements & Analysis

Goal

The primary goal of this application is to provide users with a simple and interactive tool to visualize historical stock data, including technical indicators like Exponential Moving Averages (EMAs).

Features

  • Allow users to specify a ticker symbol (e.g., MSFT, AAPL, BTC-USD, etc).
  • Allow users to select a historical time period for the data (e.g., 1 year, 5 years).
  • Allow users to configure the window sizes for short-term and long-term EMAs.
  • Display a candlestick chart of the stock's price history.
  • Overlay the short-term and long-term EMAs on the chart.
  • Volatility option.

Target Audience

  • Anyone interested in basic technical analysis of stock trends.

Phase 2: High-Level Architecture

The application follows a classic client-server architecture.

Frontend (Client)

  • Technology: Single-Page Application (SPA) built with React.
  • Core Libraries:
    • axios: For making HTTP requests to the backend API.
    • plotly.js & react-plotly.js: For rendering interactive charts.
  • Responsibility: Renders the user interface, captures user input, communicates with the backend API, and displays the returned chart data.

Backend (Server)

  • Technology: Python web server with Flask.
  • Core Libraries:
    • yfinance: To fetch historical stock data from Yahoo Finance.
    • pandas: For data manipulation and calculating technical indicators.
    • plotly: To create the chart figure object.
    • gunicorn: As the WSGI server for running the application in production (indicated by the Procfile).
  • Responsibility: Exposes a single API endpoint to receive user parameters, fetches the relevant data, performs calculations, generates a chart object, and returns it to the frontend. It also serves the static files for the built React application.

Phase 3: Detailed API Design

The backend exposes a single endpoint to generate and retrieve stock chart data.

  • Endpoint: /get_stock_data

  • Method: POST

  • Request Body (JSON):

    {
      "stock_symbol": "string",
      "selected_period": "string",
      "short_window": "integer",
      "long_window": "integer",
      "show_volatility": "bool",
      "volatility_window": "integer"
    }
    • stock_symbol: The ticker symbol for the stock (e.g., "MSFT").
    • selected_period: A string representing the time period, compatible with yfinance (e.g., "1y", "5d", "max").
    • short_window: An integer for the short-term EMA window size.
    • long_window: An integer for the long-term EMA window size.
    • show_volatility: A boolean for option to display volatility.
    • volatility_window: An integer for the volatility window size.
  • Response Body (JSON):

    • On Success (200 OK): The response is a JSON object representing a Plotly figure. This object can be directly passed to the react-plotly.js component on the frontend.
      {
        "data": [
          {
            "type": "candlestick",
            "name": "Candlestick",
            "x": ["2023-01-01", ...],
            "open": [150.00, ...],
            "high": [152.50, ...],
            "low": [149.00, ...],
            "close": [151.75, ...]
          },
          {
            "type": "scatter",
            "mode": "lines",
            "name": "10-EWMA",
            "x": ["2023-01-01", ...],
            "y": [150.50, ...]
          },
          ...
        ],
        "layout": {
          "title": "MSFT Candlestick Plot with Exponential Moving Average Crossover",
          "xaxis_title": "Date",
          "yaxis_title": "Price in $",
          ...
        }
      }

Phase 4: Implementation

Implementation Details

  • Backend: The Flask app defines the /get_stock_data route. Inside this route, it retrieves the JSON payload, calls the yfinance library to get data, uses pandas .ewm().mean() to calculate the moving averages, and then constructs a go.Figure object from the plotly library. This figure is then converted to a JSON-serializable dictionary and returned.
  • Frontend: The main App.js component uses React hooks (useState) to manage the state of the input fields. When the "Refresh Visual" button is clicked, the handleSubmit function makes an async axios.post call to the backend. The response data is then stored in the graphData state variable, triggering a re-render of the <Plot> component with the new data.

Phase 5: Deployment & Operations

Deployment

  • The presence of a Procfile with a gunicorn command indicates that the application is designed for deployment on a PaaS.
  • The deployment workflow is:
    1. Install frontend dependencies (npm install).
    2. Build the static React application (npm run build). This creates an optimized set of files in frontend/build.
    3. Install backend dependencies (pip install -r requirements.txt).
    4. Start the Gunicorn server, which runs the Flask app. The Flask app is configured to serve the static files from frontend/build as well as handle API requests.

Operations

  • The application is dependent on the external Yahoo Finance API. Any downtime or changes to this API will affect the application.
  • The application is stateless, simplifying scaling and management.

Phase 6: Running the Application Locally

Prerequisites

  • Python 3.x
  • Node.js and npm

Backend Setup

  1. Create a virtual environment:

    python3 -m venv venv
    source venv/bin/activate
  2. Install dependencies:

    pip install -r backend/requirements.txt

Frontend Setup

  1. Install dependencies:
    npm install --prefix frontend

Backend

  1. Start the server:
    python3 backend/app.py
    The backend server will start on http://localhost:10000.

Frontend

  1. Start the development server:
    npm start --prefix frontend
    The frontend development server will start on http://localhost:3000 and will proxy API requests to the backend.

How to use

  1. Refresh Visualization: Click the "Refresh Visual" button to update the graph with the selected parameters.

  2. Select a Stock and Time Period: Use the dropdown menus and input fields to choose a stock symbol (e.g., AAPL for Apple Inc.) and a time period for analysis (e.g., 1 year).

  3. Specify EWMA Windows: Input the number of days for the short-term and long-term EWMA windows to tailor the analysis to your trading strategy.

  4. Analyze Volatility: Optionally, enable the volatility plot and set the rolling window to visualize the stock's volatility over time.

  5. Analyze Signals: Observe the Up (green triangles) and Down (red triangles) signals on the stock chart based on EWMA crossovers.

EWMA Strategy

The Exponential Weighted Moving Average (EWMA) is a type of moving average that places a greater weight and significance on the most recent data points. The application uses EWMA crossover points as signals for potential buying or selling opportunities:

  1. Upward Trend signal:

    • Generated when the short-term EWMA crosses above the long-term EWMA, indicating an upward trend.
  2. Downward Trend signal:

    • Generated when the short-term EWMA crosses below the long-term EWMA, indicating a downward trend.

This strategy helps traders identify moments when a stock's momentum is changing, potentially offering opportunities for profitable trades.

EWMA(t) = α * C(t) + (1 - α) * EWMA(t - 1)

Where:

EWMA(t) = Exponential Weighted Moving Average at time t

C(t) = Closing price at time t

EWMA(t - 1) = Exponential Weighted Moving Average at time t-1

α = 2 / (N + 1)

N = number of days in the moving average period.

About

Example for stock dashboard using Python, JavaScript and other complementary tools.

Topics

Resources

Stars

Watchers

Forks

Contributors