inf answer when using while loops in python to calculate balances - python

I have to write a program that calculates Balkcom's and Brissie's balances using while-loop and then print the first year where Balkcom's balance surpasses Brissie's
The problem is that when I run the program it gives me inf as the answers for both balances, is there a way to fix this or is there another way to do it using while-loops?
Important info:
Balkcom initial deposit: 1
Brissie initial deposit: 100000
Balkcom interest rate: 5%
Brissie interest rate: 4%
#Define constant & variables
BALKCOM_INI_DEPOSIT = 1
BALKCOM_INT_RATE = 1.05
BRISSIE_INI_DEPOSIT = 100000
BRISSIE_INT_RATE = 104000
balkcom_balance = BALKCOM_INI_DEPOSIT * BALKCOM_INT_RATE
brissie_balance = BRISSIE_INI_DEPOSIT * BRISSIE_INT_RATE
year = 0
sys.set_int_max_str_digits(100000)
while balkcom_balance < brissie_balance:
balkcom_balance = balkcom_balance * BALKCOM_INT_RATE
brissie_balance = brissie_balance * BRISSIE_INT_RATE
year = year + 1
print("Year:", year, " " + "Balkcom balance:", balkcom_balance, "Brissie balance:", brissie_balance)

Related

expectation and variance of future stock price under binary tree

Probably a over-simplified model for stock price: on each day, the price will go up by a factor 1.05 with probability 0.6 or will go down to 1/1.05 with probability 0.4. So this is a non-symmetrical binary tree. How can I analytically calculate the expectation and variance of this stock price on future date, say day 100. Also, is there any module in python to handle binary tree model like this? appreciate code to implement this.
Best regards
import random as r
s = 100 # starting value
^^Initial conditions. Simulating one day on the stock market:
def day(stock_value): #One day in the stock market
k = r.uniform(0,1)
if k < 0.6:
output = 1.05*stock_value
else:
output = stock_value/1.05
return(output)
Simulating 100 days on the stock market:
for j in range(100): #simulates 100 days in the stock market
s = day(s)
print(s)
Simulating 100 days 1000 times:
data = []
for i in range(1000):
s = [100]
for j in range(100):
s.append(day(s[j]))
data.append(s)
Converting the data to only consider the last day:
def mnnm(mat): #Makes an mxn matrix into an nxm matrix
out = []
for j in range(len(mat[0])):
out.append([])
for j in range(len(mat[0])):
for m in range(len(mat)):
out[j].append(mat[m][j])
return(out)
data = mnnm(data)
data = data[-1]
Taking a mean average:
def lst_avg(lst): #Returns the average of a list
output = 0
for j in range(len(lst)):
output+= lst[j]/len(lst)
return(output)
mean = lst_avg(data)
Variance:
import numpy as np
for h in range(len(data)):
data[h] = data[h]**2
mean_square = lst_avg(data)
variance = np.fabs(mean_square - mean**2)
The theoretical value after 1 day is (assuming value on day 0 is A)
A * 0.6 * 1.05 + 100 * 0.4/1.05
And after 100 days it's
A * (0.603 + 0.380952...)**100 so...
(in the following I use 1 as stock price on day 0.)
p1 = 0.6
p2 = 0.4
x1 = 1.05
x2 = 1/1.05
initial_value = 1
no_of_days = 100
# 1 day
expected_value_after_1_day = initial_value * ( p1*x1 + p2*x2)
print (expected_value_after_1_day, 'is the expected value of price after 1 day')
ex_squared_value_1_day = initial_value * (p1*x1**2 + p2*x2**2)
# variance can be calculated as follows
variance_day_1 = ex_squared_value_1_day - expected_value_after_1_day**2
# or an alternative calculation, summing the squares of the differences from the mean
alt_variance_day_1 = p1 * (x1 - expected_value_after_1_day) ** 2 + p2 * (x2 - expected_value_after_1_day) ** 2
print ('Variance after one day is', variance_day_1)
# 100 days
expected_value_n_days = initial_value * (p1*x1 + p2*x2) ** no_of_days
ex_squared_value_n_days = initial_value * (p1*x1**2 + p2*x2**2) ** no_of_days
ex_value_n_days_squared = expected_value_n_days ** 2
variance_n_days = ex_squared_value_n_days - ex_value_n_days_squared
print(expected_value_n_days, 'is the expected value of price after {} days'.format(no_of_days))
print(ex_squared_value_n_days, 'is the expected value of the square of the price after {} days'.format(no_of_days))
print(ex_value_n_days_squared, 'is the square of the expected value of the price after {} days'.format(no_of_days))
print(variance_n_days, 'is the variance after {} days'.format(no_of_days))
It probably looks a bit old-school, hope you don't mind!
Output
1.0109523809523808 is the expected value of price after 1 day
Variance after one day is 0.0022870748299321786
2.972144657651404 is the expected value of price after 100 days
11.046309656223373 is the expected value of the square of the price after 100 days
8.833643866005783 is the square of the expected value of the price after 100 days
2.2126657902175904 is the variance after 100 days

