[2020 version] Let Python do all the tax and take-home calculations

Overview

It's difficult to calculate taxes, isn't it? When I become a member of society, taxes and insurance premiums are deducted every year, but I'm not familiar with taxes at all, so I'm in a state of something. Furthermore, I heard that the rules for deductions and income tax will change from this year. There is a saying (?) "Let's let Python do all the boring things **", so this time I will try to make a tax calculation class with Python for studying. Since I wrote it while researching various things from scratch, there may be many explanations that are obvious to those who know it.

Github I created a tax calculation class on Github.

The site that I referred to when writing the code

How to use

Before we talk about the difficult tax, let's start with a brief explanation of how to use it. The Tax class created this time is implemented in tax.py. As an example, consider ** a single man with an annual income of 5 million **. Do the following with tax.py in the parent directory:

# coding: utf-8
import sys, os
sys.path.append(os.pardir)  #Settings for importing files in the parent directory
from common.tax import Tax

gross_salary = 5000000
tax = Tax(gross_salary)
print("gross_salary, income = ", tax.gross_salary, tax.income)
print("income_tax, inhabitant_tax, insurance_premiun = ", tax.income_tax(), tax.inhabitant_tax(), tax.social_insurance_premium())
print("net_salary = ", tax.net_salary())
print("max_hurusato_donation = ", tax.max_hurusato_donation())

output


gross_salary, income =  5000000 3560000.0
income_tax, inhabitant_tax, insurance_premiun =  110575.0 215575.0 619249.9999999999
net_salary =  4054600.0
max_hurusato_donation =  56035.593432760994

-** gross_salary : Income - income : Salary income - inhabitant_tax : Resident tax - income_tax : Income tax - insurance_premium : Social insurance premiums - net_salary : Take-home - max_hurusato_donation **: The upper limit that you can fully deduct at your own expense of 2000 yen with your hometown tax payment

is. In this case, ** the face value is 5 million yen, and the take-home pay is about 4 million yen ** due to various taxes and insurance premiums. In the above example, the argument of tax gives only income (= gross_salary), but if you have ** dependents ** or ** disabled person **, it will be deducted, so take the argument Such cases can be calculated by specifying. Now, I will explain each one in turn.

Employment income

First of all, about ** salary income **. I was ignorant about taxes, so I knew that "somehow the tax would be deducted from my income and my take-home pay would be reduced", but what is ** salary income **? It was in the state. In fact, taxes are not calculated directly from face value income, but are applied to the amount after the deduction ** salary income deduction ** has been made. This time I'm talking on the premise of a company employee, but since the necessary expenses will be incurred when originally working

(income) - (Expenses) = (income) 

The scheme of is established. If you're a hired office worker, it may not be very obvious, but ** all office workers are deducted from your income, assuming that you will have to pay for it if you work. ** ** By the way, this is also listed in the ** Withholding tax table ** next to the face value income from the company under the name ** Amount after deduction of salary income ** ↓

スクリーンショット 2020-06-28 15.52.26.png

The code for Python is below. After 2020, the rules have changed and this ** salary income deduction ** has decreased by 100,000 yen, and the ** income tax ** that will come out later has increased by 100,000 yen. Therefore, the amount of money that can be deducted with Pramai Zero does not change, but those with an annual income of 8.5 million yen or more pay more with this revision. I don't have an annual income of 8.5 million, but personally, I'm not happy with this revision because I'm not motivated to think that even if I do my best and my annual income increases, I'll be deducted a lot from income tax. .. The amount after deduction of salary income calculated in this way is returned as ʻincome. This value of ʻincome is often used in other class functions, so I assign it to self.income in the constructor.

Tax.income()


def income(self):
    """
Calculation of salary income deduction,Return the deduction amount with income as an argument
After 2020, the deduction has decreased by 100,000 and the income tax has increased by 100,000, so there is no real change.
However, for 8.5 million or more, the amount of deduction for salary income has decreased, so the tax has actually increased.
    """
    employment_income_deduction = 0

    if self.gross_salary < 550000:
        employment_income_deduction = self.gross_salary

    elif self.gross_salary <1800000:
        employment_income_deduction = self.gross_salary * 0.4 - 100000

    elif self.gross_salary <3600000:
        employment_income_deduction = self.gross_salary*0.3 + 80000

    elif self.gross_salary <6600000:
        employment_income_deduction = self.gross_salary*0.2 + 440000

    elif self.gross_salary <8500000:
        employment_income_deduction = self.gross_salary*0.1 + 1100000

    else:
        employment_income_deduction = 1950000

    income = self.gross_salary - employment_income_deduction
    return income

