Part 2 : Stock Picker using API and ESP32
- electronicseternit
- May 17
- 3 min read
Welcome to the second part of our stock picker series from Electronics Eternity. In this video, we build on our previous tutorial, where we focused on cash flow assessment using the ESP32 and API integration.
This time, we dive deeper into financial analysis by introducing a new function that compares current assets with current liabilities, a vital metric for evaluating a company’s financial health. By automating this process, our ESP32-based program simplifies stock assessment, allowing you to make informed investment decisions easily. We will walk you through the coding process, explain how the API connects and retrieves data, and demonstrate results using real stocks like Apple, Nvidia, and Microsoft. Whether you are a beginner or an experienced developer, this tutorial offers practical insights to make your stock picker more comprehensive and user-friendly.
Without further ado, let's look into the code that we use to achieve comparison between current assets with current liabilities.
Below is the new current assets vs current liabilities function that we have created. This particular function will added to our existing code from Part 1.
void balance_sheet(char ticker[]) {
//ticker[] instead of ticker as the char size can be random
Serial.println("Starting Balance Sheet Analysis");
char header[255] = "https://api.financialdatasets.ai/financials/balance-sheets/?ticker=";
char footer[] = "&limit=1&period=ttm";
strcat(header, ticker);
strcat(header, footer);
//Serial.println(header);
HTTPClient http;
http.begin(header);
http.addHeader("X-API-KEY", "99ab3496-d1d1-41fb-abef-d2d7423c2725");
int httpCode = http.GET();
if (httpCode > 0) {
String payload = http.getString();
//Serial.println(httpCode);
//Serial.print("payload :");
//Serial.println(payload);
payload.remove(0, 2);
payload.replace("balance_sheets", "");
payload.remove(0, 3);
//Serial.print("Edited Payload :");
//Serial.println(payload);
int stringLen = payload.length() + 1;
char json[stringLen];
payload.toCharArray(json, stringLen);
DeserializationError error = deserializeJson(doc, json);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
//Serial.print("Json :");
//Serial.println(json);
const char* stock = doc["ticker"];
float current_assets = doc["current_assets"];
float current_liabilities = doc["current_liabilities"];
Serial.print("Ticker :");
Serial.println(stock);
Serial.print("Current_Assets :");
Serial.println(current_assets / 1000);
Serial.print("Current_Liabilities :");
Serial.println(current_liabilities / 1000);
float final_value = current_assets / current_liabilities ;
Serial.print("final_value :");
Serial.println(final_value);
if(final_value >= 1){
Serial.println("Balance Sheet is GOOD");
}else{
Serial.println("Balance Sheet is BAD");
}
header[0] = '\0'; // Makes it an empty string
}
else {
Serial.println("Error on HTTP request");
}
http.end(); //Free the resources
Serial.println("");
delay(1000);
}
Let's look at the detail breakdown of the code :
char header[255] = "https://api.financialdatasets.ai/financials/balance-sheets/?ticker=";
char footer[] = "&limit=1&period=ttm";
strcat(header, ticker);
strcat(header, footer);
Constructing the URL
header is a base URL to query balance sheet data.
footer specifies to limit results to 1 and for the trailing twelve months (ttm).
The full URL is built by appending the ticker and footer to the base URL.
Example final URL:https://api.financialdatasets.ai/financials/balance-sheets/?ticker=AAPL&limit=1&period=ttm
HTTPClient http;
http.begin(header); // Begin connection to the API
http.addHeader("X-API-KEY", "99ab3496-d1d1-41fb-abef-d212345625"); // API Key
HTTP Request Setup
Initializes an HTTPClient.
Begins the request to the constructed URL.
Adds the required API key in the header.
int httpCode = http.GET();
if (httpCode > 0) {
HTTP GET Request
Sends a GET request.
If httpCode > 0, it means the request was successful (i.e., received a response).
String payload = http.getString();
payload.remove(0, 2);
payload.replace("balance_sheets", "");
payload.remove(0, 3);
Handling the Response
Gets the response payload as a String.
These three lines are cleaning the payload. It seems the original response has some unwanted characters or structure (like wrapping in a label or array) that needs to be removed before parsing.The payload is being sanitized so it can be deserialized as JSON.
int stringLen = payload.length() + 1;
char json[stringLen];
payload.toCharArray(json, stringLen);
DeserializationError error = deserializeJson(doc, json);
if (error) {
Serial.print(F("deserializeJson() failed: "));
Serial.println(error.f_str());
return;
}
Convert to JSON & Parse
Converts the cleaned payload String into a char array (C-style string).
Tries to deserialize the JSON using ArduinoJson.
If parsing fails, it prints an error and returns.
const char* stock = doc["ticker"];
float current_assets = doc["current_assets"];
float current_liabilities = doc["current_liabilities"];
Extracting Fields
Reads key fields from the JSON:
ticker: the stock symbol.
current_assets: short-term assets.
current_liabilities: short-term debts.
Serial.print("Ticker :");
Serial.println(stock);
Serial.print("Current_Assets :");
Serial.println(current_assets / 1000); // Scaled down
Serial.print("Current_Liabilities :");
Serial.println(current_liabilities / 1000); // Scaled down
Print Financial Info
Outputs the data to the Serial Monitor.
Divides by 1000 to show values in thousands.
float final_value = current_assets / current_liabilities ;
Serial.print("final_value :");
Serial.println(final_value);
if(final_value >= 1){
Serial.println("Balance Sheet is GOOD");
}else{
Serial.println("Balance Sheet is BAD");
}
Balance Sheet Evaluation
Computes the current ratio.
Prints whether the balance sheet is GOOD or BAD based on the ratio.
header[0] = '\0'; // Reset header
http.end(); // Free resources
Serial.println("");
delay(1000); // Wait 1 second before continuing
Clean Up
Clears the header array for safety.
Ends the HTTP session.
Delays 1 second.
With that we have come to the end of the tutorial, for more detailed instruction feel free to check out my YouTube video below :
Thank You for Watching. Please Don't Forget to Like and Subscribe :)
Comments