← GO BACK

August 7, 2024

Tutorial: Integrate a Stock API

Autor:
Bavest
Engineering
Introduction

In the modern financial world, a stock API is the pillar of many financial products and companies, from trading apps, financial tools to quantitative analysis for banks and asset managers. In this tutorial, we will take you step-by-step through the process of integrating our stock API with Bavest so that you can integrate financial data such as stock prices, ETF data and more into your applications.
Where to get an API key and what exactly you need to do is explained in this blog article.

What you should consider before API integration
Statuspage and API documentation

Before you start integrating our API, be sure to read our Statuspage and API documentation carefully. The status page gives you an overview of the current availability and possible maintenance work of our services. The API documentation is your guide to using our API and provides detailed information about available endpoints, data formats, and authentication methods.

  • Statuspage: Check our regularly Statuspage to ensure that all services are working properly.
  • API documentation: Read the API documentation thoroughly to gain a full understanding of API features. Use our API documentation to select requests in the appropriate programming language based on your tech stack. Copy the code and also test the requests directly in the API documentation with your API key.

Before you start the integration process, there are a few important technical and organizational aspects to consider:

Tech Stack

Make sure your tech stack is compatible with our API. Our API supports various programming languages and frameworks, including Python, JavaScript (Node.js), and PHP. Choose the language that best suits your project.

Cloud provider

If you want to host your application in the cloud, you should choose an appropriate cloud provider. Our API can be integrated with various cloud services, such as AWS, Google Cloud, and Azure. Make sure your cloud provider provides the resources and services you need.

  • AWS: Offers comprehensive services and tools for API integration.
  • Google Cloud: Known for its powerful data analysis tools.
  • Azure: Offers seamless integration with Microsoft products.

Bavest API integration: step-by-step guide

Step 1: Get registration and API key

Before you can use our API, you must have a test API key with support@bavest.co request. You will receive an API key that you can use to access our data.

Step 2: Read the API documentation

Our API documentation contains all necessary information to use our interface. Visit the documentation page to learn about available endpoints, data formats, and authentication methods.

Step 3: Make your first request

With your API key, you can now make your first request to our API. The following is an example of how you can retrieve stock prices.

Example: Retrieving stock prices

To retrieve a company's current stock prices, use the following endpoint:

In this example, the share price is retrieved from Apple (symbol: AAPL). Substitute API KEY with your personal API key.

Sample code in Python

Here's sample code in Python that shows how you can use our API:

1import requests
2
3url = "https://api.bavest.co/v0/quote"
4
5headers = {
6    "accept": "application/json",
7    "content-type": "application/json",
8    "x-api-key": "API-Key"
9}
10
11response = requests.post(url, headers=headers)
12
13print(response.text)

Now we want to make sure that the Bavest API does not return an error and actually delivers the latest course from Apple, then the code looks like this:

1import requests
2
3url = "https://api.bavest.co/v0/quote"
4
5payload = {
6    "symbol": "AAPL",
7    "currency": "EUR"
8}
9headers = {
10    "accept": "application/json",
11    "content-type": "application/json",
12    "x-api-key": "API-Key"
13}
14
15response = requests.post(url, json=payload, headers=headers)
16
17if response.status_code == 200:
18    json_data = response.json()
19    
20    # Extracting the historical price data for "day"
21    if 'historical_price' in json_data and 'day' in json_data['historical_price']:
22        historical_day_prices = json_data['historical_price']['day']
23        
24        # Print the latest update (assuming the latest is the last in the list)
25        if historical_day_prices:
26            latest_price_update = historical_day_prices[-1]
27            print("Latest price update:", latest_price_update)
28        else:
29            print("No historical day prices available.")
30    else:
31        print("Historical price data for 'day' not found in the response.")
32else:
33    print('Error:', response.status_code, response.text)

This code performs the following actions:

- It sends a POST request to the API using the specified URL, payload, and headers.
- Checks whether the response status is 200 (which indicates success).
- Analyze the JSON response and extract the “historical_price” for “day.”
- Shows the last price update from the “historical_price” “day” data.