how to put a $ in front of my value table numbers

I'm new to python and wondering how I can put a dollar sign in this spot? i think it might have something to do with line 31 in my code but I cannot figure it out
https://i.stack.imgur.com/Flv4W.png
here is the code:
#constants
CITY_CLOSE_RATE = 2
CITY_DIST_RATE = 1
BNDRY_DIST = 20
#inputs
propValue = float(input('What is the cost of the property right now?'))
numYears = int(input('Value after how many years?'))
propDist = float(input('How far is the property from your city?'))
# select the right rate depending on the distance to the city
if propDist <= BNDRY_DIST:
rate = CITY_CLOSE_RATE
else:
rate = CITY_DIST_RATE
#calculate percantage
rate = rate / 100
#print header of the table
print(f'{"Years":>5} {"value":>15}')
# calculating property for every year. body of the table
for count in range (1, numYears +1) :
increment = propValue * rate
endVal = propValue + increment
print (f'{count:>5} {endVal :>15.2f}')
propValue= endVal
#print final prop value after appreciation
print(f'Value of the property after {count} years: ${propValue : .2f}')
One way might be to use an earlier f-string to make endVal in to a string with a $ added before. As such the for loop becomes;
for count in range (1, numYears +1):
increment = propValue * rate
endVal = propValue + increment
strEndVal = '$ ' + f'{endVal:,.2f}'
print (f'{count:>5} {strEndVal :>15}')
propValue= endVal

It is not working as expected. How can i fix this code?

I want the code to increase my semi_annual_income every six months, by making the the semi_annual income increase every six months with by specific percentage. so it was suppose to be according to my math 1000(1.2)^i/6 this equation would increase my income by 0.2 every 6 months where the i is divisible by 6.
I tried to both the expressions when I use the expression 1000(1.2)^i/6 it will give me a very huge number. and the expression 1000(1 +0.2) is giving me the exact answer that 1000(1 + 0.2) should have given me.
number_of_months = 0
total_cost = 100000
semi_annual_income = 1000
starting_salary = 10
semi_annual_rise = 0.2
while semi_annual_income < total_cost:
for i in range(100):
if float(i)%6 == 0:
power_number = float(i)/6
# i am using this to make it increase the semi_annual income just only every six months
semi_annual_income = semi_annual_income *(float(1) + float(semi_annual_rise))
print(power_number)
print(semi_annual_income)
#semi_annual_income = (semi_annual_income *(float(1) + float(semi_annual_rise))** float(power_number))
#The above written code is giving me a very huge number i want it to give me the answer as 1000(1 + 0.2)^i/6
break
I got the answer I wanted from the code but I don't understand why is it giving me the answer without the power and the one with the power is not giving me the answer.
number_of_months = 0
total_cost = 100000
semi_annual_income = 1000
starting_salary = 1000
semi_annual_rise = 0.2
number_of_months = 0
while semi_annual_income < total_cost:
for i in range(1,100):
if float(i)%6 == 0:
power_number = float(i)/6# i am using this to make it increase the
semi_annual income just only every six months
number_of_months = number_of_months + 1
semi_annual_income = starting_salary *(float(1) +
float(semi_annual_rise))**(power_number)
print(power_number)
print(semi_annual_income)
print(number_of_months)
# I think my mistake was the i used semi_annual-income instead of starting salary, this code works as i wanted it to be.
break

How to use the final value of two different function to get another value in python?

