npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

stock-average-calculator

v1.0.0

Published

A comprehensive utility for calculating stock price averages and managing investment portfolios

Downloads

3

Readme

Stock Average Calculator

A comprehensive Node.js utility for calculating stock price averages and managing investment portfolios. Powered by StockAverageCalculator, 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

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:

stock-average

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

API Usage

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

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

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

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

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.