Social insurance premiums

Next, let's look at ** social insurance premiums **. This is ** welfare pension **, ** employment insurance **, etc., which are separate from taxes. The formula is written below, but there are ** health insurance rates **, ** exemption insurance rates **, and ** employment insurance rates **. The final premium is calculated by multiplying the income by the ** premium rate ** calculated from these. ** Health insurance rate ** varies depending on the region, but in Tokyo it is 9.87%, so self.health_insurance_premium_rate contains 0.0987 by default. The exemption premium rate determines how much the welfare pension is exempted. The exemption premium rate tends to increase with age, but on average it is around 0.4% so self.rebate_contribution_rate is 0.04 by default. These values can be set individually in the constructor. These values are divided by two because they share half with the company. The ** employment insurance premium rate ** is uniformly 0.3%, so add them together to calculate the insurance premium rate.

Tax.social_insurance_preium()


def social_insurance_premium(self):
    """
Insurance premium calculation
Insurance premium rate = Health insurance premium rate/2
    + (Welfare pension premium rate 18.3%-Exemption premium rate)/2
    +Employment insurance premium rate 0.3%
    """
    #Insurance premium rate
    insurance_premium_rate = (self.health_insurance_premium_rate)/2 \
                             + (0.183 - self.rebate_contribution_rate)/2 \
                             + 0.003

    #Social insurance premiums=Annual income x premium rate
    social_insurance_premium = self.gross_salary*insurance_premium_rate
    return social_insurance_premium

income tax

