0% found this document useful (0 votes)
15 views8 pages

Stock Price Analysis in Java

The document presents a Java program for stock price analysis, including methods to calculate average price, find maximum price, count occurrences of a specific price, and compute cumulative sums of stock prices. Each method is explained in detail, outlining its purpose and functionality. The program utilizes sample stock price data to demonstrate its capabilities.

Uploaded by

nazilaramzi25
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views8 pages

Stock Price Analysis in Java

The document presents a Java program for stock price analysis, including methods to calculate average price, find maximum price, count occurrences of a specific price, and compute cumulative sums of stock prices. Each method is explained in detail, outlining its purpose and functionality. The program utilizes sample stock price data to demonstrate its capabilities.

Uploaded by

nazilaramzi25
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

The Art of Stock Price Calculation: Average, Maximum, and Cumulative Insights

CS 1102-01 Programming 1 - AY2025-T5

Programming Assignment Unit 4

Instructor: Salah Jabareen

July 17, 2025


The code:
import [Link];

public class StockAnalysis {

// Method to calculate the average price


public static float calculateAveragePrice(float[] stockPrices) {
float sum = 0;
for (float price : stockPrices) {
sum += price;
}
return sum / [Link];
}

// Method to find the maximum price


public static float findMaximumPrice(float[] stockPrices) {
float maxPrice = stockPrices[0];
for (float price : stockPrices) {
if (price > maxPrice) {
maxPrice = price;
}
}
return maxPrice;
}

// Method to count occurrences of a specific price


public static int countOccurrences(float[] stockPrices, float targetPrice)
{
int count = 0;
for (float price : stockPrices) {
if (price == targetPrice) {
count++;
}
}
return count;
}

// Method to compute cumulative sum of stock prices


public static ArrayList<Float> computeCumulativeSum(ArrayList<Float>
stockPrices) {
ArrayList<Float> cumulativeSum = new ArrayList<>();
float sum = 0;
for (float price : stockPrices) {
sum += price;
[Link](sum);
}
return cumulativeSum;
}

public static void main(String[] args) {


// Sample data for stock prices
float[] stockPricesArray = {100.0f, 102.5f, 101.0f, 98.5f, 105.0f,
110.0f, 99.0f, 104.0f, 108.0f, 107.5f};
ArrayList<Float> stockPricesList = new ArrayList<>();
for (float price : stockPricesArray) {
[Link](price);
}

// Calculating average price


float averagePrice = calculateAveragePrice(stockPricesArray);
[Link]("Average Stock Price: " + averagePrice);

// Finding maximum price


float maxPrice = findMaximumPrice(stockPricesArray);
[Link]("Maximum Stock Price: " + maxPrice);

// Counting occurrences of a specific price (e.g., 100.0f)


int occurrences = countOccurrences(stockPricesArray, 100.0f);
[Link]("Occurrences of 100.0: " + occurrences);

// Computing cumulative sum


ArrayList<Float> cumulativeSum = computeCumulativeSum(stockPricesList);
[Link]("Cumulative Sum: " + cumulativeSum);
}
}

Explanation

The calculateAveragePrice method is designed to calculate the average of stock prices. It

accomplishes this by summing up all the prices in the array and then dividing the total by the

number of prices. This provides a clear representation of the average stock price over the

specified period.

The findMaximumPrice method iterates through the stock prices array to determine the

maximum stock price. By comparing each price with the current maximum, it efficiently

identifies the highest value in the dataset.

The countOccurrences method serves the purpose of counting how many times a specific price

appears within the array. It systematically checks each price and increments a counter whenever

a match with the target price is found, providing valuable insights into price frequency.

Lastly, the computeCumulativeSum method operates on an ArrayList, calculating the cumulative

sum of stock prices. As it traverses the list, it maintains a running total, adding each price to this

total and storing the results in a new ArrayList. This method effectively illustrates how stock

prices accumulate over time.


Output:
Reference

Eck, D. J. (2022). Introduction to programming using java version 9, JavaFX edition. Licensed

under CC 4.0. [Link]

Common questions

Powered by AI

The importance of comparing each stock price against the current maximum lies in the necessity to consistently identify and update the largest value encountered. Omitting this comparison could result in the method returning an incorrect maximum value, failing to represent the true peak stock price in the dataset. This is crucial for accurate reporting and analysis of stock performance .

Improvements could include encapsulating stock price operations within a StockPriceAnalyzer object, splitting each method into a separate class file, and utilizing interfaces for extendibility. Enhancements like adding exception handling, using logging instead of print statements, and applying design patterns such as MVC would make the class more modular, testable, and maintainable .

The countOccurrences method is designed to identify how many times a specific target price appears in the stockPrices array. It initializes a counter to zero and iterates through the array, incrementing the counter each time it encounters the target price. This provides key insights into the frequency of occurrences of the target price, revealing patterns or consistencies within the stock data .

The ArrayList<Float> cumulativeSum serves to dynamically store the calculated cumulative sums of stock prices, allowing for efficient additions without predetermining the size, unlike a float array. ArrayLists offer flexibility in dynamically resizing and better represent scenarios where the accumulated results are progressively built, complementing the iterative nature of cumulative calculations .

The calculateAveragePrice method first initializes a sum variable to accumulate the total value of the stock prices. It iterates over each stock price in the provided array, adding each price to the sum. After the iteration is complete, it divides the total sum by the length of the stockPrices array to calculate the average price .

The computeCumulativeSum method is significant in that it demonstrates how stock prices accumulate cumulatively over a timeframe. It operates by traversing an ArrayList of stock prices and maintaining a running total of the sum. For each price, it updates the running total and stores it in a new ArrayList, representing the cumulative sum. This method effectively shows how investments grow over time, an important concept for financial analysis .

Analyzing the output of the main method provides a holistic view of the stock data. The average price reflects overall market trends, the maximum price highlights peak performance, and the occurrence count of specific prices indicates consistency or volatility. Cumulative sums show growth patterns over time. Together, these metrics allow for a nuanced understanding of market behavior and investment outcomes .

The findMaximumPrice method initializes the maxPrice variable to the first element of the stockPrices array. It then iterates through each price in the array, comparing each price to the current maxPrice. If a price is greater than the current maxPrice, it updates maxPrice with this new value. This methodology ensures that by the end of the iteration, maxPrice holds the maximum stock price .

To handle cases where the input array is empty, a check should be added at the beginning of the calculateAveragePrice method to return 0 or an error message if the stockPrices array's length is zero. This prevents division by zero and provides meaningful feedback to the user about the input's validity, ensuring code robustness .

The program ensures accuracy by systematically iterating over each price in ordered processes for calculating averages and maxima. However, assumptions such as non-empty input arrays, and proper data type handling can lead to pitfalls like division by zero or type mismatches. Validating input and handling exceptions are crucial to circumvent these issues and ensure reliable operations .

You might also like