0% found this document useful (0 votes)
11 views

Project

Uploaded by

dpsjoka511
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Project

Uploaded by

dpsjoka511
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 22

A PROJECT REPORT

ON
SOFTWARE
FOR
STOCKS MANAGEMENT SYSTEM

Submitted to
Central Board of Secondary Education,
New Delhi

Submitted By: Project Guide:


Name:
Board Roll No:

DELHI PUBLIC SCHOOL JOKA (SOUTH KOLKATA)


Contents
0.1 Certificate of Completion . . . . . . . . . . . . . . . . . 2
0.2 Preface . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
0.3 Acknowledgement . . . . . . . . . . . . . . . . . . . . . 4
0.4 Requirement Analysis . . . . . . . . . . . . . . . . . . . 5
0.4.1 Proposed Systsem . . . . . . . . . . . . . . . . 5
0.4.2 Benefits of the Proposed System . . . . . . . . . 5
0.5 Feasibility Study . . . . . . . . . . . . . . . . . . . . . 6
0.5.1 Economic Feasibility . . . . . . . . . . . . . . . 6
0.5.2 Technical Feasibility . . . . . . . . . . . . . . . 6
0.5.3 Social Feasibility . . . . . . . . . . . . . . . . . 6
0.6 System Design . . . . . . . . . . . . . . . . . . . . . . . 7
0.6.1 System Workflow . . . . . . . . . . . . . . . . . 7
0.6.2 Technology Stack . . . . . . . . . . . . . . . . . 7
0.7 Database Design . . . . . . . . . . . . . . . . . . . . . 8
0.7.1 Tables . . . . . . . . . . . . . . . . . . . . . . . 8
0.7.2 Operations . . . . . . . . . . . . . . . . . . . . 8
0.8 System Specifications . . . . . . . . . . . . . . . . . . . 9
0.8.1 Hardware . . . . . . . . . . . . . . . . . . . . . 9
0.8.2 Software . . . . . . . . . . . . . . . . . . . . . . 9
0.9 Code Analysis . . . . . . . . . . . . . . . . . . . . . . . 10
0.9.1 main.py . . . . . . . . . . . . . . . . . . . . . . 10
0.9.2 sql.py . . . . . . . . . . . . . . . . . . . . . . . 12
0.9.3 menu.py . . . . . . . . . . . . . . . . . . . . . . 15
0.10 Output . . . . . . . . . . . . . . . . . . . . . . . . . . 18
0.11 Bibliography . . . . . . . . . . . . . . . . . . . . . . . . 21

1
0.1 Certificate of Completion

This to certify that the project report entitled “SOFTWARE FOR


STOCKS MANAGEMENT” submitted by Arkoprovo Shaw
during the academic year 2024-2025 is a fine piece of work conducted
under my supervision and guidance. The data sources have been duly
acknowledged. I wish him success in all his future endeavours.

(Principal) (Project Guide)

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.

0.4.2 Benefits of the Proposed System


1. Automated Data Retrieval: The stock symbol.

2. Efficient Data Management: The name of the stock.

3. Real-time Insights: The current price of the stock.

4. User-Centric Design: The change in price since the last time


the stock price was updated.

5. Market Analysis Integration: The year high and low values


of stocks for trend analysis.

6. Error Prevention System: Built-in validation checks to pre-


vent incorrect data entry and duplicate records.

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.

0.5.2 Technical Feasibility


The proposed system is technically feasible since it can be implemented
using the available technologies. The system is designed to be user-
friendly and easy to use, with minimal technical requirements. The sys-
tem can be easily integrated into existing systems and workflows, making
it a practical solution for a wide range of users.

0.5.3 Social Feasibility


The system is operationally feasible as it automates tedious tasks such
as data collection, ensuring minimal user intervention. Once set up,
the system will run autonomously, fetching stock data and updating the
database accordingly.

6
0.6 System Design
0.6.1 System Workflow
The system workflow is as follows:

• Web Scraping: This module is responsible for collecting stock


data(e.g. stock price, market capitalization, trading volume) from
the internet.

• Data Storage Layer: Once collected, the data is stored in a


MySQL database, where it is structured and indexed for efficient
access.

• Menu Operations: Users can query the database to retrieve


specific stock data, update records, or analyze stock trends based
on historical data.

0.6.2 Technology Stack


The system is built using the following technologies:

• Frontend: Python The programming language used for the sys-


tem’s backend.

• Backend: MySQL The database management system used for


data storage.

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

• users: Columns include owned stocks, initial price, total quantity

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.

• Deletion: Deletes owned stocks

• Update: When stock prices or other metrics change, the database


is updated to reflect the new values.

• Select: Retrieves data from the stocks table

• Query: Users can query the database to retrieve specific stock


information (e.g., the profit) or to analyze trends (e.g., stocks with
the highest trading volume).

8
0.8 System Specifications
0.8.1 Hardware
• CPU: Intel Core i3 or higher

• RAM: 2GB or more

• Storage: 20GB or more

• Internet: 100KB/s or higher

0.8.2 Software
• Operating System: Linux/MacOS/Windows

• Database Management System: MySQL 8.x/ MariaDB 10.x

• Programming Language: Python 3.11.x

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("CREATE DATABASE IF NOT EXISTS pysql")


cur.execute("USE pysql")
return con, cur

def update_user(user, dc, mode):


con, cur = connect()

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}")

if mode not in ["update", "delete"]:


print("=" * 21, "STOP", "=" * 21)

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

Figure 1: Displaying Portfolio and calculating profit

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

You might also like