Building a Personalized Automated Investment Newsletter using n8n, GPT-4, and Alpaca API

Automatically generate personalized newsletters tailored to individual investment preferences, enabling efficient investment decisions. By combining n8n workflows, GPT-4's powerful text generation capabilities, and Alpaca API's real-time stock data access, this system helps alleviate information overload and provides optimized investment information for individuals.

1. The Challenge / Context

Individual investors find it difficult to filter out the information they need from the overwhelming amount of data available. Information pouring in from various sources such as news, analysis reports, and corporate disclosures complicates investment decisions and increases the risk of missing crucial information or making judgments based on incorrect data. Especially in highly volatile market conditions, acquiring quick and accurate information is even more critical. The key to solving this problem is to build an automated personalized newsletter system that matches an individual's investment tendencies and portfolio.

2. Deep Dive: n8n

n8n is a No-Code or Low-Code workflow automation platform. It allows users to connect various applications and services and create automated tasks through a drag-and-drop interface. As n8n is open-source, it offers high flexibility and supports self-hosting, making it suitable for users sensitive to data security. Key features include:

  • Node-based Workflow: Each node performs a specific task, and connections between nodes form the entire workflow.
  • Various Integrations: Supports integration with various APIs, databases, and apps. (e.g., HTTP Request, Google Sheets, PostgreSQL, etc.)
  • Custom Function Support: Allows implementing complex logic using Javascript code.
  • Webhook Support: Can trigger workflows when specific events occur.
  • Error Handling: Can receive notifications or automatically retry when an error occurs during workflow execution.

3. Step-by-Step Guide / Implementation

The following is a step-by-step guide to building a personalized automated investment newsletter using n8n, GPT-4, and Alpaca API.

Step 1: Set up Alpaca API Connection

Alpaca API provides real-time stock data. You need to set up your API key and secret key using the Alpaca API node in n8n.


    // Example of Alpaca API node setup in n8n
    {
        "parameters": {
            "apiKey": "YOUR_ALPACA_API_KEY",
            "secretKey": "YOUR_ALPACA_SECRET_KEY",
            "baseUrl": "https://paper-api.alpaca.markets" // Test environment
        },
        "name": "Alpaca"
    }
    

Step 2: Collect Watchlist Data

Collect real-time stock price data for the user-specified watchlist via the Alpaca API. User portfolio information can be stored in n8n or fetched from a separate database.


    // Fetch stock price data using Alpaca API in n8n
    {
        "nodes": [
            {
                "parameters": {
                    "operation": "getQuote",
                    "symbol": "AAPL" // Apple stock ticker
                },
                "name": "Alpaca Quote",
                "type": "n8n-nodes-alpaca.alpaca",
                "position": [
                    320,
                    200
                ]
            }
        ],
        "connections": []
    }
    

Step 3: Integrate News API and Collect Related News Articles

Use a News API (e.g., NewsAPI, Google News API) to fetch the latest news articles related to the collected stock tickers. Call the API using n8n's HTTP Request node and parse the results in JSON format.


    // Fetch news articles using NewsAPI in n8n
    {
        "nodes": [
            {
                "parameters": {
                    "requestMethod": "GET",
                    "url": "https://newsapi.org/v2/everything?q=AAPL&apiKey=YOUR_NEWSAPI_KEY"
                },
                "name": "News API",
                "type": "n8n-nodes-http-request.httpRequest",
                "position": [
                    640,
                    200
                ]
            }
        ],
        "connections": []
    }
    

Step 4: Integrate GPT-4 and Summarize & Analyze News Articles

Use the GPT-4 API to summarize collected news articles and analyze them from an investment perspective. For example, determine if the news is positive or negative, and predict its impact on stock prices. Call the GPT-4 API using n8n's HTTP Request node and use prompt engineering to achieve the desired results.


    // Summarize and analyze news using GPT-4 API in n8n
    {
        "nodes": [
            {
                "parameters": {
                    "requestMethod": "POST",
                    "url": "https://api.openai.com/v1/completions",
                    "headerParametersUi": {
                        "parameter": [
                            {
                                "name": "Authorization",
                                "value": "Bearer YOUR_OPENAI_API_KEY"
                            },
                            {
                                "name": "Content-Type",
                                "value": "application/json"
                            }
                        ]
                    },
                    "bodyParametersUi": {
                        "parameter": [
                            {
                                "name": "model",
                                "value": "text-davinci-003"
                            },
                            {
                                "name": "prompt",
                                "value": "Please summarize and analyze the following news article from an investment perspective:\n{{$node[\"News API\"].json[\"articles\"][0][\"description\"]}}"
                            },
                            {
                                "name": "max_tokens",
                                "value": "200"
                            }
                        ]
                    }
                },
                "name": "GPT-4",
                "type": "n8n-nodes-http-request.httpRequest",
                "position": [
                    960,
                    200
                ]
            }
        ],
        "connections": {
            "News API": {
                "main": [
                    [
                        {
                            "source": {
                                "node": "News API",
                                "type": "main",
                                "index": 0
                            },
                            "destination": {
                                "node": "GPT-4",
                                "type": "main",
                                "index": 0
                            }
                        }
                    ]
                ]
            }
        }
    }
    

Step 5: Generate Personalized Newsletter

Generate a personalized newsletter based on collected stock price data, news article summaries, and analysis results. Define a newsletter template in advance and insert data using n8n's Template node. The template can include stock price fluctuations, key news, investment opinions, and more.


    // Generate newsletter using Template node in n8n
    {
        "nodes": [
            {
                "parameters": {
                    "fieldToMap": "HTML",
                    "options": {
                        "HTML": "<h1>{{$json.title}}</h1><p>{{$json.summary}}</p><p>Stock Price: {{$json.price}}</p>"
                    }
                },
                "name": "Template",
                "type": "n8n-nodes-template.template",
                "position": [
                    1280,
                    200
                ]
            }
        ],
        "connections": {}
    }
    

Step 6: Send Email

Send the generated newsletter via email. Use n8n's Email Send node to send the newsletter to the user's email address. If necessary, an automated scheduler can be set up to send newsletters regularly, such as daily or weekly.


    // Send email using Email Send node in n8n
    {
        "nodes": [
            {
                "parameters": {
                    "fromEmail": "YOUR_EMAIL@example.com",
                    "toEmail": "USER_EMAIL@example.com",
                    "subject": "Personalized Investment Newsletter",
                    "html": "{{$node[\"Template\"].json[\"HTML\"]}}",
                    "options": {}
                },
                "name": "Email Send",
                "type": "n