Building a Custom Stock Alert Automation System with n8n, Pinecone, and NewsAPI: Portfolio-Tailored Alerts Based on Real-time News Analysis

Stock investing can be overwhelming in a sea of information. This article introduces how to build an automation system using n8n to fetch real-time stock news from NewsAPI, analyze the semantic similarity of news titles with Pinecone, and selectively alert users to news likely to impact their portfolios, thereby aiding investment decisions. With alerts tailored to your investment strategy, you can save time and effort and make better investment decisions.

1. The Challenge / Context

For individual investors to succeed in the stock market, acquiring fast and accurate information about constantly changing market conditions is essential. However, sifting through the deluge of news to identify information that directly impacts one's personal portfolio is extremely difficult. Existing alert systems often operate simply based on keywords, frequently providing irrelevant or redundant information that is not helpful for actual investment decisions. To solve this problem, a customized alert system optimized for individual investment portfolios through real-time news analysis is needed.

2. Deep Dive: n8n (No-Code Automation Platform)

n8n is a powerful open-source automation platform that provides a node-based workflow editor. It allows you to build complex automation processes by connecting various APIs and services without coding. In particular, it offers diverse functionalities such as webhooks, HTTP Requests, and data transformation, making it highly useful for data collection and processing using external APIs. The advantages of n8n are as follows:

  • No-Code/Low-Code Interface: Easily design and modify workflows using a drag-and-drop method.
  • Diverse Integration Capabilities: Can be linked with various services such as NewsAPI, Pinecone, email, and Slack.
  • Extensibility: Develop custom nodes as needed to extend functionality.
  • Open Source: Free to use and modify, with community support available.

3. Step-by-Step Guide / Implementation

Now, let's take a detailed look at the steps to build a custom stock alert automation system using n8n, NewsAPI, and Pinecone.

Step 1: Real-time News Data Collection using NewsAPI

First, collect stock-related news of interest using NewsAPI. NewsAPI provides an API that allows you to search and retrieve news data from various news sources. You need to create a NewsAPI account and obtain an API key.


    // NewsAPI Node 설정 예시 (n8n)
    {
      "nodes": [
        {
          "parameters": {
            "apiKey": "YOUR_NEWSAPI_KEY",
            "q": "삼성전자 OR Tesla", // 관심 있는 키워드 설정
            "sortBy": "relevancy",
            "language": "ko"
          },
          "name": "NewsAPI",
          "type": "n8n-nodes-newsapi.newsapi",
          "typeVersion": 1,
          "position": [200, 200]
        }
      ],
      "connections": []
    }
  

The code above is an example of setting up a NewsAPI node in an n8n workflow. Enter your issued NewsAPI key in `apiKey` and set keywords of interest in `q`. `sortBy` sets the search result sorting method, and `language` sets the news language. You can connect multiple keywords with an OR operator, such as "삼성전자 OR Tesla", to search simultaneously.

Step 2: Generate News Title Embeddings and Store in Pinecone Vector DB

Generate embedding vectors using the collected news titles and store them in the Pinecone vector DB. Embedding vectors are numerical representations of text meaning, used for comparing semantic similarity. You can convert news titles into vectors using an embedding model like OpenAI API.


    // OpenAI API Node 설정 예시 (n8n)
    {
      "nodes": [
        {
          "parameters": {
            "model": "text-embedding-ada-002",
            "inputText": "={{$json.title}}", // NewsAPI 노드에서 받은 뉴스 제목
            "apiKey": "YOUR_OPENAI_API_KEY"
          },
          "name": "OpenAI Embeddings",
          "type": "n8n-nodes-openai.embeddings",
          "typeVersion": 1,
          "position": [400, 200]
        }
      ],
      "connections": [
        {
          "source": [
            {
              "node": "NewsAPI",
              "type": "main",
              "index": 0
            }
          ],
          "destination": [
            {
              "node": "OpenAI Embeddings",
              "type": "main",
              "index": 0
            }
          ]
        }
      ]
    }
  

The code above is an example of setting up an OpenAI API node in an n8n workflow. Specify the embedding model to use in `model` and enter the news title received from the NewsAPI node in `inputText`. Enter your issued OpenAI API key in `apiKey`. `={{$json.title}}` is an n8n expression, meaning to use the value of the `title` field from the JSON data passed from the previous node (`NewsAPI`).


    // Pinecone Node 설정 예시 (n8n)
    {
      "nodes": [
        {
          "parameters": {
            "operation": "upsert",
            "indexName": "stock-news-index",
            "pineconeApiKey": "YOUR_PINECONE_API_KEY",
            "pineconeEnvironment": "YOUR_PINECONE_ENVIRONMENT",
            "vectors": "[{\n  \"id\": \"{{$json.title}}\", // 뉴스 제목을 ID로 사용\n  \"values\": {{$json.embedding}},\n  \"metadata\": {\n    \"source\": \"NewsAPI\",\n    \"url\": \"{{$json.url}}\"\n  }\n}]"
          },
          "name": "Pinecone",
          "type": "n8n-nodes-pinecone.pinecone",
          "typeVersion": 1,
          "position": [600, 200]
        }
      ],
      "connections": [
        {
          "source": [
            {
              "node": "OpenAI Embeddings",
              "type": "main",
              "index": 0
            }
          ],
          "destination": [
            {
              "node": "Pinecone",
              "type": "main",
              "index": 0
            }
          ]
        }
      ]
    }
  

