0% found this document useful (0 votes)
3 views55 pages

Class 12 Informatics Practices Project

The document outlines a project titled 'Stock Market (Trading System)' completed by Shivang Dubey for Class XII-B at St. Francis School, Gundle. It includes a certificate of completion, acknowledgments, and code snippets for a trading system that fetches stock, cryptocurrency, and mutual fund data using Python. The project also features user authentication and KYC processes for managing user data and transactions.

Uploaded by

sketchartist769
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views55 pages

Class 12 Informatics Practices Project

The document outlines a project titled 'Stock Market (Trading System)' completed by Shivang Dubey for Class XII-B at St. Francis School, Gundle. It includes a certificate of completion, acknowledgments, and code snippets for a trading system that fetches stock, cryptocurrency, and mutual fund data using Python. The project also features user authentication and KYC processes for managing user data and transactions.

Uploaded by

sketchartist769
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

ST.

FRANCIS SCHOOL, GUNDLE,


BOISAR
2024 – 2025
Class: XII-B (Commerce)
Informatics Practices (065)

Stock Market
(Trading System)
Submitted by: Submitted to:
Name: Shivang Dubey Name: Ms. Pravara Dandapat

Roll No.:
Sr. Jyoti Joseph
Principal
Certificate
This is to certify that “Computer Science Project"
titled Stock Market (Trading System) has been
successfully completed by Ms. / Mst. Shivang
Dubey of Class XII under the guidance of Ms.
Pravara Dandapat in particular fulfillment of the
curriculum of Central Board of Secondary Education
leading the award of annual examination of the year
2022-23 and that this work has not been submitted
elsewhere for certification.

___________ ___________ __________


Project Guide Sr. Jyoti Joseph External
Examiner
Internal Examiner Principal CBSE
Acknowledgement
I started this project as a part of my course
curriculum. It gave a great pleasure in building this
project, and also presenting the report of this
project-work conducted towards the fulfillment of
the project titled Stock Market (Trading
System) as per the guidelines laid by the CBSE
Board.

I am extremely thankful to our Principal


Rev. Sr. Jyoti Joseph who gave me the golden
opportunity to do such a project.
I would like to express my gratitude to my Computer
Science subject teacher Ms. Pravara Dandapat for
constantly guiding me. Her suggestions and her
instructions have served as the major contribution
towards the completion of the project.
My heartfelt thanks to CBSE.
I also express my deepest gratitude to my parents.

Shivang Dubey
Missllaneous.py

1 import yfinance as yf
2
3 def get_stock_data(symbol):
4 try:
5 stock = yf.Ticker(symbol)
6 stock_info = stock.info
7
8 # Fundamental Data
9 fundamental_data = {
10 'Market Cap': stock_info.get('marketCap'),
11 'Forward P/E': stock_info.get('forwardPE'),
12 'Dividend Yield': stock_info.get('dividendYield'),
13 'EPS (ttm)': stock_info.get('trailingEps'),
14 'Book Value': stock_info.get('bookValue'),
15 # Add more fundamental data as needed
16 }
17
18 # Price Data
19 price_data = {
20 'Previous Close': stock_info.get('previousClose'),
21 'Open': stock_info.get('open'),
22 'Bid': stock_info.get('bid'),
23 'Ask': stock_info.get('ask'),
24 'Day\'s Range': stock_info.get('dayRange'),
25 '52 Week Range': stock_info.get('fiftyTwoWeekRange'),
26 # Add more price data as needed
27 }
28
29 return fundamental_data, price_data
30
31 except Exception as e:
32 print(f"Error fetching data for {symbol}: {e}")
33 return None, None
34
35 def get_crypto_data1(symbol):
36 try:
37 stock = yf.Ticker(symbol)
38 stock_info = stock.info
39
40 # Fundamental Data
41 fundamental_data = {
42 'Market Cap': stock_info.get('marketCap'),
43 'Forward P/E': stock_info.get('forwardPE'),
44 'Dividend Yield': stock_info.get('dividendYield'),
45 'EPS (ttm)': stock_info.get('trailingEps'),
46 'Book Value': stock_info.get('bookValue'),
47 # Add more fundamental data as needed
48 }
49
50 # Price Data
51 price_data = {
52 'Previous Close': stock_info.get('previousClose'),
53 'Open': stock_info.get('open'),
54 'Bid': stock_info.get('bid'),
55 'Ask': stock_info.get('ask'),
56 'Day\'s Range': stock_info.get('dayRange'),
57 '52 Week Range': stock_info.get('fiftyTwoWeekRange'),
58 # Add more price data as needed
59 }
60
61 return fundamental_data, price_data
62
63 except Exception as e:
64 print(f"Error fetching data for {symbol}: {e}")
65 return None, None
66
67
68 def get_mutual_fund_data(symbol):
69 try:
70 fund = yf.Ticker(symbol)
71 fund_info = fund.info
72
73 # Performance & Risk
74 performance_risk_data = {
75 'Beta (3Y Monthly)': fund_info.get('beta3Year'),
76 'Annual Report Expense Ratio (net)': fund_info.get('annualReportExpenseRatio'),
77 'Total Assets': fund_info.get('totalAssets'),
78 'Morningstar Risk Rating': fund_info.get('morningStarRiskRating'),
79 'YTD Return': fund_info.get('ytdReturn'),
80 # Add more performance and risk metrics as needed
81 }
82
83 # Fund Overview
84 fund_overview_data = {
85 'Category': fund_info.get('category'),
86 'Family': fund_info.get('fundFamily'),
87 'Net Assets': fund_info.get('netAssets'),
88 'Legal Type': fund_info.get('legalType'),
89 # Add more fund overview data as needed
90 }
91
92 return performance_risk_data, fund_overview_data
93
94 except Exception as e:
95 print(f"Error fetching data for {symbol}: {e}")
96 return None, None
97
98
99
UserAuth.py