Next is ** income tax **. ** Income tax ** first subtracts the ** basic deduction ** from the income calculated by ʻincome (). Until now, the ** basic deduction ** was a flat rate of 380,000 yen, but from 2020 it has been raised to 480,000 yen. (As mentioned above, the ** salary income deduction ** has been reduced by 100,000 yen.) However, as a new rule added from this time, if the annual income exceeds 24 million, the amount of basic deduction will gradually decrease, and if it exceeds 25 million yen, it will be zero. In addition, the dependent deduction (dependents_deduction) and the disability deduction (handicapped_deduction) are deducted from it. Both dependents_deduction and handicapped_deduction` are set to zero unless otherwise specified in the constructor.

The income after various deductions is set as target_of_income_tax, and ** income tax ** is calculated from this. The higher the annual income, the more you can get. The ** income tax rate ** (self.income_tax_rate) that appears here is also used for the calculation when you make ** hometown tax payment **.

Tax.income_tax()


def income_tax(self):
    """
Income tax calculation
    """

    #Deduction for dependents on income tax
    dependents_deduction = self.high_school_student * 480000 + self.college_student * 630000
    #Deduction for persons with disabilities in income tax
    handicapped_deduction = self.handicapped * 260000
    #The basic deduction was 380,000 yen until 2019, but from 2020 it will be 480,000 yen. However, if it exceeds 20 million, it will gradually decrease.
    basic_deduction = 0
    if self.income < 24000000:
        basic_deduction = 480000
    elif self.income < 24500000:
        basic_deduction = 320000
    elif self.income < 25000000:
        basic_deduction = 160000

    #Amount subject to income tax, income minus deductions and insurance premiums
    target_of_income_tax = (self.income \
                            - self.social_insurance_premium() \
                            - self.spousal_deduction() \
                            - dependents_deduction \
                            - handicapped_deduction \
                            - basic_deduction)
    #Income tax rate and deduction amount by annual income
    if target_of_income_tax < 1950000:
        self.income_tax_rate = 0.05
        deduction = 0

    elif target_of_income_tax < 3300000:
        self.income_tax_rate = 0.1
        deduction = 97500

    elif target_of_income_tax < 6950000:
        self.income_tax_rate = 0.2
        deduction = 427500

    elif target_of_income_tax < 9000000:
        self.income_tax_rate = 0.23
        deduction = 636000

    elif target_of_income_tax < 18000000:
        self.income_tax_rate = 0.33
        deduction = 1536000

    elif target_of_income_tax < 40000000:
        self.income_tax_rate = 0.40
        deduction = 2796000

    else:
        self.income_tax_rate = 0.45
        deduction = 479.6

    #Income tax calculation
    income_tax = target_of_income_tax * self.income_tax_rate - deduction
    #If the income tax becomes negative, make it zero
    if income_tax <= 0:
        income_tax = 0
    return income_tax

Resident tax

The calculation of ** residence tax ** is similar to income tax, so I think it will not be so difficult if you understand the mechanism of income tax. The amount of deduction is different from ** income tax **, and it is also different in that tax is levied on the income of the previous year. (There is no particular distinction between the previous year and this year in the program)

Tax.inhabitant_tax()


def inhabitant_tax(self):
    """
Resident tax calculation,Calculate residence tax with taxable income as an argument
    """

    #Deduction for dependents in residence tax
    dependents_deduction = self.high_school_student * 330000 + self.college_student * 450000
    #Deduction for persons with disabilities in residence tax
    handicapped_deduction = self.handicapped * 270000
    #Same as basic deduction and income tax, changed from 2020
    basic_deduction = 0
    if self.income < 24000000:
        basic_deduction = 430000
    elif self.income < 24500000:
        basic_deduction = 190000
    elif self.income < 25000000:
        basic_deduction = 150000

    #Various deductions and basic deductions (430,000 yen) are deducted from income, and the tax rate is 10%multiply
    #Add the per capita rate of 5,000 yen and subtract the adjustment deduction of 2,500 yen.
    inhabitant_tax = (self.income
                      - self.social_insurance_premium()
                      - self.spousal_deduction()
                      - dependents_deduction
                      - handicapped_deduction
                      - basic_deduction) * 0.1 + 5000 - 2500

    #If the calculated residence tax becomes negative, it will be zero.
    if inhabitant_tax <=0:
        inhabitant_tax = 0
    return inhabitant_tax

Take home

At this point, you can calculate the ** take-home **. Subtract the ** social insurance premiums, income tax, and residence tax ** that have been calculated so far from the face value income.

Tax.net_salary()


def net_salary(self):
    """
Take-home calculation, income minus income tax, residence tax, social insurance premiums
    """
    total_tax = self.inhabitant_tax() + self.income_tax()
    net_salary = self.gross_salary - total_tax - self.social_insurance_premium()
    return net_salary

Hometown tax payment

The coat color is a little different from the ones that have appeared so far, but we have also implemented ** Furusato Tax Payment **. ** Furusato Tax Payment ** is a system where you can receive gifts by donating to local areas. At that time, ** income tax and inhabitant tax ** can be reduced according to the donation. Up to the maximum amount, only 2000 yen of the donated amount is paid by yourself, and all the remaining amount can be deducted. The following function calculates the maximum amount of donations that can be fully deducted. Please refer to the comments and code for the calculation formula.

Tax.max_hurusato_donation()


    def max_hurusato_donation(self):
        """
Calculation of the upper limit that can be fully deducted at the hometown tax payment of 2000 yen
In other words, the amount of return minus 2000 yen will be deducted from income tax and residence tax.
        """
        #Resident tax income percent(=Resident tax)Calculate from
        #Upper limit of hometown tax deduction
        hurusato_deduction = self.inhabitant_tax() * 0.2

        # (Deduction amount) =(Donation amount-2000)×(90%-Income tax rate x 1.021)
        # (Donation amount) = (Deduction amount)/(90%-Income tax rate x 1.021)+2000
        max_hurusato_donation = hurusato_deduction / (0.9 - self.income_tax_rate * 1.021) + 2000
        return max_hurusato_donation

Visualization

Does it make sense to write in Python with just this? So I will try to visualize it using matplotlib. First, ʻimport` the required library.

Tax.show_ipynb


# coding: utf-8
import sys, os
sys.path.append(os.pardir)  #Settings for importing files in the parent directory
from common.tax import Tax
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
%matplotlib inline
pd.options.display.precision = 0
plt.rcParams['font.family'] = 'AppleGothic'

Calculate the annual income from 2 to 12 million yen in 1 million yen increments and plunge into list.

Tax.show_ipynb2