The code above is an example of setting up a Pinecone node in an n8n workflow. `operation` specifies the action to perform, here `upsert` for adding data. Enter the index name created in Pinecone in `indexName`, and your Pinecone API key and environment in `pineconeApiKey` and `pineconeEnvironment`. In `vectors`, enter the vector data to be stored in JSON format. The news title is used as the ID, and the embedding vector received from the OpenAI API node is used as the value. Additionally, the news source and URL are stored as metadata to be utilized when sending alerts later.

Step 3: Search for Portfolio-Related News and Send Alerts

Search for news related to stock items included in the user's portfolio, and search for similar news titles in the Pinecone vector DB to send alerts. Generate search queries based on portfolio information and use Pinecone's query function to find similar news titles.


    // Function Node 설정 예시 (n8n) - 포트폴리오 기반 검색 쿼리 생성
    {
      "nodes": [
        {
          "parameters": {
            "functionCode": "const portfolio = ['삼성전자', 'Tesla', 'Apple'];\nlet query = '';\nportfolio.forEach((stock, index) => {\n  query += stock;\n  if (index < portfolio.length - 1) {\n    query += ' OR ';\n  }\n});\n\nreturn [{json: {query: query}}];"
          },
          "name": "Generate Query",
          "type": "n8n-nodes-base.function",
          "typeVersion": 1,
          "position": [200, 400]
        }
      ],
      "connections": []
    }
  

The code above is an example of using a Function node in an n8n workflow to generate a search query based on portfolio information. Enter the stock items included in the user's portfolio into the `portfolio` array. This code generates a search query like "삼성전자 OR Tesla OR Apple".


    // Pinecone Node 설정 예시 (n8n) - 유사 뉴스 검색
    {
      "nodes": [
        {
          "parameters": {
            "operation": "query",
            "indexName": "stock-news-index",
            "pineconeApiKey": "YOUR_PINECONE_API_KEY",
            "pineconeEnvironment": "YOUR_PINECONE_ENVIRONMENT",
            "topK": 5,
            "vector": {{$json.embedding}}, // OpenAI Embeddings 노드에서 받은 임베딩 벡터
            "includeValues": false,
            "includeMetadata": true
          },
          "name": "Pinecone Query",
          "type": "n8n-nodes-pinecone.pinecone",
          "typeVersion": 1,
          "position": [400, 400]
        }
      ],
      "connections": [
        {
          "source": [
            {
              "node": "OpenAI Embeddings",
              "type": "main",
              "index": 0
            }
          ],
          "destination": [
            {
              "node": "Pinecone Query",
              "type": "main",
              "index": 0
            }
          ]
        }
      ]
    }
  

The code above is an example of using a Pinecone node in an n8n workflow to search for similar news. `operation` is set to `query`, and `topK` specifies the number of search results. Enter the embedding vector received from the OpenAI Embeddings node in `vector`. `includeValues` sets whether to include vector values, and `includeMetadata` sets whether to include metadata. Since metadata includes the news source and URL, `includeMetadata` must be set to `true`.


    // Email/Slack Node 설정 예시 (n8n) - 알림 발송
    {
      "nodes": [
        {
          "parameters": {
            "toEmail": "YOUR_EMAIL_ADDRESS",
            "subject": "Portfolio Related Important News Alert",
            "text": "The following news may affect your portfolio:\n\n{{$json.matches[0].metadata.url}}" // Pinecone Query 노드에서 받은 검색 결과
          },
          "name": "Send Email",
          "type": "n8n-nodes-email.emailSend",
          "typeVersion": 1,
          "position": [600, 400]
        }
      ],
      "connections": [
        {
          "source": [
            {
              "node": "Pinecone Query",
              "type": "main",
              "index": 0
            }
          ],
          "destination": [
            {
              "node": "Send Email",
              "type": "main",
              "index": 0
            }
          ]
        }
      ]
    }
  

The code above is an example of using an Email node in an n8n workflow to send alerts. Enter the email address to receive alerts in `toEmail`, and set the email subject and content in `subject` and `text`. `{{$json.matches[0].metadata.url}}` is an n8n expression that retrieves the URL of the most similar news from the search results received from the Pinecone Query node. You can also use a Slack node instead of email to send alerts to a Slack channel.

4. Real-world Use Case / Example

I personally built this system and reduced my investment time by over 2 hours per week. Previously, I had to check countless news sites daily and manually filter relevant information. However, after building this system, I can selectively receive alerts only for news highly likely to impact my portfolio, reducing unnecessary information checking time and allowing me to dedicate more time to improving my investment strategy.

5. Pros & Cons / Critical Analysis

  • Pros:
    • Provides personalized custom news alerts, reducing information overload.
    • Helps make investment decisions quickly through real-time news analysis.
    • Easily build an automation system without coding through n8n's No-