Skip to content

Unified Stock Market Data API Client - Fetch data from multiple stock market APIs (prices, earnings, estimates, financials, historical, and more ) in a single consistent schema in Typescript.

License

Notifications You must be signed in to change notification settings

Johnson-f/stocksapi

Repository files navigation

stocksapi with Finance Query endpoint under the hood

npm version License: ISC TypeScript Tests Coverage

A high-performance, type-safe TypeScript SDK for the Finance Query API - completely free with no API key required!

Access comprehensive stock market data including real-time quotes, historical data, market news, sector performance, and more through a clean, intuitive TypeScript interface.

πŸš€ Quick Start

import { 
  getMarketStatus, 
  getDetailedQuotes, 
  getHistoricalData,
  getMostActive,
  getNews,
  FinanceQueryClient 
} from 'stocksapi';

// No setup required - start immediately!
const marketStatus = await getMarketStatus();
console.log(`Market is ${marketStatus.status}`);

// Get detailed stock quotes
const quotes = await getDetailedQuotes(['TSLA', 'AAPL', 'MSFT']);
quotes.forEach(quote => {
  console.log(`${quote.symbol}: $${quote.price} (${quote.change})`);
});

// Get historical data
const historicalData = await getHistoricalData('TSLA', '1d', '1m');
console.log(`Retrieved ${Object.keys(historicalData).length} data points`);

// Get most active stocks
const mostActive = await getMostActive(25);

✨ Features

  • βœ… No API Key Required - Start using immediately
  • βœ… Unlimited Usage - No rate limits or quotas
  • βœ… Real-time Data - Live stock prices and market data
  • βœ… Historical Data - OHLCV data with flexible time ranges
  • βœ… Market Analysis - Most active, gainers, losers, sector performance
  • βœ… Market News - General and stock-specific news
  • βœ… Symbol Search - Find stocks by name or symbol
  • βœ… TypeScript Support - Full type safety with comprehensive interfaces
  • βœ… High Performance - Fast response times
  • βœ… Completely Free - No costs or hidden fees

πŸ“¦ Installation

npm install stocksapi
# or
yarn add stocksapi

🎯 Available Endpoints

1. Market Status

Get current market open/closed status.

import { StocksAPI } from 'stocksapi';

// Initialize with your Alpha Vantage API key
const stocksAPI = new StocksAPI('YOUR_ALPHA_VANTAGE_API_KEY');

// Or specify the provider (default is 'alpha-vantage')
// const stocksAPI = new StocksAPI('YOUR_API_KEY', 'alpha-vantage');
import { getMarketStatus } from 'stocksapi';

const marketStatus = await getMarketStatus();
console.log(`Market Status: ${marketStatus.status}`);
console.log(`Reason: ${marketStatus.reason}`);
console.log(`Timestamp: ${marketStatus.timestamp}`);

2. Detailed Stock Quotes

Get comprehensive stock quotes with full market data.

import { getDetailedQuotes } from 'stocksapi';

const quotes = await getDetailedQuotes(['TSLA', 'AAPL', 'MSFT']);
quotes.forEach(quote => {
  console.log(`${quote.symbol}: $${quote.price}`);
  console.log(`Change: ${quote.change} (${quote.percentChange})`);
  console.log(`Volume: ${quote.volume.toLocaleString()}`);
  console.log(`Market Cap: ${quote.marketCap}`);
  console.log(`Sector: ${quote.sector}`);
  console.log(`Exchange: ${quote.exchange}`);
  console.log('---');
});

3. Simple Quotes (Lightweight)

Get lightweight stock quotes for basic price information.

import { getSimpleQuotes } from 'stocksapi';

const simpleQuotes = await getSimpleQuotes(['TSLA', 'AAPL']);
simpleQuotes.forEach(quote => {
  console.log(`${quote.symbol}: $${quote.price} (${quote.change})`);
});

4. Similar Stocks

Get stocks similar to a given symbol.

import { getSimilarQuotes } from 'stocksapi';

const similarStocks = await getSimilarQuotes('TSLA');
similarStocks.forEach(stock => {
  console.log(`${stock.symbol}: ${stock.name} - $${stock.price}`);
});

5. Historical Data

Get historical price data with flexible time ranges and intervals.

import { getHistoricalData } from 'stocksapi';