#Annual face value, 200-1,Up to 2 million in 10,000 increments
gross_salaries = [i for i in range(2000000,12010000, 1000000)]
#income
incomes = []
#tax
total_taxes = []
#Resident tax
inhabitant_taxes = []
#income tax
income_taxes = []
#Social insurance premiums (=Social insurance deduction)
social_insurance_premiums = []
#Take-home annual income
net_salaries = []
#Hometown tax deduction upper limit and donation amount at that time
max_hurusato_donation = []

for gross_salary in gross_salaries:
    tax = Tax(gross_salary)

    #Add value to list
    incomes.append(tax.income)
    total_taxes.append(tax.income_tax() + tax.inhabitant_tax())
    inhabitant_taxes.append(tax.inhabitant_tax())
    income_taxes.append(tax.income_tax())
    social_insurance_premiums.append(tax.social_insurance_premium())
    net_salaries.append(tax.net_salary())
    max_hurusato_donation.append(tax.max_hurusato_donation() - 2000) #Subtract 2000 yen at your own expense

Store in dataframe. You can see the contents with df.head ().

Tax.show_ipynb3


df = pd.DataFrame()
df['annual income'] = gross_salaries
df['Take home'] = net_salaries
df['tax'] = total_taxes
df['Resident tax'] = inhabitant_taxes
df['income tax'] = income_taxes
df['Social insurance premiums'] = social_insurance_premiums
df['Hometown tax deduction upper limit'] = max_hurusato_donation

Visualize with a bar graph.

Tax.show_ipynb4



df.index = ['200', '300', '400', '500', '600', '700',  '800', '900', '1000', '1100', '1200']
plt.figure(figsize=(12,7))
plt.rcParams["font.size"] = 14
plt.grid(axis='y')
yticks = [0, 1000000, 2000000, 3000000, 4000000, 5000000, 6000000, 7000000, 8000000, 9000000, 10000000, 11000000, 12000000]
plt.ylim(0, 12500000)
plt.yticks(yticks)
plt.bar(df.index, df['Take home'])
plt.bar(df.index, df['tax'], bottom= df['Take home'])
plt.bar(df.index, df['Hometown tax deduction upper limit'], bottom= df['Take home'] + df['tax'] - df['Hometown tax deduction upper limit'])
plt.bar(df.index, df['Social insurance premiums'], bottom= df['Take home'] + df['tax'])
plt.xlabel('Salary (yen*10000)')
plt.ylabel('Breakdown (yen)')
plt.title('')
plt.legend(['net-salary', 'tax','hurusato_deduction', 'insurance'])
plt.show()

ダウンロード (1).png

** Graph description **

――The horizontal axis is the annual income, the vertical axis is blue, the tax is (orange + green), the green is the upper limit that can be deducted from the hometown tax, and the red is the social insurance premium.

** My impression of seeing the graph **

--Social insurance premiums are higher than taxes up to an annual income of about 8 million yen, but above that, taxes are higher. ――It turns out that Japan is now supported by high-paying taxpayers (= high-income people) ――Is it possible to get a little over 7 million even with an annual income of 10 million yen? ――You should pay your hometown tax

Summary

--I made a class to calculate taxes and take-homes using Python and visualized it. ――If there is an error in calculation or interpretation, I will fix it at any time, so if you find one, I would be grateful if you could let me know.

Recommended Posts

[2020 version] Let Python do all the tax and take-home calculations
Receive the form in Python and do various things
(◎◎) {Let's let Python do the boring things) ......... (Hey? Let's let Python do the homework} (゜) (゜)
[Python beginner] How do I develop and execute Python after all?
"Let Python do the boring things" exercise ~ Command line mailer ~
The websocket of toio (nodejs) and python / websocket do not connect.
[Python] df Read and do the first memo (NaN confirmation etc.)
Let the Japanese BERT model do the center test and sentence generation
MoneyForward Cloud Automates time stamping [Let's let Python do the trouble]
What should I do with the Python directory structure after all?
[Python] Let's master all and any
pyenv-change the python version of virtualenv
How to get the Python version
[Code] Module and Python version output
Change the Python version of Homebrew
Faster Fibonacci sequence calculations (Python version)
About the virtual environment of python version 3.7
Let Heroku do background processing with Python
[Python] Try pydash of the Python version of lodash
Academia Potter and the Mysterious Python Pass
Python open and io.open are the same
[Python] Combine all the elements in the array
I compared the speed of regular expressions in Ruby, Python, and Perl (2013 version)
Examples and solutions that the Python version specified in pyenv does not run