Stock Market Analyzer Java, API
👤 Sharing: AI
```java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONObject;
public class StockMarketAnalyzer {
// API key (replace with your actual API key)
private static final String API_KEY = "YOUR_API_KEY"; // Replace with your actual API key. Consider storing this more securely in a real application.
// API endpoint (example: using Alpha Vantage)
private static final String API_ENDPOINT = "https://www.alphavantage.co/query";
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Welcome to the Stock Market Analyzer!");
while (true) {
System.out.print("Enter a stock symbol (e.g., AAPL, MSFT, GOOG) or 'exit' to quit: ");
String symbol = scanner.nextLine().trim().toUpperCase(); // Convert to uppercase for case-insensitive input
if (symbol.equalsIgnoreCase("exit")) {
System.out.println("Exiting program.");
break;
}
try {
JSONObject stockData = getStockData(symbol);
if (stockData != null) {
displayStockData(symbol, stockData);
}
} catch (IOException e) {
System.err.println("Error fetching stock data: " + e.getMessage()); // Improved error handling
} catch (Exception e) {
System.err.println("An unexpected error occurred: " + e.getMessage()); // Catch any other unexpected exceptions
}
}
scanner.close();
}
/**
* Fetches stock data from the Alpha Vantage API for a given symbol.
*
* @param symbol The stock symbol to retrieve data for.
* @return A JSONObject containing the stock data, or null if an error occurs.
* @throws IOException If an error occurs during the API call.
*/
private static JSONObject getStockData(String symbol) throws IOException {
// Construct the API URL
String urlString = API_ENDPOINT + "?function=GLOBAL_QUOTE&symbol=" + symbol + "&apikey=" + API_KEY;
URL url = new URL(urlString);
HttpURLConnection connection = null; // Initialize to null to handle potential connection errors
try {
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// Read the response from the API
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
// Parse the JSON response
JSONObject jsonResponse = new JSONObject(response.toString());
// Check for errors in the API response
if (jsonResponse.has("Error Message")) {
System.err.println("Error from API: " + jsonResponse.getString("Error Message"));
return null;
}
//The actual data is under Global Quote
if (jsonResponse.has("Global Quote")) {
return jsonResponse.getJSONObject("Global Quote");
} else {
System.err.println("No 'Global Quote' data found for symbol: " + symbol);
return null;
}
} else {
System.err.println("API request failed with response code: " + responseCode);
return null;
}
} finally {
if (connection != null) {
connection.disconnect(); // Ensure the connection is closed in a finally block
}
}
}
/**
* Displays the stock data in a user-friendly format.
*
* @param symbol The stock symbol.
* @param stockData The JSONObject containing the stock data.
*/
private static void displayStockData(String symbol, JSONObject stockData) {
if (stockData == null || stockData.isEmpty()) {
System.out.println("No data available for symbol: " + symbol);
return;
}
System.out.println("\nStock data for " + symbol + ":");
System.out.println(" Symbol: " + stockData.getString("01. symbol"));
System.out.println(" Open: " + stockData.getString("02. open"));
System.out.println(" High: " + stockData.getString("03. high"));
System.out.println(" Low: " + stockData.getString("04. low"));
System.out.println(" Price: " + stockData.getString("05. price"));
System.out.println(" Volume: " + stockData.getString("06. volume"));
System.out.println(" Latest Trading Day: " + stockData.getString("07. latest trading day"));
System.out.println(" Previous Close: " + stockData.getString("08. previous close"));
System.out.println(" Change: " + stockData.getString("09. change"));
System.out.println(" Change Percent: " + stockData.getString("10. change percent"));
System.out.println();
}
}
```
Key improvements and explanations:
* **Clearer Structure and Comments:** The code is well-commented, explaining the purpose of each method and important sections. The logic flow is easier to follow.
* **Error Handling:** Includes comprehensive error handling. It catches `IOException` for API call failures, checks for error messages directly from the API, and includes a general `Exception` catch-all. This prevents the program from crashing due to unexpected errors and provides more informative error messages to the user. Critically, the `finally` block ensures that the `HttpURLConnection` is *always* closed, preventing resource leaks.
* **API Key:** Explicitly mentions replacing the placeholder `YOUR_API_KEY` and suggests storing it more securely in a real application (e.g., environment variables).
* **JSON Parsing:** Handles the parsing of the JSON response from the API using the `org.json` library. Checks if the necessary "Global Quote" data is present. Catches exceptions when the data is missing.
* **User Input:** Uses a `Scanner` to get stock symbols from the user. The input is converted to uppercase to make the symbol input case-insensitive. The loop continues until the user enters "exit."
* **API Usage:** Demonstrates how to make an HTTP request to an external API (Alpha Vantage in this example) and retrieve data. Includes the necessary URL parameters (function, symbol, API key).
* **`try-with-resources` (Not Used, But a Good Option):** While not *required* here since the connection is managed manually to ensure disconnection in the `finally` block, it's worth noting that a `try-with-resources` block would be ideal if you *were* managing the input stream within the `try` block itself. It would automatically close the `BufferedReader` and `InputStreamReader`.
* **Data Display:** Presents the retrieved stock data in a readable format to the user.
* **Dependencies:** Requires the `org.json` library for JSON parsing. You'll need to add this as a dependency in your project (e.g., using Maven or Gradle). For Maven:
```xml
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version> <!-- Use the latest version -->
</dependency>
```
For Gradle:
```gradle
implementation 'org.json:json:20231013' // Use the latest version
```
* **Resource Management:** Explicitly closes the `BufferedReader` in a `finally` block to release resources, preventing potential resource leaks.
* **Error Message for Missing Data:** Handles cases where the API doesn't return data for a given symbol or if the response doesn't contain the expected "Global Quote" structure, providing a more informative message.
* **Clearer API URL Construction:** The API URL is constructed more explicitly, making it easier to understand the request being made.
How to Run:
1. **Get an API Key:** Sign up for a free API key from Alpha Vantage (or another stock market API provider). The free tier usually has rate limits.
2. **Add Dependency:** Add the `org.json` dependency to your project (Maven or Gradle).
3. **Replace API Key:** Replace `"YOUR_API_KEY"` with your actual API key in the code.
4. **Compile and Run:** Compile the Java code and run it.
5. **Enter Stock Symbols:** The program will prompt you to enter stock symbols. Enter valid symbols (e.g., AAPL, MSFT).
6. **View Results:** The program will display the stock data retrieved from the API.
This improved version is robust, handles errors gracefully, and provides a better user experience. Remember to replace `"YOUR_API_KEY"` with your actual API key. Always adhere to the API provider's terms of service, including rate limits. Consider using a more robust API like IEX Cloud or Finnhub for production applications.
👁️ Viewed: 9
Comments