Repository navigation
Expand file tree
/
Copy pathhomes.js
More file actions
406 lines (347 loc) · 11.4 KB
/
Copy pathhomes.js
File metadata and controls
406 lines (347 loc) · 11.4 KB
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
// Global variables
let processedData = [];
let inflationData = [];
let buyDate = null;
let buyPrice = null;
let sellDate = null;
let sellPrice = null;
let xScale, yScale;
let svg, g, line, buyMarker, sellMarker, buyText, sellText;
let buyTooltip, sellTooltip;
// Load and process data
Promise.all([d3.csv("MSPUS.csv"), d3.csv("yearly_inflation.csv")]).then(
([housingData, inflation]) => {
processedData = housingData.map((d) => ({
date: new Date(d.observation_date),
value: +d.MSPUS,
}));
inflationData = inflation.map((d) => {
const date = new Date(d.Date);
return {
date: date,
year: date.getFullYear(),
value: +d.Value,
};
});
buyDate = processedData[0].date;
buyPrice = processedData[0].value;
const midIndex = Math.floor(processedData.length / 2);
sellDate = processedData[midIndex].date;
sellPrice = processedData[midIndex].value;
createChart();
}
);
function createChart() {
d3.select("#homes_chart").selectAll("*").remove();
const margin = { top: 40, right: 40, bottom: 60, left: 80 };
const width = 800 - margin.left - margin.right;
const height = 500 - margin.top - margin.bottom;
svg = d3
.select("#homes_chart")
.append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom);
g = svg
.append("g")
.attr("transform", `translate(${margin.left},${margin.top})`);
xScale = d3
.scaleTime()
.domain(d3.extent(processedData, (d) => d.date))
.range([0, width]);
yScale = d3
.scaleLinear()
.domain(d3.extent(processedData, (d) => d.value))
.nice()
.range([height, 0]);
line = d3
.line()
.x((d) => xScale(d.date))
.y((d) => yScale(d.value))
.curve(d3.curveMonotoneX);
g.append("g")
.attr("transform", `translate(0,${height})`)
.call(d3.axisBottom(xScale))
.append("text")
.attr("x", width / 2)
.attr("y", 50)
.attr("fill", "black")
.style("text-anchor", "middle")
.text("Date");
g.append("g")
.call(d3.axisLeft(yScale))
.append("text")
.attr("transform", "rotate(-90)")
.attr("y", -60)
.attr("x", -height / 2)
.attr("fill", "black")
.style("text-anchor", "middle")
.text("Price in USD");
g.append("text")
.attr("x", width / 2)
.attr("y", -10)
.attr("text-anchor", "middle")
.style("font-size", "18px")
.style("font-weight", "bold")
.text("Median Housing Prices in the US Over Time");
g.append("path")
.datum(processedData)
.attr("fill", "none")
.attr("stroke", "steelblue")
.attr("stroke-width", 2)
.attr("d", line);
const buyGroup = g.append("g").attr("class", "buy-marker");
buyMarker = buyGroup
.append("path")
.attr("d", d3.symbol().type(d3.symbolStar).size(400)())
.attr("fill", "green")
.attr("stroke", "darkgreen")
.attr("stroke-width", 2)
.attr("transform", `translate(${xScale(buyDate)},${yScale(buyPrice)})`)
.style("cursor", "grab")
.call(
d3
.drag()
.on("start", dragStarted)
.on("drag", dragged)
.on("end", dragEnded)
);
buyText = buyGroup
.append("text")
.attr("x", xScale(buyDate))
.attr("y", yScale(buyPrice) - 25)
.attr("text-anchor", "middle")
.attr("fill", "green")
.style("font-size", "16px")
.style("font-weight", "bold")
.text("Buy");
buyTooltip = buyGroup.append("g").attr("class", "buy-tooltip");
buyTooltip
.append("rect")
.attr("x", xScale(buyDate) - 85)
.attr("y", yScale(buyPrice) - 85)
.attr("width", 170)
.attr("height", 40)
.attr("fill", "white")
.attr("stroke", "green")
.attr("stroke-width", 2)
.attr("rx", 5);
updateTooltip(buyTooltip, buyDate, buyPrice);
const sellGroup = g.append("g").attr("class", "sell-marker");
sellMarker = sellGroup
.append("path")
.attr("d", d3.symbol().type(d3.symbolStar).size(400)())
.attr("fill", "red")
.attr("stroke", "darkred")
.attr("stroke-width", 2)
.attr("transform", `translate(${xScale(sellDate)},${yScale(sellPrice)})`)
.style("cursor", "grab")
.call(
d3
.drag()
.on("start", dragStarted)
.on("drag", dragged)
.on("end", dragEnded)
);
sellText = sellGroup
.append("text")
.attr("x", xScale(sellDate))
.attr("y", yScale(sellPrice) - 25)
.attr("text-anchor", "middle")
.attr("fill", "red")
.style("font-size", "16px")
.style("font-weight", "bold")
.text("Sell");
sellTooltip = sellGroup.append("g").attr("class", "sell-tooltip");
sellTooltip
.append("rect")
.attr("x", xScale(sellDate) - 85)
.attr("y", yScale(sellPrice) - 85)
.attr("width", 170)
.attr("height", 40)
.attr("fill", "white")
.attr("stroke", "red")
.attr("stroke-width", 2)
.attr("rx", 5);
updateTooltip(sellTooltip, sellDate, sellPrice);
updateCostDisplays();
}
function formatTooltip(date, price) {
const dateStr = d3.timeFormat("%Y-%m-%d")(date);
const priceStr = d3.format("$,.0f")(price);
return `${dateStr}\n${priceStr}`;
}
function updateTooltip(tooltip, date, price) {
const dateStr = d3.timeFormat("%Y-%m-%d")(date);
const priceStr = d3.format("$,.0f")(price);
tooltip.selectAll("text").remove();
tooltip
.append("text")
.attr("x", xScale(date))
.attr("y", yScale(price) - 75)
.attr("text-anchor", "middle")
.attr("fill", "black")
.style("font-size", "13px")
.text(dateStr);
tooltip
.append("text")
.attr("x", xScale(date))
.attr("y", yScale(price) - 60)
.attr("text-anchor", "middle")
.attr("fill", "black")
.style("font-size", "13px")
.style("font-weight", "bold")
.text(priceStr);
}
function dragStarted(event) {
d3.select(this).style("cursor", "grabbing");
}
function dragged(event) {
const x = event.x;
const y = event.y;
const date = xScale.invert(x);
const price = yScale.invert(y);
const closest = findClosestPoint(date);
const isBuy = d3.select(this).attr("fill") === "green";
if (isBuy) {
buyDate = closest.date;
buyPrice = closest.value;
buyMarker.attr(
"transform",
`translate(${xScale(buyDate)},${yScale(buyPrice)})`
);
buyText.attr("x", xScale(buyDate)).attr("y", yScale(buyPrice) - 25);
buyTooltip
.select("rect")
.attr("x", xScale(buyDate) - 85)
.attr("y", yScale(buyPrice) - 85);
updateTooltip(buyTooltip, buyDate, buyPrice);
} else {
sellDate = closest.date;
sellPrice = closest.value;
sellMarker.attr(
"transform",
`translate(${xScale(sellDate)},${yScale(sellPrice)})`
);
sellText.attr("x", xScale(sellDate)).attr("y", yScale(sellPrice) - 25);
sellTooltip
.select("rect")
.attr("x", xScale(sellDate) - 85)
.attr("y", yScale(sellPrice) - 85);
updateTooltip(sellTooltip, sellDate, sellPrice);
}
updateCostDisplays();
}
function dragEnded(event) {
d3.select(this).style("cursor", "grab");
}
function findClosestPoint(targetDate) {
return processedData.reduce((closest, d) => {
const diff = Math.abs(targetDate - d.date);
const closestDiff = Math.abs(targetDate - closest.date);
return diff < closestDiff ? d : closest;
});
}
// Filter inflation data for the period between buy and sell dates
function filterInflationData(buyDate, sellDate) {
const buyYear = buyDate.getFullYear();
const sellYear = sellDate.getFullYear();
return inflationData.filter((d) => {
return d.year >= buyYear && d.year <= sellYear;
});
}
// Calculate cumulative inflation
function calculateCumulativeInflation(filteredInflationData) {
if (!filteredInflationData || filteredInflationData.length === 0) {
return 1;
}
let cumulativeInflation = 1;
for (let i = 0; i < filteredInflationData.length; i++) {
cumulativeInflation *= 1 + filteredInflationData[i].value / 100;
}
return cumulativeInflation;
}
// Calculate real return for housing investment
function calculateHousingRealReturn(buyPrice, sellPrice, buyDate, sellDate) {
if (!buyPrice || !sellPrice || !buyDate || !sellDate) {
return 0;
}
if (buyPrice === 0) {
return 0;
}
const filteredInflation = filterInflationData(buyDate, sellDate);
if (!filteredInflation || filteredInflation.length === 0) {
return 0;
}
const cumulativeInflation = calculateCumulativeInflation(filteredInflation);
const nominalReturnVal = sellPrice / buyPrice - 1;
const realReturn = (1 + nominalReturnVal) / cumulativeInflation - 1;
return realReturn * 100;
}
function updateCostDisplays() {
if (!buyPrice) return;
const regularCost = buyPrice;
const expensiveCost = buyPrice * 2;
const veryExpensiveCost = buyPrice * 3;
const formatCost = (cost) => d3.format("$,.0f")(cost);
const regularEl = document.getElementById("regular_home_cost");
const expensiveEl = document.getElementById("expensive_home_cost");
const veryExpensiveEl = document.getElementById("very_expensive_home_cost");
const regularProfitEl = document.getElementById("regular_home_profit");
const expensiveProfitEl = document.getElementById("expensive_home_profit");
const veryExpensiveProfitEl = document.getElementById(
"very_expensive_home_profit"
);
const housingRealReturnEl = document.getElementById("housing_real_return");
const regularHomeBox = document.getElementById("buy_regular_home");
const expensiveHomeBox = document.getElementById("buy_expensive_home");
const veryExpensiveHomeBox = document.getElementById(
"buy_very_expensive_home"
);
// Calculate growth factor based on how much the regular median price grew
const growthFactor = sellPrice / buyPrice;
const regularProfit = sellPrice - regularCost;
// Expensive house grows by same percentage: (2 * buyPrice) * growthFactor - (2 * buyPrice)
const expensiveProfit = expensiveCost * growthFactor - expensiveCost;
// Very expensive house grows by same percentage: (3 * buyPrice) * growthFactor - (3 * buyPrice)
const veryExpensiveProfit =
veryExpensiveCost * growthFactor - veryExpensiveCost;
// Calculate real return (same for all since they all grow by the same percentage)
const realReturn = calculateHousingRealReturn(
regularCost,
regularCost * growthFactor,
buyDate,
sellDate
);
if (regularEl) {
regularEl.textContent = formatCost(regularCost);
regularProfitEl.textContent = formatCost(regularProfit);
}
if (expensiveEl) {
expensiveEl.textContent = formatCost(expensiveCost);
expensiveProfitEl.textContent = formatCost(expensiveProfit);
}
if (veryExpensiveEl) {
veryExpensiveEl.textContent = formatCost(veryExpensiveCost);
veryExpensiveProfitEl.textContent = formatCost(veryExpensiveProfit);
}
// Update real return display
if (housingRealReturnEl) {
housingRealReturnEl.textContent = `${realReturn.toFixed(2)} %`;
}
// Update background colors based on profit and real return
if (regularProfit < 0 || realReturn < 0) {
regularHomeBox.style.backgroundColor = "rgba(255, 200, 200, 0.4)";
} else {
regularHomeBox.style.backgroundColor = "rgba(200, 255, 200, 0.4)";
}
if (expensiveProfit < 0 || realReturn < 0) {
expensiveHomeBox.style.backgroundColor = "rgba(255, 200, 200, 0.4)";
} else {
expensiveHomeBox.style.backgroundColor = "rgba(200, 255, 200, 0.4)";
}
if (veryExpensiveProfit < 0 || realReturn < 0) {
veryExpensiveHomeBox.style.backgroundColor = "rgba(255, 200, 200, 0.4)";
} else {
veryExpensiveHomeBox.style.backgroundColor = "rgba(200, 255, 200, 0.4)";
}
}