Home Web Front-end JS Tutorial Building a High-Quality Stock Report Generator with Node.js, Express, and OpenAI API

Building a High-Quality Stock Report Generator with Node.js, Express, and OpenAI API

Nov 04, 2024 pm 02:54 PM

Building a High-Quality Stock Report Generator with Node.js, Express, and OpenAI API

In this article, we will delve into creating a professional-grade stock report generator using Node.js, Express, and the OpenAI API. Our focus will be on writing high-quality, maintainable code while preserving the integrity of the prompt messages used in the OpenAI API interactions. The application will fetch stock data, perform sentiment and industry analysis, and generate a comprehensive investment report.

Table of Contents

  1. Project Overview
  2. Setting Up the Environment
  3. Creating the Express Server
  4. Fetching and Processing Data
  5. Integrating with OpenAI API
  6. Generating the Final Report
  7. Testing the Application
  8. Conclusion

Project Overview

Our goal is to build an API endpoint that generates a detailed investment report for a given stock ticker. The report will include:

  • Company Overview
  • Financial Performance
  • Management Discussion and Analysis (MDA)
  • Sentiment Analysis
  • Industry Analysis
  • Risks and Opportunities
  • Investment Recommendation

We will fetch stock data from external APIs and use the OpenAI API for advanced analysis, ensuring that the prompt messages are accurately preserved.

Setting Up the Environment