// Get 1 day of 1-minute data
const minuteData = await getHistoricalData('TSLA', '1d', '1m');
console.log(`Retrieved ${Object.keys(minuteData).length} minute data points`);

// Get 5 days of 5-minute data
const fiveMinuteData = await getHistoricalData('AAPL', '5d', '5m');

// Get 1 month of daily data
const dailyData = await getHistoricalData('MSFT', '1mo', '1d');

// Get 1 year of weekly data
const weeklyData = await getHistoricalData('GOOGL', '1y', '1wk');

// Available ranges: '1d', '5d', '1mo', '3mo', '6mo', '1y', '2y', '5y', '10y', 'ytd', 'max'
// Available intervals: '1m', '2m', '5m', '15m', '30m', '60m', '90m', '1h', '1d', '5d', '1wk', '1mo', '3mo'

6. Most Active Stocks

Get the most actively traded stocks.

import { getMostActive } from 'stocksapi';

// Get top 25 most active stocks (default)
const mostActive = await getMostActive();

// Get top 50 most active stocks
const top50 = await getMostActive(50);

// Get top 100 most active stocks
const top100 = await getMostActive(100);

mostActive.forEach(stock => {
  console.log(`${stock.symbol}: $${stock.price} (${stock.percentChange})`);
  console.log(`Volume: ${stock.volume.toLocaleString()}`);
});

7. Top Gainers

Get the top gaining stocks.

import { getTopGainers } from 'stocksapi';

const gainers = await getTopGainers(25);
console.log('Top Gainers:');
gainers.forEach(stock => {
  console.log(`${stock.symbol}: +${stock.percentChange}% ($${stock.price})`);
});

8. Top Losers

Get the top losing stocks.

import { getTopLosers } from 'stocksapi';

const losers = await getTopLosers(25);
console.log('Top Losers:');
losers.forEach(stock => {
  console.log(`${stock.symbol}: ${stock.percentChange}% ($${stock.price})`);
});

9. Market News

Get market news (general or stock-specific).

import { getNews } from 'stocksapi';

// Get general market news
const marketNews = await getNews();
marketNews.slice(0, 5).forEach(article => {
  console.log(`Title: ${article.title}`);
  console.log(`Source: ${article.source}`);
  console.log(`Time: ${article.time}`);
  console.log(`URL: ${article.url}`);
  console.log('---');
});

// Get Tesla-specific news
const teslaNews = await getNews('TSLA');
teslaNews.forEach(article => {
  console.log(`${article.title} - ${article.source}`);
});

10. Sector Performance

Get sector performance data.

import { getSectorPerformance } from 'stocksapi';

const sectors = await getSectorPerformance();
sectors.forEach(sector => {
  console.log(`${sector.sector}:`);
  console.log(`  Day: ${sector.dayReturn}%`);
  console.log(`  YTD: ${sector.ytdReturn}%`);
  console.log(`  Year: ${sector.yearReturn}%`);
  console.log('---');
});

11. Symbol Search

Search for stocks by name or symbol.

import { searchSymbols } from 'stocksapi';

// Search for Tesla-related symbols
const results = await searchSymbols('TSLA', 10);
results.forEach(result => {
  console.log(`${result.symbol}: ${result.name}`);
  console.log(`Exchange: ${result.exchange}, Type: ${result.type}`);
});

// Search for Apple-related symbols
const appleResults = await searchSymbols('Apple', 5);
appleResults.forEach(result => {
  console.log(`${result.symbol}: ${result.name}`);
});

πŸ—οΈ Using the Client Class

For more advanced usage, you can use the FinanceQueryClient class:

import { FinanceQueryClient } from 'stocksapi';

// Create a client instance
const client = new FinanceQueryClient();

// Use all methods
const marketStatus = await client.getMarketStatus();
const quotes = await client.getDetailedQuotes({ symbols: ['AAPL'] });
const historical = await client.getHistoricalData({
  symbol: 'TSLA',
  range: '1d',
  interval: '1m',
  epoch: true
});

// Configure client with custom settings
const customClient = new FinanceQueryClient({
  baseUrl: 'https://custom-api.com',
  timeout: 5000
});

🎭 TypeScript Types

All interfaces are fully typed for IntelliSense support:

