Subtract loan payment every month with daily compounding interest - python

I'm trying to figure out how to subtract a monthly loan payment with daily compounded interest. Right now I think I've got the right code for subtracting the payment amount daily over a 10 year loan:
P = 20000
r = .068
t = 10
n = 365
payment = 200
for payment_number in xrange(1, n*t):
daily_interest = P * (1+(r/n)) - P
P = (P + daily_interest) - payment
print P
I'd like it if possible to still print the daily balances but instead subtract the payment every month rather than every day. Initially I though maybe use a nested for loop with xrange(1, 30) but I'm not sure that worked correctly. Thanks in advance for the suggestions!

What about inserting an if statement for the purpose?
P = P-200 if payment_number%30 == 0 else P
This will run if the payment_number variable is a multiple of 30.

"Monthly" is a complicated idea. To fully handle the months you will need to use the datetime module.
from datetime import date, timedelta
date_started = date(2000,1,1)
So say you are 123 days from the start date, we need to calculate that date:
date = date_started + timedelta(days=123)
>>> date
datetime.date(2000, 5, 3)
So now we know need to figure how many days are between that date and the first of the month, the dateutil module can help us with that (you will have to download it).
from dateutil.relativedata import relativedelta
firstofmonth_date = date_started + relativedelta(months=4)
tddays = firstofmonth_date - date_started
days = tddays.days
Then just put "days" into the function you already have and you should be good. The only part I left for you to do is figuring out how many months have passed between your dates.

Related

Convert days data in years data in a list

I want to do a time serie with temperature data from 1850 to 2014. And I have an issue because when I plot the time series the start is 0 and it corresponds to day 1 of January 1850 and it stops day 60 230 with the 31 December of 2014.
I try to do a loop to create a new list with the time in month-years but it didn't succeed, and to create the plot with this new list and my initial temperature list.
This is the kind of loop that I tested :
days = list(range(1,365+1))
years = []
y = 1850
years.append(y)
while y<2015:
for i in days:
years.append(y+i)
y = y+1
del years [-1]
dsetyears = Dataset(years)
I also try with the tool called "datetime" but it didn't work also (maybe this tool is better because it will take into account the bissextile years...).
day_number = "0"
year = "1850"
res = datetime.strptime(year + "-" + day_number, "%Y-%j").strftime("%m-%d-%Y")
If anyone has a clue or a lead I can look into I'm interested.
Thanks by advance !
You can achieve that using datetime module. Let's declare starting and ending date.
import datetime
dates = []
starting_date = datetime.datetime(1850, 1, 1)
ending_date = datetime.datetime(2014, 1, 1)
Then we can create a while loop and check if the ending date is greater or equal to starting date and add 1-day using timedelta function for every iteration. before iteration, we will append the formatted date as a string to the dates list.
while starting_date <= ending_date:
dates.append(starting_date.strftime("%m-%d-%Y"))
starting_date += datetime.timedelta(days=1)

Datetime usage in Python for finance related task

I am a complete beginner in Python and it is my first question on Stackoverflow. I have tried numerous tutorials on youtube + some additional google searching, but havent been really able to completely solve my task. Briefly putting it below asf:
We have a dataset of futures prices (values) for next 12-36 months. Each value corresponds to one month in future. The idea for the code is to have an input of following:
starting date in days (like 2nd of Feb 2021 or any other)
duration of given days (say 95 or 150 days or 425 days)
The code has to calculate the number of days from each given month between starting and ending date (which is starting + duration) and then to use appropriate values from corresponding month to calculate an average price for this particular duration in time.
Example:
Starting date is 2nd of Feb 2021 and duration is 95 days (end date 8th of May). Values are Feb - 7750, Mar - 9200, April - 9500, May is 10100.
I have managed to do same in Excel (which was very clumsy and too complicated to use on the daily basis) and average stands for around 8949 taking in mind all above. But I cant figure out how to code same "interval" with days per month in Python. All of the articles just simply point out to "monthrange" function, but how is that possible to apply same for this task?
Appreciate your understanding of a newbie question and sorry for the lack of knowledge to express/explain my thoughts more clear.
Looking forward to any help relative to above.
You can use dataframe.todatetime() to constuct your code. If you need further help, just click ctrl + tab within your code to see the inputs and their usage.
You can try the following code.
The input_start_date() function will input the start date, and return it when called.
After we have the start date we input the duration of days.
Then we simply add them using timedelta
For the Distribution of days in the month : SO - #wwii
import datetime
from datetime import timedelta
def input_start_date():
YEAR = int(input('Enter the year : '))
MONTH = int(input('Enter the month : '))
DAY = int(input('Enter the day : '))
DATE = datetime.date(YEAR, MONTH, DAY)
return DATE
# get the start date:
Start_date = input_start_date()
# get the Duration
Duration = int(input('Enter the duration : '))
print('Start Date : ', Start_date)
print('Duration :', Duration)
# final date.
Final_date = Start_date + timedelta(days=Duration)
print(Final_date)
# credit goes to #wwii -----------------------
one_day = datetime.timedelta(1)
start_dates = [Start_date]
end_dates = []
today = Start_date
while today <= Final_date:
tomorrow = today + one_day
if tomorrow.month != today.month:
start_dates.append(tomorrow)
end_dates.append(today)
today = tomorrow
end_dates.append(Final_date)
# -----------------------------------------------
print("Distribution : ")
for i in range(len(start_dates)):
days = int(str(end_dates[i]-start_dates[i]).split()[0]) + 1
print(start_dates[i], ' to ', end_dates[i], ' = ', days)
print(str(end_dates[0]-start_dates[0]))
'''
Distribution :
2021-02-02 to 2021-02-28 = 27
2021-03-01 to 2021-03-31 = 31
2021-04-01 to 2021-04-30 = 30
2021-05-01 to 2021-05-08 = 8
'''

