# Stock Average Calculator

A comprehensive Node.js utility for calculating stock price averages and managing investment portfolios. Powered by [StockAverageCalculator](https://stockaveragecalculator.org/), this package helps investors track their average purchase prices, analyze portfolio performance, and plan averaging strategies.

## Features

- **Multiple Calculation Types**:
  - Basic average price calculations
  - Portfolio performance metrics with profit/loss analysis
  - Dollar cost averaging simulation
  - Target average strategy calculator

- **Detailed Results**:
  - Average purchase price
  - Total shares and investment
  - Current portfolio value
  - Profit/loss analysis
  - Optimal purchase strategy recommendations

- **Easy to Use**:
  - Simple API for developers
  - Interactive command-line interface
  - Comprehensive documentation with examples

## Installation

```bash
npm install stock-average-calculator
```

## Command Line Usage

After installing globally with `npm install -g stock-average-calculator`, you can use the calculator directly from your terminal:

```bash
stock-average
```

This will launch an interactive CLI that guides you through the calculation process.

## API Usage

```javascript
const { 
  calculateAveragePrice,
  calculatePortfolioMetrics,
  calculateDollarCostAveraging
} = require('stock-average-calculator');

// Example 1: Calculate average price from multiple purchases
const transactions = [
  { shares: 10, price: 100 },
  { shares: 15, price: 90 },
  { shares: 5, price: 105 }
];

const avgResult = calculateAveragePrice(transactions);
console.log(`Average Price: $${avgResult.averagePrice}`);
// Output: Average Price: $96.67

// Example 2: Calculate portfolio performance with current market price
const portfolioResult = calculatePortfolioMetrics(transactions, 110);
console.log(`Profit/Loss: $${portfolioResult.profitLoss} (${portfolioResult.profitLossPercentage}%)`);
// Output: Profit/Loss: $401.67 (13.79%)

// Example 3: Calculate dollar cost averaging performance
const dcaResult = calculateDollarCostAveraging(
  1000,     // Initial investment
  500,      // Periodic investment
  [100, 90, 110, 105, 120],  // Stock prices over time
  'monthly' // Frequency
);
console.log(`Total Shares: ${dcaResult.totalShares}, Average Price: $${dcaResult.averagePrice}`);
```

## API Reference

### calculateAveragePrice(transactions)

Calculates the average purchase price from multiple transactions.

**Parameters:**
- `transactions`: Array of objects with `shares` and `price` properties

**Returns:**
- Object containing `totalShares`, `totalCost`, and `averagePrice`

### calculatePortfolioMetrics(transactions, currentPrice)

Calculates portfolio performance metrics based on purchase history and current market price.

**Parameters:**
- `transactions`: Array of objects with `shares` and `price` properties
- `currentPrice`: Current market price per share

**Returns:**
- Object containing average price, total shares, current value, profit/loss, etc.

### calculateDollarCostAveraging(initialInvestment, periodicInvestment, prices, frequency)

Simulates a dollar cost averaging investment strategy.

**Parameters:**
- `initialInvestment`: Initial investment amount
- `periodicInvestment`: Amount invested in each period
- `prices`: Array of stock prices for each period
- `frequency`: Investment frequency (e.g., 'monthly', 'weekly')

**Returns:**
- Object containing results of the DCA strategy

### calculateOptimalAveragingStrategy(currentTransactions, targetAveragePrice, currentMarketPrice)

Calculates the optimal strategy to reach a target average price.

**Parameters:**
- `currentTransactions`: Current holdings as an array of transactions
- `targetAveragePrice`: Desired average purchase price
- `currentMarketPrice`: Current market price per share

**Returns:**
- Object containing the suggested action to reach the target average

### Other Utility Functions

- `calculateBreakEvenPrice(transactions)`
- `formatAveragePriceResult(result)`
- `formatPortfolioMetricsResult(result)`
- `formatDCAResult(result)`
- `quickCalculateAverage(amounts, prices)`

## Examples

### Average Price Calculation
```javascript
const result = calculateAveragePrice([
  { shares: 5, price: 100 },
  { shares: 8, price: 90 },
  { shares: 12, price: 110 }
]);

// Result: Average price $101.60 for 25 shares with total cost of $2,540
```

### Portfolio Performance Analysis
```javascript
const transactions = [
  { shares: 100, price: 50 },
  { shares: 50, price: 45 }
];

const result = calculatePortfolioMetrics(transactions, 55);
// Result: 150 shares at average $48.33, current value $8,250
// Profit: $1,000 (13.79%)
```

### Dollar Cost Averaging
```javascript
const result = calculateDollarCostAveraging(
  5000,    // $5,000 initial investment
  1000,    // $1,000 monthly investment
  [100, 90, 110, 105, 95, 115],  // Stock prices over 6 months
  'monthly'
);
// Result shows performance of DCA strategy over the 6-month period
```

### Target Averaging Strategy
```javascript
const transactions = [
  { shares: 100, price: 50 }
];

const result = calculateOptimalAveragingStrategy(
  transactions,
  45,     // Target average price of $45
  40      // Current market price is $40
);
// Result shows how many shares to buy at $40 to reach an average of $45
```

## Use Cases

- **Individual Investors**: Calculate and track average purchase prices
- **Financial Advisors**: Demonstrate DCA strategies to clients
- **Portfolio Managers**: Analyze portfolio performance and plan averaging strategies
- **Investment Apps**: Integrate average price calculations into investment platforms
- **Educational Tools**: Teach concepts of cost averaging and breakeven analysis

## License

MIT

---

Try our [advanced stock averaging calculator](https://discountcalculator.org/).