Prerequisites

  • Node.js installed on your machine
  • OpenAI API Key (If you don't have one, sign up at OpenAI)

Initializing the Project

Create a new directory and initialize a Node.js project:

mkdir stock-report-generator
cd stock-report-generator
npm init -y
Copy after login
Copy after login
Copy after login

Install the necessary dependencies:

npm install express axios
Copy after login
Copy after login

Set up the project structure:

mkdir routes utils data
touch app.js routes/report.js utils/helpers.js
Copy after login
Copy after login

Creating the Express Server

Setting Up app.js

// app.js
const express = require('express');
const reportRouter = require('./routes/report');

const app = express();

app.use(express.json());
app.use('/api', reportRouter);

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Copy after login
Copy after login
  • Express Initialization: Import Express and initialize the application.
  • Middleware: Use express.json() to parse JSON request bodies.
  • Routing: Mount the report router on the /api path.
  • Server Listening: Start the server on the specified port.

Fetching and Processing Data

Creating Helper Functions

In utils/helpers.js, we'll define utility functions for data fetching and processing.

mkdir stock-report-generator
cd stock-report-generator
npm init -y
Copy after login
Copy after login
Copy after login
  • getLastYearDates: Calculates the start and end dates for the previous year.
  • objectToString: Converts an object to a readable string, excluding specified keys.
  • fetchData: Handles GET requests to external APIs, returning data or a default value.
  • readLocalJson: Reads data from local JSON files.

Implementing Stock Data Fetching

In routes/report.js, define functions to fetch stock data.

npm install express axios
Copy after login
Copy after login
  • fetchStockData: Concurrently fetches multiple data points and processes the results.
  • Data Processing: Formats and transforms data for subsequent use.
  • Error Handling: Logs errors and rethrows them for higher-level handling.

Integrating with OpenAI API

OpenAI API Interaction Function

mkdir routes utils data
touch app.js routes/report.js utils/helpers.js
Copy after login
Copy after login
  • analyzeWithOpenAI: Handles communication with the OpenAI API.
  • API Configuration: Sets parameters such as model and temperature.
  • Error Handling: Logs and throws errors for upstream handling.

Performing Sentiment Analysis

// app.js
const express = require('express');
const reportRouter = require('./routes/report');

const app = express();

app.use(express.json());
app.use('/api', reportRouter);

const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Copy after login
Copy after login
  • performSentimentAnalysis: Constructs prompt messages and calls the OpenAI API for analysis.
  • Prompt Design: Ensures that the prompt messages are clear and include necessary context.

Analyzing the Industry

// utils/helpers.js
const axios = require('axios');
const fs = require('fs');
const path = require('path');

const BASE_URL = 'https://your-data-api.com'; // Replace with your actual data API

/**
 * Get the start and end dates for the last year.
 * @returns {object} - An object containing `start` and `end` dates.
 */
function getLastYearDates() {
  const now = new Date();
  const end = now.toISOString().split('T')[0];
  now.setFullYear(now.getFullYear() - 1);
  const start = now.toISOString().split('T')[0];
  return { start, end };
}

/**
 * Convert an object to a string, excluding specified keys.
 * @param {object} obj - The object to convert.
 * @param {string[]} excludeKeys - Keys to exclude.
 * @returns {string} - The resulting string.
 */
function objectToString(obj, excludeKeys = []) {
  return Object.entries(obj)
    .filter(([key]) => !excludeKeys.includes(key))
    .map(([key, value]) => `${key}: ${value}`)
    .join('\n');
}

/**
 * Fetch data from a specified endpoint with given parameters.
 * @param {string} endpoint - API endpoint.
 * @param {object} params - Query parameters.
 * @param {any} defaultValue - Default value if the request fails.
 * @returns {Promise<any>} - The fetched data or default value.
 */
async function fetchData(endpoint, params = {}, defaultValue = null) {
  try {
    const response = await axios.get(`${BASE_URL}${endpoint}`, { params });
    return response.data || defaultValue;
  } catch (error) {
    console.error(`Error fetching data from ${endpoint}:`, error.message);
    return defaultValue;
  }
}

/**
 * Read data from a local JSON file.
 * @param {string} fileName - Name of the JSON file.
 * @returns {any} - The parsed data.
 */
function readLocalJson(fileName) {
  const filePath = path.join(__dirname, '../data', fileName);
  const data = fs.readFileSync(filePath, 'utf-8');
  return JSON.parse(data);
}

module.exports = {
  fetchData,
  objectToString,
  getLastYearDates,
  readLocalJson,
};
Copy after login
  • analyzeIndustry: Similar to sentiment analysis but focuses on broader industry context.
  • Prompt Preservation: Maintains the integrity of the original prompt messages.

Generating the Final Report

Compiling All Data

// routes/report.js
const express = require('express');
const {
  fetchData,
  objectToString,
  getLastYearDates,
  readLocalJson,
} = require('../utils/helpers');

const router = express.Router();

/**
 * Fetches stock data including historical prices, financials, MDA, and main business info.
 * @param {string} ticker - Stock ticker symbol.
 * @returns {Promise<object>} - An object containing all fetched data.
 */
async function fetchStockData(ticker) {
  try {
    const dates = getLastYearDates();
    const [historicalData, financialData, mdaData, businessData] = await Promise.all([
      fetchData('/stock_zh_a_hist', {
        symbol: ticker,
        period: 'weekly',
        start_date: dates.start,
        end_date: dates.end,
      }, []),

      fetchData('/stock_financial_benefit_ths', {
        code: ticker,
        indicator: '按年度',
      }, [{}]),

      fetchData('/stock_mda', { code: ticker }, []),

      fetchData('/stock_main_business', { code: ticker }, []),
    ]);

    const hist = historicalData[historicalData.length - 1];
    const currentPrice = (hist ? hist['开盘'] : 'N/A') + ' CNY';
    const historical = historicalData
      .map((item) => objectToString(item, ['股票代码']))
      .join('\n----------\n');

    const zsfzJson = readLocalJson('zcfz.json');
    const balanceSheet = objectToString(zsfzJson.find((item) => item['股票代码'] === ticker));

    const financial = objectToString(financialData[0]);

    const mda = mdaData.map(item => `${item['报告期']}\n${item['内容']}`).join('\n-----------\n');

    const mainBusiness = businessData.map(item =>
      `主营业务: ${item['主营业务']}\n产品名称: ${item['产品名称']}\n产品类型: ${item['产品类型']}\n经营范围: ${item['经营范围']}`
    ).join('\n-----------\n');

    return { currentPrice, historical, balanceSheet, mda, mainBusiness, financial };
  } catch (error) {
    console.error('Error fetching stock data:', error.message);
    throw error;
  }
}
Copy after login
  • provideFinalAnalysis: Carefully crafts prompt messages, incorporating all collected data.
  • Prompt Integrity: Ensures that the original prompt messages are not altered or corrupted.

Testing the Application

Defining the Route Handler

Add the route handler in routes/report.js:

const axios = require('axios');

const OPENAI_API_KEY = 'your-openai-api-key'; // Replace with your OpenAI API key

/**
 * Interacts with the OpenAI API to get completion results.
 * @param {array} messages - Array of messages, including system prompts and user messages.
 * @returns {Promise<string>} - The AI's response.
 */
async function analyzeWithOpenAI(messages) {
  try {
    const headers = {
      'Authorization': `Bearer ${OPENAI_API_KEY}`,
      'Content-Type': 'application/json',
    };
    const requestData = {
      model: 'gpt-4',
      temperature: 0.3,
      messages: messages,
    };

    const response = await axios.post(
      'https://api.openai.com/v1/chat/completions',
      requestData,
      { headers }
    );
    return response.data.choices[0].message.content.trim();
  } catch (error) {
    console.error('Error fetching analysis from OpenAI:', error.message);
    throw error;
  }
}
Copy after login
  • Input Validation: Checks if the ticker symbol is provided.
  • Data Gathering: Concurrently fetches stock data and performs analyses.
  • Error Handling: Logs errors and sends a 500 response in case of failure.

Starting the Server

Ensure your app.js and routes/report.js are correctly set up, then start the server:

/**
 * Performs sentiment analysis on news articles using the OpenAI API.
 * @param {string} ticker - Stock ticker symbol.
 * @returns {Promise<string>} - Sentiment analysis summary.
 */
async function performSentimentAnalysis(ticker) {
  const systemPrompt = `You are a sentiment analysis assistant. Analyze the sentiment of the given news articles for ${ticker} and provide a summary of the overall sentiment and any notable changes over time. Be measured and discerning. You are a skeptical investor.`;

  const tickerNewsResponse = await fetchData('/stock_news_specific', { code: ticker }, []);

  const newsText = tickerNewsResponse
    .map(item => `${item['文章来源']} Date: ${item['发布时间']}\n${item['新闻内容']}`)
    .join('\n----------\n');

  const messages = [
    { role: 'system', content: systemPrompt },
    {
      role: 'user',
      content: `News articles for ${ticker}:\n${newsText || 'N/A'}\n----\nProvide a summary of the overall sentiment and any notable changes over time.`,
    },
  ];

  return await analyzeWithOpenAI(messages);
}
Copy after login

Sending a Test Request

Use curl or Postman to send a POST request:

mkdir stock-report-generator
cd stock-report-generator
npm init -y
Copy after login
Copy after login
Copy after login
  • Response: The server should return a JSON object containing the generated report.

Conclusion

We have built a high-quality stock report generator with the following capabilities:

  • Fetching and processing stock data from external APIs.
  • Performing advanced analyses using the OpenAI API.
  • Generating a comprehensive investment report, while ensuring the integrity of the prompt messages.

Throughout the development process, we focused on writing professional, maintainable code and provided detailed explanations and annotations.

Best Practices Implemented

  • Modular Code Structure: Functions are modularized for reusability and clarity.
  • Asynchronous Operations: Used async/await and Promise.all for efficient asynchronous programming.
  • Error Handling: Comprehensive try-catch blocks and error messages.
  • API Abstraction: Separated API interaction logic for better maintainability.
  • Prompt Engineering: Carefully designed prompt messages for the OpenAI API to achieve the desired output.
  • Input Validation: Checked for required input parameters to prevent unnecessary errors.
  • Code Documentation: Added JSDoc comments for better understanding and maintenance.

Next Steps

  • Caching: Implement caching mechanisms to reduce redundant API calls.
  • Authentication: Secure the API endpoints with authentication and rate limiting.
  • Frontend Development: Build a user interface for interacting with the application.
  • Additional Analyses: Incorporate technical analysis or other financial models.

References

  • Node.js Documentation
  • Express.js Documentation
  • Axios Documentation
  • OpenAI API Reference

Disclaimer: This application is for educational purposes only. Ensure compliance with all API terms of service and handle sensitive data appropriately.

The above is the detailed content of Building a High-Quality Stock Report Generator with Node.js, Express, and OpenAI API. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1268
29
C# Tutorial
1243
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

See all articles