import { 
  MarketStatusResponse,
  DetailedQuote,
  SimpleQuote,
  SimilarQuote,
  HistoricalData,
  ActiveStock,
  GainersLosersStock,
  NewsItem,
  SectorPerformance,
  SearchResult,
  FinanceQueryClient
} from 'stocksapi';

// Type-safe API calls
const marketStatus: MarketStatusResponse = await getMarketStatus();
const quotes: DetailedQuote[] = await getDetailedQuotes(['AAPL']);
const historical: HistoricalData = await getHistoricalData('TSLA', '1d', '1m');
const mostActive: ActiveStock[] = await getMostActive(25);
const news: NewsItem[] = await getNews('AAPL');
const sectors: SectorPerformance[] = await getSectorPerformance();
const searchResults: SearchResult[] = await searchSymbols('Apple');

🚨 Error Handling

import { getDetailedQuotes, getHistoricalData } from 'stocksapi';

try {
  const quotes = await getDetailedQuotes(['INVALID_SYMBOL']);
} catch (error: any) {
  console.error('Finance Query Error:', error.message);
  if (error.response?.status === 404) {
    console.log('Symbol not found');
  } else if (error.response?.status === 500) {
    console.log('Server error - try again later');
  }
}

// Graceful degradation
const quotes = await getDetailedQuotes(['AAPL']).catch(() => []);
const historical = await getHistoricalData('TSLA', '1d', '1m').catch(() => ({}));

⚑ Performance & Best Practices

Batch Operations

// Efficient: Batch quotes in single call
const quotes = await getDetailedQuotes(['AAPL', 'MSFT', 'GOOGL', 'TSLA']);

// Efficient: Use appropriate time ranges
const dailyData = await getHistoricalData('AAPL', '1mo', '1d'); // 1 month of daily data
const intradayData = await getHistoricalData('AAPL', '1d', '1m'); // 1 day of minute data

// Efficient: Use valid count values for most active/gainers/losers
const mostActive = await getMostActive(25); // Valid: 25, 50, or 100

Caching

// Consider implementing caching for frequently accessed data
const cache = new Map();

const getCachedQuote = async (symbol: string) => {
  if (cache.has(symbol)) return cache.get(symbol);
  const quotes = await getDetailedQuotes([symbol]);
  const quote = quotes[0];
  cache.set(symbol, quote);
  return quote;
};

πŸ§ͺ Testing for developers

# Run all tests
npm test

# Run specific test suites
npm run test:providers
npm run test:economic

# Test with your API keys
FINANCIAL_MODELING_PREP_API_KEY=your_key npm run test:economic

πŸ“ Examples

Portfolio Tracker

import { getDetailedQuotes, getHistoricalData } from 'stocksapi';

const symbols = ['AAPL', 'MSFT', 'GOOGL', 'TSLA'];

// Get current portfolio value
const quotes = await getDetailedQuotes(symbols);
const totalValue = quotes.reduce((sum, quote) => sum + quote.price, 0);

console.log('Portfolio Summary:');
quotes.forEach(quote => {
  console.log(`${quote.symbol}: $${quote.price} (${quote.percentChange}%)`);
});
console.log(`Total Value: $${totalValue.toFixed(2)}`);

// Get historical performance
const historicalData = await getHistoricalData('AAPL', '1mo', '1d');
console.log(`AAPL 1-month data points: ${Object.keys(historicalData).length}`);

Market Dashboard

import { 
  getMarketStatus, 
  getMostActive, 
  getTopGainers, 
  getTopLosers,
  getSectorPerformance,
  getNews 
} from 'stocksapi';

// Market overview
const marketStatus = await getMarketStatus();
console.log(`Market Status: ${marketStatus.status}`);

// Most active stocks
const mostActive = await getMostActive(10);
console.log('Most Active Stocks:');
mostActive.forEach(stock => {
  console.log(`${stock.symbol}: $${stock.price} (${stock.percentChange}%)`);
});

// Top gainers and losers
const gainers = await getTopGainers(5);
const losers = await getTopLosers(5);

// Sector performance
const sectors = await getSectorPerformance();
console.log('Sector Performance:');
sectors.forEach(sector => {
  console.log(`${sector.sector}: ${sector.dayReturn}%`);
});

// Latest news
const news = await getNews();
console.log('Latest Market News:');
news.slice(0, 3).forEach(article => {
  console.log(`${article.title} - ${article.source}`);
});

Stock Analysis Tool

