forked from PolicyEngine/us-marriage-incentive
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
263 lines (224 loc) · 11.1 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
import streamlit as st
import plotly.express as px
from policyengine_us import Simulation
from policyengine_core.charts import format_fig
from policyengine_us.variables.household.demographic.geographic.state_code import (
StateCode,
)
# Create a function to get net income for the household, married or separate.
def get_net_incomes(state_code, head_employment_income, spouse_employment_income, children_ages = {}):
# Tuple of net income for separate and married.
net_income_married = get_net_income(
state_code, head_employment_income, spouse_employment_income, children_ages
)
net_income_head = get_net_income(state_code, head_employment_income, None,children_ages)
net_income_spouse = get_net_income(state_code, spouse_employment_income, None, children_ages={})
return net_income_married, net_income_head + net_income_spouse
DEFAULT_AGE = 40
def get_programs(state_code, head_employment_income, spouse_employment_income=None, children_ages = {}):
# Start by adding the single head.
situation = {
"people": {
"you": {
"age": {"2023": DEFAULT_AGE},
"employment_income": {"2023": head_employment_income},
}
}
}
members = ["you"]
if spouse_employment_income is not None:
situation["people"]["your partner"] = {
"age": {"2023": DEFAULT_AGE},
"employment_income": {"2023": spouse_employment_income},
}
# Add your partner to members list.
members.append("your partner")
for key, value in children_ages.items():
situation["people"][f"child {key}"] = {
"age": {"2023": value}
}
# Add child to members list.
members.append(f"child {key}")
# Create all parent entities.
situation["families"] = {"your family": {"members": members}}
situation["marital_units"] = {"your marital unit": {"members": members}}
situation["tax_units"] = {"your tax unit": {"members": members}}
situation["spm_units"] = {"your spm_unit": {"members": members}}
situation["households"] = {
"your household": {"members": members, "state_name": {"2023": state_code}}
}
simulation = Simulation(situation=situation)
simulation = Simulation(situation=situation)
household_net_income = int(simulation.calculate("household_net_income", 2023)[0])
household_benefits = int(simulation.calculate("household_benefits", 2023)[0])
household_refundable_tax_credits = int(simulation.calculate("household_refundable_tax_credits", 2023)[0])
household_tax_before_refundable_credits = int(simulation.calculate("household_tax_before_refundable_credits", 2023)[0])
return [household_net_income ,household_benefits ,household_refundable_tax_credits,household_tax_before_refundable_credits]
def get_categorized_programs(state_code, head_employment_income, spouse_employment_income, children_ages):
programs_married = get_programs(state_code, head_employment_income, spouse_employment_income, children_ages)
programs_head = get_programs(state_code, head_employment_income, None, children_ages)
programs_spouse = get_programs(state_code, spouse_employment_income,None, children_ages)
return [programs_married, programs_head, programs_spouse]
# Create a function to get net income for household
def get_net_income(state_code, head_employment_income, spouse_employment_income=None, children_ages = {}):
# Start by adding the single head.
situation = {
"people": {
"you": {
"age": {"2023": DEFAULT_AGE},
"employment_income": {"2023": head_employment_income},
}
}
}
members = ["you"]
if spouse_employment_income is not None:
situation["people"]["your partner"] = {
"age": {"2023": DEFAULT_AGE},
"employment_income": {"2023": spouse_employment_income},
}
# Add your partner to members list.
members.append("your partner")
for key, value in children_ages.items():
situation["people"][f"child {key}"] = {
"age": {"2023": value}
}
# Add child to members list.
members.append(f"child {key}")
# Create all parent entities.
situation["families"] = {"your family": {"members": members}}
situation["marital_units"] = {"your marital unit": {"members": members}}
situation["tax_units"] = {"your tax unit": {"members": members}}
situation["spm_units"] = {"your spm_unit": {"members": members}}
situation["households"] = {
"your household": {"members": members, "state_name": {"2023": state_code}}
}
simulation = Simulation(situation=situation)
return simulation.calculate("household_net_income", 2023)[0]
#Streamlit heading and description
header = st.header("Marriage Incentive Calculator")
header_description = st.write("This application evaluates marriage penalties and bonuses of couples, based on state and individual employment income")
repo_link = st.markdown("This application utilizes <a href='https://github.com/PolicyEngine/us-marriage-incentive'>the policyengine API</a>", unsafe_allow_html=True)
# Create Streamlit inputs for state code, head income, and spouse income.
options = [s.value for s in StateCode]
state_code = st.selectbox("State Code", options)
head_employment_income = st.number_input("Head Employment Income", step=20000, value=0)
spouse_employment_income = st.number_input("Spouse Employment Income", step=10000, value=0)
num_children = st.number_input("Number of Children", 0)
children_ages = {}
for num in range(1,num_children + 1):
children_ages[num] = st.number_input(f"Child {num} Age", 0)
#submit button
submit = st.button("Calculate")
# Get net incomes.
if submit:
programs = get_categorized_programs(state_code, head_employment_income, spouse_employment_income, children_ages)
married_programs = programs[0]
formatted_married_programs = list(map(lambda x: "${:,}".format(round(x)), married_programs))
head_separate = programs[1]
spouse_separate = programs[2]
separate = [x + y for x, y in zip(head_separate, spouse_separate)]
formatted_separate = list(map(lambda x: "${:,}".format(round(x)), separate))
head_separate = programs[1]
delta = [x - y for x, y in zip(married_programs, separate)]
delta_percent = [(x - y) / x if y != 0 else 0 for x, y in zip(married_programs, separate)]
formatted_delta = list(map(lambda x: "${:,}".format(round(x)), delta))
formatted_delta_percent = list(map(lambda x: "{:.1%}".format(x), delta_percent))
programs = ["Net Income", "Benefits", "Refundable tax credits", "Taxes before refundable credits"]
# Determine marriage penalty or bonus, and extent in dollars and percentage.
marriage_bonus = married_programs[0] - separate[0]
marriage_bonus_percent = marriage_bonus / married_programs[0]
def summarize_marriage_bonus(marriage_bonus):
# Create a string to summarize the marriage bonus or penalty.
return (
f"If you file separately, your combined net income will be ${abs(marriage_bonus):,.2f} "
f"{'less' if marriage_bonus > 0 else 'more'} "
f"({abs(marriage_bonus_percent):.1%}) than if you file together."
)
if marriage_bonus > 0:
st.write("You face a marriage BONUS.")
elif marriage_bonus < 0:
st.write("You face a marriage PENALTY.")
else:
st.write("You face no marriage penalty or bonus.")
st.write(summarize_marriage_bonus(marriage_bonus))
# Sample data
table_data = {
'Program': programs,
'Not Married': formatted_separate,
'Married': formatted_married_programs,
'Delta': formatted_delta,
'Delta Percentage': formatted_delta_percent
}
# Display the table in Streamlit
st.dataframe(table_data, hide_index=True)
def check_child_influence():
salary_ranges = [10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000]
data = []
for i in range(len(salary_ranges)):
temp_data = []
for j in range(len(salary_ranges)):
head_employment_income = salary_ranges[i]
spouse_employment_income = salary_ranges[j]
# Assuming get_net_incomes now returns a tuple (net_income_married, net_income_head_spouse)
net_income_married, net_income_separate = get_net_incomes(
state_code, head_employment_income, spouse_employment_income
)
marriage_bonus = net_income_married - net_income_separate
temp_data.append(marriage_bonus)
data.append(temp_data)
return data
def get_chart():
# Function to calculate the input data (replace with your actual data calculation)
# Set numerical values for x and y axes
x_values = [10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000]
y_values = [10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000]
# Display loading spinner while calculating data
with st.spinner("Calculating Heatmap... May take 90 seconds"):
# Calculate data (replace with your actual data calculation)
data = check_child_influence()
abs_max = max(abs(min(map(min, data))), abs(max(map(max, data))))
z_min = -abs_max
z_max = abs_max
color_scale = [
(0, '#616161'),
(0.5, '#FFFFFF'),
(1, '#2C6496')
]
# Display the chart once data calculation is complete
fig = px.imshow(data,
labels=dict(x="Head Employment Income", y="Spouse Employment Income", color="Bonus"),
x=x_values,
y=y_values,
zmin=z_min,
zmax=z_max,
color_continuous_scale=color_scale,
origin='lower'
)
fig.update_xaxes(side="bottom")
fig.update_layout(
xaxis=dict(
tickmode='array',
tickvals=[10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000],
ticktext=["{}k".format(int(val/1000)) for val in [10000,20000, 30000,40000,50000, 60000, 70000, 80000]],
showgrid=True,
zeroline=False,
title=dict(text='Head Employment Income', standoff=15),
),
yaxis=dict(
tickmode='array',
tickvals=[10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000],
ticktext=["{}k".format(int(val/1000)) for val in [10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000]],
showgrid=True,
zeroline=False,
title=dict(text='Spouse Employment Income', standoff=15),
scaleanchor="x",
scaleratio=1,
)
)
fig.update_layout(height=600, width=800)
# Add header
st.markdown("<h3 style='text-align: center; color: black;'>Marriage Incentive and Penalty Analysis</h3>", unsafe_allow_html=True)
fig = format_fig(fig)
# Display the chart
st.plotly_chart(fig, use_container_width=True)
get_chart()