1 import mysql.connector
2 import pandas as pd
3 import random
4 import warnings
5
6 warnings.filterwarnings("ignore", message="pandas only supports SQLAlchemy connectable")
7 # Establish a connection to the MySQL database
8 db_connection = mysql.connector.connect(
9 host="localhost",
10 user="root",
11 password="iafiaa2.0",
12 database="s_brokers"
13 )
14 mydb = mysql.connector.connect(
15 host="localhost",
16 user="root",
17 password="iafiaa2.0",
18 database="nifty50"
19 )
20 mydb2 = mysql.connector.connect(
21 host="localhost",
22 user="root",
23 password="iafiaa2.0",
24 database="crypto.cix"
25 )
26 mydb3 = mysql.connector.connect(
27 host="localhost",
28 user="root",
29 password="iafiaa2.0",
30 database="holdings"
31 )
32 # Create a cursor object to execute SQL queries
33 cursor = db_connection.cursor()
34 mcursor = mydb3.cursor()
35
36 print('''
37
38 _ _ _ _
39 (_)(_)(_) | | _
40 _ _ _ _____| | ____ ___ ____ _____ _| |_ ___
41 | || || | ___ | |/ ___) _ \| \| ___ | (_ _) _ \
42 | || || | ____| ( (__| |_| | | | | ____| | || |_| |
43 \______/|_____)\_)____)___/|_|_|_|_____) \__) ____/
44
45 _____ ___ _
46 / ___\ / __\_ __ ___ | | _____ _ __ ___
47 \ \ _____ /__\// '__/ _ \| |/ / _ \ '__/ __|
48 _\ \_____/ \/ \ | | (_) | < __/ | \__ \
49 \____/ \_____/_| \___/|_|\_\___|_| |___/
50
51
52 ''')
53
54 def verify_auth():
55 print('''
56 | | _ _ _ /\ _|_|_ (~ _ _ _ _| _| _ _|
57 |_|_\(/_| /~~\|_| | | | _)|_|(_(_(/_(_|(_|(/_(_|
58
59 ''')
60
61 auth = input("New user? type y/n: ")
62
63 if auth == 'y':
64
65 def user_data():
66 username2 = input("\nTry another username: ")
67 password = input("Enter password: ")
68 email = input("Enter email: ")
69 full_name = input("Enter your full-name: ")
70 dob = input("Enter Date-of-Birth: ")
71 address = input("Enter your address: ")
72 phone_no = int(input("Enter Mob-No.: "))
73 r_date = input("Registration Date: ")
74
75 insert_query = "INSERT INTO users (username, password, email, full_name, date_of_birth, address,
phone_number, registration_date) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
76 cursor.execute(insert_query, (username2, password, email, full_name, dob, address, phone_no,
r_date))
77 db_connection.commit()
78
79
80 def user_data2():
81 password = input("Enter password: ")
82 email = input("Enter email: ")
83 full_name = input("Enter your full-name: ")
84 dob = input("Enter Date-of-Birth: ")
85 address = input("Enter your address: ")
86 phone_no = int(input("Enter Mob-No.: "))
87 r_date = input("Registration Date: ")
88
89 insert_query = "INSERT INTO users (username, password, email, full_name, date_of_birth, address,
phone_number, registration_date) VALUES (%s, %s, %s, %s, %s, %s, %s, %s)"
90 cursor.execute(insert_query, (username, password, email, full_name, dob, address, phone_no,
r_date))
91 db_connection.commit()
92
93
94 def create_user_table(username):
95 mcursor.execute(f"""
96 CREATE TABLE {username} (
97 User_Id INT AUTO_INCREMENT,
98 UserName VARCHAR(50),
99 Symbol VARCHAR(255),
100 Quantity INT,
101 Price INT,
102 T_Type VARCHAR(20),
103 P_Date TIMESTAMP,
104 PRIMARY KEY (User_Id)
105 )
106 """)
107
108
109
110 username = input("\nEnter username: ")
111 print("Checking Username!")
112 # Check if the user already exists in the database
113 check_query = "SELECT * FROM users WHERE username = %s"
114 cursor.execute(check_query, (username,))
115 existing_user = cursor.fetchone()
116
117 if existing_user:
118 print("User already exists!\n")
119 user_data()
120 create_user_table(username)
121 else:
122 print("Username Verified :)\n")
123 user_data2()
124 verify_auth()
125 create_user_table(username)
126
127 #checks if new user has completed his kyc or not
128 #before starting to trade
129 #query = "SELECT Name FROM kyc WHERE Name = %s"
130 #values = (username)
131 #cursor.execute(query, (values,))
132 #result = cursor.fetchone()
133
134
135 # Get user input for username, password, and email
136 elif auth == 'n':
137 print("\n••••••••• LOGIN •••••••••")
138 def login():
139 global username
140 username = input("\nEnter your username: ")
141 password2 = input("Enter password: ")
142 email2 = input("Enter email: ")
143
144 check_query = "SELECT * FROM users WHERE username = %s AND password = %s AND email = %s"
145 cursor.execute(check_query, (username, password2, email2))
146 global existing_user
147 existing_user = cursor.fetchone()
148 login()
149 if existing_user:
150 verify_auth()
151 else:
152 print("Invalid Details! Please try Again!")
153 login()
154 verify_auth()
155
156
157 # Function to insert KYC data into the database
158 def insert_kyc_data(pan, name, dob, gender, aadhar, passport, mob, tin, bank_name, ifsc_no, acc_no):
159 query = "INSERT INTO kyc (PAN, Name, DateOfBirth, Gender, AadharNo, PassportNo, MobNo, TIN, BankName,
ACCDetails, ifsc) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
160 values = (pan, name, dob, gender, aadhar, passport, mob, tin, bank_name, ifsc_no, acc_no)
161 cursor.execute(query, values)
162 db_connection.commit()
163 print("\nKYC completed successfully!")
164
165
166 # Function to update KYC data in the database
167 def update_kyc_data(pan, name, dob, gender, aadhar, passport, mob, tin):
168 query = "UPDATE kyc SET Name = %s, DateOfBirth = %s, Gender = %s, AadharNo = %s, PassportNo = %s,
MobNo = %s, TIN = %s WHERE PAN = %s"
169 values = (name, dob, gender, aadhar, passport, mob, tin, pan)
170 cursor.execute(query, values)
171 db_connection.commit()
172 print("\nKYC information updated successfully!")
173
174
175 # Function to verify KYC data
176 def verify_kyc(aadhar, pan):
177 query = "SELECT * FROM kyc WHERE AadharNo = %s AND PAN = %s"
178 values = (aadhar, pan)
179 cursor.execute(query, values)
180 result = cursor.fetchone()
181 if result:
182 print("\nKYC verification successful!")
183 else:
184 print("\nKYC verification failed. Please provide valid KYC information.")
185
186
187 def bank_details(user_id):
188 query = "SELECT Name FROM s_brokers.kyc WHERE MobNo = %s"
189 cursor.execute(query, (user_id,))
190 result = cursor.fetchone()
191 if result:
192 # KYC completed, retrieve bank account details
193 query = "SELECT Name, BankName, ifsc, ACCDetails FROM s_brokers.kyc WHERE MobNo = %s"
194 cursor.execute(query, (user_id,))
195 bank_details = cursor.fetchone()
196
197 holder_name, bank_name, ifsc_code, account_no = bank_details
198 print('''\n••••••• BANK DETAILS •••••••''')
199 print("Bank Account Holder Name:", holder_name)
200 print("Bank Name:", bank_name)
201 print("IFSC Code:", ifsc_code)
202 print("Bank Account Number:", account_no)
203 print("Bank Status: ACTIVE")
204
205 else:
206 print("Please complete your KYC first!")
207
208
209 def new_portfolio():
210 u_name = input("Enter your username: ")
211 p_name = input("\nEnter Portfolio Name: ")
212 p_date = input("Enter Current Date(YYYY-MM-DD): ")
213 p_type = input("Portolio type: ")
214 account_id = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
215 Acc_id = ''.join(random.choice(account_id) for _ in range(6))
216 broker_id = "0123456789"
217
218 print("\nNOTE: Deposit Balance for Inapp-transactions")
219 Amt = int(input("Enter your amount: "))
220 method = input("Select UPI or Debit/Credit Cards: ")
221 if method == 'UPI':
222 upi_id = input("Enter UPI-Id: ")
223 Id_proof = input("Id-Proof (PAN/Aadhar No.): ")
224
225 elif method == 'Debit Card':
226 card_no = input("Enter your Debit/Credit Card No: ")
227 expiry = input("Enter Expiry Date: ")
228 cvv = input("Enter your CVV: ")
229 name = input("Enter full name: ")
230 Id_proof = input("Id-Proof (PAN/Aadhar No.): ")
231
232 Br_id = ''.join(random.choice("SM" + broker_id) for _ in range(6))
233
234 query = "INSERT INTO portfolio (UName, PName, Creation_Date, PType, Account_ID, Broker_ID,
Depo_Balance) VALUES (%s, %s, %s, %s, %s, %s, %s)"
235 values = (u_name, p_name, p_date, p_type, Acc_id, Br_id, Amt)
236 cursor.execute(query, values)
237 db_connection.commit()
238 print("\nPortfolio Created Successfully!")
239
240 def fill_portfolio(get_name, qty, total, method):
241 mcursor.execute(f"INSERT INTO {username} (UserName, Symbol, Quantity, Price, T_Type) VALUES
('{username}', '{get_name}', {qty}, {total}, '{method}')")
242 mydb3.commit()
243
244 def view_portfolio():
245 cursor.execute(f"SELECT * FROM s_brokers.portfolio WHERE UName = '{username}'")
246 Amt = cursor.fetchone()
247 if Amt:
248 print("\n----- CURRENT INVESTMENTS -----")
249 # Read data from MySQL into a pandas DataFrame
250 df = pd.read_sql(f"SELECT Symbol, Quantity, Price FROM {username};", mydb3)
251 print(df)
252 sum_column_A = df['Price'].sum()
253 print("\nValue of Portfolio(₹): ", sum_column_A)
254 try:
255 cursor.execute(f"SELECT Depo_Balance FROM s_brokers.portfolio WHERE UName = '{username}'")
256 Amt = cursor.fetchone()
257 Amount = int(Amt[0])
258 print("Your Amount(₹): ", Amount)
259 except:
260 print("Your Amount(₹): 0")
261 else:
262 print("Create new portfolio!")
263
264
265 def update_deposits(total, name1):
266 cursor.execute(f"UPDATE s_brokers.portfolio SET Depo_Balance = Depo_Balance - {total} WHERE UName =
'{name1}'")
267 db_connection.commit()
268 def update_deposits1(total_value_to_deduct):
269 cursor.execute(f"UPDATE s_brokers.portfolio SET Depo_Balance = Depo_Balance + {total_value_to_deduct}
WHERE UName = '{username}'")
270 db_connection.commit()
271
272 def sell_stocks():
273 stk = input("Enter Stock symbol: ")
274 qt = int(input("Enter the quantity: "))
275 mcursor.execute(f"SELECT Quantity FROM holdings.{username} WHERE Symbol = '{stk}'")
276 res = mcursor.fetchone()
277
278 try:
279 result2 = int(res[0])
280 conf = input("To confirm type(y): ")
281 if conf == 'y':
282 print("\nTransaction Successfull!")
283 print("You'll recieve payment shortly!")
284
285 cursor.execute(f"select Close from nifty50.`{stk}` order by `index` desc limit 1;")
286 result1 = cursor.fetchall()
287 stk_mprice = int(result1[0][0])
288
289 available_quantity = result2
290 if available_quantity >= qt:
291 # Calculate the total value of the sold stocks
292 total_value_to_deduct = qt * stk_mprice
293
294 # Update the holdings table to deduct the sold stocks
295 remaining_quantity = available_quantity - qt
296 if remaining_quantity == 0:
297 # If the remaining quantity becomes zero, delete the row
298 mcursor.execute(f"DELETE FROM holdings.{username} WHERE Symbol = '{stk}'")
299 else:
300 # Otherwise, update the row with the remaining quantity and price
301 mcursor.execute(f"UPDATE holdings.{username} SET Quantity = Quantity - {qt}, Price =
Price - {total_value_to_deduct} WHERE Symbol = '{stk}'")
302
303 # Commit the transaction
304 mydb3.commit()
305 print(f"\nDeducted {qt} stocks of {stk} from the portfolio.")
306 print(f"Total value deducted(₹): {total_value_to_deduct}")
307 update_deposits1(total_value_to_deduct)
308
309 except:
310 print("\nInsufficient quantity of stocks to sell!!")
311
312
313 def sell_crypto():
314 crpt = input("Enter crypto symbol: ")
315 qt = int(input("Enter the quantity: "))
316 walet_id = input("Enter your Crypto Wallet-ID: ")
317 print("\nPayment recieving methods: [UPI, Net Banking]")
318 p_method = input("Enter P_Recieving Method: ")
319 if p_method == 'UPI' or 'upi':
320 get_id = input("Enter UPI_ID: ")
321 elif p_method == 'Net Banking':
322 get_bnm = input("Enter Bank Name: ")
323 get_acc = input("Enter Bank AC.NO: ")
324 mcursor.execute(f"SELECT Quantity FROM holdings.{username} WHERE Symbol = '{crpt}'")
325 re = mcursor.fetchone()
326
327 try:
328 result = int(re[0])
329 conf = input("To confirm type(y): ")
330 if conf == 'y':
331 print("Order Successfull!")
332 print("You'll recieve payment shortly!")
333
334 cursor.execute(f"select Close from `crypto.cix`.`{crpt}` order by `index` desc limit 1;")
335 result2 = cursor.fetchall()
336 crypt_mprice = int(result2[0][0])
337
338 available_quantity = result
339 if available_quantity >= qt:
340 # Calculate the total value of the sold stocks
341 total_value_to_deduct = qt * crypt_mprice
342
343 # Update the holdings table to deduct the sold stocks
344 remaining_quantity = available_quantity - qt
345 if remaining_quantity == 0:
346 # If the remaining quantity becomes zero, delete the row
347 mcursor.execute(f"DELETE FROM holdings.{username} WHERE Symbol = '{crpt}'")
348 else:
349 # Otherwise, update the row with the remaining quantity and price
350 update_query = f"UPDATE holdings.{username} SET Quantity = Quantity - {qt}, Price =
Price - {total_value_to_deduct} WHERE Symbol = '{crpt}'"
351 mcursor.execute(update_query, (qt, total_value_to_deduct, crpt))
352
353 # Commit the transaction
354 mydb3.commit()
355 print(f"\nDeducted {qt} Currency of {crpt} from the portfolio.")
356 print(f"Total value deducted(₹): {total_value_to_deduct}")
357 update_deposits1(total_value_to_deduct)
358
359 except:
360 print("\nInsufficient quantity of currency to sell!!")
361
362
363
364 def sell_mf(get_name2, units_to_sell, mf_price):
365 mcursor.execute(f"SELECT Quantity FROM holdings.{username} WHERE Symbol = '{get_name2}'")
366 result = mcursor.fetchone()
367
368 try:
369 result3 = int(result[0])
370 available_quantity = result3
371 if available_quantity >= units_to_sell:
372 # Calculate the total value of the sold stocks
373 total_value_to_deduct = units_to_sell * mf_price
374
375 # Update the holdings table to deduct the sold stocks
376 remaining_quantity = available_quantity - units_to_sell
377 if remaining_quantity == 0:
378 # If the remaining quantity becomes zero, delete the row
379 mcursor.execute(f"DELETE FROM holdings.{username} WHERE Symbol = '{get_name2}'")
380 else:
381 # Otherwise, update the row with the remaining quantity and price
382 update_query = f"UPDATE holdings.{username} SET Quantity = Quantity - {units_to_sell},
Price = Price - {mf_price} WHERE Symbol = '{get_name2}'"
383 mcursor.execute(update_query)
384
385 # Commit the transaction
386 mydb3.commit()
387 print(f"\nDeducted {units_to_sell} Units of {get_name2} from the portfolio.")
388 print(f"Total value deducted(₹): {total_value_to_deduct}")
389 update_deposits1(total_value_to_deduct)
390
391 except:
392 print("\nInsufficient Units to sell!!")
393
394 # Closing the cursor and database connection
395 def close_connection():
396 cursor.close()
397 mcursor.close()
398 db_connection.close()
399 mydb3.close()
400
401
402
Main.py

1 import pandas as pd
2 import matplotlib.pyplot as plt
3 import mysql.connector
4 from rich.console import Console
5 from rich.table import Table
6 from tqdm import tqdm
7 from time import sleep
8 from Missllaneous import (get_stock_data, get_crypto_data1, get_mutual_fund_data)
9 from UserAuth import (insert_kyc_data, verify_kyc, bank_details, fill_portfolio,
10 new_portfolio, view_portfolio, sell_stocks, update_deposits,
11 sell_crypto, sell_mf)
12
13 mydb = mysql.connector.connect(
14 host="localhost",
15 user="root",
16 password="iafiaa2.0",
17 database="nifty50"
18 )
19
20 holdings = mysql.connector.connect(
21 host="localhost",
22 user="root",
23 password="iafiaa2.0",
24 database="holdings"
25 )
26
27 db_conn1 = mysql.connector.connect(
28 host="localhost",
29 user="root",
30 password="iafiaa2.0",
31 database="s_brokers"
32 )
33
34 mycursor=mydb.cursor()
35 cursor=holdings.cursor()
36 curs=db_conn1.cursor()
37 #exec(open("UserAuth.py").read())
38
39 def user_dashboard():
40 table = Table(title="\nS-Brokers User's Dashboard")
41 rows = [
42 ["[1] Trading in Stocks/Securities", "[4] User Account"],
43 ["[2] Trading in Crypto Indices", "[5] Personal Loans"],
44 ["[3] Investing in Mutual Funds", "[6] Investment Research/Analysis"],
45 ]
46
47 columns = ["Stocks and Securities", "Personal"]
48 for column in columns:
49 table.add_column(column)
50
51 for row in rows:
52 table.add_row(*row, style='#94DBEE')
53
54 console = Console()
55 console.print(table)
56
57
58 def welcome():
59 user_dashboard()
60
61 print("NOTE: To select any services type their [n], E.g., 1,2,3...")
62 choice = int(input("What would you like to do? "))
63
64 if choice == 1:
65 trade_stocks()
66 elif choice == 2:
67 trade_crypto()
68 elif choice == 3:
69 trade_mf()
70 elif choice == 4:
71 user_acc()
72 elif choice == 5:
73 personal_loans()
74 elif choice == 6:
75 inv_analysis()
76
77
78
79 def trade_stocks():
80 print('List of Stocks traded on NSE(Nifty50)\n')
81 nifty = pd.read_csv('nifty50.csv')
82 print(nifty)
83
84 print("\nNOTE: Please write symbols in lowerCase and add '.ns' at the end [E.g. adanient.ns]")
85 get_name = input("Enter Stock(Company) Symbol: ")
86 cap_inp = get_name.upper()
87 if cap_inp in nifty['Symbol'].values:
88
89 graph = input("See performance chart? (y/n): ")
90 if graph == 'y':
91 mycursor.execute(f"select Date, Close from nifty50.`{get_name}`;")
92 result = mycursor.fetchall()
93
94 Date = []
95 Close = []
96 for i in result:
97 Date.append(i[0])
98 Close.append(i[1])
99 # Visualizing Data using Matplotlib
100 plt.plot(Date, Close)
101 plt.title(get_name)
102 plt.xlabel("Performing years")
103 plt.ylabel("Fluactuating Prices")
104 plt.grid(True)
105 plt.show()
106
107 if graph == 'n':
108 print('')
109
110 confirm = input("Want to trade(y/n): ")
111 if confirm == 'y':
112 ch1 = input("Want to (buy/sell): ")
113 if ch1 == 'buy':
114 print("\nDISCLAIMER: Investment in securities are subject to market risks")
115 print("\nNOTE: When buying or selling stocks\n • there are different types of orders\n •
Some common order types include market orders & limit orders\n • Market orders are executed immediately at
the current market price\n • while limit orders allow users to set a specific price at which they want to
buy or sell")
116 order = input("\nSelect Order type: ")
117
118 mycursor.execute(f"select Close from nifty50.`{get_name}` order by `index` desc limit 1;")
119 result = mycursor.fetchall()
120 stk_mprice = int(result[0][0])
121
122
123 if order == 'Market':
124
125 print("Market price of", get_name, 'is: ', stk_mprice)
126 qty = int(input("Enter the quantity: "))
127 total = stk_mprice * qty
128 print("Your total amount is: ", total)
129 method = 'In-App Transaction'
130
131 name1 = input("\nAgain enter your username: ")
132 curs.execute(f"SELECT Depo_Balance FROM s_brokers.portfolio WHERE UName = '{name1}'")
133 Amt = curs.fetchone()
134
135 try:
136 Amount = int(Amt[0])
137 if Amount >= total:
138 print("\nOrder successful of", get_name)
139 fill_portfolio(get_name, qty, total, method)
140 update_deposits(total, name1)
141 cho = input("back & exit(b/ext): ")
142 if cho == 'b':
143 trade_stocks()
144 elif cho == 'ext':
145 welcome()
146 elif Amount < total:
147 print("Deposited amount is insufficient!")
148 welcome()
149 except:
150 print("\nInsufficient amount!\nDeposits amount from your bank/UPI")
151 print("To Deposit: [User Account => Create new portfolio]")
152 welcome()
153
154 elif order == "Limit":
155 print("Market price of", get_name, 'is: ', stk_mprice)
156 amt = int(input("Enter your amount to buy (Exclude decimals): "))
157 qty = int(input("Enter the quantity: "))
158 total = amt * qty
159 print("Your total amount is: ", total)
160
161 print("\nYour order will be executed later!")
162 print("When your asked amount reaches at that price")
163 cho = input("\nback & exit(b/ext): ")
164 if cho == 'b':
165 trade_stocks()
166 elif cho == 'ext':
167 welcome()
168
169
170
171 if ch1 == 'sell':
172 sell_stocks()
173 cho = input("back & exit(b/ext): ")
174 if cho == 'b':
175 trade_stocks()
176 elif cho == 'ext':
177 welcome()
178
179
180 elif confirm == 'n':
181 welcome()
182
183 else:
184 print("Incorrect Symbol! Try Again!")
185 welcome()
186
187
188 def trade_crypto():
189 print('List of Crypto Currencies traded in market\n')
190 ctx = pd.read_csv('crypto.csv')
191 print(ctx)
192
193 print("\nNOTE: Please write symbols in lowerCase")
194 get_name1 = input("\nEnter Crypto(Currency) Symbol: ")
195 cap_inp1 = get_name1.upper()
196 if cap_inp1 in ctx['Symbol'].values:
197
198 graph1 = input("See performance chart? (y/n): ")
199 if graph1 == 'y':
200 mycursor.execute(f"select Date, Close from `crypto.cix`.`{get_name1}`;")
201 result2 = mycursor.fetchall()
202
203 Date1 = []
204 Close1 = []
205 for i in result2:
206 Date1.append(i[0])
207 Close1.append(i[1])
208
209 # Visualizing Data using Matplotlib
210 plt.plot(Date1, Close1)
211 plt.title(get_name1)
212 plt.xlabel("Performing years")
213 plt.ylabel("Fluactuating Prices")
214 plt.grid(True)
215 plt.show()
216
217 elif graph1 == 'n':
218 print('')
219
220 confirm = input("Want to trade(y/n): ")
221 if confirm == 'y':
222 ch2 = input("want to (buy/sell): ")
223 if ch2 == 'buy':
224 print("\nNOTE: When buying or selling crypto-currencies\nthere are different types of
orders\nSome common order types include market orders & limit orders\nMarket orders are executed
immediately at the current market price\nwhile limit orders allow users to set a specific price at which
they want to buy or sell")
225 order = input("\nSelect Order type: ")
226
227 if order == 'Market':
228 mycursor.execute(f"select Close from `crypto.cix`.`{get_name1}` order by `index` desc
limit 1;")
229 result2 = mycursor.fetchall()
230 cix_mprice = int(result2[0][0])
231
232 print("Market price of", get_name1, 'is: ', cix_mprice)
233 qty = int(input("Enter the quantity: "))
234 total = cix_mprice * qty
235 print("Your total amount is: ", total)
236 method = 'In-App Transaction'
237
238 name1 = input("\nAgain enter your username: ")
239 curs.execute(f"SELECT Depo_Balance FROM s_brokers.portfolio WHERE UName = '{name1}'")
240 Amt = curs.fetchone()
241
242 try:
243 Amount = int(Amt[0])
244 if Amount >= total:
245 print("\nOrder successful of", get_name1)
246 fill_portfolio(get_name1, qty, total, method)
247 update_deposits(total, name1)
248 cho = input("back & exit(b/ext): ")
249 if cho == 'b':
250 trade_stocks()
251 elif cho == 'ext':
252 welcome()
253 elif Amount < total:
254 print("Deposited amount is insufficient!")
255 welcome()
256 except:
257 print("\nInsufficient amount!\nDeposits amount from your bank/UPI")
258 print("To Deposit: [User Account => Create new portfolio]")
259 welcome()
260
261 elif order == "Limit":
262 print("\nNOTE: You can see Market Prices in that given chart")
263 amt = int(input("Enter your amount to buy (Exclude decimals): "))
264 qty = int(input("Enter the quantity: "))
265 total = amt * qty
266 print("Your total amount is: ", total)
267 method = 'In-App Transaction'
268
269 name1 = input("\nAgain enter your username: ")
270 wallet_ID = input("Enter your Crypto Wallet-ID: ")
271
272 print("\nYour order will be executed later!")
273 print("When your asked amount reaches at that price")
274 cho = input("\nback & exit(b/ext): ")
275 if cho == 'b':
276 trade_stocks()
277 elif cho == 'ext':
278 welcome()
279
280
281 elif ch2 == 'sell':
282 sell_crypto()
283 cho = input("back & exit(b/ext): ")
284 if cho == 'b':
285 trade_crypto()
286 elif cho == 'ext':
287 welcome()
288
289 elif confirm == 'n':
290 welcome()
291
292 else:
293 print("Incorrect Symbol! Try Again!")
294 welcome()
295
296 def trade_mf():
297 print('Major Mutual Funds in market\n')
298 mtx = pd.read_csv('mutual_funds.csv')
299 mtx = pd.DataFrame(mtx)
300 print(mtx)
301
302
303 print("\nNOTE: Please write symbols in lowerCase and add '.bo' at the end [E.g. 0p00005unh.bo]")
304 get_name2 = input("\nEnter Mutual Fund Symbol: ")
305 cap_inp2 = get_name2.upper()
306 if cap_inp2 in mtx['Symbol'].values:
307
308 graph2 = input("See performance chart? (y/n): ")
309 if graph2 == 'y':
310 mycursor.execute(f"select Date, Open, High, Low, Close from `mutual.funds`.`{get_name2}`;")
311 result3 = mycursor.fetchall()
312
313 Date2 = []
314 Close2 = []
315 for i in result3:
316 Date2.append(i[0])
317 Close2.append(i[4])
318
319 # Visualizing Data using Matplotlib
320 plt.plot(Date2, Close2)
321 plt.title(get_name2)
322 plt.xlabel("Performing years")
323 plt.ylabel("Fluactuating Prices")
324 plt.grid(True)
325 plt.show()
326
327 elif graph2 == 'n':
328 print('')
329
330 confirm = input("Want to trade (y/n): ")
331 if confirm == 'y':
332 def generate_receipt(fname, transaction_type, amount, units_to_buy, unit_price):
333 receipt = f"Transaction Confirmation:\n"
334 receipt += f"----------------------------------------\n"
335 receipt += f"Fund Name: {fname}\n"
336 receipt += f"Transaction Type: {transaction_type.capitalize()}\n"
337 receipt += f"Amount: ₹{amount:.2f}\n"
338 receipt += f"Units: {units_to_buy}\n"
339 receipt += f"Unit Price: ₹{unit_price:.2f}\n"
340 receipt += f"----------------------------------------\n"
341 return receipt
342
343
344 def process_transaction1(fund_name, transaction_type, amount, unit_price):
345 """Buy a mutual fund."""
346
347 units_to_buy = amount / unit_price
348 print("Available units to buy: ", units_to_buy)
349
350 print("\nINFO: Use UPI or Debit/Credit cards for payments")
351 method = input("Specify payment method: ")
352 if method == 'UPI':
353 upi_id = input("Enter UPI-Id: ")
354 Id_proof = input("Enter PAN No.: ")
355 print("\nOrder successful of", fund_name)
356
357 elif method == 'Debit Card':
358 card_no = input("Enter your Debit Card No: ")
359 expiry = input("Enter Expiry Date: ")
360 cvv = input("Enter your CVV: ")
361 name1 = input("Enter full name: ")
362 Id_proof = input("Enter PAN No.: ")
363 print("\nOrder successful of", fund_name)
364
365
366 print(f"You have successfully bought {units_to_buy} units of {fund_name}.")
367 get_name = get_name2
368 qty = units_to_buy
369 total = amount
370 fill_portfolio(get_name, qty, total, method)
371
372 name = fund_name.upper()
373 fname = mtx.loc[mtx['Symbol'] == name, 'Funds Name'].values[0]
374 receipt = generate_receipt(fname, transaction_type, amount, units_to_buy, unit_price)
375 print(receipt)
376
377 get_choice = input("Back or exit (b/ext): ")
378 if get_choice == 'b':
379 trade_mf()
380 elif get_choice == 'ext':
381 welcome()
382
383
384 def process_transaction2(fund_name, transaction_type, units_to_buy, mf_price):
385 """Sell a mutual fund."""
386
387 if units_to_buy is None:
388 print("No units to sell. Please buy units first.")
389 trade_mf()
390 return
391
392
393 units_to_sell = int(input("Enter the units to sell: "))
394 sell_mf(get_name2, units_to_sell, mf_price)
395
396 # Generate and print receipt
397 name = fund_name.upper()
398 fname = mtx.loc[mtx['Symbol'] == name, 'Funds Name'].values[0]
399
400 #generating reciept with sale details
401 units_to_buy = units_to_sell
402 amount = units_to_sell * mf_price
403 print(f"You have successfully sold {fund_name} for ₹{amount}.")
404 receipt = generate_receipt(fname, transaction_type, amount, units_to_buy, mf_price)
405 print(receipt)
406
407 get_choice = input("Back or exit (b/ext): ")
408 if get_choice == 'b':
409 trade_mf()
410 elif get_choice == 'ext':
411 welcome()
412
413 # Example usage
414 fund_name = get_name2
415 transaction_type = input("Enter choice (buy/sell): ") # or "sell" # in USD
416 if transaction_type == 'buy':
417 amount = float(input("Enter amount to invest(₹): "))
418 mycursor.execute(f"select Close from `mutual.funds`.`{get_name2}` order by `index` desc
limit 1;")
419 result2 = mycursor.fetchall()
420 mf_price = int(result2[0][0])
421 unit_price = mf_price # price per unit in USD
422 process_transaction1(fund_name, transaction_type, amount, unit_price)
423
424 elif transaction_type == 'sell':
425 mycursor.execute(f"select Close from `mutual.funds`.`{get_name2}` order by `index` desc
limit 1;")
426 result2 = mycursor.fetchall()
427 mf_price = int(result2[0][0])
428
429 name = input("Again enter your username: ")
430 def check_availability():
431 cursor.execute(f"SELECT Quantity FROM holdings.{name} WHERE Symbol = '{get_name2}'")
432 global res
433 res = cursor.fetchone()
434 check_availability()
435
436 try:
437 result = int(res[0])
438 units_to_buy = result
439 print(f"Available units of {get_name2}: ", result)
440 process_transaction2(fund_name, transaction_type, units_to_buy, mf_price)
441 except:
442 print("\nInsufficient units to sell!!")
443 get_choice = input("Back or exit (b/ext): ")
444 if get_choice == 'b':
445 trade_mf()
446 elif get_choice == 'ext':
447 welcome()
448
449 if confirm == 'n':
450 welcome()
451
452 else:
453 print("Incorrect Symbol! Try Again!")
454 welcome()
455
456
457 def user_acc():
458 print('''
459 _ _ ______ ______ ______
460 | | | | / | | | | | | \
461 | | | | '------. | |---- | |__| |
462 \_|__|_| ____|_/ |_|____ |_| \_\ ACCOUNT
463 ''')
464 print("[1] Account Information \n[2] Portfolio")
465 print("[3] KYC Verification \n[4] Bank Details")
466 print("[5] Exit")
467
468 choice = int(input("Select an option: "))
469 print()
470 if choice == 1:
471 print('''
472 ____ ____ ____ ____ __ __ __ _ _____
473 / () \ / (__`/ (__`/ () \| | || \| ||_ _|
474 /__/\__\\____)\____)\____/ \___/ |_|\__| |_| STATUS
475 ''')
476
477 print("\nAccount Status: ACTIVE")
478 print("Account Type: DEMAT")
479 print("Frozen Status: NOT FROZEN")
480 print("BDSA Flag: NO")
481 print("Nomination Status: Registered")
482 print("BO Status: INDIVIDUAL")
483 print("REEGS Flag: Individual-Residence")
484 print("Income Tax Return (ITR): ACTIVE")
485 print("Annual Maintenance (AMC): ACTIVE")
486 ext = input("\nTo exit type(e): ")
487 if ext == 'e':
488 user_acc()
489
490 if choice == 2:
491 def portfolio():
492 print('''
493 | | _ _ |) |-[` |.
494 |_|_\(/_|` | ()|`|_| ()||()
495
496 ''')
497 print("[1] Create New Portfolio")
498 print("[2] View Portfolios\n[3] Exit")
499
500 user_ch = int(input("Enter you choice: "))
501 if user_ch == 1:
502 new_portfolio()
503 portfolio()
504 if user_ch == 2:
505 view_portfolio()
506 ext = input("\nTo exit type(e): ")
507 if ext == 'e':
508 portfolio()
509 elif user_ch == 3:
510 user_acc()
511 portfolio()
512
513 if choice == 3:
514 def kyc_comp():
515 while True:
516 print('''
517
518 __ ,__ _ ,___ _, _
519 ( /,/( / / / / ( | / o /)o _/_o
520 /< (__/ / | /_ _ , //, _, __, / , __ __
521 / \_ _/_(___/ |/(/_/ (_(_//_(_(__(_/(_(__(_(_)/ /_
522 // /)
523 (/ (/
524
525 ''')
526 print("[1] Verify KYC")
527 print("[2] Update KYC")
528 print("[3] Submit KYC Information")
529 print("[4] Exit")
530
531 choice = int(input("Select an option: "))
532 print()
533
534 if choice == 1:
535 aadhar = input("Enter your Aadhar Card number: ")
536 pan = input("Enter your PAN: ")
537 verify_kyc(aadhar, pan)
538
539 elif choice == 2:
540 pan = input("Enter your PAN: ")
541 name = input("Enter your Name: ")
542 dob = input("Enter your Date of Birth (YYYY-MM-DD): ")
543 gender = input("Enter your Gender: ")
544 aadhar = input("Enter your Aadhar Card number: ")
545 passport = input("Enter your Passport number: ")
546 mob = input("Enter your Mobile number: ")
547 tin = input("Enter your TIN: ")
548 insert_kyc_data(pan, name, dob, gender, aadhar, passport, mob, tin)
549
550 elif choice == 3:
551 pan = input("Enter your PAN: ")
552 name = input("Enter your Name: ")
553 dob = input("Enter your Date of Birth (YYYY-MM-DD): ")
554 gender = input("Enter your Gender: ")
555 aadhar = input("Enter your Aadhar Card number: ")
556 passport = input("Enter your Passport number: ")
557 mob = input("Enter your Mobile number: ")
558 tin = input("Enter your TIN: ")
559 bank_name = input("Enter your bank name: ")
560 ifsc_no = input("Enter IFSC CODE: ")
561 acc_no = input("Enter A/c No: ")
562 insert_kyc_data(pan, name, dob, gender, aadhar, passport, mob, tin, bank_name,
ifsc_no, acc_no)
563
564 elif choice == 4:
565 print("Thank you for KYC Verification!")
566 user_acc()
567
568 else:
569 print("Invalid choice. Please select a valid option (1-3).")
570 print()
571 kyc_comp()
572
573 if choice == 4:
574 user_id = input("Enter Mob-no: ")
575 bank_details(user_id)
576 ask = input("\nWant to Deposit balance(y/n): ")
577 if ask == 'y':
578 uname = input("Enter your usernname: ")
579 Amt = int(input("Enter your amount: "))
580 method = input("Select UPI or Debit/Credit Cards: ")
581 if method == 'UPI':
582 upi_id = input("Enter UPI-Id: ")
583 Id_proof = input("Id-Proof (PAN/Aadhar No.): ")
584
585 elif method == 'Debit Card':
586 card_no = input("Enter your Debit/Credit Card No: ")
587 expiry = input("Enter Expiry Date: ")
588 cvv = input("Enter your CVV: ")
589 name = input("Enter full name: ")
590 Id_proof = input("Id-Proof (PAN/Aadhar No.): ")
591
592 query = "UPDATE s_brokers.portfolio SET Depo_Balance= Depo_Balance + %s WHERE UName=%s;"
593 values = (Amt, uname)
594 curs.execute(query, values)
595 db_conn1.commit()
596 print("\nBalance Updated Successfully!!")
597 ext = input("\nTo exit type(e): ")
598 if ext == 'e':
599 user_acc()
600
601 elif ask == 'n':
602 user_acc()
603
604 if choice == 5:
605 welcome()
606
607 def personal_loans():
608 print('''
609 __
610 /__)_ _ _ _ / / _ _
611 / (-/_)()/)(/( (__()(//)_)
612 ''')
613 print("S-Brokers provides instant online personal loans \nwith minimum and paperless documentation and
zero credit history to get a loan.")
614 print("It offers lower interest rates at affordable EMIs with flexible repayment tenure.")
615 print("\n• Interest Rates: 6.8-10.6% P.A.\n• Get Up-to: Rs.5,000 to 5 Lacs\n• For 3 to 60 Months In
Just 1-2 Days")
616
617 loan_amount = int(input("\nEnter the loan amount you need (Rs.): "))
618 loan_duration = int(input("Enter the loan duration(in months): "))
619 id_proof = input("Enter your ID-Proff(Aadhar no.): ")
620 # Validate loan duration
621 if loan_duration < 3 or loan_duration > 60:
622 print("Loan duration must be between 3 and 60 months.")
623 return
624
625 # Process loan application (not implemented in this example)
626 print("\nYour loan application has been received and is being processed.")
627 print("You will receive further instructions via E-mail or Phone.")
628
629 # Display required documents
630 print("\nPlease prepare the following documents:")
631 print("- Proof of address (e.g., Utility bill)")
632 print("- Proof of income (e.g., Salary slips, ITRs)")
633 print("- Bank statements (last 6 months)")
634
635 ext = input("\nTo exit type(e): ")
636 if ext == 'e':
637 welcome()
638
639
640
641 def inv_analysis():
642 print('''
643 __ _, _
644 ( / _/_ _/_ / | // o
645 / _ _ _ ,__ ( / _ _ _ _ _ _ / /--| _ _ __, // __ , ( , (
646 _/_/ / /_/ |/ (/_/_)_(__/ / / /_(/_/ / /_(__ _/ |_/ / /_(_/(_(/_/ (_/_/_)_(_/_)_
647 /
648 '
649 ''')
650 print("[1] Analyse Stocks\n[2] Analyse Crypto")
651 print("[3] Analyze Mutual funds\n[4] Exit")
652 ch = int(input("Enter your choice: "))
653 if ch == 1:
654 stock_symbol = input("Enter Stock Symbol(E.g. WIPRO.NS): ") # Example stock symbol (Apple Inc.)
655 fundamental_data, price_data = get_stock_data(stock_symbol)
656 if fundamental_data and price_data:
657 print("\nFundamental Data:")
658 for key, value in fundamental_data.items():
659 print(f"{key}: {value}")
660
661 print("\nPrice Data:")
662 for key, value in price_data.items():
663 print(f"{key}: {value}")
664 cho = input("back & exit(b/ext): ")
665 if cho == 'b':
666 inv_analysis()
667 elif cho == 'ext':
668 welcome()
669
670
671 else:
672 print("Failed to retrieve data.")
673 inv_analysis()
674
675 elif ch == 2:
676 crypto_symbol = input("Enter Crypto symbol(e.g: BTC-USD): ") # Example cryptocurrency symbol
(Bitcoin)
677 fundamental_data, price_data = get_crypto_data1(crypto_symbol)
678 if fundamental_data and price_data:
679 print("\n\nFundamental Data:")
680 for key, value in fundamental_data.items():
681 print(f"{key}: {value}")
682
683 print("\nPrice Data:")
684 for key, value in price_data.items():
685 print(f"{key}: {value}")
686 cho = input("back & exit(b/ext): ")
687 if cho == 'b':
688 inv_analysis()
689 elif cho == 'ext':
690 welcome()
691 else:
692 print("Failed to retrieve data.")
693 inv_analysis()
694
695 elif ch == 3:
696 symbol = input("Enter MF Symbol(e.g. 0P0000NRF4.BO): ")
697 performance_data, overview_data = get_mutual_fund_data(symbol)
698 if performance_data and overview_data:
699 print("\nPerformance & Risk:")
700 for key, value in performance_data.items():
701 print(f"{key}: {value}")
702
703 print("\nFund Overview:")
704 for key, value in overview_data.items():
705 print(f"{key}: {value}")
706 cho = input("back & exit(b/ext): ")
707 if cho == 'b':
708 inv_analysis()
709 elif cho == 'ext':
710 welcome()
711 else:
712 print("Failed to retrieve data.")
713 inv_analysis()
714
715 if ch == 4:
716 welcome()
717
718
719 for i in tqdm(range(0, 10), ncols = 75, desc ="Loading... "):
720 sleep(.4)
721 welcome()

You might also like