Archive

Posts Tagged ‘Lesson’

Python Project: Drawing Cloud Number

March 25, 2021 Leave a comment


Learning : Python, Drawing
Subject: Using Python to Draw Cloud Number

In this project we will write a code to draw a cloud of number, we will do this as layers each layer with different font size and different color density.

To do this we will write a function def draw_cloud(tcolor,max_r,sr,lr) : to fill the screen with max_r random numbers from sr to lr (small range, large ramge) using tcolor color. We will recall the function several time each time we will change the tcolor,max_r,sr,lr. Here is the code ..

The Code
ali radwani python project learning sql codeing

Example with Gray theme

Another Example with Pink theme.


Follow me on Twitter..


By: Ali Radwani

Python: My Orders Tracker P-4

March 17, 2021 Leave a comment


Learning : Pythn, sqlite, Database, SQL
Subject: Create a system to track the orders

In this last part we will write the code to Edit an Order, in editing an order function first we will show all orders and will ask the user to select the one to be EDIT, then we will display that order detail on the screen and ask the user to confirm the action by entering ‘Y’ [our code will handel both y and Y]. We will ask the user about each attribute in the Order details if it need to be change or [Just press Enter to Keep the Current Data], also if the user enter ‘e’ or ‘E’ we will exit from the Editing mode.

Here is the code ..

# Function to Edit an Order

def edit_order():
    os.system('clear')
    print("\n==========[ Edit Orders ]==========")
    
    show_order('yes')
    
    edit_order = input('   Select the Order ID to be Edited. [E to Exit] > ')
    
    if edit_order in ['e','E'] : 
        return
    elif not edit_order.isnumeric() :
        input('\n   You need to enter an Order''s ID [Numeric]. .. Press any Key .. ')
        return 
               
    try:        
        
        c.execute ("select * from orders where o_id ={}".format(edit_order))  
        order_list = c.fetchone() 
        
        if order_list == [] :
            input('\n   ID {} Not Exsist. .. Press any key to continue.  '.format(edit_order))
            return
        
        os.system('clear')
        print("\n==========[ Edit Orders ]==========\n")
        print('\n   Details of the Order you select:\n ')
    
        print(" "*15,"ID: ",order_list[0])  
        print(" "*13,"Date: ",order_list[1])
        print(" "*5,"Order Number: ",order_list[2])
        print(" "*12,"Price: ",order_list[4])
        print(" "*9,"Quantity: ",order_list[5])
        print(" "*3,"Shipment Price: ",order_list[6])
        print(" "*7,"Total Cost:  {:.2f}".format((order_list[4]*order_list[5]) + order_list[6]))
        print(" "*6,"Description: ",order_list[3])
        print(" "*12,"Image:",order_list[8])
        print(" "*13,"Link:",order_list[7])
    
        user_confirm = input("\n\n   You Select to EDIT the above Order, Enter Y to confirm, E to Exit. > ") 
        if user_confirm in ['e','E'] : 
            input('\n   You entered ''E'' to Exit. Nothing  will be change. Press any key. ')
            return 
        
        if user_confirm in ['y','Y'] :
            #To Edit the order.. 
            
            print("#"*57)
            print("##"," "*51,"##")
            print("##   NOTE: Enter E any time to EXIT/Quit."," "*12,"##")
            print("##     OR  JUST Press Enter to keep the Current data."," ##")
            print("##"," "*51,"##")
            print("#"*57,)
            
            while True :
                 
                new_date = input (f'\n   The current date is: {order_list[1]}, Enter the New date as[dd-mm-yyyy] > ')
                
                if e_to_exit(new_date) =='e' : return
                if new_date =="" : break   # Break the while loop if the user want to keep the current Date.
                
                if date_validation (new_date) == 'valid' :
                    break           
                else :
                    print(date_validation (new_date))    
        
                      
            new_onum = input (f'\n   The current Order Number is: {order_list[2]}, Enter the New Order Number. [E to Exit]. > ')
            if e_to_exit(new_onum) =='e' : return           
            
            new_qunt = input (f'\n   The current Quantity is: {order_list[5]}, Enter the New Quantity. [E to Exit]. > ')
            if e_to_exit(new_qunt) =='e' : return
            
            new_price = input (f'\n   The current Price is: {order_list[4]}, Enter the New Price. [E to Exit]. > ')
            if e_to_exit(new_price) =='e' : return
            
            new_ship_price = input (f'\n   The current shipment Price is: {order_list[6]}, Enter the New Quantity. [E to Exit]. > ')
            if e_to_exit(new_ship_price) =='e' : return
            
            new_link = input (f'\n   The current link is: {order_list[7]}, Enter the New Link. [E to Exit]. > ')
            if e_to_exit(new_link) =='e' : return
            
            new_image = input (f'\n   The current Image is: {order_list[8]}, Enter the New Image (path). [E to Exit]. > ')
            if e_to_exit(new_image) =='e' : return
                        
            
            new_desc = input (f'\n   The current Description is:\n     {order_list[3]}.\n\n      Enter the New Description. [E to Exit]. > ')
            if e_to_exit(new_image) =='e' : return
            
            
            # Updating the record in the DataBase. 
            if new_date > '' and new_date != "e" :
                c.execute("update orders set order_date = '{}' where o_id = {}".format(new_date,int(order_list[0]))) 
                db_conn.commit()
            
            if new_onum > '' and new_onum != "e" :
                c.execute("update orders set order_num = '{}' where o_id = {}".format(new_onum,int(order_list[0]))) 
                db_conn.commit() 
        
            if new_qunt > '' and new_qunt != "e" :
                c.execute("update orders set order_quantity = '{}' where o_id = {}".format(new_qunt,int(order_list[0]))) 
                db_conn.commit() 
                        
            if new_price > '' and new_price != "e" :
                c.execute("update orders set order_price = '{}' where o_id = {}".format(new_price,int(order_list[0]))) 
                db_conn.commit() 
            
            if new_ship_price > '' and new_ship_price != "e" :
                c.execute("update orders set order_price = '{}' where o_id = {}".format(new_ship_price,int(order_list[0]))) 
                db_conn.commit() 
                                
            if new_link > '' and new_link != "e" :
                c.execute("update orders set order_link = '{}' where o_id = {}".format(new_link,int(order_list[0]))) 
                db_conn.commit() 
                           
            if new_image > '' and new_image != "e" :
                c.execute("update orders set order_img = '{}' where o_id = {}".format(new_image,int(order_list[0]))) 
                db_conn.commit() 
             
            if new_desc > '' and new_image != "e" : 
                new_desc = " ".join([word.capitalize() for word in new_desc.split(" ")]) 
    
                c.execute("update orders set order_desc = '{}' where o_id = {}".format(new_desc,int(order_list[0]))) 
                db_conn.commit() 
            
            input('\n   One record has been EDITED and Saved... \n      ... Press any key to Continue ...')   
    
        else:        
            input('\n      Wrong input ... Press any key to continue ..')    
    
    except:
        pass