import { 
  getDetailedQuotes, 
  getHistoricalData, 
  getNews,
  getSimilarQuotes 
} from 'stocksapi';

async function analyzeStock(symbol: string) {
  console.log(`\n=== ${symbol} Analysis ===`);
  
  // Get current quote
  const quotes = await getDetailedQuotes([symbol]);
  const quote = quotes[0];
  
  console.log(`Price: $${quote.price}`);
  console.log(`Change: ${quote.change} (${quote.percentChange}%)`);
  console.log(`Volume: ${quote.volume.toLocaleString()}`);
  console.log(`Market Cap: ${quote.marketCap}`);
  console.log(`Sector: ${quote.sector}`);
  
  // Get historical data
  const historical = await getHistoricalData(symbol, '1mo', '1d');
  const dataPoints = Object.keys(historical).length;
  console.log(`Historical data points: ${dataPoints}`);
  
  // Get recent news
  const news = await getNews(symbol);
  console.log(`Recent news articles: ${news.length}`);
  
  // Get similar stocks
  const similar = await getSimilarQuotes(symbol);
  console.log(`Similar stocks: ${similar.length}`);
}

// Analyze multiple stocks
await analyzeStock('AAPL');
await analyzeStock('TSLA');
await analyzeStock('MSFT');

πŸ§ͺ Testing

# Run all tests
npm test

# Run tests with coverage
npm run test:coverage

# Run specific test suites
npm run test:finance-query

πŸ“š API Reference

Convenience Functions

Function Description Parameters
getMarketStatus() Get market open/closed status None
getDetailedQuotes(symbols) Get comprehensive stock quotes symbols: string[]
getSimpleQuotes(symbols) Get lightweight stock quotes symbols: string[]
getSimilarQuotes(symbol) Get similar stocks symbol: string
getHistoricalData(symbol, range, interval) Get historical price data symbol: string, range: string, interval: string
getMostActive(count?) Get most active stocks count?: 25 | 50 | 100
getTopGainers(count?) Get top gaining stocks count?: 25 | 50 | 100
getTopLosers(count?) Get top losing stocks count?: 25 | 50 | 100
getNews(symbol?) Get market news symbol?: string
getSectorPerformance() Get sector performance None
searchSymbols(query, limit?) Search for stocks query: string, limit?: number

FinanceQueryClient Class

class FinanceQueryClient {
  constructor(config?: ClientConfig)
  
  // All convenience functions are available as methods
  async getMarketStatus(): Promise<MarketStatusResponse>
  async getDetailedQuotes(params: DetailedQuotesParams): Promise<DetailedQuote[]>
  async getSimpleQuotes(params: SimpleQuotesParams): Promise<SimpleQuote[]>
  async getSimilarQuotes(params: SimilarQuotesParams): Promise<SimilarQuote[]>
  async getHistoricalData(params: HistoricalDataParams): Promise<HistoricalData>
  async getMostActive(params?: MostActiveParams): Promise<MostActiveResponse>
  async getTopGainers(params?: GainersLosersParams): Promise<GainersLosersResponse>
  async getTopLosers(params?: GainersLosersParams): Promise<GainersLosersResponse>
  async getNews(params?: NewsParams): Promise<NewsResponse>
  async getSectorPerformance(): Promise<SectorPerformanceResponse>
  async searchSymbols(params: SearchParams): Promise<SearchResponse>
}

🌐 API Endpoints

The SDK connects to the Finance Query API at https://finance-query.onrender.com:

  • GET /hours - Market status
  • GET /v1/quotes - Detailed quotes
  • GET /v1/simple-quotes - Simple quotes
  • GET /v1/similar - Similar stocks
  • GET /v1/historical - Historical data
  • GET /v1/actives - Most active stocks
  • GET /v1/gainers - Top gainers
  • GET /v1/losers - Top losers
  • GET /v1/news - Market news
  • GET /v1/sectors - Sector performance
  • GET /v1/search - Symbol search

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the ISC License - see the LICENSE file for details.

⭐ Support

If you find this library useful, please give it a star! It helps others discover the project.

For issues and questions:


Made with ❀️ by Johnson-f

About

Unified Stock Market Data API Client - Fetch data from multiple stock market APIs (prices, earnings, estimates, financials, historical, and more ) in a single consistent schema in Typescript.

Resources

License

Stars

Watchers

Forks

Packages

No packages published