Class Stock
java.lang.Object
me.thiagorigonatti.capitalgains.core.Stock
Represents a stock position and manages buy and sell operations while tracking cost, shares, and tax calculations.
This class is responsible for:
- Maintaining the total number of shares owned
- Calculating the average cost per share after each buy
- Calculating capital gains taxes on sales
- Tracking accumulated losses to offset future gains
Exceptions are thrown if the quantity is zero or negative, or if trying to sell more shares than are owned.
This class is not thread-safe.
- Since:
- 1.0
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionprotected voidbuy(long quantity, BigDecimal unitCost) Processes a buy operation, increasing the number of shares and updating the average cost.protected BigDecimalsell(long quantity, BigDecimal unitCost) Processes a sell operation, updating shares and calculating the capital gains tax based on profit and thresholds.protected BigDecimaltaxRate()Returns the applicable tax rate for capital gains.protected BigDecimalReturns the sales threshold under which capital gains are exempt from taxation.
-
Constructor Details
-
Stock
public Stock()Default constructor for theStockclass.Initializes a new stock instance with zero shares, zero total cost, and zero accumulated losses. Intended for use when the initial state will be populated through operations (e.g., buy/sell).
-
-
Method Details
-
taxRate
Returns the applicable tax rate for capital gains.The current rate is fixed at 20% (0.20).
- Returns:
- the capital gains tax rate as a
BigDecimal
-
threshold
Returns the sales threshold under which capital gains are exempt from taxation.Currently, operations with total sales less than or equal to R$20,000.00 are exempt.
- Returns:
- the tax exemption threshold as a
BigDecimal
-
buy
Processes a buy operation, increasing the number of shares and updating the average cost.- Parameters:
quantity- the number of shares to buy; must be greater than zerounitCost- the cost per share- Throws:
ZeroOrNegativeQuantityException- if the quantity is less than or equal to zero
-
sell
Processes a sell operation, updating shares and calculating the capital gains tax based on profit and thresholds.If the sale results in a loss, the value is added to
accumulatedLoss. If there's a gain and the total value of the sale exceeds R$20,000, tax is calculated at 20% on the net profit after subtracting accumulated losses.- Parameters:
quantity- the number of shares to sell; must be greater than zero and not exceed current holdingsunitCost- the sale price per share- Returns:
- the amount of tax due from the operation, rounded to two decimal places
- Throws:
ZeroOrNegativeQuantityException- if the quantity is less than or equal to zeroInsufficientSharesException- if attempting to sell more shares than currently owned
-