Step 4: Integrate with Your Application

Depending on which programming language or platform you use, you can integrate our API into your application. Here are a few examples for different languages:

JavaScript (Node.js)

Let's use node-fetch-requests:

npm install node-fetch@2 --save

1const fetch = require('node-fetch');
2
3const url = 'https://api.bavest.co/v0/quote';
4const options = {
5  method: 'POST',
6  headers: {
7    accept: 'application/json',
8    'content-type': 'application/json',
9    'x-api-key': 'API-Key'
10  },
11  body: JSON.stringify({symbol: 'AAPL', currency: 'EUR'})
12};
13
14fetch(url, options)
15  .then(res => res.json())
16  .then(json => console.log(json))
17  .catch(err => console.error('error:' + err));

PHP

For php, we use guzzle-requests:

composer require guzzlehttp/guzzle

1<?php
2require_once('vendor/autoload.php');
3
4$client = new \GuzzleHttp\Client();
5
6$response = $client->request('POST', 'https://api.bavest.co/v0/quote', [
7  'body' => '{"symbol":"AAPL","currency":"EUR"}',
8  'headers' => [
9    'accept' => 'application/json',
10    'content-type' => 'application/json',
11    'x-api-key' => 'API-Key',
12  ],
13]);
14
15echo $response->getBody();

Integrate real-time courses
How to use websockets with wscat

To integrate real-time data via Websockets, you can use wscat. wscat is a WebSocket client that allows you to receive real-time data from our API.

Installing wscat

npm install -g wscat

Make a connection

wscat -c "wss://ws.bavest.co/v0" -H "x-api-key: <API KEY>"

Get real-time data from various exchanges

Our API supports various exchanges. To get real-time data for a specific symbol from a specific exchange, append the stock exchange symbol as a suffix to the symbol. For example:

  • AAPL.BE: Retrieve real-time data for Apple from the Berlin Stock Exchange.
  • AAPL.NY: Get real-time data for Apple from the New York Stock Exchange.

Financial data integration
Fundamentals

To retrieve fundamental financial data, use the following endpoint: Bavest API Docs: Fundamentals →

Sample code in Python

Request in general:

1const url = 'https://api.bavest.co/v0/stock/fundamentals';
2const options = {
3  method: 'POST',
4  headers: {
5    accept: 'application/json',
6    'content-type': 'application/json',
7    'x-api-key': 'API-Key'
8  },
9  body: JSON.stringify({symbol: 'AAPL'})
10};
11
12fetch(url, options)
13  .then(res => res.json())
14  .then(json => console.log(json))
15  .catch(err => console.error('error:' + err));

Expanded code to save the API response:

1import requests
2import json
3
4url = 'https://api.bavest.co/v0/stock/fundamentals'
5headers = {
6    'accept': 'application/json',
7    'content-type': 'application/json',
8    'x-api-key': 'API-Key'
9}
10data = {
11    'symbol': 'AAPL'
12}
13
14response = requests.post(url, headers=headers, data=json.dumps(data))
15
16if response.status_code == 200:
17    json_data = response.json()
18    print(json_data)
19else:
20    print('Fehler:', response.status_code, response.text)

Financials

To retrieve financial data, use the following endpoint: Bavest API Docs: Financials →

The endpoint returns financial data from the income sheet, balance sheet, and cash flow statement, such as the balance sheet, income statement, or cash flow statement.

Sample code in Python

1const fetch = require('node-fetch');
2
3const url = 'https://api.bavest.co/v0/stock/financials';
4const options = {
5  method: 'POST',
6  headers: {
7    accept: 'application/json',
8    'content-type': 'application/json',
9    'x-api-key': 'API-Key'
10  },
11  body: JSON.stringify({
12    symbol: 'AAPL.DE',
13    freq: 'quarterly',
14    statement: 'cf',
15    currency: 'EUR',
16    limit: 1
17  })
18};
19
20fetch(url, options)
21  .then(res => res.json())
22  .then(json => console.log(json))
23  .catch(err => console.error('error:' + err));