[All the System Codes available in Download Page.]



Finish: Now we have an application that will store and retrieve our simple order data.
Enhancement:
We can do some enhancement in [link and image] data part to show and display them in better way.


Part 1 Part 2 Part 3 Part 4



To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Python: My Orders Tracker P-3

March 10, 2021 1 comment


Learning : Pythn, sqlite, Database, SQL
Subject: Create a system to track the orders

In this part we will write the code to Delete an Order that we have from our system, also we will add some validations on the user input, like if the user enter something not from the menu, or to do so, first we will re-call the show_orders() function that we have and passing the ‘yes’ parameter which means we are calling the function from inside another function [we will not print the function header, and will not clear the screen]. Then we will ask the user to select/Enter the ID of the order to be Deleted, after that we will print tha order details again on the screen and ask the user to confirm Deleting command by entering ‘Y’ … thats it.. let’s write the code..

# Delete Order

def del_order():
os.system('clear')
print("\n==========[ Delete Orders ]==========\n")

show_order('yes')

del_order = input(' Select the Order ID to be Deleted. [E to Exit] > ')

if not del_order.isnumeric() :
input('\n You need to enter an Orders ID [Numeric]. .. Press any Key .. ')
return

elif del_order in ['e','E'] :
return

try:
c.execute ("select * from orders where o_id ={}".format(del_order))
order_list = c.fetchone()

if order_list == [] :
input('\n ID {} not exsist.'.format(del_order))
return

os.system('clear')
print("\n==========[ Delete Orders ]==========\n")
print('\n Details of the Order you select:\n ')

print(" ID: ",order_list[0])
print(" Date: ",order_list[1])
print(" Order Number: ",order_list[2])
print(" Price: ",order_list[4])
print(" Quantity: ",order_list[5])
print(" Shipment Price: ",order_list[6])
print(" Total Cost: {:.2f}".format((order_list[4]*order_list[5]) + order_list[6]))
print("\n Description:",order_list[3])
print(" Image:",order_list[8])
print(" Link:",order_list[7])

user_confirm = input("\n\n You Select to DELETE the above Order, Enter Y to confirm, E to Exit. > ")
if user_confirm in ['y','Y'] :
#To Delete the order..
c.execute ("delete from orders where o_id ={}".format(int(del_order)))
db_conn.commit()

input('\n One record has been DELETED ... \n ... Press any key to Continue ...')

elif user_confirm in ['n','N']:
input("\n You select not to DELETE any thing. Press any key to Continue .. ")

elif user_confirm in ['e','E']:
input("\n You select stop the process and EXIT. ... Press any key to Continue .. ")
return

else:
input('\n Wrong input ... Press any key to continue ..')

except:
pass
The user select #3 from the menu to Delete an Order
ali radwani python project learning sql codeing
The screen display the list of orders we have in the system, and the user select Order ID Number 3 to delete it.
The screen display the details of the order ID 3 and ask the user to confirm the deleting by entering ‘Y’

In Next Post: In the coming post P4 , we will write the codes to Edit an order information.

Part 1 Part 2 Part 3 Part 4

To Download my Python code (.py) files Click-Here


Follow me on Twitter..


By: Ali Radwani

Python: Data Visualization Part-1

January 6, 2021 1 comment


Learning : python, pygal, Data Visualization, Bar Chart
Subject: Data visualization using pygal library

pygal is a Data Visualization library in python to help us showing our Data as a graph. In coming several posts we will discover and learn how to use the pygal library in simple and easy configuration and style.

