Creating a balance table on Python (edited) - python

I have this code which display the payment I need to make to student loan depending on different factors but I was wondering how could I display a table telling me for example... if my program says that I'll be making 36 payments of $153.02 to pay a loan of 5000 at 6.4% interest, how do I display a table telling me (payment 1 of 153 this is the remaining balance, this much goes to interest or to principal payment, then the same payment 2 this the new balance... and so on...) In other words a table telling me about those 36 payments and how my balance gets reduced with each payment.
IT DOESN'T HAVE TO BE AS A TABLE MAYBE JUST A LIST... LISTING PAYMENT AFTER PAYMENT UNTILL THE BALANCE IS 0 or -SOMETHING?
This is the code I have so far using python 2.7.3
def calcDebt (principal, interestRate, numPayments, freqPayment):
#This code will make different predictions to pay off student loan
#Input Meanings
'''
Inputs
- interestRate - The Interest Rate of a Loan
- numPayments - The Number of Payments Needed
- principal - The Original Student Loan Amount
- freqPayment - Frequency of Payments Based on Weekly, Monthly, Annually
Returns
- paymentAmount - The Payment Amount Will Be
'''
freqPayment_lookup = {'weekly': 52, 'monthly':12, 'annually':1}
interestRate = float(interestRate) / 100
x = interestRate/freqPayment_lookup[freqPayment]
y = (1.0 + x) ** numPayments
z = x/(y - 1.0)
paymentAmount = (x + z) * principal
return paymentAmount
def main():
a = input('Student Loan Amount: ')
i = input('Student Loan Interest Rate: ')
n = input('Number of Payments: ')
f = None
while f not in ['weekly', 'monthly', 'annually']:
if f:
f = raw_input('Sorry! That is NOT an Option. Please Enter weekly, monthly, or annually: ').lower()
else:
f = raw_input('How Often Do You Want To Make Your Payments? ').lower()
payment = calcDebt(a, i, n, f)
print 'Your %s payment will be %.2f' % (f, payment)
if __name__ == '__main__':
main()
raw_input('Please Press Enter to Exit')
Any ideas?

I would say the best thing for this is to use numpy! here is a general idea for the kind of code you would need:
import numpy as np
#this creates your table with numPayments rows and 4 columns
numPayments = 40
row_index = range(1,numPayments + 1)
real_row_index = []
for i in row_index:
real_row_index.append(str(i))
columns = ["payment number", "remaining balance", "interest amount", "principal amount"]
total_payments = np.chararray((numPayments,3), itemsize=20)
total_payments[:] = "none"
total_payments = np.insert(total_payments, 0, np.array((real_row_index)),1)
total_payments = np.insert(total_payments, 0, np.array((columns)),0)
for row in total_payments[1::,1::]:
#the 1 skips the lables so you don't mess with them
#row[0] will be the number payment column
#row[1] will be the remaining balance column
#row[2] will be the interest amount column
#row[3] will be the principal amount column
now that you have an array of tables set up in a for loop (which I will not finish for you), you can use it in you function to iterate through and for every payment, set the cell to the correct value for the column. So if you calculate the interest amount in a variable interest, you just need to throw this in your for loop to make the interest that belongs in the right place to go there:
row[2] = str(interest)
interest is iterating at the same pace row is, so they should match up if done correctly

Related

Plotting (discrete sum over time period) vs. (time period) yields graph with discontinuities