Python - Split a time period into multiple time periods of fixed length

Given two dates, I would like to generate a list of dates with a fixed time length in between one another using datetime, starting from the later date.
For instance, given 01/01/2018 and 01/09/2018 and time interval of 2 months the output would be:
[01/01/2018, 01/03/2018, 01/05/2018, 01/07/2018, 01/09/2018]
For an interval of 3 months:
[01/03/2018, 01/06/2018, 01/09/2018]
I cannot just subtract months using the .replace method on a datetime object since going from a 31 days month to a 30 days month would return an error.
I think relativedeleta module can help you on this - pip install python-dateutil
from dateutil.relativedelta import *
import datetime
date1 = datetime.datetime.strptime('01/01/2018', "%d/%m/%Y").date()
date2 = datetime.datetime.strptime('01/09/2018', "%d/%m/%Y").date()
f = [(date1 + relativedelta(months=i)).strftime("%d/%m/%Y") for i in range(date1.month, date2.month,2)]
Result will be - ['01/02/2018', '01/04/2018', '01/06/2018', '01/08/2018']
You did specify datetime, but if you're interested,
a time.localtime object can be broken down like so:
import time
secSinceEpoch = time.time()
currentTime = time.localtime(secSinceEpoch)
month = currentTime.tm_mon
day = currentTime.tm_mday
year = currentTime.tm_year
hour = currentTime.tm_hour
min = currentTime.tm_min
sec = currentTime.tm_sec
From here you could perform operations on specific parts of the date/time...

Where and how to calculate total price depending on date range user selected?

i'm working on site for renting rooms. User picks 2 dates(UserStartDate & UserEndDate).
with this python code i gonna get number of days in his date range:
user_date_range = [endUser - timedelta(i) for i in range((endUser - startUser).days+1)]
user_range_num_days = len(user_date_range)
and i have a day price for room: 20$
but due to lack of proficiency in Django,I can't figure out how to calculate user price according to his date range. And where it should be done.
hope for your help.
It doesn't have anything to do with django but rather python. I assume user_start_date and user_end_date are both python datetime.date or datetime.datetime objects, then you could do:
num_days = (user_end_date - user_start_date).days
total_price = num_days * 20
https://docs.python.org/2/library/calendar.html
A calendar is necessary as you should be aware that not all months have the same amount of days in them. itermonthdates(year, month) returns an iterator for all days in the month. Run through that iterator and increment a count for every date match within the range. Of course if the end date extends into the next month keep the same counter.

How can I subtract or add 100 years to a datetime field in the database in Django?

How can I subtract or add 100 years to a datetime field in the database in Django?
The date is in database, I just want to directly update the field without retrieving it out to calculate and then insert.
I would use the relativedelta function of the dateutil.relativedelta package, which will give you are more accurate 'n-years ago' calculation:
from dateutil.relativedelta import relativedelta
import datetime
years_ago = datetime.datetime.now() - relativedelta(years=5)
Then simply update the date field as others have shown here.
Use timedelta. Something like this should do the trick:
import datetime
years = 100
days_per_year = 365.24
hundred_years_later = my_object.date + datetime.timedelta(days=(years*days_per_year))
The .update() method on a Django query set allows you update all values without retrieving the object from the database. You can refer to the existing value using an F() object.
Unfortunately Python's timedelta doesn't work with years, so you'll have to work out 100 years expressed in days (it's 36524.25):
MyModel.objects.update(timestamp=F('timestamp')+timedelta(days=36524.25))
Though setting the number of days in a year as 365.25 (from (365+365+365+366)/4) perfectly offsets the difference-in-days error, it would sometimes lead to unwanted results as you might cause undesirable changes in attributes other than year, especially when you are adding/subtracting 1 or a few years.
If you want to just change the year while preventing changes in other datetime's attributes, just do the algebra on the year attribute like the following:
from datetime import datetime
d = my_obj.my_datetime_field
""" subtract 100 years. """
my_obj.my_datetime_field = datetime(d.year-100, d.month, d.day, d.hour, d.minute, d.second, d.microsecond, d.tzinfo)
my_obj.save()
Hope it helps!
Subtract year from today and use this format.
x = datetime.datetime(2020 - 100, 5, 17)
import datetime
datetime.date(datetime.date.today().year - 100, datetime.date.today().month, datetime.date.today().day)
I Know it's an old question, but I had the problem to find out a good one to solve my problem, I have created this: Use plus(+) or minus(-) to handle with:
import datetime # Don't forget to import it
def subadd_date(date,years):
''' Subtract or add Years to a specific date by pre add + or - '''
if isinstance(date,datetime.datetime) and isinstance(years,int):
day,month,year = date.day , date.month , date.year
#If you want to have HOUR, MINUTE, SECOND
#With TIME:
# day,month,year,hour,minute,second = date.day, date.month,date.year,date.hour,date.minute,date.second
py = year + years # The Past / Futur Year
new_date_str = "%s-%s-%s" % (day,month,py) # New Complete Date
# With TIME : new_date_str = "%s-%s-%s %s:%s:%s" % (month,day,py,hour,minute,second)
try:
new_date = datetime.datetime.strptime(new_date_str,"%d-%m-%Y")
except ValueError: # day is out of range for month (February 29th)
new_date_str = "%s-%s-%s" % (1,month+1,py) # New Complete Date : March 1st
new_date = datetime.datetime.strptime(new_date_str,"%d-%m-%Y")
return new_date
# With TIME : return datetime.datetime.strptime(new_date_str,"%d-%m-%Y %H:%M:%Y")
return None

Categories

Resources