Project
Project
ON
SOFTWARE
FOR
STOCKS MANAGEMENT SYSTEM
Submitted to
Central Board of Secondary Education,
New Delhi
1
0.1 Certificate of Completion
2
0.2 Preface
Over the past five decades, computers have become deeply integrated
into nearly every aspect of our lives and work. What were once spe-
cialized, bulky machines have evolved into ubiquitous tools that now
facilitate and augment the majority of our daily tasks.
Computers have proven invaluable across a wide range of industries
and applications. In fields like science and technology, their extraordi-
nary processing speed, massive storage capacity, and unparalleled ac-
curacy have enabled the achievement of targets and discoveries that
would have been impossible without computational power. Even in more
commonplace business functions, computers have revolutionized how we
manage financial records, track sales and inventory, and design products.
The characteristics that make computers so indispensable today in-
clude not just their raw capabilities, but also their consistency and flex-
ibility. Unlike human workers, computers can perform repetitive tasks
with flawless precision time and time again. And the versatility of com-
puting platforms allows them to be seamlessly integrated into an ever-
expanding array of workflows and use cases.
The analysis presented in the following pages has been undertaken
with the utmost sincerity and diligence. It is our hope that the insights
contained herein will be appreciated for their value in illuminating the
transformative role of computers in the modern world.
3
0.3 Acknowledgement
I am deeply grateful to all those who have supported and guided me
throughout the completion of this project.
First and foremost, I would like to express my sincere appreciation
to Ms. Writuparna Chatterjee, the Principal of my school. I am
indebted to her for providing the opportunity to undertake this work, as
well as the necessary infrastructure and cooperation.
I would also like to extend my heartfelt thanks to my esteemed
teacher, Mr. Joydeep Kundu, for his invaluable guidance, encour-
agement, and unwavering support throughout the project. This endeavor
is a testament to his vision and expertise, and I owe much of its func-
tionality to his mentorship.
Finally, I am overwhelmed with gratitude towards my family and
friends, who have been a constant source of motivation and support,
enabling me to persist with this undertaking.
I am deeply appreciative of the time, effort, and insights contributed
by all who have helped make this project a success. Their collective
support has been instrumental in shaping the final outcome.
4
0.4 Requirement Analysis
0.4.1 Proposed Systsem
The goal of this project is to automate the collection, storage, and pro-
cessing of stock and user portfolio using Python and MySQL. The
proposed system will consist of three main components: a scraping
module to collect stock data, and a database management sys-
tem to store and manage the data, and an user friendly interface
to navigate and analyze data.
5
0.5 Feasibility Study
0.5.1 Economic Feasibility
The project is economically viable since it relies on open-source technolo-
gies like Python and MySQL. The system significantly reduces the cost
of manually gathering and organizing stock data while also improving
the accuracy and reliability of the data.
6
0.6 System Design
0.6.1 System Workflow
The system workflow is as follows:
7
0.7 Database Design
0.7.1 Tables
• stocks: Columns include stock symbol, last price, change, previ-
ous close, final quantity, year high, year low, market cap and last
update time
0.7.2 Operations
• Insertion: New stock data is inserted into the database after
each scraping session. Similarly, new user profiles are added when
created.
8
0.8 System Specifications
0.8.1 Hardware
• CPU: Intel Core i3 or higher
0.8.2 Software
• Operating System: Linux/MacOS/Windows
9
0.9 Code Analysis
0.9.1 main.py
import requests
import json
from datetime import datetime
import sql
import menu
# NOTE: SCRAPING
BASE_URL =
,→ "https://www.nseindia.com/api/market-data-pre-open"
HEADERS = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64;
,→ rv:131.0) Gecko/20100101 Firefox/131.0",
"Accept": "*/*",
"Connection": "keep-alive",
"Referer":
,→ "https://www.nseindia.com/market-data/pre-open-market-
}
def fetch_stocks():
try:
auth = requests.get(HEADERS["Referer"],
,→ headers=HEADERS)
response = requests.get(
BASE_URL, headers=HEADERS, params={"key":
,→ "NIFTY"}, cookies=auth.cookies
)
return json.loads(response.text)["data"]
10
except Exception as e:
print("Error: ", e)
exit(1)
def sanitize(json):
del json["metadata"]["purpose"]
del json["metadata"]["chartTodayPath"]
del json["metadata"]["identifier"]
del json["metadata"]["iep"]
json["metadata"]["lastUpdateTime"] =
,→ datetime.strptime(
,→ json["detail"]["preOpenMarket"]["lastUpdateTime"],
,→ "%d-%b-%Y %H:%M:%S"
)
return json["metadata"]
# NOTE: MAIN
def main():
stocks = fetch_stocks()
ls = list()
for i in stocks:
ls.append(sanitize(i))
sql.update_stocks(ls)
menu.menu()
if __name__ == "__main__":
main()
11
0.9.2 sql.py
import mysql.connector
def connect():
con = mysql.connector.connect(
host="localhost", user="root",
,→ passwd=open("secret.txt").read()
)
cur = con.cursor()
cur.execute(
f"""CREATE TABLE IF NOT EXISTS {user} (symbol
,→ VARCHAR(255) PRIMARY KEY, quantity DOUBLE,
,→ initialPrice DOUBLE, FOREIGN KEY (symbol)
,→ REFERENCES stocks(symbol))"""
)
if mode not in ["update", "delete"]:
print("=" * 20, "OUTPUT", "=" * 20)
if mode == "update":
cur.execute(
f"INSERT INTO {user} (symbol, quantity,
,→ initialPrice) VALUES(%s, %s, %s)",
tuple(dc.values()),
12
)
elif mode == "delete":
cur.execute(f"DELETE FROM {user} WHERE symbol =
,→ %s", tuple(dc.values()))
elif mode == "view":
print("Owned Stocks:")
cur.execute(f"DESC {user}")
for i in cur.fetchall():
print(i[0], end=" ")
print()
cur.execute(f"SELECT * FROM {user}")
for row in cur.fetchall():
print(row)
elif mode == "users":
cur.execute("SHOW TABLES WHERE Tables_in_pysql
,→ != 'stocks';")
print("Users:")
for row in cur.fetchall():
print(row[0])
elif mode == "all":
cur.execute("SELECT symbol FROM stocks")
print("Available Stocks:")
for row in cur.fetchall():
print(row[0], end=" ")
print()
elif mode == "dataset":
cur.execute("DESC stocks")
for i in cur.fetchall():
print(i[0], end=" ")
print()
cur.execute("SELECT * FROM stocks")
for row in cur.fetchall():
print(row)
elif mode == "profit":
13
cur.execute(
f"SELECT {user}.symbol, quantity *
,→ (lastPrice - initialPrice) FROM {user},
,→ stocks WHERE {user}.symbol =
,→ stocks.symbol"
)
total = 0
for row in cur.fetchall():
total += row[1]
print(f"{row[0]}", f"-> Profit: {row[1]}")
print(f"Total Profit: {total}")
con.commit()
con.close()
def update_stocks(ls):
con, cur = connect()
cur.execute(
"CREATE TABLE IF NOT EXISTS stocks (symbol
,→ VARCHAR(255) PRIMARY KEY, lastPrice DOUBLE,
,→ pChange DOUBLE, \
`change` DOUBLE, previousClose DOUBLE,
,→ finalQuantity DOUBLE, totalTurnover
,→ DOUBLE, marketCap DOUBLE, \
yearHigh DOUBLE, yearLow DOUBLE,
,→ lastUpdateTime DATETIME)"
)
for i in ls:
cur.execute(
14
"INSERT INTO stocks VALUES(%s, %s, %s, %s,
,→ %s, %s, %s, %s, %s, %s, %s) ON
,→ DUPLICATE KEY UPDATE \
lastPrice = %s, pChange = %s,
,→ `change` = %s, previousClose =
,→ %s, finalQuantity = %s, \
totalTurnover = %s, marketCap = %s,
,→ yearHigh = %s, yearLow = %s,
,→ lastUpdateTime = %s",
(tuple(i.values()) +
,→ tuple(i.values())[1:]),
)
con.commit()
con.close()
0.9.3 menu.py
import sql
def input_owned(user):
while True:
sql.update_user(user, {}, mode="all")
symbol = input("Enter Symbol: ").upper()
quantity = float(input("Enter Quantity: "))
initialPrice = float(input("Enter Initial
,→ Price: "))
sql.update_user(
user,
{symbol: symbol, quantity: quantity,
,→ initialPrice: initialPrice},
mode="update",
)
15
if input("Do you want to continue? (Y/n):
,→ ").lower() == "y":
continue
else:
break
def dlt_owned(user):
while True:
sql.update_user(user, {}, mode="view")
symbol = input("Enter Symbol: ")
sql.update_user(user, {symbol: symbol},
,→ mode="delete")
if input("Do you want to continue? (Y/n):
,→ ").lower() == "y":
continue
else:
break
def view_owned(user):
sql.update_user(user, {}, mode="view")
def view_users(user):
sql.update_user(user, {}, mode="users")
def view_stocks(user):
sql.update_user(user, {}, mode="dataset")
def view_profit(user):
sql.update_user(user, {}, mode="profit")
16
def menu():
user = input("Enter user: ")
while True:
print(
"1 \t Input stocks",
"2 \t Display portfolio",
"3 \t Delete stocks",
"4 \t Show users",
"5 \t View parent database",
"6 \t Calculate profit",
"",
"any key \t Quit",
sep="\n",
)
parameter = input("Enter choice: ")
match parameter:
case "1":
input_owned(user)
case "2":
view_owned(user)
case "3":
dlt_owned(user)
case "4":
view_users(user)
case "5":
view_stocks(user)
case "6":
view_profit(user)
case _:
print("Exiting")
exit(0)
17
0.10 Output
18
Figure 2: Inserting and deleting owned stocks
19
Figure 3: Stocks Dataset
20
0.11 Bibliography
• Python: https://www.python.org/
• MySQL: https://www.mysql.com/
• Requests: https://requests.readthedocs.io
• NSEIndia: https://www.nseindia.com/market-data
21