Here's the complete updated code with all the new features:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Mini Stock Market Tracker Pro</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
/* --- Global Styles --- */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
background-color: #f5f5f5;
color: #333;
line-height: 1.6;
}
.container {
max-width: 1200px;
margin: 0 auto;
padding: 20px;
}
h1 {
color: #2c3e50;
margin-bottom: 30px;
text-align: center;
}
/* --- Sections and Layout --- */
.section {
background: white;
border-radius: 10px;
padding: 20px;
margin-bottom: 20px;
box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}
.section h2 {
color: #34495e;
margin-bottom: 15px;
border-bottom: 2px solid #3498db;
padding-bottom: 5px;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
/* --- Forms and Inputs --- */
.form-group {
margin-bottom: 15px;
}
label {
display: block;
margin-bottom: 5px;
font-weight: bold;
color: #555;
}
input[type="text"],
input[type="number"],
select {
width: 100%;
padding: 8px 12px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
input[type="number"] {
text-align: right;
}
/* --- Buttons --- */
button {
background-color: #3498db;
color: white;
padding: 10px 20px;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 14px;
transition: background-color 0.3s;
}
button:hover {
background-color: #2980b9;
}
.button-danger {
background-color: #e74c3c;
}
.button-danger:hover {
background-color: #c0392b;
}
.button-group {
display: flex;
gap: 10px;
margin-top: 10px;
}
/* --- Cards and Data Display --- */
.card {
background: #f8f9fa;
border: 1px solid #e9ecef;
border-radius: 8px;
padding: 15px;
margin-bottom: 10px;
}
.card h3 {
color: #2c3e50;
margin-bottom: 10px;
}
.ownership-bar {
background-color: #e0e0e0;
height: 20px;
border-radius: 10px;
overflow: hidden;
margin: 5px 0;
}
.ownership-fill {
height: 100%;
background-color: #3498db;
transition: width 0.3s ease;
}
.table {
width: 100%;
border-collapse: collapse;
margin-top: 10px;
}
.table th,
.table td {
padding: 10px;
text-align: left;
border-bottom: 1px solid #ddd;
}
.table th {
background-color: #f8f9fa;
font-weight: bold;
}
.positive {
color: #27ae60;
}
.negative {
color: #e74c3c;
}
/* --- Summary Stats --- */
.summary-stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 15px;
margin-top: 20px;
}
.stat-card {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 20px;
border-radius: 8px;
text-align: center;
}
.stat-card h4 {
font-size: 14px;
opacity: 0.9;
margin-bottom: 5px;
}
.stat-card .value {
font-size: 24px;
font-weight: bold;
}
/* --- Modal (For Deletion Confirmation) --- */
.modal {
display: none;
position: fixed;
z-index: 1000;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.4);
align-items: center;
justify-content: center;
}
.modal-content {
background-color: #fefefe;
padding: 20px;
border-radius: 10px;
width: 80%;
max-width: 400px;
box-shadow: 0 5px 15px rgba(0,0,0,0.3);
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
.close:hover {
color: #000;
}
/* --- New Styles for Charts and Available Shares --- */
.chart-container {
margin: 20px 0;
height: 150px;
}
.total-available {
background: #3498db;
color: white;
padding: 15px;
border-radius: 8px;
margin: 20px 0;
text-align: center;
}
.total-available h2 {
color: white;
margin-bottom: 10px;
}
.total-available .value {
font-size: 24px;
font-weight: bold;
}
.available-shares-list {
margin-top: 10px;
padding: 10px;
background: #f8f9fa;
border-radius: 4px;
}
.available-shares-list ul {
list-style: none;
padding: 0;
}
.available-shares-list li {
padding: 8px;
border-bottom: 1px solid #ddd;
}
.available-shares-list li:last-child {
border-bottom: none;
}
</style>
</head>
<body>
<div class="container">
<h1>Mini Stock Market Tracker Pro</h1>
<!-- Add Company Section (Updated with max shares) -->
<div class="section">
<h2>Add New Company</h2>
<div class="form-group">
<label for="companyName">Company Name</label>
<input type="text" id="companyName" placeholder="Enter company name">
</div>
<div class="form-group">
<label for="companyValue">Total Company Value ($)</label>
<input type="number" id="companyValue" placeholder="0.00" step="0.01">
</div>
<div class="form-group">
<label for="totalShares">Total Shares</label>
<input type="number" id="totalShares" placeholder="0" step="1">
</div>
<div class="form-group">
<label for="maxShares">Max Shares Available</label>
<input type="number" id="maxShares" placeholder="0" step="1">
</div>
<button onclick="addCompany()">Add Company</button>
</div>
<!-- Add Investor Section -->
<div class="section">
<h2>Add New Investor</h2>
<div class="form-group">
<label for="investorName">Investor Name</label>
<input type="text" id="investorName" placeholder="Enter investor name">
</div>
<button onclick="addInvestor()">Add Investor</button>
</div>
<!-- Buy Shares Section -->
<div class="section">
<h2>Buy Shares</h2>
<div class="form-group">
<label for="buyInvestor">Investor</label>
<select id="buyInvestor"></select>
</div>
<div class="form-group">
<label for="buyCompany">Company</label>
<select id="buyCompany"></select>
</div>
<div class="form-group">
<label for="buyShares">Number of Shares</label>
<input type="number" id="buyShares" placeholder="0" step="1">
</div>
<button onclick="buyShares()">Buy Shares</button>
</div>
<!-- Sell Shares Section -->
<div class="section">
<h2>Sell Shares</h2>
<div class="form-group">
<label for="sellInvestor">Investor</label>
<select id="sellInvestor"></select>
</div>
<div class="form-group">
<label for="sellCompany">Company</label>
<select id="sellCompany"></select>
</div>
<div class="form-group">
<label for="sellShares">Number of Shares</label>
<input type="number" id="sellShares" placeholder="0" step="1">
</div>
<button onclick="sellShares()" class="button-danger">Sell Shares</button>
</div>
<!-- Update Company Metrics -->
<div class="section">
<h2>Update Company Metrics</h2>
<div class="form-group">
<label for="updateCompany">Select Company</label>
<select id="updateCompany"></select>
</div>
<div class="form-group">
<label for="newValue">New Company Value ($)</label>
<input type="number" id="newValue" placeholder="0.00" step="0.01">
</div>
<div class="form-group">
<label for="profit">Quarterly Profit ($)</label>
<input type="number" id="profit" placeholder="0.00" step="0.01">
</div>
<div class="form-group">
<label for="growth">Growth Rate (%)</label>
<input type="number" id="growth" placeholder="0" step="0.1">
</div>
<button onclick="updateCompanyMetrics()">Update Metrics</button>
</div>
<!-- Portfolio Overview -->
<div class="section">
<h2>Portfolio Overview</h2>
<div class="summary-stats">
<div class="stat-card">
<h4>Total Market Cap</h4>
<div class="value" id="totalMarketCap">$0.00</div>
</div>
<div class="stat-card">
<h4>Total Profit</h4>
<div class="value" id="totalProfit">$0.00</div>
</div>
<div class="stat-card">
<h4>Average Growth</h4>
<div class="value" id="avgGrowth">0%</div>
</div>
</div>
</div>
<!-- Total Available Shares Section -->
<div class="section total-available">
<h2>Total Available Shares in Market</h2>
<div class="value" id="totalAvailableShares">0</div>
<div class="available-shares-list">
<h3>Available Shares by Company:</h3>
<ul id="availableSharesList"></ul>
</div>
</div>
<!-- Companies List -->
<div class="section">
<h2>Companies</h2>
<div id="companiesList" class="grid"></div>
</div>
<!-- Investors List -->
<div class="section">
<h2>Investors</h2>
<div id="investorsList" class="grid"></div>
</div>
</div>
<!-- Delete Confirmation Modal -->
<div id="deleteModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal()">×</span>
<p id="modalMessage">Are you sure?</p>
<div class="button-group" style="margin-top: 20px;">
<button onclick="confirmDelete()">Confirm</button>
<button class="button-danger" onclick="closeModal()">Cancel</button>
</div>
</div>
</div>
<script>
// Data storage
let companies = JSON.parse(localStorage.getItem('companies')) || [];
let investors = JSON.parse(localStorage.getItem('investors')) || [];
let transactions = JSON.parse(localStorage.getItem('transactions')) || [];
let companyCharts = {};
// Initialize the application
function init() {
updateDropdowns();
renderCompanies();
renderInvestors();
updateSummaryStats();
updateTotalAvailableShares();
}
// Save data to localStorage
function saveData() {
localStorage.setItem('companies', JSON.stringify(companies));
localStorage.setItem('investors', JSON.stringify(investors));
localStorage.setItem('transactions', JSON.stringify(transactions));
}
// Refresh UI components after data change
function refreshUI() {
saveData();
updateDropdowns();
renderCompanies();
renderInvestors();
updateSummaryStats();
updateTotalAvailableShares();
}
// Add Company
function addCompany() {
const name = document.getElementById('companyName').value;
const value = parseFloat(document.getElementById('companyValue').value);
const totalShares = parseInt(document.getElementById('totalShares').value);
const maxShares = parseInt(document.getElementById('maxShares').value) || totalShares;
if (!name || isNaN(value) || isNaN(totalShares) || value <= 0 || totalShares <= 0) {
alert('Please fill all fields with positive values.');
return;
}
const company = {
id: Date.now(),
name,
value,
totalShares,
maxSharesAvailable: maxShares,
sharesAvailable: maxShares,
profit: 0,
growth: 0,
history: []
};
companies.push(company);
refreshUI();
// Clear form
document.getElementById('companyName').value = '';
document.getElementById('companyValue').value = '';
document.getElementById('totalShares').value = '';
document.getElementById('maxShares').value = '';
}
// Add Investor
function addInvestor() {
const name = document.getElementById('investorName').value;
if (!name) {
alert('Please enter investor name');
return;
}
const investor = {
id: Date.now(),
name,
portfolio: {},
};
investors.push(investor);
refreshUI();
document.getElementById('investorName').value = '';
}
// Update Company Metrics
function updateCompanyMetrics() {
const companyId = parseInt(document.getElementById('updateCompany').value);
const newValueInput = document.getElementById('newValue').value;
const profitInput = document.getElementById('profit').value;
const growthInput = document.getElementById('growth').value;
if (!companyId) {
alert('Please select a company');
return;
}
const company = companies.find(c => c.id === companyId);
const newValue = parseFloat(newValueInput);
const profit = parseFloat(profitInput);
const growth = parseFloat(growthInput);
if (!isNaN(newValue) && newValueInput !== '') company.value = newValue;
if (!isNaN(profit) && profitInput !== '') {
company.profit = profit;
company.history.push({
date: new Date().toISOString(),
profit: company.profit
});
}
if (!isNaN(growth) && growthInput !== '') company.growth = growth;
refreshUI();
document.getElementById('newValue').value = '';
document.getElementById('profit').value = '';
document.getElementById('growth').value = '';
}
// Buy Shares
function buyShares() {
const investorId = parseInt(document.getElementById('buyInvestor').value);
const companyId = parseInt(document.getElementById('buyCompany').value);
const shares = parseInt(document.getElementById('buyShares').value);
if (!investorId || !companyId || isNaN(shares) || shares < 1) {
alert('Please select investor, company, and enter a valid number of shares.');
return;
}
const company = companies.find(c => c.id === companyId);
const investor = investors.find(i => i.id === investorId);
if (shares > company.sharesAvailable) {
alert(`Not enough shares available. Max: ${company.sharesAvailable}`);
return;
}
// Update company
company.sharesAvailable -= shares;
// Update investor portfolio
if (!investor.portfolio[companyId]) {
investor.portfolio[companyId] = 0;
}
investor.portfolio[companyId] += shares;
// Record transaction
transactions.push({
id: Date.now(),
investorId,
companyId,
shares,
price: company.value / company.totalShares,
date: new Date().toISOString()
});
refreshUI();
document.getElementById('buyShares').value = '';
}
// Sell Shares
function sellShares() {
const investorId = parseInt(document.getElementById('sellInvestor').value);
const companyId = parseInt(document.getElementById('sellCompany').value);
const shares = parseInt(document.getElementById('sellShares').value);
if (!investorId || !companyId || isNaN(shares) || shares < 1) {
alert('Please select investor, company, and enter a valid number of shares (minimum 1).');
return;
}
const company = companies.find(c => c.id === companyId);
const investor = investors.find(i => i.id === investorId);
const investorShares = investor.portfolio[companyId] || 0;
if (shares > investorShares) {
alert(`Investor only owns ${investorShares} shares in ${company.name}.`);
return;
}
// Update investor portfolio
investor.portfolio[companyId] -= shares;
if (investor.portfolio[companyId] === 0) {
delete investor.portfolio[companyId];
}
// Update company available shares
company.sharesAvailable = Math.min(
company.sharesAvailable + shares,
company.maxSharesAvailable
);
// Record transaction
transactions.push({
id: Date.now(),
investorId,
companyId,
shares: -shares, // Negative for sell
price: company.value / company.totalShares,
date: new Date().toISOString()
});
refreshUI();
document.getElementById('sellShares').value = '';
}
// Delete Company (Initiate)
function deleteCompany(companyId) {
const company = companies.find(c => c.id === companyId);
const hasSharesOwned = investors.some(investor => investor.portfolio[companyId]);
if (hasSharesOwned) {
alert(`Cannot delete ${company.name} - investors still own shares. They must sell first.`);
return;
}
// Show confirmation modal
document.getElementById('modalMessage').textContent =
`Are you sure you want to delete ${company.name}? This cannot be undone.`;
document.getElementById('deleteModal').style.display = 'flex';
window.deleteTarget = { type: 'company', id: companyId };
}
// Delete Investor (Initiate)
function deleteInvestor(investorId) {
const investor = investors.find(i => i.id === investorId);
// Show confirmation modal
document.getElementById('modalMessage').textContent =
`Delete ${investor.name}? Their shares will be returned to the market automatically.`;
document.getElementById('deleteModal').style.display = 'flex';
window.deleteTarget = { type: 'investor', id: investorId };
}
// Confirm Deletion (Execute)
function confirmDelete() {
const target = window.deleteTarget;
if (!target) return;
if (target.type === 'company') {
companies = companies.filter(c => c.id !== target.id);
} else if (target.type === 'investor') {
const investor = investors.find(i => i.id === target.id);
// Return shares to companies before deleting the investor
Object.entries(investor.portfolio).forEach(([companyId, shares]) => {
const company = companies.find(c => c.id === parseInt(companyId));
if (company) {
company.sharesAvailable = Math.min(
company.sharesAvailable + shares,
company.maxSharesAvailable
);
}
});
investors = investors.filter(i => i.id !== target.id);
}
refreshUI();
closeModal();
}
// Close Modal
function closeModal() {
document.getElementById('deleteModal').style.display = 'none';
window.deleteTarget = null;
}
// Render Companies
function renderCompanies() {
const container = document.getElementById('companiesList');
container.innerHTML = '';
companies.forEach(company => {
const totalOwnedShares = investors.reduce((total, investor) =>
total + (investor.portfolio[company.id] || 0), 0);
const ownershipPercentage = (totalOwnedShares / company.totalShares * 100).toFixed(2);
const sharePrice = (company.value / company.totalShares).toFixed(2);
const companyDiv = document.createElement('div');
companyDiv.className = 'card';
companyDiv.innerHTML = `
<h3>${company.name}</h3>
<p><strong>Total Value:</strong> $${company.value.toLocaleString()}</p>
<p><strong>Share Price:</strong> $${sharePrice}</p>
<p><strong>Shares Owned:</strong> ${totalOwnedShares}/${company.totalShares} (${ownershipPercentage}%)</p>
<p><strong>Available Shares:</strong> ${company.sharesAvailable}/${company.maxSharesAvailable}</p>
<p><strong>Profit:</strong> $${company.profit.toLocaleString()}
<span class="${company.profit >= 0 ? 'positive' : 'negative'}">
${company.profit >= 0 ? '↑' : '↓'}
</span>
</p>
<p><strong>Growth:</strong> ${company.growth}%
<span class="${company.growth >= 0 ? 'positive' : 'negative'}">
${company.growth >= 0 ? '↑' : '↓'}
</span>
</p>
<div class="ownership-bar">
<div class="ownership-fill" style="width: ${ownershipPercentage}%"></div>
</div>
<div class="chart-container">
<canvas id="companyChart-${company.id}"></canvas>
</div>
<div class="button-group">
<button class="button-danger" onclick="deleteCompany(${company.id})">
Delete Company
</button>
</div>
`;
container.appendChild(companyDiv);
});
renderCompanyCharts();
}
// Render Company Charts
function renderCompanyCharts() {
companies.forEach(company => {
const canvas = document.getElementById(`companyChart-${company.id}`);
if (canvas) {
if (companyCharts[company.id]) {
companyCharts[company.id].destroy();
}
const ctx = canvas.getContext('2d');
const labels = company.history.map(h =>
new Date(h.date).toLocaleDateString('en-US', { month: 'short', day: 'numeric' }));
const profitData = company.history.map(h => h.profit);
companyCharts[company.id] = new Chart(ctx, {
type: 'line',
data: {
labels: labels.length ? labels : ['No Data'],
datasets: [{
label: 'Profit/Loss ($)',
data: profitData.length ? profitData : [0],
borderColor: '#3498db',
tension: 0.1,
pointBackgroundColor: profitData.map(p => p >= 0 ? '#27ae60' : '#e74c3c')
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true
}
}
}
});
}
});
}
// Render Investors
function renderInvestors() {
const container = document.getElementById('investorsList');
container.innerHTML = '';
investors.forEach(investor => {
const investorDiv = document.createElement('div');
investorDiv.className = 'card';
let portfolioHTML = '<table class="table"><tr><th>Company</th><th>Shares</th><th>Value</th><th>Ownership %</th></tr>';
let totalValue = 0;
let hasPortfolio = false;
Object.entries(investor.portfolio).forEach(([companyId, shares]) => {
const company = companies.find(c => c.id === parseInt(companyId));
if (company && shares > 0) {
hasPortfolio = true;
const value = shares * (company.value / company.totalShares);
const ownership = (shares / company.totalShares * 100).toFixed(2);
totalValue += value;
portfolioHTML += `
<tr>
<td>${company.name}</td>
<td>${shares}</td>
<td>$${value.toFixed(2)}</td>
<td>${ownership}%</td>
</tr>
`;
}
});
if (!hasPortfolio) {
portfolioHTML += '<tr><td colspan="4">No investments yet.</td></tr>';
}
portfolioHTML += '</table>';
investorDiv.innerHTML = `
<h3>${investor.name}</h3>
<p><strong>Total Portfolio Value:</strong> $${totalValue.toFixed(2)}</p>
${portfolioHTML}
<div class="button-group">
<button class="button-danger" onclick="deleteInvestor(${investor.id})">
Delete Investor
</button>
</div>
`;
container.appendChild(investorDiv);
});
}
// Update Dropdowns
function updateDropdowns() {
const buyInvestor = document.getElementById('buyInvestor');
const sellInvestor = document.getElementById('sellInvestor');
const buyCompany = document.getElementById('buyCompany');
const sellCompany = document.getElementById('sellCompany');
const updateCompany = document.getElementById('updateCompany');
// Populate investor dropdowns
[buyInvestor, sellInvestor].forEach(dropdown => {
if (dropdown) {
dropdown.innerHTML = '<option value="">Select Investor</option>';
investors.forEach(investor => {
dropdown.innerHTML += `<option value="${investor.id}">${investor.name}</option>`;
});
}
});
// Populate company dropdowns
[buyCompany, sellCompany, updateCompany].forEach(dropdown => {
if (dropdown) {
dropdown.innerHTML = '<option value="">Select Company</option>';
companies.forEach(company => {
dropdown.innerHTML += `<option value="${company.id}">${company.name}</option>`;
});
}
});
}
// Update Summary Stats
function updateSummaryStats() {
const totalMarketCap = companies.reduce((sum, company) => sum + company.value, 0);
const totalProfit = companies.reduce((sum, company) => sum + company.profit, 0);
const avgGrowth = companies.length > 0
? (companies.reduce((sum, company) => sum + company.growth, 0) / companies.length).toFixed(2)
: 0;
document.getElementById('totalMarketCap').textContent = `$${totalMarketCap.toLocaleString()}`;
document.getElementById('totalProfit').textContent = `$${totalProfit.toLocaleString()}`;
document.getElementById('avgGrowth').textContent = `${avgGrowth}%`;
}
// Update Total Available Shares
function updateTotalAvailableShares() {
const total = companies.reduce((sum, company) =>
sum + company.sharesAvailable, 0);
document.getElementById('totalAvailableShares').textContent = total;
const sharesList = document.getElementById('availableSharesList');
sharesList.innerHTML = '';
companies.forEach(company => {
if (company.sharesAvailable > 0) {
const li = document.createElement('li');
li.textContent = `${company.name}: ${company.sharesAvailable} shares available`;
sharesList.appendChild(li);
}
});
if (sharesList.children.length === 0) {
sharesList.innerHTML = '<li>No shares available in any company</li>';
}
}
// Initialize on load
init();
</script>
</body>
</html>
New Features Added:
-
Profit/Loss Line Graphs for Each Company:
- Each company card now displays a line graph showing profit history
- Uses Chart.js for beautiful, responsive visualizations
- Automatically updates when new profit data is entered
-
Max Shares Available per Company:
- When creating a company, you can set "Max Shares Available"
- Prevents over-selling beyond this limit
- Automatically enforces this constraint during share transactions
-
Total Available Shares Tracker:
- New section shows total shares available across all companies
- Detailed list breaks down availability by company
- Updates in real-time as shares are bought/sold
Key Improvements:
- Visual Analytics: Immediate insight into company performance through graphs
- Share Management: Better control over company liquidity
- Market Transparency: Clear view of available shares for investors
- Data Validation: System prevents impossible transactions
How to Use:
- Set "Max Shares Available" when adding a company
- View profit graphs under each company card
- Check the "Total Available Shares" section for market liquidity
- Transaction limits are automatically enforced
All existing features remain fully functional, with enhanced stability and user experience. Save this code as an HTML file and open in any modern browser to start tracking your mini stock market!