What should you look for when choosing a stock API?

When choosing a stock market API, there are several important criteria to consider to ensure that it meets the needs of your project. Here are the key points:

1. Data coverage

  • Markets and stock exchanges: Make sure that the API covers data from the markets and exchanges that are relevant to your project.
  • Financial instruments: Verify that the API supports all necessary financial instruments, such as stocks, ETFs, funds, bonds, cryptocurrencies, etc.

2. Data quality and timeliness

  • real-time data: Check whether the API provides real-time data and how often it is updated.
  • Historical data: The availability and scope of historical data can be decisive for analysis and backtesting.

3. Reliability and availability

  • Uptime: High availability and reliability are essential, particularly for retail applications.
  • Statuspage: A publicly available status page to monitor services is beneficial.

4. Documentation and Support

  • API documentation: Documentation should be clear and comprehensive, with examples and detailed descriptions of endpoints.
  • Support: Availability of technical support or a developer community to fix issues and help with integration.

5. Costs and subscription plans

  • pricing model: Understand the pricing model and make sure it fits your budget
  • Free trial: Many APIs offer a free trial period or a freemium model to pre-test the services.

6. Technical aspects and integration

  • compatibility: Verify that the API is compatible with your tech stack and development tools.
  • Request speed and limits: Check the rate limits (number of requests per minute/hour) and the latency of the API.

7. Security and authentication

  • Auth methods: Make sure that the API supports secure authentication methods, such as API keys, OAuth, or others.
  • data encryption: Check whether data transmission is encrypted (e.g. using HTTPS).

8. Additional Features

  • Websockets: Websocket support can be useful for real-time applications.
  • Analytics and statistics tools: Some APIs provide additional analytical tools and features.

9. User reviews and reputation

  • valuations: Take a look at reviews and testimonials from other users to better assess the reliability and quality of the API.
  • Vendor reputation: An established provider with a good reputation is often more trustworthy.

10. Flexibility and adaptability

  • Custom endpoints: Sometimes it's useful if the API supports customizable endpoints or flexible data queries.

By carefully reviewing these criteria, you can choose the exchange API that best suits your needs and requirements.

Benefits of Bavest API

Our stock API at Bavest offers numerous benefits:

  1. real-time data: Get the latest prices and market information in real time.
  2. Global data coverage & assets: Access to data on stocks, ETFs, funds, and more.
  3. Data-on-demand: If there are missing data points or securities, Bavest collects the data within 2 weeks and makes it available via API.
  4. Alternative dates: Access to ESG & climate data, sentiment data and KPIs for listed companies, such as sales by region and products.
  5. High availability and reliability: Our infrastructure ensures continuous availability of data.
  6. Easy integration: Our API is user-friendly and easy to integrate into existing applications.
  7. Diverse endpoints: From real-time quotes to historical data and financial reports, our API covers all your needs.
  8. customer support: Our dedicated support team is always available to answer any questions or problems you may have, we will answer within 24 hours.

Bavest stands out for its user-centered model, which emphasizes simplicity and transparency. Customers benefit from:

  • Single API solution: Consolidates data access into one API and reduces backend maintenance that you would have with multiple APIs.
  • Data on Demand: Do you need data, but it is missing from the Bavest API? No problem, within 2 weeks Bavest collects this data and makes it available to you.
  • Transparent pricing: Simple pricing structure without complex licensing, so users only pay for what they need.

Use-Cases

Bavest caters to a wide range of business types, including asset managers, fintech companies, banks, family offices, consulting firms, companies, and media organizations. The infrastructure supports various applications, from automating research processes to developing innovative financial products

Conclusion

With our infrastructure at Bavest, you can quickly and easily integrate financial data into your applications. Regardless of whether you need current stock prices, historical data or ETF information, alternative data or quantitative portfolio analysis, our API provides you with the necessary basis for your product or asset management.

Are you interested? Then book a demo and talk to us. We look forward to meeting you and would like to get to know you and learn more about your company.

blog

More articles