Machine Learning Model
Relevant source files
The following files were used as context for generating this wiki page: - [backend/ml_model.py](https://github.com/asixham/greenline/blob/HEAD/backend/ml_model.py) - [client/src/components/StockSummary/index.tsx](https://github.com/asixham/greenline/blob/HEAD/client/src/components/StockSummary/index.tsx) - [client/src/components/TickerChat/index.tsx](https://github.com/asixham/greenline/blob/HEAD/client/src/components/TickerChat/index.tsx) - [client/src/app/quote/[ticker]/page.tsx](https://github.com/asixham/greenline/blob/HEAD/client/src/app/quote/%5Bticker%5D/page.tsx) - [client/package.json](https://github.com/asixham/greenline/blob/HEAD/client/package.json) - [client/src/components/Hero/index.tsx](https://github.com/asixham/greenline/blob/HEAD/client/src/components/Hero/index.tsx)The Greenline application leverages machine learning through two primary avenues: a backend time-series forecasting service for price prediction and frontend-integrated Natural Language Processing (NLP) for generating textual insights. The backend uses the Prophet library to forecast stock prices, while the frontend communicates directly with the OpenAI API to power features like AI-driven summaries and interactive chats.
This dual approach provides both quantitative predictions and qualitative, human-readable analysis. The forecasting model is exposed via a dedicated API endpoint, while the NLP features are implemented within specific React components on the client side.
Sources: backend/ml_model.py, client/src/components/StockSummary/index.tsx, client/src/components/TickerChat/index.tsx, client/src/components/Hero/index.tsx:180-186
Time-Series Forecasting API
The backend provides a stock price forecasting service built with FastAPI and the Prophet library. It exposes a single endpoint, /forecast/, that accepts historical stock data and returns a price forecast for a specified number of days.
Sources: backend/ml_model.py
Architecture and Data Flow
The forecasting process is initiated when a client sends a POST request with historical stock data to the /forecast/ endpoint. The server processes this data, trains a Prophet model, generates a forecast, and returns the prediction along with confidence intervals and performance metrics.
The following diagram illustrates the data flow for a forecast request.
Sources: backend/ml_model.py:53-128
API Endpoint: POST /forecast/
This endpoint is responsible for generating stock price predictions.
| Property | Description |
|---|---|
| Method | POST |
| Path | /forecast/ |
| Request Body | ForecastRequest JSON object. |
| Response Body | ForecastResponse JSON object containing historical and forecasted data. |
Sources: backend/ml_model.py:51-52
Data Models
The API uses Pydantic models to define the structure of requests and responses, ensuring data validation.
The diagram below shows the relationship between the request and response data models.
Sources: backend/ml_model.py:27-49
ForecastRequest Model:
| Field | Type | Default | Description |
|---|---|---|---|
historical_data | List[HistoricalDataPoint] | - | A list of historical data points for the stock. |
forecast_days | Optional[int] | 5 | The number of days to forecast into the future (max 5). |
Sources: backend/ml_model.py:32-34
ForecastResponse Model:
| Field | Type | Description |
|---|---|---|
historical_dates | List[str] | Dates of the historical data provided. |
historical_prices | List[float] | Closing prices of the historical data. |
forecast_dates | List[str] | Future dates for the forecast. |
forecast_prices | List[float] | Predicted prices (yhat) for the future dates. |
confidence_intervals | List[dict] | A list of dictionaries with lower and upper forecast bounds. |
metrics | dict | A dictionary containing mae and mape performance metrics. |
Sources: backend/ml_model.py:36-43
Core Logic and Components
The forecasting logic is encapsulated within the predict_stock function.
- Data Preparation: The function receives a list of
HistoricalDataPointobjects and converts them into a Pandas DataFrame withds(datetime) andy(close price) columns, which is the required format for Prophet. It requires a minimum of 30 data points to proceed.
Sources: backend/ml_model.py:57-67 - Frequency Inference: The
infer_data_frequencyhelper function attempts to determine the time frequency of the historical data (e.g., daily, hourly). If it cannot be inferred, it defaults to daily ('D').
Sources: backend/ml_model.py:45-49 - Model Configuration: A
Prophetmodel is instantiated withchangepoint_prior_scale=0.5. Based on the inferred data frequency, different seasonalities are added:- Intraday (T, H, etc.):
dailyandweeklyseasonality. - Daily or longer:
monthlyseasonality.
Sources: backend/ml_model.py:74-82
- Intraday (T, H, etc.):
- Performance Metrics: To evaluate the model's accuracy, Mean Absolute Error (MAE) and Mean Absolute Percentage Error (MAPE) are calculated on a training subset (the first 80% of the historical data).
Sources: backend/ml_model.py:90-94
Natural Language Processing (NLP) Features
The Greenline frontend uses the openai library directly to integrate generative AI features for textual analysis and user interaction. This is confirmed by its inclusion as a dependency.
Sources: client/package.json:17
Stock Summary Generation
The StockSummary component generates a timeline of significant price movements over the last 6 months and uses OpenAI's gpt-3.5-turbo model to provide a concise explanation for each event.
Sources: client/src/components/StockSummary/index.tsx
The process is as follows:
- Fetch 6 months of daily stock data from the Polygon API.
- Iterate through the data to find days with a price change greater than 2%.
- For each significant change, make a request to the OpenAI API.
- The prompt asks the model to analyze the event (date, price, percentage change) and describe potential market influences.
- The generated descriptions are displayed in a timeline view.
The following sequence diagram shows the interactions for generating the summary.
Ticker Chat
The TickerChat component, found on the quote page, provides an interactive chat experience where users can "talk" to a stock ticker. It uses the gpt-4o-mini model from OpenAI.
Sources: client/src/components/TickerChat/index.tsx, client/src/app/quote/[ticker]/page.tsx:125
A system prompt configures the AI's persona:
You are the stock ticker {ticker}. You will respond as if you are the ticker itself, providing insights, information, and relevant advice for those that wants to learn about {ticker} and potentially purchase some shares. Keep responses to the point while still being useful. Respond in paragraph format.
Sources: client/src/components/TickerChat/index.tsx:23-26
When a user sends a message, the component streams the response from the OpenAI API and updates the chat interface in real-time.