Price to Earning Ratio Calculator

Price to Earnings (P/E) Ratio Calculator & Guide :root { –primary-color: #004a99; –success-color: #28a745; –background-color: #f8f9fa; –text-color: #333; –secondary-text-color: #555; –border-color: #ccc; –light-gray: #e9ecef; –white: #fff; } body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background-color: var(–background-color); color: var(–text-color); margin: 0; padding: 0; line-height: 1.6; } .container { max-width: 1000px; margin: 20px auto; padding: 20px; background-color: var(–white); border-radius: 8px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); } header { text-align: center; margin-bottom: 30px; padding-bottom: 20px; border-bottom: 1px solid var(–light-gray); } h1 { color: var(–primary-color); font-size: 2.5em; margin-bottom: 0.5em; } h2, h3 { color: var(–primary-color); margin-top: 1.5em; margin-bottom: 0.8em; } .calculator-wrapper { background-color: var(–white); padding: 25px; border-radius: 8px; box-shadow: 0 1px 5px rgba(0, 0, 0, 0.05); margin-bottom: 30px; } .input-group { margin-bottom: 20px; } .input-group label { display: block; margin-bottom: 8px; font-weight: bold; color: var(–primary-color); } .input-group input[type="number"], .input-group select { width: calc(100% – 20px); padding: 10px; border: 1px solid var(–border-color); border-radius: 4px; font-size: 1em; box-sizing: border-box; } .input-group input[type="number"]:focus, .input-group select:focus { outline: none; border-color: var(–primary-color); box-shadow: 0 0 0 2px rgba(0, 74, 153, 0.2); } .input-group .helper-text { font-size: 0.85em; color: var(–secondary-text-color); margin-top: 5px; display: block; } .error-message { color: red; font-size: 0.8em; margin-top: 5px; display: none; /* Hidden by default */ } .button-group { display: flex; gap: 10px; margin-top: 25px; flex-wrap: wrap; } button { padding: 10px 20px; border: none; border-radius: 4px; cursor: pointer; font-size: 1em; font-weight: bold; transition: background-color 0.3s ease; } .btn-calculate { background-color: var(–primary-color); color: var(–white); } .btn-calculate:hover { background-color: #003366; } .btn-reset { background-color: var(–secondary-text-color); color: var(–white); } .btn-reset:hover { background-color: #555; } .btn-copy { background-color: var(–light-gray); color: var(–text-color); border: 1px solid var(–border-color); } .btn-copy:hover { background-color: #ddd; } #results { margin-top: 30px; padding: 25px; border: 1px solid var(–border-color); border-radius: 8px; background-color: var(–light-gray); } #results h3 { margin-top: 0; color: var(–primary-color); } .result-item { margin-bottom: 15px; } .result-item label { font-weight: normal; color: var(–text-color); display: inline-block; min-width: 180px; /* Align labels */ } .result-item .value { font-weight: bold; color: var(–primary-color); font-size: 1.2em; } .primary-result { text-align: center; margin-bottom: 25px; padding: 20px; background-color: var(–success-color); color: var(–white); border-radius: 8px; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1); } .primary-result h3 { color: var(–white); margin-bottom: 10px; font-size: 1.5em; } .primary-result .value { font-size: 2.5em; font-weight: bold; } .formula-explanation { font-size: 0.9em; color: var(–secondary-text-color); margin-top: 15px; font-style: italic; } table { width: 100%; border-collapse: collapse; margin-top: 20px; margin-bottom: 20px; overflow-x: auto; /* Make tables scrollable */ display: block; /* Needed for overflow-x */ white-space: nowrap; /* Prevent wrapping in cells */ } th, td { padding: 10px 15px; text-align: left; border: 1px solid var(–border-color); } thead { background-color: var(–primary-color); color: var(–white); } th { font-weight: bold; } tbody tr:nth-child(even) { background-color: var(–light-gray); } caption { font-size: 1.1em; font-weight: bold; color: var(–primary-color); margin-bottom: 10px; text-align: left; } canvas { max-width: 100%; /* Make charts responsive */ height: auto; display: block; /* Prevent extra space below */ margin: 20px auto; background-color: var(–white); border-radius: 4px; border: 1px solid var(–border-color); } .chart-legend { text-align: center; margin-top: 10px; font-size: 0.9em; color: var(–secondary-text-color); } .chart-legend span { margin: 0 10px; } .article-content { margin-top: 40px; padding-top: 30px; border-top: 1px solid var(–light-gray); } .article-content h2 { font-size: 1.8em; border-bottom: 2px solid var(–primary-color); padding-bottom: 5px; } .article-content h3 { font-size: 1.4em; margin-top: 1.8em; } .article-content p, .article-content ul, .article-content ol { margin-bottom: 1.5em; font-size: 1.05em; } .article-content ul, .article-content ol { padding-left: 25px; } .article-content li { margin-bottom: 0.8em; } .faq-section { background-color: var(–light-gray); padding: 20px; border-radius: 5px; margin-top: 20px; } .faq-section h3 { font-size: 1.3em; margin-top: 0; margin-bottom: 15px; } .faq-item { margin-bottom: 15px; } .faq-item .question { font-weight: bold; color: var(–primary-color); cursor: pointer; position: relative; padding-left: 25px; } .faq-item .question::before { content: '+'; position: absolute; left: 5px; font-weight: bold; color: var(–primary-color); } .faq-item.open .question::before { content: '-'; } .faq-item .answer { display: none; padding-left: 20px; margin-top: 10px; border-left: 2px solid var(–primary-color); color: var(–secondary-text-color); } .internal-links { background-color: var(–light-gray); padding: 20px; border-radius: 5px; margin-top: 20px; } .internal-links h3 { font-size: 1.3em; margin-top: 0; margin-bottom: 15px; } .internal-links ul { list-style: none; padding: 0; } .internal-links li { margin-bottom: 10px; } .internal-links a { color: var(–primary-color); text-decoration: none; font-weight: bold; } .internal-links a:hover { text-decoration: underline; } .internal-links p { font-size: 0.95em; color: var(–secondary-text-color); margin-top: 5px; } .variable-table table { margin-top: 10px; } .variable-table th, .variable-table td { padding: 8px 12px; } .variable-table thead { background-color: var(–secondary-text-color); } @media (max-width: 600px) { h1 { font-size: 1.8em; } .container { margin: 10px; padding: 15px; } .button-group { flex-direction: column; } .result-item label { min-width: auto; display: block; margin-bottom: 5px; } .primary-result .value { font-size: 2em; } table { font-size: 0.9em; } }

Price to Earnings (P/E) Ratio Calculator

Analyze stock valuation by calculating and understanding the Price to Earnings ratio.

P/E Ratio Calculator

Enter the current market price of one share of the stock.
Enter the company's total earnings divided by its outstanding shares. (TTM – Trailing Twelve Months is common).

Calculation Results

P/E Ratio

The Price to Earnings (P/E) Ratio is calculated by dividing the current market price per share by the earnings per share (EPS).
Formula: P/E Ratio = Current Stock Price / Earnings Per Share (EPS)

Understanding a company's valuation is crucial for any investor. The Price to Earnings (P/E) ratio is one of the most fundamental metrics used to assess how a stock's market price relates to its profitability. This P/E ratio calculator and guide will help you demystify this key financial indicator.

What is the Price to Earnings (P/E) Ratio?

The Price to Earnings (P/E) ratio is a valuation multiple that measures the current share price of a company relative to its earnings per share (EPS). In simpler terms, it tells you how much investors are willing to pay for every dollar of a company's earnings. A higher P/E ratio generally suggests that investors expect higher earnings growth in the future, compared to companies with a lower P/E ratio. Conversely, a low P/E ratio might indicate that a stock is undervalued or that investors anticipate lower growth.

Who Should Use the P/E Ratio?

The P/E ratio is primarily used by:

  • Stock Investors: To compare the relative valuation of different stocks within the same industry or sector.
  • Financial Analysts: To assess a company's market value and identify potential investment opportunities.
  • Traders: To gauge market sentiment and potential over/undervaluation.

Common Misconceptions about P/E Ratio

  • A High P/E is Always Bad: Not necessarily. High-growth companies often command higher P/E ratios. The context of the industry and growth prospects is vital.
  • A Low P/E is Always Good: A low P/E could signal that a company is undervalued, but it might also indicate underlying problems or declining future earnings.
  • P/E is the Only Metric Needed: P/E is just one piece of the puzzle. It should be used in conjunction with other financial ratios and qualitative analysis.

P/E Ratio Formula and Mathematical Explanation

The calculation for the Price to Earnings ratio is straightforward but requires accurate data. Here's the breakdown:

The P/E Ratio Formula

The core formula is:

P/E Ratio = Current Stock Price / Earnings Per Share (EPS)

Variable Explanations

  • Current Stock Price: This is the most recent trading price of one share of the company's stock on the open market.
  • Earnings Per Share (EPS): This represents the portion of a company's profit allocated to each outstanding share of common stock. It's calculated by taking the company's net income and subtracting any preferred dividends, then dividing by the total number of outstanding common shares.

Variable Details and Typical Ranges

P/E Ratio Variables
Variable Meaning Unit Typical Range
Current Stock Price Market price of one share Currency (e.g., $, €, £) Varies widely (e.g., $1 to $1000+)
Earnings Per Share (EPS) Company's profit per outstanding share Currency (e.g., $, €, £) Can be positive or negative. Positive can range from negligible to hundreds.
P/E Ratio Valuation multiple Ratio (e.g., 15x, 25x) Often 10-25 for mature companies. Growth stocks can be 30+. Negative P/E for unprofitable companies.

Derivation and Context

The P/E ratio is derived by comparing the value investors place on a company (its stock price) to its ability to generate profits (its earnings). When EPS is negative (the company is losing money), the P/E ratio is considered meaningless or negative, and other metrics like Price-to-Sales (P/S) might be more relevant.

Practical Examples (Real-World Use Cases)

Example 1: Tech Growth Stock vs. Utility Company

Let's compare two hypothetical companies:

Company A: "InnovateTech Inc." (Growth Tech)

  • Current Stock Price: $150.00
  • Earnings Per Share (EPS) (TTM): $3.00

Calculation:

P/E Ratio = $150.00 / $3.00 = 50x

Interpretation: InnovateTech has a high P/E ratio of 50. This suggests investors expect significant future earnings growth from this tech company, and they are willing to pay a premium for its stock based on those expectations. This P/E might be considered normal or even low for a fast-growing tech company.

Company B: "Reliable Power Corp." (Mature Utility)

  • Current Stock Price: $45.00
  • Earnings Per Share (EPS) (TTM): $3.00

Calculation:

P/E Ratio = $45.00 / $3.00 = 15x

Interpretation: Reliable Power Corp. has a P/E ratio of 15. This is much lower than InnovateTech. Utility companies are typically mature, stable businesses with slower growth prospects. A P/E of 15 might be considered fair or even high for a mature utility, reflecting its stability and dividend payments rather than rapid growth.

Example 2: Undervalued Company Scenario

Consider "Global Manufacturing Ltd.":

  • Current Stock Price: $20.00
  • Earnings Per Share (EPS) (TTM): $4.00

Calculation:

P/E Ratio = $20.00 / $4.00 = 5x

Interpretation: A P/E ratio of 5 is quite low. While it might seem like a bargain, investors would need to investigate why. Is the company facing temporary challenges that depress its stock price but are expected to resolve? Or are there fundamental issues (e.g., declining industry, poor management) that justify the low valuation? Further analysis is crucial before concluding it's undervalued.

How to Use This P/E Ratio Calculator

Our P/E ratio calculator simplifies the process of determining this important valuation metric. Follow these simple steps:

  1. Enter Current Stock Price: Input the current market price for one share of the stock you are analyzing.
  2. Enter Earnings Per Share (EPS): Input the company's Earnings Per Share (EPS) for the desired period. The Trailing Twelve Months (TTM) EPS is most commonly used.
  3. Click 'Calculate P/E Ratio': The calculator will instantly compute the P/E ratio.

How to Read the Results

  • P/E Ratio: The main result displayed prominently. This is your calculated P/E multiple.
  • Input Values: The calculator confirms the stock price and EPS you entered.
  • Valuation Interpretation: A brief guide based on common P/E ranges, offering initial context (e.g., "High – Potential Growth," "Moderate – Stable," "Low – Potential Undervaluation"). Remember this is a general guide and requires further research.

Decision-Making Guidance

Use the calculated P/E ratio as a starting point for your investment decisions:

  • Compare: Benchmark the P/E against the company's historical P/E ratios, industry averages, and competitors.
  • Investigate: If the P/E seems unusually high or low, dig deeper into the company's financial health, growth prospects, competitive landscape, and management quality.
  • Context is Key: Always consider the P/E ratio within the broader economic environment and the specific industry dynamics.
  • Combine with Other Metrics: Don't rely solely on P/E. Analyze other financial ratios like P/B, P/S, Debt-to-Equity, and dividend yields.

Key Factors That Affect P/E Ratio Results

Several elements influence a stock's price and a company's earnings, thereby impacting the P/E ratio. Understanding these factors provides crucial context:

  1. Growth Expectations: The most significant factor. Higher expected future earnings growth typically leads to a higher P/E ratio as investors anticipate greater returns. Companies in rapidly expanding industries often have higher P/Es.
  2. Industry Norms: Different industries naturally have different average P/E ratios. Mature, stable industries like utilities tend to have lower P/Es than dynamic sectors like technology or biotechnology.
  3. Economic Conditions: Broader economic health influences investor confidence and corporate earnings. In a strong economy, P/Es might rise; in a recession, they may fall as earnings decline and investor sentiment weakens.
  4. Interest Rates: When interest rates rise, the cost of capital increases, and future earnings become less valuable in present terms (discounting). This can put downward pressure on stock prices and thus P/E ratios. Conversely, low rates can inflate P/E multiples.
  5. Company Profitability and Stability: A company with consistent, predictable earnings, even if slow-growing, may command a higher P/E than one with volatile earnings, reflecting lower risk.
  6. Debt Levels (Leverage): High levels of debt can increase financial risk. Investors might demand a lower P/E for highly leveraged companies, as higher interest payments reduce net income available to shareholders.
  7. Market Sentiment and Investor Psychology: Sometimes, stock prices (and thus P/E ratios) are driven by speculation, hype, or fear, leading to valuations that deviate significantly from fundamental earnings.
  8. Inflation: High inflation can erode the purchasing power of future earnings and increase costs for businesses, potentially impacting both stock prices and earnings, thereby affecting the P/E ratio.

Frequently Asked Questions (FAQ)

What is a "good" P/E ratio?
There's no universal "good" P/E ratio. It depends heavily on the industry, growth prospects, and economic conditions. A P/E of 15-25 is often considered average for established companies, but tech stocks might justify higher multiples (30+) while utilities might have lower ones (10-15). Always compare within the context of the specific company and its peers.
Can a P/E ratio be negative?
Yes, a P/E ratio is negative when a company's Earnings Per Share (EPS) is negative, meaning the company is losing money. In such cases, the P/E ratio is not meaningful, and investors often look at other metrics like the Price-to-Sales (P/S) ratio or Price-to-Book (P/B) ratio.
What's the difference between Trailing P/E and Forward P/E?
Trailing P/E uses the EPS from the last twelve months (TTM). Forward P/E uses analysts' estimated EPS for the next twelve months. Forward P/E can be useful for growth stocks, but it relies on future estimates which may not be accurate.
Is a P/E ratio of 0 possible?
A P/E ratio of 0 is theoretically impossible unless the stock price is zero (which means the company is worthless) or EPS is infinite (which is impossible). However, a P/E can be very close to zero if the stock price is extremely low relative to very high earnings.
How does P/E help in comparing stocks?
P/E helps investors compare the relative valuation of stocks within the same industry. A stock with a significantly lower P/E than its peers might be undervalued, while one with a much higher P/E might be overvalued, assuming similar growth prospects.
Should I only invest in stocks with low P/E ratios?
Not necessarily. Low P/E stocks can be value traps (companies facing serious issues). High P/E stocks can be justified if the company has strong, sustainable growth potential. It's crucial to understand the reasons behind the P/E ratio.
How often should I check the P/E ratio?
For active investors, checking P/E ratios regularly (e.g., quarterly when earnings reports are released) is advisable. For long-term investors, understanding the P/E trend and its context over time is more important than daily checks.
What other ratios are important alongside P/E?
Other crucial ratios include Price-to-Book (P/B), Price-to-Sales (P/S), Dividend Yield, Debt-to-Equity Ratio, Return on Equity (ROE), and Profit Margins. A comprehensive analysis uses multiple metrics.

Dynamic P/E Ratio Chart Example

The chart below illustrates how the P/E ratio might fluctuate based on changes in stock price while keeping EPS constant. This helps visualize the direct relationship between stock price and P/E.

P/E Ratio Stock Price
Stock Price vs. P/E Ratio (with constant EPS)

© 2023 Your Financial Website. All rights reserved. This calculator and content are for informational purposes only and do not constitute financial advice.

var chartInstance = null; // Global variable to hold the chart instance function isNumeric(value) { return !isNaN(parseFloat(value)) && isFinite(value); } function validateInput(inputId, errorId, minValue = 0) { var input = document.getElementById(inputId); var errorElement = document.getElementById(errorId); var value = input.value.trim(); var isValid = true; errorElement.style.display = 'none'; // Hide error by default if (value === ") { errorElement.textContent = 'This field is required.'; errorElement.style.display = 'block'; isValid = false; } else if (!isNumeric(value)) { errorElement.textContent = 'Please enter a valid number.'; errorElement.style.display = 'block'; isValid = false; } else { var numValue = parseFloat(value); if (numValue < minValue) { errorElement.textContent = 'Value cannot be negative.'; errorElement.style.display = 'block'; isValid = false; } } return isValid; } function calculatePE() { var stockPriceInput = document.getElementById('stockPrice'); var epsInput = document.getElementById('earningsPerShare'); var peRatioResult = document.getElementById('peRatioResult'); var inputStockPriceDisplay = document.getElementById('inputStockPriceDisplay'); var inputEPDisplay = document.getElementById('inputEPDisplay'); var interpretationResult = document.getElementById('interpretationResult'); var stockPriceError = document.getElementById('stockPriceError'); var epsError = document.getElementById('earningsPerShareError'); var isValidStockPrice = validateInput('stockPrice', 'stockPriceError'); var isValidEPS = validateInput('earningsPerShare', 'earningsPerShareError'); if (!isValidStockPrice || !isValidEPS) { peRatioResult.textContent = '–'; inputStockPriceDisplay.textContent = '–'; inputEPDisplay.textContent = '–'; interpretationResult.textContent = 'Please correct the errors.'; return; } var stockPrice = parseFloat(stockPriceInput.value); var eps = parseFloat(epsInput.value); var peRatio = null; var interpretation = ''; if (eps === 0) { peRatio = 'N/A (EPS is zero)'; interpretation = 'Cannot calculate P/E ratio when EPS is zero.'; } else if (eps < 0) { peRatio = 'N/A (Negative EPS)'; interpretation = 'Company is unprofitable. Consider other metrics.'; } else { peRatio = (stockPrice / eps).toFixed(2); var numericPE = parseFloat(peRatio); if (numericPE = 10 && numericPE 20 && numericPE 30) { interpretation = 'Very High P/E – Indicates strong growth expectations or potential overvaluation'; } } peRatioResult.textContent = peRatio; inputStockPriceDisplay.textContent = '$' + stockPrice.toFixed(2); inputEPDisplay.textContent = '$' + eps.toFixed(2); interpretationResult.textContent = interpretation; updateChart(stockPrice, eps); // Update chart after calculation } function resetCalculator() { document.getElementById('stockPrice').value = '50.00'; document.getElementById('earningsPerShare').value = '2.50'; document.getElementById('stockPriceError').style.display = 'none'; document.getElementById('earningsPerShareError').style.display = 'none'; calculatePE(); // Recalculate with default values } function copyResults() { var peRatio = document.getElementById('peRatioResult').textContent; var stockPrice = document.getElementById('inputStockPriceDisplay').textContent; var eps = document.getElementById('inputEPDisplay').textContent; var interpretation = document.getElementById('interpretationResult').textContent; if (peRatio === '–') { alert('No results to copy yet.'); return; } var resultsText = "P/E Ratio Calculation:\n\n" + "P/E Ratio: " + peRatio + "\n" + "Stock Price: " + stockPrice + "\n" + "Earnings Per Share (EPS): " + eps + "\n" + "Interpretation: " + interpretation + "\n\n" + "Formula: P/E Ratio = Current Stock Price / EPS"; navigator.clipboard.writeText(resultsText).then(function() { alert('Results copied to clipboard!'); }, function(err) { console.error('Could not copy text: ', err); alert('Failed to copy results. Please copy manually.'); }); } function toggleFaq(element) { var faqItem = element.closest('.faq-item'); faqItem.classList.toggle('open'); } function initializeChart() { var ctx = document.getElementById('peRatioChart').getContext('2d'); var chartData = { labels: [], datasets: [{ label: 'P/E Ratio', data: [], borderColor: 'var(–primary-color)', backgroundColor: 'rgba(0, 74, 153, 0.1)', tension: 0.1, yAxisID: 'y-axis-pe', fill: false }, { label: 'Stock Price', data: [], borderColor: '#ffc107', // A yellow/gold color backgroundColor: 'rgba(255, 193, 7, 0.1)', tension: 0.1, yAxisID: 'y-axis-price', fill: false }] }; var options = { responsive: true, maintainAspectRatio: false, scales: { x: { title: { display: true, text: 'Stock Price Simulation ($)', color: 'var(–primary-color)' } }, 'y-axis-pe': { type: 'linear', position: 'left', title: { display: true, text: 'P/E Ratio (x)', color: 'var(–primary-color)' }, ticks: { beginAtZero: true } }, 'y-axis-price': { type: 'linear', position: 'right', title: { display: true, text: 'Stock Price ($)', color: '#ffc107' }, ticks: { beginAtZero: true, callback: function(value) { return '$' + value; } }, grid: { drawOnChartArea: false, // only want the grid lines for one axis to show up }, } }, plugins: { legend: { display: false // Legend is handled by custom span below canvas }, tooltip: { callbacks: { label: function(context) { var label = context.dataset.label || "; if (label) { label += ': '; } if (context.parsed.y !== null) { if (context.dataset.label === 'P/E Ratio') { label += context.parsed.y.toFixed(2) + 'x'; } else if (context.dataset.label === 'Stock Price') { label += '$' + context.parsed.y.toFixed(2); } } return label; } } } } }; // Dynamically create canvas element if it doesn't exist or clear it var canvasContainer = document.getElementById('peRatioChart').parentElement; var existingCanvas = document.getElementById('peRatioChart'); if (existingCanvas) { existingCanvas.remove(); } var newCanvas = document.createElement('canvas'); newCanvas.id = 'peRatioChart'; canvasContainer.prepend(newCanvas); // Add new canvas to the container ctx = newCanvas.getContext('2d'); chartInstance = new Chart(ctx, { type: 'line', data: chartData, options: options }); } function updateChart(currentEPS, currentStockPrice) { if (!chartInstance) { initializeChart(); } var stockPriceInput = document.getElementById('stockPrice'); var epsInput = document.getElementById('earningsPerShare'); var currentEPSValue = parseFloat(epsInput.value) || 2.50; // Default EPS if invalid // Simulate stock prices around the current input value var simulatedStockPrices = []; var simulatedPERatios = []; var startPrice = Math.max(0, currentStockPrice – 50); // Start simulation below current price var endPrice = currentStockPrice + 50; // End simulation above current price var step = Math.max(1, (endPrice – startPrice) / 10); // Generate 10-11 points for (var price = startPrice; price 0) { simulatedPERatios.push(price / currentEPSValue); } else { simulatedPERatios.push(null); // Cannot calculate if EPS is zero or negative } } // Ensure the exact input stock price is plotted if not already covered if (!simulatedStockPrices.includes(currentStockPrice)) { simulatedStockPrices.push(currentStockPrice); simulatedPERatios.push(currentEPSValue > 0 ? currentStockPrice / currentEPSValue : null); } // Sort data by stock price for a clean line chart var combined = simulatedStockPrices.map(function(price, i) { return { price: price, pe: simulatedPERatios[i] }; }).sort(function(a, b) { return a.price – b.price; }); chartInstance.data.labels = combined.map(function(item) { return item.price.toFixed(2); }); chartInstance.data.datasets[0].data = combined.map(function(item) { return item.pe; }); // P/E Ratio data chartInstance.data.datasets[1].data = combined.map(function(item) { return item.price; }); // Stock Price data // Update axes titles and ranges dynamically chartInstance.options.scales['y-axis-pe'].max = Math.max(…combined.map(item => item.pe || 0)) * 1.2; // Add some buffer chartInstance.options.scales['y-axis-price'].max = Math.max(…combined.map(item => item.price || 0)) * 1.2; chartInstance.update(); } // Initial calculation and chart update on page load document.addEventListener('DOMContentLoaded', function() { calculatePE(); initializeChart(); // Initialize chart structure updateChart(parseFloat(document.getElementById('stockPrice').value), parseFloat(document.getElementById('earningsPerShare').value)); // Populate chart data document.getElementById('stockPrice').addEventListener('input', function() { calculatePE(); }); document.getElementById('earningsPerShare').addEventListener('input', function() { calculatePE(); }); });

Leave a Comment