I have some lists related to buying and selling bitcoin.
One is the price (of a buy or sell) and the other is an associated date.
When I plot the total money made (or lost) from my buying/selling over different lengths of time vs. those different lengths of time, the result is 'choppy' - not what I expected. And I think my logic might be wrong
My raw input lists look like:
dates=['2013-05-12 00:00:00', '2013-05-13 00:00:00', '2013-05-14 00:00:00', ....]
prices=[114.713, 117.18, 114.5, 114.156,...]
#simple moving average of prices calced over a short period
sma_short_list = [None, None, None, None, 115.2098, 116.8872, 118.2272, 119.42739999999999, 121.11219999999999, 122.59219999999998....]
#simple moving average of prices calced over a longer period
sma_long_list = [...None, None, None, None, 115.2098, 116.8872, 118.2272, 119.42739999999999, 121.11219999999999, 122.59219999999998....]
Based on the moving average cross-overs (which were calculated based on https://stackoverflow.com/a/14884058/2089889) I will either buy or sell the bitcoin at the date/price where crossover occurred.
I wanted to plot how (much money this approach would have made me as of today) vs. (days ago that I started this approach)
BUT
I am having trouble in that the resulting graph is really choppy. First I thought this was because I have one more buy than sell (or vis-versa) so I tried to account for that. But it was still choppy. NOTE the following code is called in a loop for days_ago in reversed(range(0,approach_started_days_ago)): so each time the following code executes it should spit out how much money that approach would have made had I started it days_ago (I call this bank), and the choppy plot is the days_ago vs. bank
dates = data_dict[file]['dates']
prices = data_dict[file]['prices']
sma_short_list = data_dict[file]['sma'][str(sma_short)]
sma_long_list = data_dict[file]['sma'][str(sma_long)]
prev_diff=0
bank = 0.0
buy_amt, sell_amt = 0.0,0.0
buys,sells, amt, first_tx_amt, last_tx_amt=0,0,0, 0, 0
start, finish = len(dates)-days_ago,len(dates)
for j in range(start, finish):
diff = sma_short_list[j]-sma_long_list[j]
amt=prices[j]
#If a crossover of the moving averages occured
if diff*prev_diff<0:
if first_tx_amt==0:
first_tx_amt = amt
#BUY
if diff>=0 and prev_diff<=0:
buys+=1
bank = bank - amt
#buy_amt = buy_amt+amt
#print('BUY ON %s (PRICE %s)'%(dates[j], prices[j]))
#SELL
elif diff<=0 and prev_diff>=0:
sells+=1
bank = bank + amt
#sell_amt = sell_amt + amt
#print('SELL ON %s (PRICE %s)'%(dates[j], prices[j]))
prev_diff=diff
last_tx_amt=amt
#if buys > sells, subtract last
if buys > sells:
bank = bank + amt
elif sells < buys:
bank = bank - amt
#THIS IS RELATED TO SOME OTHER APPROACH I TRIED
#a = (buy_amt) / buys if buys else 0
#b = (sell_amt) / sells if sells else 0
#diff_of_sum_of_avg_tx_amts = a - b
start_date = datetime.now()-timedelta(days=days_ago)
return bank, start_date
I reasoned that my amount in the 'bank' would be the amount I have sold - the amount I have bought
But, if the first crossover was a sell I don't want to count that (I am going to assume that the first tx I make will be a buy.
Then if the last tx I make is a buy (negative to my bank), I will count today's price into my 'bank'
if last_tx_type=='buy':
sell_amt=sell_amt+prices[len(prices)-1] #add the current amount to the sell amount if the last purchase you made is a buy
if sell_first==True:
sell_amt = sell_amt - first_tx_amt #if the first thing you did was sell, you do not want to add this to money made b/c it was with apriori money
bank = sell_amt-buy_amt

Counting entries in a CSV?

I'm just learning Python, and have been having a little bit of trouble with the list functionality of the language. I have a .csv file named purchases.csv and I need to do four things with it:
output the total number of "purchase orders" aka count the total number of entries in the csv
output the average amount of the purchases, showing three decimals.
output the total number of purchases made over 1,800
output the average amount of purchases made that are over 1,800 showing three decimals.
The output needs to look something like:
Total Number of Purchases: xxxx
Amount of Average Purchase: xxxx
Number of Purchase Orders over $1,800: xxxx
Amount of Average Purchases over $1,800: xxxx
So far I've written
import csv
with open('purchases.csv') as csvfile:
readCSV = csv.reader(csvfile,delimiter=',')
total_purchases=[]
for row in readCSV:
total=row[0]
total_purchases.append(total)
print(total_purchases)
my_sum=0
for x in home_runs:
my_sum=my_sum+int(x)
print("The total number of purchases was: ", my_sum)
To find the total number of purchases, but I've hit a wall and can't seem to figure out the rest! I'd love any help and guidance with this...I just can't figure it out!
You need an a series of separate similar for loops, but with if statements to only count the sum conditionally.
Assuming row[0] is your price column:
var sumAbove1800 = 0;
var countAbove1800 = 0;
var totalSum = 0;
var totalPurchases = 0;
for row in readCSV:
var price = float(row[0])
totalPurchases = totalPurchases + 1;
totalSum = totalSum + price;
if(price > 1800):
sumAbove1800 = sumAbove1800 + price;
countAbove1800 = countAbove1800 + 1;
Now to print them out with 3 decimal places:
print("Total Average Price: {:.3f}".format(totalSum / totalPurchases));
print("Total Transactions: {:.3f}".format(totalPurchases));
print("Total Average Price above 1800: {:.3f}".format(sumAbove1800 / countAbove1800 ));
print("Total Transactions above 1800: {:.3f}".format(countAbove1800 ));
Your question is a bit too vague, but here goes anyway.
Unless you are constrained by requirements as this appears to be homework / an assignment, you should give Pandas a try. It's a Python library that helps tremendously with data wrangling and data analysis.
output the total number of "purchase orders" aka count the total number of entries in the csv
This is dead easy with Pandas:
import pandas as pd
df = pd.read_csv('purchases.csv')
num = df.shape[0]
The first two lines are self-explanatory. You build an instance of a Pandas.DataFrame object with read_csv() and store it in df. For the last line, just know that Pandas.DataFrame has a member named shape with the format (number of lines, number of columns), so shape[0] returns the number of lines.
output the average amount of the purchases, showing three decimals.
mean = df['purchase_amount'].mean()
Access column 'purchase_amount' using brackets.
output the total number of purchases made over 1,800
num_over_1800 = df[df['purchase_amount'] > 1800].shape[0]
Slight twist here, just know that this is one way to set a condition in Pandas.
output the average amount of purchases made that are over 1,800
showing three decimals.
mean_over_1800 = df[df['purchase_amount'] > 1800].mean()
This should be self-explanatory from the rest above.

python for loop issue

I currently have this as an assignment. I have written the code below, but there seems to be an issue as the calculations keep on adding. Is there a way to restart the for loop?
There are 7 employees. Write a program with nested loops, to ask the yearly salary of each employee for 5 years. Your program should keep track of the highest salary, lowest salary, and calculate the average salary of each employee. After you collect each employees data, display the highest salary, lowest salary, and average salary for that employee.
totalsalary = 0
salaryhigh = 0
salarylow = 10000000
employee = 0
for employee in range(1,4):
print("Please enter the 5 year salaries of Employee#",employee,":")
for year in range(1,6):
salary = int(input('Enter you salary:'+""))
totalsalary = totalsalary + salary
if(salary > salaryhigh):
salaryhigh = salary
if(salary < salarylow):
salarylow = salary
avesalary = totalsalary/5
print('Total Salary entered for 5 years for Employee#',employee,':',totalsalary)
print("Average is:",avesalary)
print("Highest Salary entered is:",salaryhigh)
print("Lowest Salary entered is:",salarylow)
print("------------------------------------")
Your first three lines should be run for each employee, so they should be inside the outer for loop. The fourth line doesn't really do anything: your for-loop resets the employee number. Also, your for-loop does only three employees, but you state that there are seven employees. It's generally recommended that you set the number of employees at the beginning and then use that in the following code, so it's clear what the number represents and it's easier to keep track of and change the number. E.g.
number_of_employees = 7
for employee in range(0,number_of_employees):
...

Error in Code, unable to process based on user parameters (Python 3)

I am new to Python, and working on a project for school.I need to find a similar user profile based on the dataset and user inputs. Essentially a user inputs his/her information, i would like to assign a grade and interest rate of a similar existing applicant in dataframe. However, I am failing miserably. Could somoene please help.
loading data
df = pd.read_csv("LoanStats_2017Q1.csv")
df = df[["verification_status","loan_amnt", "term","grade","int_rate","dti","delinq_amnt","annual_inc", "emp_length" ]]
loan = int(input("What loan amount are you looking to obtain? "))
inc = int(input("What is your annual income? "))
dti = int(input("What is your current Debt-to-Equity Ratio (DTI)? "))
lst=[loan,inc,dti]
similar user is someone within 1% of potential applicant
def simUser(a,b):
return (abs(a-b)/b) <=0.01
if dti > 35:
print('\n'+"Your Debt-to-Income Ratio is too High. Please lower it before proceeding.")
else:
print('\n'+"analyzing..."+'\n')
#create dataframe for analysis
columns = ["loan_amnt","annual_inc","dti"]
lst1 = list(zip(lst,columns))
#go over the loan grades and interest rates
for rowNum in range(len(df)):
lamnt = df.iloc[rowNum]['loan_amnt']
ainc = df.iloc[rowNum]['annual_inc']
dtiu = df.iloc[rowNum]['dti']
#scan data for similar a similar loan profile
for user_input,col in lst1:
lst2 = df[simUser(df.iloc[rowNum][col],user_input) == True]

python compounding interest

I'm trying to figure out how to get the interest and principal to display correctly over the years. Here is the part of my code I am having trouble with:
print ('Luke\n-----')
print ('Year\tPrincipal\tInterest\t Total')
LU_RATE = .05
YEAR = 1
Principal = 100
for YEAR in range (1,28):
# Calculating Luke's total using formula for compounding interest
Lu_Total = (Principal * ((1 + LU_RATE) ** YEAR))
# I realize it's a logical error occurring somewhere here
Lu_Interest = #I'm not sure what to code here
Lu_Principal = #And here
# Displaying the Principal, Interest, and Total over the 27
print (YEAR,'\t%.02f\t\t %.02f\t\t %.02f' %(Lu_Principal, Lu_Interest, Lu_Total))
This is what gets displayed (minus the comment symbols of course):
Luke
-----
Year Principal Interest Total
1 # # 105.00
2 # # 110.25
3 # # 115.76
4 # # 121.55
5 # # 127.63
6 # # 134.01
#etc etc....
Every equation I've tried to code had the correct Interest for year one but ends up putting the Principal as the Total. Every year past that calculates out to the wrong numbers.
It should look like:
Luke
-----
Year Principal Interest Total
1 100.00 5.00 105.00
2 105.00 5.25 110.25
3 110.25 5.51 115.76
#etc etc....
I've been working at it on and off throughout the day and just can't seem to figure it out. Thank you in advance for any help or suggestions.
This sounds like homework, so I'll be a little vague:
You have a loop. Your program executes from the top of the loop to the bottom of the loop, and then goes back and starts over at the top of the loop again.
You can change things by setting values in the bottom of the loop that will be used in the top of the loop next time.
For example, you can compute the interest based on this year's principal. You're doing that in the top of the loop.
At the bottom of the loop, after you print everything out for this year, you could change the (next year's) principal by adding (this year's) interest to it. Then 100 would become 105, etc.
And another contestant ;-)
print ('Luke\n-----')
print ('Year\tPrincipal\tInterest\t Total')
rate = .05
principal = 100.
for year in range (1, 28):
# calculate interest and total
interest = principal * rate
total = principal + interest
# displaying this year's values
print(year,'\t%.02f\t\t %.02f\t\t %.02f' %(principal, interest, total))
# next year's principal == this year's total
principal = total
produces
Luke
-----
Year Principal Interest Total
1 100.00 5.00 105.00
2 105.00 5.25 110.25
3 110.25 5.51 115.76
4 115.76 5.79 121.55
# ... etc ...
Here is what I did:
print ('Luke\n-----')
print ('Year\tPrincipal\tInterest\t Total')
LU_RATE = .05
YEAR = 1
Principal = 100
Prev_Principal = 100 #added to store previous year principal
for YEAR in range (1,28):
# Calculating Luke's total using formula for compounding interest
Lu_Total = (Principal * ((1 + LU_RATE) ** YEAR))
Lu_Interest = Lu_Total - Prev_Principal
Lu_Principal = Lu_Total - Lu_Interest
Prev_Principal = Lu_Total
# Displaying the Principal, Interest, and Total over the 27
print (YEAR,'\t%.02f\t\t %.02f\t\t %.02f' %(Lu_Principal, Lu_Interest, Lu_Total))
There may be another way to do this, but I think you have a few issues. One is that you need to base your "total" calculation (where you're multiplying the principal by the 1+rate ** year) on the original principal value, and you need to keep this value separate from the rest of the calculations.
So you can work with two names like p0 and pN, where p0 represents the initial principal at year 0, and pN represents the original principal PLUS accrued interest at year N, then we reassign pN at the end of the loop.
r = .05
p0, pN = 100, p0
for y in range(1,5):
total = p0 * ((1+r)**y)
i = total - pN
print (y,'\t%.02f\t\t %.02f\t\t %.02f' %(pN, i, total))
pN = total
The output is as you expect:

Categories

Resources