Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • Software and Tools
    • School Learning
    • Practice Coding Problems
  • Go Premium
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • jQuery
  • AngularJS
  • ReactJS
  • Next.js
  • React Native
  • NodeJS
  • Express.js
  • MongoDB
  • MERN Stack
  • PHP
  • WordPress
  • Bootstrap
  • Tailwind
  • CSS Frameworks
  • JS Frameworks
  • Web Development
Open In App
Next Article:
Hospital Management Application using MERN Stack
Next article icon

Stock Market Portfolio App using MERN Stack

Last Updated : 19 Jun, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Stock Market Portfolio project is a dynamic web application designed to help users efficiently manage and track their stock market investments and portfolios. With more than 70% of modern financial tools adopting full-stack technologies, building such an application using the MERN stack (MongoDB, Express.js, React, and Node.js) provides a robust, scalable, and responsive solution.

In this article, we’ll walk through a step-by-step guide to developing a complete Stock Market Portfolio system using the power of the MERN stack.

Project Preview

 project preview

Prerequisites:

  • Node.js and npm
  • MongoDB
  • React
  • Express
  • MERN Stack

Step-by-Step guide to create Stock Market Portfolio App

  • In the database there will be a list of stocks data which will be fetched by the server.
  • There will be also option to manually add the data though API request.
  • In the frontend there will be two routes-one will show all the stocks and other will show all the stocks watchlisted.
  • There is an option to add your favorite stocks in the watchlist.
  • If the stocks value is increasing it will show price in green color otherwise show red color.

Steps to Create the Project:

Step 1: Create a folder for the project backend and initialized the Express Application.

mkdir stock-market-portfolio
cd stock-market-portfolio
npm init -y

Step 2: Install Express and other required packages:

npm install express mongoose body-parser cors

Folder Structure:

hk

Dependencies (Backend):

"dependencies": {
"body-parser": "^1.20.2",
"cors": "^2.8.5",
"express": "^4.18.2",
"mongoose": "^8.0.4"
}

Example: Create a file named server.js and add the following code.

index.js
const express = require("express");
const mongoose = require("mongoose");
const cors = require("cors");
const bodyParser = require("body-parser");
const app = express();
const PORT = process.env.PORT || 5000;
app.use(cors());
app.use(bodyParser.json());
mongoose.connect("Your MongoDB URI link", {
	useNewUrlParser: true,
	useUnifiedTopology: true,
});
const stockSchema = new mongoose.Schema({
	company: String,
	description: String,
	initial_price: Number,
	price_2002: Number,
	price_2007: Number,
	symbol: String,
});
const Stock = mongoose.model("Stock", stockSchema);
app.get("/api/stocks", async (req, res) => {
	try {
		const stocks = await Stock.find();
		res.json(stocks);
	} catch (error) {
		console.error(error);
		res.status(500).json({ error: "Internal Server Error" });
	}
});
app.post("/api/watchlist", async (req, res) => {
	try {
		const {
			company,
			description,
			initial_price,
			price_2002,
			price_2007,
			symbol,
		} = req.body;
		const stock = new Stock({
			company,
			description,
			initial_price,
			price_2002,
			price_2007,
			symbol,
		});
		await stock.save();
		res.json({ message: "Stock added to watchlist successfully" });
	} catch (error) {
		console.error(error);
		res.status(500).json({ error: "Internal Server Error" });
	}
});
app.listen(PORT, () => {
	console.log(`Server is running on port ${PORT}`);
});

Step 3: Open the MongoDB atlas or compass and insert the following JSON file in the stocks collection.

"https://gist.github.com/stevekinney/f96d5800852e91282f46#file-stocks-json".

Step 4: Create the Frontend (React.js) by running the below command.

npx create-react-app stock-market-frontend
cd stock-market-frontend

Step 5: Install the required dependencies.

npm install axios

Dependencies (Frontend):

"dependencies": {
"@emotion/react": "^11.11.3",
"@emotion/styled": "^11.11.0",
"@mui/material": "^5.15.4",
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"axios": "^1.6.5",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.21.2",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
}