First we need to install pygal packeg, to do so write this:
pip install pygal

Now we need some Data to show, in this leson I am using aGalaxy Tab S4, so all the codes will be tested and applyed on trinket.io website [trinket.io alow us to use pygal package online so we don’t need to install it on our divice]

Type of Chart:
pygal has several types of charts that we can use, here we will list them all then in coming posts will use each one with simple data. So what we have:
Line, Bar, Histogram, XY,
Pie, Radar, Box, Dot,
Funnel, SolidGauge, Gauge, Pyramid,
Treemap, Maps

Some of those charts has a sub-types such as in Bar char we have: Basic, Stacked and Horizontal. Also for each chart we can add a title and labels and we can use some styles.

So let’s start ..
First we will go for the Bar chart, and we have three sub-types as Basic, Stacked and Horizontal.

First chart: Bar chart:
In this part we will demonstrate the Bar Chart, it has three sub-types as Basic, Stacked and Horizontal.

We assume that our data is the Males and Female ages on first marage, the data will be as dictionary (later we will see how to customize each bar)

 # Basic Bar Chart using pygal

import pygal 
bar_chart = pygal.Bar() # To create a bar graph object
bar_chart.add('Females', [22,25,18,35,33,18]) 
bar_chart.add('Males', [30,20,23,31,39,44]) 

bar_chart.title = "Males and Females First Marage Age"
bar_chart.x_labels=(range(1,6))
 
bar_chart.render() 


Sample code for Basic bar chart


Another sub-type in Bar chart is Horizontal-Bar, it is semelar to the Basic but as if fliped 90 degree. Here is the code ..

 # Horizontal Bar Chart using pygal

import pygal

# HorizontalBar()
HBar = pygal.HorizontalBar()
HBar.add('Females', [22,25,18,35,33,18]) 
HBar.add('Males', [30,20,23,31,39,44]) 

HBar.title = "Males and Females First Marage Age"

HBar.x_labels=(range(1,6))

HBar.render() 


Sample code for Horizontal Bar chart


Last sub-type in Bar chart is Stacked Bar were all data of each element will be in one bar. Here is the code and example..

 # Stacked Bar Chart using pygal

import pygal 
# StackedBar() 
stackedbar = pygal.StackedBar()
stackedbar.add('Females', [22,25,18,35,33,18]) 
stackedbar.add('Males', [30,20,23,31,39,44]) 
stackedbar.x_labels=(range(1,0))
stackedbar.title = "Males and Females First Marage Age"

stackedbar.render() 




If we say we have another data-set as “age in First-Divorces” and we want to add this set to the Stacked Bar chart, then we first will create the data-set as:
stackedbar.add(‘Divorses’, [35,22,45,33,40,38])
and we will arrange the code line to be at top,middle or bottom of the bar. Here is the code..

Sample code for stacke Bar chart with Divorce data




Next we will talk about Line chart.


:: Data Visualization using pygal ::

Part-1
Bar-Chart
Part-2 Part-3 Part-4




Follow me on Twitter..




By: Ali Radwani




Python: Password Generator

January 1, 2021 Leave a comment


Learning : Python Project
Subject: Password Generator

In this function we will use the string library to select a random X numbers of letters as a Password length and print it on the screen.

First: We create a list of letters type l_type that hold the following: lowercase, uppercase, digits, punctuation and we will use the (random.choice) to select from the list.
Then we will call the ‘password Generator’ pass_generator function torandomly select a letter based on the selected type, we will do so for a X time (X is the length of the password). In this project we will print the password on the screen, in real-life we can send the password via email or SMS. Here is the Code ..

# Password Generator Function

"""

Project: Python Password Generator
By: Ali Radwani
Date: Des-2020


    This function will use the string library to select a random X numbers of letters as a Password and print it on the screen. 

    We create a list of letter type l_type that hold the following lowercase, uppercase, digits, punctuation and we will
    use the (random.choice) to select from the list, then we will call the 'password Generator' pass_generator function to
    randomly select a letter, we will do so for a X time (X is the length of the password). In this project we will print 
    the password on the screen, in real-life we can send the password via email or SMS. 

"""

import random, string 

l_type = ["lowercase","uppercase","digits","punctuation"]

the_password =[]

def pass_generator(lt) :
    if lt =="lowercase":
        the_password.append(random.choice(string.ascii_lowercase))
        
    elif lt =="uppercase" :
        the_password.append(random.choice(string.ascii_uppercase))
        
    elif lt =="digits" :
        the_password.append(random.choice(string.digits))
        
    elif lt =="punctuation":
        the_password.append(random.choice(string.punctuation))
            
    return the_password
   
    
pass_length = int(input("\n   Enter the password Length: > "))


while len(the_password) < pass_length:
    pass_generator(random.choice(l_type))
    

print("\n   The New Generated Password is: ","".join(the_password))





To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Library System with Excel -P4

November 24, 2020 Leave a comment


Learning :Excel formulas and VBA Cods
Subject: To Develop a Library System with Excel

In last post we wrote all the codes needed to Manage the Authors.

In this part we will do all the coding needed to enter New Books and Edit or Delete anyone we select, in Classifications and Authors we were dealing with one attribute, but here with Books Manage form we have several pieces of information to collect from the user such as [Book Title, Book Author, Book Classification, Publish date, Notes, Book Language ]. So first let’s design the form..

1. Open the Books sheet
2. Change the color of the range(B6:E24)
3. In Cell B6 write “Select a Book to Edit or Delete”, Color and format it as you want.

4. In Cell H6 write “Books Form”, Color and format it as you want.

5. Color and format the Range (B6:L26) as you want.
6. Create three rectangular shapes as New, Delete, and Save buttons.
7. Create another three small rectangular shapes write “+” inside them.
5. We need to create a ListBox name it “books_ListBox 4”.
6. Arrange everything as in the image.


Now move to the “setting” sheet and write the following: B4:Books, B5:current_book, C5:1, B6:mode, C6: edit.

Then in the “Data” Sheet starting from A1 write the following:
A1:Books Data, B1:BookTitle, C1:book_author, D1:class, E1:Published, F1:Note, G1:lang
A2:ID, B2:Title, C2:Author, D2:Class, E2:Published, F2:Note, G2:language

CODING:

To copy the list of the Books we have into the books_ListBox 4 we create:
1.1 From the Menu go to Formulas and click on Name Manager.
1.2 From the pop-up screen click on New, then write books_list in Name, and =OFFSET(Data!$B$3,,,COUNTA(Data!$B:$B)) in Refers to.

2.1. Select books_ListBox 4 on the Books sheet.
2.2. Right-click the mouse, and select FormatControl.
2.3. Goto Control Tab, and in Input range write: books_list, and in Cell link write Setting!$C$5 then press OK.

Now the listBox will contain the Books we have in the Books table in Data Sheet. (If we have any Data there)
3. Data Validation: We need to create Data Validation-list in the cells K12: for Authors list, K14: for Classifications list and K18: for Language list.
1. Select K12, from Data-menu click on Data-validation, select List then in the source type this: =OFFSET(Data!$K$3,,,COUNTA(Data!$K:$K))
2. Select K14, from Data-menu click on Data-validation, select List then in the source type this: =OFFSET(Data!$P$3,,,COUNTA(Data!$P:$P))
3. Select K18, from Data-menu click on Data-validation, select List then in the source type this: =OFFSET(Data!$M$3,,,COUNTA(Data!$M:$M))

book_new_Click() In this function we will Clear all cells [k8, k10,k12,k14,k16,k18, K20] also the note_TextBox1 and will change the cell C6 in Setting Sheet to “new”. Here is the code..

Sub book_new_Click()

‘ Clear all cells.
Sheets(“Books”).Range(“K8”).Value = “” ‘ID/number
Sheets(“Books”).Range(“K10”).Value = “” ‘Title
Sheets(“Books”).Range(“K12”).Value = “” ‘Author name
Sheets(“Books”).Range(“K14”).Value = “” ‘classification
Sheets(“Books”).Range(“K16”).Value = “” ‘published date
Sheets(“Books”).Range(“K18”).Value = “” ‘language
Sheets(“Books”).Range(“K20”).Value = “” ‘note
Sheets(“Books”).note_TextBox1 = “”

‘ change book mode to “new”
Sheets(“setting”).Range(“c6”).Value = “new”

Sheets(“Books”).Range(“K8”).Select

End Sub

now in the Books sheet select the button “New” we create and assign the “book_new_Click” macro to it.

book_save_Click() The Save function will have tow parts, if the user click on New then we will have:

Sheets(“setting”).Range(“C6”).Value = “new” in this case we will copy all the Book Data from Range(“K8”),Range(“K10”),Range(“K12”),Range(“K14”),Range(“K16”),Range(“K18”) and the value of the note_TextBox1 to the Data sheet under Boos Table, then will empty all the range in the book form, also will pop-up a MsgBox ” One New Book has been Added.”.

if Sheets(“setting”).Range(“C6”).Value = “edit” in this case we will get the current selected book location by selected_book = Sheets(“setting”).Range(“C5”).Value + 2 then re-copy the book data from the form to the Book Table in the Data Sheet and pop-up MsgBox ” One Book Data has been Updated.”.

In Books form we have also three + buttons next to Author, Classification and Language cells, if the user did not find say the Author in the list then he/she can add new one by clicking on the +

Edit Book Data: The user can select any Book from the Book List on the left-hand list then it’s Data will show-up in the form, the user then can change any of the Book-Data and press on Save.

book_delete_Click() The user will select the Book to de deleted then click on “Delete” button, a massage will pop-up to make sure that Book will be DELETED, if the user confirm the cation (press OK) we will run this line of code:

‘To get the book row number.
selected_book = Sheets(“setting”).Range(“C5”).Value + 2
‘To delete the book row
Sheets(“data”).Range(“A” & selected_book & “:G” & selected_book).Delete Shift:=xlUp

Pressing the (+) button: We have three (+) buttons in this form to add New Authors, Classifications, and Languages if not exist in the list; for example, if the user couldn’t find the Author of the Book (he/she want to enter to the system) pressing the (+) will pop-up a dialog box to Enter New Author and the same for classification and Language. Here is the code..

Sub book_form_new_author()

Sheets(“Books”).Range(“K12”).Value = “”
new_author_name = InputBox(“Enter a New Author Name and Click OK:”, “:: New Author :: “)

‘if we add new author then save it.
If new_author_name > “” Then
‘ Get next empty row
next_row = Sheets(“Data”).Range(“K” & Rows.Count).End(xlUp).Offset(1).Row
Sheets(“Data”).Range(“K” & next_row) = new_author_name
Sheets(“Books”).Range(“K12”).Value = new_author_name ‘Author name
Sheets(“setting”).Range(“F6”).Value = “still”

‘ To Sort the Authors list
next_row = Sheets(“Data”).Range(“K” & Rows.Count).End(xlUp).Offset(1).Row
Sheets(“Data”).Range(“K3:K” & next_row – 1).SortSpecial SortMethod:=xlPinYin

End If
Sheets(“Books”).Range(“K12”).Select

End Sub


End of Part-4

Recap this part:
1. We Create the Books header Tabke.
2. We Create a form to collect the Books from the user.
3. We Create the Books ListBox.
4. We wrote the VBA code to Save, Delete, and Create New Book also to retrieve the Books information into Books ListBox.
5. We let the user to Enter New Author, classification, Language into the system through a dialog box.


:: Library System with Excel ::

Part 1 Part 2 Part 3 Part 4 Part 5



To Download EXCEL (.xlsm) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Python: Shares Speculation System – Part 7

August 18, 2020 Leave a comment


Learning : Python, DataBase, SQL, SQlite3
Subject: Plan, Design and Build a Shares Speculation System

Project Card:
Project Name: Shares Speculation System
By: Ali
Date: 2.7.2020
Version: V01-2.7.2020

In this Part we will write the Function to Delete a Transaction from the System, and will write the last part of show_all_Transaction function.
First we will write a Function to Delete a Transaction, we have two types of Transactions “Buying” and “Selling” so the user will select the Transaction Type to delete.
1. Buying Transaction: If the user select to Delete a Buying Transaction, we will call show_all function to display all the Buying Transactions and the ask the user to Enter the ID of the record to be Deleted. Here is the Code ..

ali radwani python project learning sql codeing

Then we will print-out the Selected Transaction Details and ask the user to Confirm the Deleting action by Entering ‘Y’.
After Confirming we need to perform or to Aplay three parts of code:
1. Deleting the Buying Transaction from Buying Table (buy_t_table).
2. Deleting the Buying Record from the Budget Table.
3. Updating the Share Basket Table (s_basket).
For the “Update the Share Basket Table (s_basket).” we need to Subtract the amount of the shares from the Share Basket.
Here is the code for all three action..

The Same actions will be taken if the user select to Delete a Selling
transaction. So if the user select “2. Selling Transaction:” we will call show_all function to display all the Selling Transactions and the ask the user to Enter the ID of the record to be Deleted and will display the Transaction Details. Here is the Code ..

And will waite for the user to Confirm the Deleting action, then again three blocks of code will Delete and update records in our system, here are the code ..

Now we finish the def del_trans(): Function to Delete a Buying or Selling Transaction and will work on the last part of def show_all_trans (inside = ‘No’, show=’3′): to Show/Display both Buying and Selling Transactions in one table format. To do so First we will RUN two SQL commands to ‘fetchall’ Buying and Selling Transaction… Here is the code ..


# Get All Sell Transactions Order by id desc
c.execute (" select * from sell_t_table where st_id > 0 order by st_id desc")
show_s_trans = c.fetchall()

# Get All buy Transactions Order by id desc
c.execute (" select * from buy_t_table where bt_id > 0 order by bt_id desc")
show_b_trans = c.fetchall()

Then we print-out the Table header as the following line:
print(“\n”,” “*11,”{:<9}{:<13}{:<30}{:<16}{:<11}{:<15}{}”.format(‘ID’,’Date’,’Share Name’,’SAmount’,’Price’,’Cost’,’Income’))
Then using a For loop we will print-out the transactions in same format of the table header .. Here is the full Code

Last thing we will print the Totals of Investment, Incomes and the Net Profit.


print(" "*73,'Total Investment is: {:,}'.format(total_inv))
print(" "*76,'Total Incomes is: {:,}'.format(total_inc))
print(" "*75,"-"*30,"\n"," "*75,' Net Profit is: {:,} '.format(total_inc - total_inv))

We Done with this Part ..
Coming Up: In the Next post we will write the Function to Edit a Transaction.

[NOTES]
1. Part-1 has no code file.
2. We are applying some basic Validations on some part of the code, and assuming that the user will not enter a messy data.
3. This Application Purpose for Saving Transactions and NOT for Desetion Making and Dose’t Have any type of AI or ML Model to Predict the Prices and/or Giving Sugestions on Buying or Selling Shares.
:: Shares Speculation System ::

Part 1 Part 2 Part 3 Part 4 Part 5
Part 6 Part 7 Part 8

All the code are available ..

To Download my Python code (.py) files Click-Here


Follow me on Twitter..

By: Ali Radwani

Python: Shares Speculation System – Part 4

July 19, 2020 3 comments


Learning : Python, DataBase, SQL, SQlite3
Subject: Plan, Design and Build a Shares Speculation System

Project Card:
Project Name: Shares Speculation System
By: Ali
Date: 2.7.2020
Version: V01-2.7.2020

Last time we worked on Budgets Managment for our system, now before we start Buying and Selling shares we need to create list of shares name so we can select from it, we have a table called shares_name this Table have the following fields :
s_id: as a PRIMARY KEY.
full_name: To hold the full name of the share.
abb_name: To hold the Abbreviation of a share name.
The Share Managment section will have four main Functions to Add, Edit, Delete and Show shares. .. Let’s start with it’s Main Menu ..



First Function we will work on will be to Add New Share to the system, we will call it def add_share(): , we will ask the user to input the Share Full Name and its Abbreviation. With Abbreviation we will apply the .upper() function to convert the user input to Upper-case, and for the Full Name we will will apply this code [“ “.join([word.capitalize() for word in user-input] to upper case each first character of the Name. The we will check if the Share Name exist in the DataBase If not we will add it.

 # Add New Share
def add_share() :
        
    os.system('clear')
    print('\n   ====== Add New Share ======\n\n')
    while True :
            
        abb_name = input("   Enter the Abbreviation Name of the Share.. > ").upper() 
        full_name = " ".join([word.capitalize() for word in input('     Enter the Full Name of the Share.. > ').split(" ")])

        c.execute ("select * from shares_name where full_name ='{}' or abb_name = '{}'".format(full_name, abb_name)) 
        share_exist = c.fetchone ()
        if share_exist[0] > 0 :
            print('\n   It seams that the Share Exist in the Database, Name or Abbreviation CAN NOT be Duplicated.')
            print('   Try another Name. ')
        else :      
            c.execute ("INSERT INTO shares_name (full_name , abb_name)  VALUES(:full_name , :abb_name)",{"full_name":full_name, "abb_name":abb_name}) 
            db_conn.commit()
            
        if input ('\n   Do you want to Enter another Share Name?.  [Y,N]. >  ')  not in ['Y','y']: 
            input ('\n    .... Press any key to  Exit.  ')
            return



After adding shares we want to see them and to make sure if every things are fine, so we will write the show_share function, and it will take one argument as inside with default value = ‘Yes’, if we call the function from inside another function the value will be Yes, otherwise it will be ‘No’. Here is the code ..


Next is Editing Share Name, in this function we will call the show_share (‘Yes’) so the user will select the ID of the Share Name to be Edit, then with each attribute we will ask the user ether to Enter the new Edit of the attribute or to press Enter to keep the exist variable. .. Here is a copy of the code ..


Last Function in this Artical is Delete def delete_share() : again we will call the Shoe function to display all the Shares Name on the screen and let the user to select the one to be Deleted by Entering it’s ID.

 # Delete Function.    
def delete_share() :
    os.system('clear')
    print('\n   ====== Delete a Share  ======\n\n')
    
    print('   Here is a list of Shares we have in the System .. \n')
    show_share('Yes')
    
    del_share = input('\n\n   Enter the ID for the Share Name you want to Delete. [Q to Exit] >  ') 

    if del_share in ['q', 'Q'] :
        input ('\n\n    .... Press any key to  Exit.')
        return    
    elif del_share.isnumeric() :
        if (input ('   Are you SURE you want to DELETE Share ID {} ? [Y,N] >  '.format(del_share))) in ['y','Y'] :   
            c.execute ("delete from shares_name where s_id ={}".format(int(del_share))) 
            db_conn.commit()
            input ('\n    ....One Record DELETED. Press any key to  Exit.')
            return
        else :
            input ('\n    ....Share will NOT be Deleted. Press any key to  Exit.')
            return
    else :
        input ('\n    ....Invalid Inpout. Press any key to  Exit.')
        return



Now we can create or Enter a Budget and Enter the Shares Name we have in our Stock Market and we are ready to write the functions to make the transactions.


Coming Up: In Next part we will write the Function to submit/Save Buying and Selling Transactions to our system.


[NOTES]
1. Part-1 has no code file.
2. We are applying some basic Validations on some part of the code, and assuming that the user will not enter a messy data.


:: Shares Speculation System ::

Part 1 Part 2 Part 3 Part 4
Part5



To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Python: Shares Speculation System – Part 3

July 14, 2020 4 comments


Learning : Python, DataBase, SQL, SQlite3
Subject: Plan, Design and Build a Shares Speculation System

Project Card:
Project Name: Shares Speculation System
By: Ali
Date: 2.7.2020
Version: V01-2.7.2020

In this part we will start writing some codes for our System, we will start with Budget Managment.

Budget: In the Shares Speculation System, and before the user can submit any Buying Transactions the system will check If there is enough money in the Budget Repository, so first we have to Insert a Budget. Therefore, we will start from Budget Managment.
Budget Managment will have five sub-menu as follow:
1. Add New Budget.
2. Withdraw Budget.
3. Edit a Budget.
4. Delete a Budget.
5. Show all Budget.
9. Exit.

So we will start writing the functions for each one.. let’s start with the Budget Menu, we use the while True: loop to keep the Menu until uer_choice == 9 where we return the user to the previous Menu. Here is the code:

Now, lets go through each Function..

Add New Budget: This Function will ask the user to Enter three pieces of information, The Date, The Budget Amount and if the user want to add some Notes such as cheque number or the source of the mouney/fund. For the Date, we want to make sure that the user entry is in the format we want and it is a date, so i wrote a function called date_validation () we will talk about this function later. For the Note part after the user enter the notes we will do (upper-case) for each first character in the text using this code: bud_note = ” “.join([word.capitalize() for word in bud_note.split(” “)]) Here is the full code ..

 # Add New Budget to the system.

def add_budget (): 
    os.system('clear')
    print('\n   ====== Add New Budget ======\n\n') 
    print('   Enter the Details of the Budget..\n')
      
    while True :
        bud_date = input ('   Enter the Date as [dd-mm-yyyy].  >  ') 
        msg = (date_validation (bud_date))
        if msg !='valid' :
            print(msg) 
        else:
            break
    bud_amount = input ('   Enter the Budget Amount.  >  ')
    bud_note = input ('   Enter any Notes if you want. [Hint: Cheque No.] >  ') 
    bud_note = " ".join([word.capitalize() for word in bud_note.split(" ")])    
    c.execute ("INSERT INTO budget_t (bud_date ,bud_amount, bud_note)  VALUES(:bud_date ,:bud_amount, :bud_note)",{"bud_date":bud_date ,"bud_amount":float(bud_amount), "bud_note":bud_note}) 
    db_conn.commit()
          
    input('\n\n        ... Press any Key to Exit')   


For the Budget Date we want the date to be in certain format, so we wrote a function that will take the user_input and check it’s format then return a message back, the message will be ‘Valid’ if the date format is correct, otherwise the message will give a hint if format error as:
Date Not Valid “Bad Year” or Date Not Valid “Bad Month” or Date Not Valid “Bad Day”. Here is the code for the Date Validation Function ..


Next we will write a function so we can withdraw some amount of money from the Budget, Why?? If we assume we start our Shares Speculation with 100,000$ and after several Buying and Selling we gain say 50,000$ as Profits, and we want to use this cash the [50,000$] to buy something; therefore we need to subtract / withdraw from the system. Here is the code to do this and the system will add [ WITHDRAW ] to the Note field.

 # To withdraw form the Budget


def sub_budget (): 
    os.system('clear')
    print('\n   ====== Withdraw from Budget ======\n\n')
    print('   Enter the Details of Withdraw Amount..\n')
    while True :
        bud_date = input ('   Enter the Date as [dd-mm-yyyy].  >  ') 
        msg = (date_validation (bud_date))
        if msg !='valid' :
            print(msg) 
        else:
            break
   
    bud_amount = input ('   Enter the Withdraw Amount.  >  ') 
    if int(bud_amount) > 0 : 
        bud_amount = int(bud_amount) * (-1)
    bud_note = input ('   Enter any Notes if you want. [Hint: Cheque No.] >  ')
    bud_note = "[ WITHDRAW ], " + bud_note 
    bud_note = " ".join([word.capitalize() for word in bud_note.split(" ")])
    c.execute ("INSERT INTO budget_t (bud_date ,bud_amount, bud_note)  VALUES(:bud_date ,:bud_amount, :bud_note)",{"bud_date":bud_date ,"bud_amount":bud_amount, "bud_note": bud_note}) 
    db_conn.commit()
           
    input('\n\n        ... Press any Ket to Exit')   


Now, in both Edit and Delete function we need to show the Budgets we have so the user will select the one for processing. So we will write the code to show Budgets in the system and we will present it as a Table. Here is the code ..

 # To show the Budget Table
        
def show_budget (inside='No'): 
    if inside =='No' :
        os.system('clear')
        print('\n   ====== Show Budgets ======\n\n') 
        print('   List of Budgets ..\n')
    c.execute ("select * from budget_t where bud_id >0") 
    budgets = c.fetchall() 
    print('      {:<10}{:<13}{:<16}{}'.format('ID','Date','Amount','Note'))
    print("    ","-"*70)
    try:
        for x in range(0,len(budgets)) : 
           print("      {:<8}{:<14}{:,}{:0") 
        budget_amount = c.fetchone() 
        print('\n\n    The Total Amount Budgets in the Account is : {:,} '.format(budget_amount[0]))
   
        input('\n   ... Press any key to Exit')   


So we have another two Functions [Edit, Delete] to go, the easyer one is Deleting Budget. In Delete function we will display a table with all Budgets we have in the system and the user will enter the ID of the Budget to be Deleted, we will ask the user to confirm the action then if CONFIRMED the Budget will be Delete. .. Here is the code ..


Last function in this part is to Edit a Budget that we have in the system, to do this we first will display all Budgets we have and the user will Enter the ID of the one to be Edited, we will go through it’s attributes asking the user to Edit or just Press enter to skip and keep the current value. For the Date we will call the date_validation() after user input, and for the Note we will check the Amount if it is Negative we will add “[ WITHDRAW ]” in the beginning of the Note line.

 # Edit Budget Function

def edit_budget (): 
    os.system('clear')
    print('\n   ====== Edit Budget ======\n\n') 
    show_budget (inside='Yes')
    try: 
        edit_budget = input ('\n\n    Select the Budget ID to Edit.  > ')
        c.execute ("select * from budget_t where bud_id ={}".format(int(edit_budget))) 
        e_budget = c.fetchone()
        if e_budget != None: 
            print('\n    You Select to Edit this Budget ..') 
        else:
            print('\n    ID Not Valid ... ')
             
        print('\n       ID: ',e_budget[0])
        print('     Date: ',e_budget[1])
        print('   Amount:  {:,}'.format(e_budget[2]))
        print('     Note: ',e_budget[3])
    
        print('\n\n   Edit Each Attribute OR Press Enter to Skip.. \n')
    
        while True :
            new_b_date = input('   Enter the New Date as [dd-mm-yyyy]. > ')
            if new_b_date >"" : 
                msg = (date_validation (new_b_date))
                if msg !='valid' :
                    print(msg) 
                else:
                    c.execute("update budget_t set bud_date = '{}' where bud_id = {}".format(new_b_date,int(e_budget[0]))) 
                    db_conn.commit() 
                    break    
            elif new_b_date =="" :break
                        
        new_b_amount = input('   Enter the New Amount > ')
        if new_b_amount > "" : 
            if input ('\n   You want to change the Budget Amount From {:,}  To {:,}. CONFIRM [Y,N] > '.format(float(e_budget[2]),float(new_b_amount))) in ['Y','y'] :
                c.execute("update budget_t set bud_amount = '{}' where bud_id = {}".format(float(new_b_amount),int(e_budget[0]))) 
                db_conn.commit() 
        else:
            print('   Budget Amount Not changed..\n')
            
        new_b_note = input('\n   Enter the New Note: > ')
        if new_b_note > "" :
            new_b_note = " ".join([word.capitalize() for word in new_b_note.split(" ")])
            if (e_budget[3])[0] =='[' and int(new_b_amount) < 0 :
                new_b_note = "[ WITHDRAW ], " + new_b_note     
        
            c.execute("update budget_t set bud_note = '{}' where bud_id = {}".format(new_b_note,int(e_budget[0])))          
            db_conn.commit() 
    
        input('\n   ... DONE ...  Press any key to Exit')
    except:
        input('\n       ... Error in User Input.  ... Press any key to Exit ...')


Coming Up: In Next part we will write the menu and the functions for the Shares Managment.

[NOTES]
1. Part-1 has no code file.


:: Shares Speculation System ::

Part 1 Part 2 Part 3 Part 4



To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani




Python: Shares Speculation System – Part 2

July 12, 2020 5 comments


Learning : Python, DataBase, SQL, SQlite3
Subject: Plan, Design and Build a Shares Speculation System

Project Card:
Project Name: Shares Speculation System
By: Ali
Date: 2.7.2020
Version: V01-2.7.2020

In this part we will set the database connection, create the Tables and Insert the Zero records. So first let’s do the Import and the database connection..

# Database connection

import sqlite3, os 

# Create the data-base and name it as Share_S_System. 
db_conn = sqlite3.connect ("Share_S_System.db") 

# Set the connection. 
c = db_conn.cursor() 


Now we will write the function to creates the Tables, we have five tables and this could be change during the project.

# Code to create the Tables

def create_tables_() :
    # to create tables. 
    sql_share_t =    "CREATE TABLE if not exists shares_name  (s_id INTEGER PRIMARY KEY AUTOINCREMENT, full_name text, abb_name text )" 
        
    sql_buy_t_t =   "CREATE TABLE if not exists buy_t_table (bt_id INTEGER PRIMARY KEY AUTOINCREMENT ,buy_date text, sn_id integer, buy_amount integer, buy_price float, cost float)" 
    
    sql_sell_t_t  = "CREATE TABLE if not exists sell_t_table (st_id INTEGER PRIMARY KEY AUTOINCREMENT, sell_date text, sn_id integer, sell_amount integer, sell_price float, profit float)" 
 
    sql_budget_t  = "CREATE TABLE if not exists budget_t (bud_id INTEGER PRIMARY KEY AUTOINCREMENT, bud_date text, bud_amount float, bud_note text )"  

    sql_year_roi =  "CREATE TABLE if not exists year_roi (y_id INTEGER PRIMARY KEY AUTOINCREMENT, bud_amount float, profits float, costs float, roi float, t_buy float, t_sell float )"

    c.execute(sql_share_t) 
    db_conn.commit() 
    c.execute(sql_buy_t_t) 
    db_conn.commit() 
    c.execute(sql_sell_t_t)
    db_conn.commit()        
    c.execute(sql_budget_t) 
    db_conn.commit() 
    c.execute(sql_year_roi) 
    db_conn.commit()  

    input('\n .. Shares Speculation System Tables created.. Press any key .. ') 


Next we will Insert a ‘Zero’ records in the Tables, this weill set the ID’s field in each table to ‘0’ so with next records the AUTOINCREMENT will work as it should. here is the code ..


Last function in this part will be the Main-Menu of the system. The system will have five Menus each one will have it’s own page and functions to manage it, we will write all the needed functions. Here is the Main-Menu.


Coming Up: In Next part we will write the menu and the functions for the Budget Managment.

[NOTES]
1. Part-1 has no code file.


:: Shares Speculation System ::

Part 1 Part 2 Part 3 Part 4



To Download my Python code (.py) files Click-Here




Follow me on Twitter..




By: Ali Radwani