I want to develop an electric calculator which :
Converts money into units(KWh).
It also takes user input to determine how many electric component he/she uses in home in order to determine average electricity consumption per day.
After having those in inputs and calculation it will also show how many day he/she can have against the money he/she recharged(Ex: for 10$ he can have 100 Kwh, if average use per day is 10 KWh how many day he can have? [day=100kwh/10kwh=10 days]
I have solved 1 and 2 problem using two function, now i want to use the final value of those two function to get the day. i was trying to divide the final of those function. is it possible to divide the value of those function?
1. this function converts money into units in KWh
def money_to_unit():
recharge=int(input("Enter yor recharge amount : "))
amount=recharge-(recharge*(5/100)) # after deducting 5% vat
unit=0
if amount<=300: #300 is max value for using 75 Kwh
unit=amount/4 # 4 is the slab rate for 0-75 Kwh
elif amount<=981.25: #981.25 is max value for using 200 Kwh
unit=75+((amount-300)/5.45) #5.45 is the slab rate for 76-200 Kwh
elif amount<=1551.25: #1551.25 is max value for using 300 Kwh
unit=75+125+((amount-681.25)/5.7) #5.7 is the slab rate for 201-300 Kwh
elif amount<=2153.25:
unit=75+125+100+((amount-1551.25)/6.02)
elif amount<=4013.25:
unit=75+125+100+100+((amount-2153.25)/9.30)
else:
unit=75+125+100+100+200+((amount-4013.25)/10.7)
print("Useable amount is :"+ " "+str(round(amount,2))+" "+"Taka")
print("Useable unit is: "+" "+str(round(unit,2))+" "+"Kwh")
money_to_unit()
2. to determine the average use per day in KWh
def comp():
light=int(input("Enter the number of light :"))
watt=int(input("Enter the watt : "))
hour=int(input("Enter the agerage use of light in hour per day : "))
consumption=(light*watt*hour)/1000
print("you total consumption is"+ " " + str(consumption)+ " " + "Kwh per day")
comp()
3. divided money_to_unit() by comp(). how to do it?
(1).for 500 taka, usable amount is 475 taka, usable unit is 107.11 Kwh
(2).for 5 light of 20 w per hour using 6 hour a day, average use is 0.6 Kwh per day.
(3). day = 107.11 Kwh/0.6 Kwh = 178.5 day
Both of your function should return the calculated value that you want to use for further calculations (instead of just printing it).
def money_to_unit():
/* function definition */
return round(amount,2), round(amount,2)
and
def comp():
/* function definition */
return consumption
Then you can simply call the functions like this:
x, y = money_to_unit()
z = comp()
and finally you can perform any extra calculation you want with x,y,z like:
result = x/z
/* or */
result2 = y/z
def money_to_unit():
# all your previous code
return round(unit,2)
def comp():
# all your previous code
return consumption
and perhaps:
money_unit = money_to_unit()
consumption = comp()
day = money_unit / consumption
print(round(day,1), "{}".format("day"))
OUTPUT:
178.5 day
Use return. Give functions specific tasks to do, not only wrapping around some scripts.
1.Define two functions for first step:
def recharge_to_amount(recharge, vat):
return recharge * (1 - vat)
and
def amount_to_kwh(amount):
if amount <= 300:
return amount / 4
elif amount <= 981.25:
return 75 + ((amount - 300) / 5.45)
elif amount <= 1551.25:
return 75 + 125 + ((amount - 681.25) / 5.7)
elif amount <= 2153.25:
return 75 + 125 + 100 + ((amount - 1551.25) / 6.02)
elif amount <= 4013.25:
return 75 + 125 + 100 + 100 + ((amount - 2153.25) / 9.30)
else:
return 75 + 125 + 100 + 100 + 200 + ((amount - 4013.25) / 10.7)
2.Define another function for second step:
def consumption(light, watt, hour):
return light * watt * hour / 1000
3.Define last function:
def days(watt, cons):
return watt / cons
And perform your calculation:
amount = recharge_to_amount(500)
kwh = amount_to_kwh(amount)
consumption = consumption(5, 20, 6)
days = days(kwh, consumption)

Calculating monthly growth percentage from cumulative total growth

I am trying to calculate a constant for month-to-month growth rate from an annual growth rate (goal) in Python.
My question has arithmetic similarities to this question, but was not completely answered.
For example, if total annual sales for 2018 are $5,600,000.00 and I have an expected 30% increase for the next year, I would expect total annual sales for 2019 to be $7,280,000.00.
BV_2018 = 5600000.00
Annual_GR = 0.3
EV_2019 = (BV * 0.3) + BV
I am using the last month of 2018 to forecast the first month of 2019
Last_Month_2018 = 522000.00
Month_01_2019 = (Last_Month_2018 * CONSTANT) + Last_Month_2018
For the second month of 2019 I would use
Month_02_2019 = (Month_01_2019 * CONSTANT) + Month_01_2019
...and so on and so forth
The cumulative sum of Month_01_2019 through Month_12_2019 needs to be equal to EV_2019.
Does anyone know how to go about calculating the constant in Python? I am familiar with the np.cumsum function, so that part is not an issue. My problem is I cannot solve for the constant I need.
Thank you in advance and please do not hesitate to ask for further clarification.
More clarification:
# get beginning value (BV)
BV = 522000.00
# get desired end value (EV)
EV = 7280000.00
We are trying to get from BV to EV (which is a cumulative sum) by calculating the cumulative sum of the [12] monthly totals. Each monthly total will have a % increase from the previous month that is constant across months. It is this % increase that I want to solve for.
Keep in mind, BV is the last month of the previous year. It is from BV that our forecast (i.e., Months 1 through 12) will be calculated. So, I'm thinking that it makes sense to go from BV to the EV plus the BV. Then, just remove BV and its value from the list, giving us EV as the cumulative total of Months 1 through 12.
I imagine using this constant in a function like this:
def supplier_forecast_calculator(sales_at_cost_prior_year, sales_at_cost_prior_month, year_pct_growth_expected):
"""
Calculates monthly supplier forecast
Example:
monthly_forecast = supplier_forecast_calculator(sales_at_cost_prior_year = 5600000,
sales_at_cost_prior_month = 522000,
year_pct_growth_expected = 0.30)
monthly_forecast.all_metrics
"""
# get monthly growth rate
monthly_growth_expected = CONSTANT
# get first month sales at cost
month1_sales_at_cost = (sales_at_cost_prior_month*monthly_growth_expected)+sales_at_cost_prior_month
# instantiate lists
month_list = ['Month 1'] # for months
sales_at_cost_list = [month1_sales_at_cost] # for sales at cost
# start loop
for i in list(range(2,13)):
# Append month to list
month_list.append(str('Month ') + str(i))
# get sales at cost and append to list
month1_sales_at_cost = (month1_sales_at_cost*monthly_growth_expected)+month1_sales_at_cost
# append month1_sales_at_cost to sales at cost list
sales_at_cost_list.append(month1_sales_at_cost)
# add total to the end of month_list
month_list.insert(len(month_list), 'Total')
# add the total to the end of sales_at_cost_list
sales_at_cost_list.insert(len(sales_at_cost_list), np.sum(sales_at_cost_list))
# put the metrics into a df
all_metrics = pd.DataFrame({'Month': month_list,
'Sales at Cost': sales_at_cost_list}).round(2)
# return the df
return all_metrics
Let r = 1 + monthly_rate. Then, the problem we are trying to solve is
r + ... + r**12 = EV/BV. We can use numpy to get the numeric solution. This should be relatively fast in practice. We are solving a polynomial r + ... + r**12 - EV/BV = 0 and recovering monthly rate from r. There will twelve complex roots, but only one real positive one - which is what we want.
import numpy as np
# get beginning value (BV)
BV = 522000.00
# get desired end value (EV)
EV = 7280000.00
def get_monthly(BV, EV):
coefs = np.ones(13)
coefs[-1] -= EV / BV + 1
# there will be a unique positive real root
roots = np.roots(coefs)
return roots[(roots.imag == 0) & (roots.real > 0)][0].real - 1
rate = get_monthly(BV, EV)
print(rate)
# 0.022913299846925694
Some comments:
roots.imag == 0 may be problematic in some cases since roots uses a numeric algorithm. As an alternative, we can pick a root with the least imaginary part (in absolute value) among all roots with a positive real part.
We can use the same method to get rates for other time intervals. For example, for weekly rates, we can replace 13 == 12 + 1 with 52 + 1.
The above polynomial has a solution by radicals, as outlined here.
Update on performance. We could also frame this as a fixed point problem, i.e. to look for a fixed point of a function
x = EV/BV * x ** 13 - EV/BV + 1
The fix point x will be equal to (1 + rate)**13.
The following pure-Python implementation is roughly four times faster than the above numpy version on my machine.
def get_monthly_fix(BV, EV, periods=12):
ratio = EV / BV
r = guess = ratio
while True:
r = ratio * r ** (1 / periods) - ratio + 1
if abs(r - guess) < TOLERANCE:
return r ** (1 / periods) - 1
guess = r
We can make this run even faster with a help of numba.jit.
I am not sure if this works (tell me if it doesn't) but try this.
def get_value(start, end, times, trials=100, _amount=None, _last=-1, _increase=None):
#don't call with _amount, _last, or _increase! Only start, end and times
if _amount is None:
_amount = start / times
if _increase is None:
_increase = start / times
attempt = 1
for n in range(times):
attempt = (attempt * _amount) + attempt
if attempt > end:
if _last != 0:
_increase /= 2
_last = 0
_amount -= _increase
elif attempt < end:
if _last != 1:
_increase /= 2
_last = 1
_amount += _increase
else:
return _amount
if trials <= 0:
return _amount
return get_value(start, end, times, trials=trials-1,
_amount=_amount, _last=_last, _increase=_increase)
Tell me if it works.
Used like this:
get_value(522000.00, 7280000.00, 12)

Categories