Example: Write the given code in the respective files.

style.css
/* src/App.css */
body {
    font-family: 'Arial', sans-serif;
    background-color: #d9d7ca;
    margin: 0;
    padding: 0;
}
.App {
    text-align: center;
    padding: 20px;
}
h1 {
    color: #1f454d;
}
h2 {
    color: #3c8d93;
    margin-top: 30px;
}
ul {
    list-style-type: none;
    padding: 0;
}
li {
    background-color: #3c8d93;
    color: #d9d7ca;
    padding: 10px;
    margin: 10px 0;
    border-radius: 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
button {
    background-color: #1f454d;
    color: #d9d7ca;
    border: none;
    padding: 8px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}
button:hover {
    background-color: #3c8d93;
}
/* Navigation bar styles */
nav {
    background-color: #1f454d;
    padding: 15px 0;
}
nav a {
    color: #d9d7ca;
    text-decoration: none;
    margin: 0 20px;
    font-size: 18px;
    transition: color 0.3s ease;
}
nav a:hover {
    color: #3c8d93;
}
index.js
// src/App.js
import React, { useState, useEffect } from "react";
import {
	BrowserRouter as Router,
	Routes,
	Route,
	NavLink,
} from "react-router-dom";
import "./App.css";
const Stocks = ({ addToWatchlist }) => {
	const [stocks, setStocks] = useState([]);

	useEffect(() => {
		// Fetch stock data from the backend
		fetch("http://localhost:5000/api/stocks")
			.then((res) => res.json())
			.then((data) => setStocks(data))
			.catch((error) => console.error("Error fetching stocks:", error));
	}, []);
	console.log(setStocks, "Stocksdata");

	const getRandomColor = () => {
		const colors = ["#FF0000", "#00FF00"]; // Red and Green
		return colors[Math.floor(Math.random() * colors.length)];
	};
	return (
		<div className="App">
			<h1>Stock Market MERN App</h1>
			<h2>Stocks</h2>
			<ul>
				{stocks.map((stock) => (
					<li key={stock.symbol}>
						{stock.company} ({stock.symbol}) -
						<span style={{ color: getRandomColor() }}>
							{" "}
							${stock.initial_price}
						</span>
						<button onClick={() => addToWatchlist(stock)}>
							Add to My Watchlist
						</button>
					</li>
				))}
			</ul>
		</div>
	);
};
const Watchlist = ({ watchlist }) => {
	const getRandomColor = () => {
		const colors = ["#FF0000", "#00FF00"]; // Red and Green
		return colors[Math.floor(Math.random() * colors.length)];
	};

	return (
		<div className="App">
			<h1>Stock Market MERN App</h1>
			<h2>My Watchlist</h2>
			<ul>
				{watchlist.map((stock) => (
					<li key={stock.symbol}>
						{stock.company} ({stock.symbol}) -
						<span style={{ color: getRandomColor() }}>
							{" "}
							${stock.initial_price}
						</span>
					</li>
				))}
			</ul>
		</div>
	);
};

function App() {
	const [watchlist, setWatchlist] = useState([]);

	const addToWatchlist = (stock) => {
		// Add stock to watchlist
		fetch("http://localhost:5000/api/watchlist", {
			method: "POST",
			headers: {
				"Content-Type": "application/json",
			},
			body: JSON.stringify(stock),
		})
			.then((res) => res.json())
			.then((data) => {
				// Show an alert with the message received from the server
				alert(data.message);
				setWatchlist([...watchlist, stock]);
			})
			.catch((error) =>
				console.error("Error adding to watchlist:", error)
			);
	};
	return (
		<Router>
			<nav>
				<NavLink to="/stocks">Stocks</NavLink>
				<NavLink to="/watchlist">Watchlist</NavLink>
			</nav>
			<Routes>
				<Route
					path="/stocks"
					element={<Stocks addToWatchlist={addToWatchlist} />}
				/>
				<Route
					path="/watchlist"
					element={<Watchlist watchlist={watchlist} />}
				/>
			</Routes>
		</Router>
	);
}
export default App;

To start the frontend run the following command.

npm start

Output:


Next Article
Hospital Management Application using MERN Stack

D

dhruvitr0sgc
Improve
Article Tags :
  • Project
  • Web Technologies
  • Geeks Premier League
  • MERN Stack
  • Geeks Premier League 2023
  • MERN-Projects

Similar Reads

    35+ MERN Stack Projects with Source Code [2024]
    The MERN stack, comprising MongoDB, Express JS, React, and Node JS, is a powerful combination that enables developers to build full-stack web applications using JavaScript. MongoDB serves as the database, Express.js handles server-side logic, React manages the client-side interface, and Node.js faci
    6 min read
    Stock Market Portfolio App using MERN Stack
    The Stock Market Portfolio project is a dynamic web application designed to help users efficiently manage and track their stock market investments and portfolios. With more than 70% of modern financial tools adopting full-stack technologies, building such an application using the MERN stack (MongoDB
    5 min read
    Hospital Management Application using MERN Stack
    In the fast-paced world of healthcare, it's vital to manage hospital tasks effectively to ensure top-notch patient care. This article explores creating a strong Hospital Management App using the MERN stack – that's MongoDB, Express, React, and Node.js, breaking down the process for easier understand
    15+ min read
    Social Media Platform using MERN Stack
    In web development, creating a "Social Media Website" will showcase and utilising the power of MERN stack – MongoDB, Express, React, and Node. This application will provide users the functionality to add a post, like the post and able to comment on it.Preview Image: Let us have a look at how the fin
    7 min read
    Bookstore Ecommerce App using MERN Stack
    Bookstore E-commerce project is a great way to showcase your understanding of full-stack development. In this article, we'll walk through the step-by-step process of creating a Bookstore E-commerce using the MERN (MongoDB, Express.js, React, Node.js) stack. This project will showcase how to set up a
    8 min read
    Chat Website using MERN Stack
    The "Chat Website" project is a dynamic web application that is used for real-time communication. The MERN stack, comprised of MongoDB, Express.js, React.js, and Node.js, is a powerful combination of technologies for developing robust and scalable web applications. In this article, we'll explore the
    4 min read
    Restaurant App using MERN Stack
    Creating a Restaurant app will cover a lot of features of the MERN stack. In this tutorial, we'll guide you through the process of creating a restaurant application using the MERN stack. The application will allow users to browse through a list of restaurants, view their menus, and add items to a sh
    11 min read
    Real Estate Management using MERN
    In this article, we will guide you through the process of building a Real Estate Management Application using the MERN stack. MERN stands for MongoDB, Express, React, and Node. MongoDB will serve as our database, Express will handle the backend, React will create the frontend, and Node.js will be th
    9 min read
    Fruit and Vegetable Market Shop using MERN
    In this comprehensive guide, we'll walk through the step-by-step process of creating a Fruit and Vegetable Market Shop using the MERN (MongoDB, Express.js, React, Node.js) stack. This project will showcase how to set up a full-stack web application where users can view, filter, and purchase various
    8 min read
    Event Management Web App using MERN
    In this guide, we'll walk through the step-by-step process of building a feature-rich Event Management Web App. We will make use of the MERN stack to build this project.Preview of final output: Let us have a look at how the final output will look like.Final Output of Event Management AppPrerequisite
    9 min read
`; $(commentSectionTemplate).insertBefore(".article--recommended"); } loadComments(); }); }); function loadComments() { if ($("iframe[id*='discuss-iframe']").length top_of_element && top_of_screen articleRecommendedTop && top_of_screen articleRecommendedBottom)) { if (!isfollowingApiCall) { isfollowingApiCall = true; setTimeout(function(){ if (loginData && loginData.isLoggedIn) { if (loginData.userName !== $('#followAuthor').val()) { is_following(); } else { $('.profileCard-profile-picture').css('background-color', '#E7E7E7'); } } else { $('.follow-btn').removeClass('hideIt'); } }, 3000); } } }); } $(".accordion-header").click(function() { var arrowIcon = $(this).find('.bottom-arrow-icon'); arrowIcon.toggleClass('rotate180'); }); }); window.isReportArticle = false; function report_article(){ if (!loginData || !loginData.isLoggedIn) { const loginModalButton = $('.login-modal-btn') if (loginModalButton.length) { loginModalButton.click(); } return; } if(!window.isReportArticle){ //to add loader $('.report-loader').addClass('spinner'); jQuery('#report_modal_content').load(gfgSiteUrl+'wp-content/themes/iconic-one/report-modal.php', { PRACTICE_API_URL: practiceAPIURL, PRACTICE_URL:practiceURL },function(responseTxt, statusTxt, xhr){ if(statusTxt == "error"){ alert("Error: " + xhr.status + ": " + xhr.statusText); } }); }else{ window.scrollTo({ top: 0, behavior: 'smooth' }); $("#report_modal_content").show(); } } function closeShareModal() { const shareOption = document.querySelector('[data-gfg-action="share-article"]'); shareOption.classList.remove("hover_share_menu"); let shareModal = document.querySelector(".hover__share-modal-container"); shareModal && shareModal.remove(); } function openShareModal() { closeShareModal(); // Remove existing modal if any let shareModal = document.querySelector(".three_dot_dropdown_share"); shareModal.appendChild(Object.assign(document.createElement("div"), { className: "hover__share-modal-container" })); document.querySelector(".hover__share-modal-container").append( Object.assign(document.createElement('div'), { className: "share__modal" }), ); document.querySelector(".share__modal").append(Object.assign(document.createElement('h1'), { className: "share__modal-heading" }, { textContent: "Share to" })); const socialOptions = ["LinkedIn", "WhatsApp","Twitter", "Copy Link"]; socialOptions.forEach((socialOption) => { const socialContainer = Object.assign(document.createElement('div'), { className: "social__container" }); const icon = Object.assign(document.createElement("div"), { className: `share__icon share__${socialOption.split(" ").join("")}-icon` }); const socialText = Object.assign(document.createElement("span"), { className: "share__option-text" }, { textContent: `${socialOption}` }); const shareLink = (socialOption === "Copy Link") ? Object.assign(document.createElement('div'), { role: "button", className: "link-container CopyLink" }) : Object.assign(document.createElement('a'), { className: "link-container" }); if (socialOption === "LinkedIn") { shareLink.setAttribute('href', `https://www.linkedin.com/sharing/share-offsite/?url=${window.location.href}`); shareLink.setAttribute('target', '_blank'); } if (socialOption === "WhatsApp") { shareLink.setAttribute('href', `https://api.whatsapp.com/send?text=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } if (socialOption === "Twitter") { shareLink.setAttribute('href', `https://twitter.com/intent/tweet?url=${window.location.href}`); shareLink.setAttribute('target', "_blank"); } shareLink.append(icon, socialText); socialContainer.append(shareLink); document.querySelector(".share__modal").appendChild(socialContainer); //adding copy url functionality if(socialOption === "Copy Link") { shareLink.addEventListener("click", function() { var tempInput = document.createElement("input"); tempInput.value = window.location.href; document.body.appendChild(tempInput); tempInput.select(); tempInput.setSelectionRange(0, 99999); // For mobile devices document.execCommand('copy'); document.body.removeChild(tempInput); this.querySelector(".share__option-text").textContent = "Copied" }) } }); // document.querySelector(".hover__share-modal-container").addEventListener("mouseover", () => document.querySelector('[data-gfg-action="share-article"]').classList.add("hover_share_menu")); } function toggleLikeElementVisibility(selector, show) { document.querySelector(`.${selector}`).style.display = show ? "block" : "none"; } function closeKebabMenu(){ document.getElementById("myDropdown").classList.toggle("show"); }
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences