Free cookie consent management tool by TermsFeed

How to calculate the return on your investment in Python - Step by Step Tutorial

Hello! In this tutorial, we'll learn how to use a function in Python to calculate the return on an investment based on some initial information. Let's go!


Step 1: Defining the function

def calculate_profit(initial_investment, days_invested, guaranteed_return):


This line declares the function "calculate_profit" with three parameters: initial_investment, days_of_investment and guaranteed_return.


daily_return = guaranteed_return / 100 / investment_days


This line calculates the daily return that the person will have based on the guaranteed return and the number of days of investment. The value is stored in the "retorno_diario" variable.


total_profit = initial_investment * (1 + guaranteed_return / 100)


This line calculates the total profit the person will make based on the initial investment and the guaranteed return. The value is stored in the "profit_total" variable.


daily_profit = initial_investment * daily_return


This line calculates the daily profit that the person will have based on the initial investment and the previously calculated daily return. The value is stored in the variable "lucro_diario".


weekly_profit = daily_profit * 7


This line calculates the weekly profit that the person will have based on the previously calculated daily profit. The value is stored in the "weekly_profit" variable.


monthly_profit = daily_profit * 30


This line calculates the monthly profit that the person will have based on the previously calculated daily profit. The value is stored in the variable "profit_monthly".


print("Daily profit: {:.2f}".format(daily_profit))
print("Weekly profit: {:.2f}".format(weekly_profit))
print("Monthly profit: {:.2f}".format(monthly_profit))
print("Lucro total: {:.2f}".format(lucro_total))


These four lines print the results to the screen. Each line prints a text message with the calculated profit value. The {:.2f} part formats the number to display only two decimal places. The daily, weekly, monthly, and total profit values ​​are populated in the appropriate places.

Step 2: Calling the function


Now that we have our function defined, we can call it to calculate the return on our investment. Let's use the following values ​​as an example:


initial_investment = 1000
investment_days = 30
return_guaranteed = 126


To call the function and calculate the profit, just run the following command:


calculate_profit(initial_investment, days_invested, guaranteed_return)


This will print on the screen the daily, weekly, monthly and total profit of our investment based on the values ​​we have defined.


Step 3: Interpreting the results

When running our function with the example values, we can see the following results on the screen:


Daily profit: 3.31
Weekly profit: 23.17
Monthly profit: 99.13
Total profit: 2262.60


This means that with an initial investment of R$1000, a guaranteed return of 126%, and an investment period of 30 days, we can expect a daily profit of R$3.31, a weekly profit of R$23.17, a profit monthly income of R$99.13, and a total profit of R$2262.60.


Creation of the graphical interface of the project

Let's now create a graphical interface that we will connect to this function, we will use tkinter for this.

The code below creates a GUI using tkinter.

For the icon use an image of your choice and you will also have to install the Python pillow library to manipulate the image size.

  • install the pillow using this command:pip install pillow

  • download the icons here: https://icons8.com/icons/set/profit


GUI code:


from tkinter.ttk import *
from tkinter import*
from tkinter import ttk
from PIL import Image, ImageTk

# cores ---------------------
co0 = "#2e2d2b"
co1 = "#feffff"
co2 = "#4fa882"
co3 = "#38576b"
co4 = "#403d3d"  
co5 = "#F3E99F"
co6 = "#03091f" 

# Creating window --------------------------------------------
window = Tk()
window.title ("")
window.geometry('400x350')
window.configure(background=co1)
janela.resizable(width=FALSE, height=FALSE)

style = Style(window)
style.theme_use("clam")

# Frames -----------------------------------------------------
frameCima = Frame(janela, width=450, height=50, bg=co1,  relief="flat",)
frameCima.grid(row=0, column=0)
framePergunta = Frame(janela, width=450, height=100, bg=co1,  relief="solid",)
framePergunta.grid(row=1, column=0,padx=5, sticky=NSEW)
frameResultado = Frame(janela,width=300, height=310,bg='#4E6E81', relief="raised")
frameResultado.grid(row=3, column=0,  sticky=NSEW)
frameDia = Frame(frameResultado,width=200, height=100,bg=co1, relief="solid")
frameDia.grid(row=0, column=0,padx=1, pady=1,  sticky=NSEW)
frameMes = Frame(frameResultado,width=200, height=100,bg=co1, relief="solid")
frameMes.grid(row=1, column=0,padx=1, pady=1,  sticky=NSEW)
frameSemana = Frame(frameResultado,width=200, height=100,bg=co1, relief="solid")
frameSemana.grid(row=0, column=1,padx=1, pady=1,  sticky=NSEW)
frameTotal = Frame(frameResultado,width=200, height=100,bg=co1, relief="solid")
frameTotal.grid(row=1, column=1,padx=1, pady=1,  sticky=NSEW)


# Logo -----------------------------------------------------
# opening image
app_img  = Image.open('logo.png')
app_img = app_img.resize((45, 45))
app_img = ImageTk.PhotoImage(app_img)

app_logo = Label(frameCima, image=app_img,text=" Calculadora de investimento",font=('Verdana 14 '), width=350,compound=LEFT, padx=5, relief=FLAT, anchor=CENTER,bg=co1, fg=co0)
app_logo.place(x=5, y=0)

l_linha = Label(frameCima, width=450, height=1,anchor=NW, font=('Verdana 1 '), bg='#4E6E81', fg=co1)
l_line.place(x=0, y=48)

# Frame Question ------------------------------------------
app_ = Label(framePergunta,text="Investimento*", width=20, height=1, relief=FLAT, anchor=NW, font=('Verdana 10'),bg=co1, fg=co0)
app_.place(x=50, y=15)

e_valor = Entry(framePergunta, width=10, font=('Ivy 22'), justify='center', relief='solid',bg='#F3E99F', fg='#4E6E81')
e_valor.place(x=5, y=50)


app_ = Label(framePergunta,text="Dias*", width=10, height=1, relief=FLAT, anchor=NW, font=('Verdana 10'),bg=co1, fg=co0)
app_.place(x=200, y=15)
e_valor_dias = Entry(framePergunta, width=5, font=('Ivy 22'), justify='center', relief='solid',bg='#F3E99F', fg='#4E6E81')
e_value_days.place(x=174, y=50)

app_ = Label(framePergunta,text="Percentagem %", width=13, height=1, relief=FLAT, anchor=NW, font=('Verdana 10'),bg=co1, fg=co0)
app_.place(x=260, y=15)
e_valor_percentagem = Entry(framePergunta, width=5, font=('Ivy 22'), justify='center', relief='solid',bg='#F3E99F', fg='#4E6E81')
e_percent_value.place(x=270, y=50)


# Frame Results -------------------------------------------
# Daily
app_ = Label(frameDia,text="Daily Profit", width=15, height=1, anchor=CENTER, font=('Verdana 11'),bg=co1, fg='#4E6E81')
app_.place(x=20, y=7)

app_dia = Label(frameDia,text="", width=10, height=1,anchor=CENTER, font=('Verdana 15'),bg=co1, fg=co0)
app_day.place(x=20, y=35)

# We
app_ = Label(frameMes,text="Lucro Mensal", width=15, height=1, anchor=CENTER, font=('Verdana 11'),bg=co1, fg='#4E6E81')
app_.place(x=20, y=7)

app_mes = Label(frameMes,text="", width=10, height=1,anchor=CENTER, font=('Verdana 15'),bg=co1, fg=co0)
app_mes.place(x=20, y=35)

# week
app_ = Label(frameSemana,text="Lucro Semanal", width=15, height=1, anchor=CENTER, font=('Verdana 11'),bg=co1, fg='#4E6E81')
app_.place(x=20, y=7)

app_semana = Label(frameSemana,text="", width=10, height=1,anchor=CENTER, font=('Verdana 15'),bg=co1, fg=co0)
app_week.place(x=20, y=35)


# Total
app_ = Label(frameTotal,text="Lucro total", width=15, height=1, anchor=CENTER, font=('Verdana 11'),bg=co1, fg='#4E6E81')
app_.place(x=20, y=7)

app_total = Label(frameTotal,text="", width=10, height=1,anchor=CENTER, font=('Verdana 15'),bg=co1, fg=co0)
app_total.place(x=20, y=35)


window.mainloop()


Connecting the function with the GUI

Now that we already have the graphical interface, let's connect the function to interact with the graphical interface, so the integration will be done as follows.

Go to the GUI after the logo, paste the following function, but first define the following:


import locale
# Set the locale to Brazilian Reais
locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8'


This will help us to format currencies regardless of country.

Then paste the code:


# Function to calculate
def calcular_lucro(event):

try:
# getting value
amount = float(e_value.get())

# getting investment days
days_of_investment = int(e_value_days.get())

# getting the percentage
percentage = float(e_percent_value.get())

initial_investment = amount
return_guaranteed = percentage

daily_return = guaranteed_return / 100 / investment_days
total_profit = initial_investment * (1 + guaranteed_return / 100)
daily_profit = initial_investment * daily_return
weekly_profit = daily_profit * 7
monthly_profit = daily_profit * 30

app_dia['text'] = locale.currency(lucro_diario, symbol=True, grouping=True)
app_semana['text'] = locale.currency(lucro_semanal, symbol=True, grouping=True)
app_mes['text'] = locale.currency(lucro_mensal, symbol=True, grouping=True)
app_total['text'] = locale.currency(lucro_total, symbol=True, grouping=True)

# Format the number as a currency string with a dollar symbol
dinheiro_str = locale.currency(1234.56, symbol=True, grouping=True)
except ValueError as e:
pass




I hope this tutorial was useful for you to understand how to use a function in Python to calculate the return on an investment. If you have any questions, just leave them in the comments!


Post a Comment

0 Comments

Close Menu