Stock Profit/Loss Calculator
Calculate profit, loss, ROI from stock trading. Essential for investment analysis. Handles multiple buy/sell transactions, fees, taxes. Computes portfolio performance metrics.
Visualization
Interactive visualization for Stock Profit/Loss Calculator
Stock Profit/Loss:
- • P/L = (Sell - Buy) × Shares
Interactive visualization with step-by-step execution
Implementation
1class StockCalculator {
2 calculateProfit(
3 buyPrice: number,
4 sellPrice: number,
5 shares: number,
6 fees: number = 0
7 ): number {
8 const investment = buyPrice * shares + fees;
9 const revenue = sellPrice * shares - fees;
10 return revenue - investment;
11 }
12
13 calculateROI(
14 buyPrice: number,
15 sellPrice: number,
16 shares: number,
17 fees: number = 0
18 ): number {
19 const profit = this.calculateProfit(buyPrice, sellPrice, shares, fees);
20 const investment = buyPrice * shares + fees;
21 return (profit / investment) * 100;
22 }
23
24 calculateAverageCost(transactions: Array<{price: number; shares: number}>): number {
25 let totalCost = 0;
26 let totalShares = 0;
27
28 for (const tx of transactions) {
29 totalCost += tx.price * tx.shares;
30 totalShares += tx.shares;
31 }
32
33 return totalCost / totalShares;
34 }
35
36 calculatePortfolioValue(holdings: Array<{shares: number; currentPrice: number}>): number {
37 return holdings.reduce((sum, h) => sum + h.shares * h.currentPrice, 0);
38 }
39
40 calculateCapitalGainsTax(profit: number, taxRate: number): number {
41 return profit > 0 ? profit * taxRate : 0;
42 }
43
44 breakEvenPrice(buyPrice: number, fees: number, shares: number): number {
45 return buyPrice + (fees * 2) / shares;
46 }
47
48 sharpeRatio(returns: number[], riskFreeRate: number): number {
49 const avgReturn = returns.reduce((a, b) => a + b) / returns.length;
50 const variance = returns.reduce((sum, r) =>
51 sum + Math.pow(r - avgReturn, 2), 0) / returns.length;
52 const stdDev = Math.sqrt(variance);
53
54 return (avgReturn - riskFreeRate) / stdDev;
55 }
56}Deep Dive
Theoretical Foundation
Profit = (Sell Price - Buy Price) × Shares - Fees. ROI = (Profit / Investment) × 100%. Capital gains tax on profits. Average cost basis for multiple purchases. Realized vs unrealized gains. Portfolio diversification metrics.
Complexity
Time
O(1) single, O(n) portfolio
O(n)
O(n)
Space
O(1)
Applications
Industry Use
Individual stock trading analysis
Portfolio performance tracking
Tax preparation and reporting
Investment strategy evaluation
Day trading profit calculations
Mutual fund and ETF analysis
Retirement account management
Financial advisor client reporting
Use Cases
Related Algorithms
GCD (Euclidean Algorithm)
Compute the Greatest Common Divisor (GCD) of two integers using the Euclidean algorithm. Dating back to around 300 BC and appearing in Euclid's Elements, it's one of the oldest algorithms still in common use. The algorithm is based on the principle that GCD(a,b) = GCD(b, a mod b) and is remarkably efficient with O(log min(a,b)) time complexity. The GCD is the largest positive integer that divides both numbers without remainder.
LCM (Least Common Multiple)
Calculate the Least Common Multiple (LCM) of two integers - the smallest positive integer that is divisible by both numbers. The LCM is intimately related to the GCD through the formula: LCM(a,b) = |a×b| / GCD(a,b). This relationship allows us to compute LCM efficiently using the Euclidean algorithm for GCD, achieving O(log min(a,b)) time complexity instead of naive factorization methods.
Sieve of Eratosthenes
Ancient and highly efficient algorithm to find all prime numbers up to a given limit n. Invented by Greek mathematician Eratosthenes of Cyrene (276-194 BC), this sieve method systematically eliminates multiples of primes, leaving only primes in the array. With O(n log log n) time complexity, it remains one of the most practical algorithms for generating large lists of primes, vastly superior to trial division which runs in O(n² / log n) time.
Prime Factorization
Decompose a positive integer into its unique prime factor representation. Every integer greater than 1 can be expressed as a product of prime numbers in exactly one way (Fundamental Theorem of Arithmetic). This algorithm uses trial division optimized to check only up to √n, as any composite number must have a prime factor ≤ √n. Returns a map of prime factors to their powers, e.g., 360 = 2³ × 3² × 5¹.