Published
Edited
Feb 24, 2020
4 stars
Insert cell
Insert cell
chart = {
const svg = d3.select(DOM.svg(width, height + bottomBarHeight + margin.bottom * 2));
const initialHoldings = {quantity: 100, price: 90}
svg.append("g").call(xAxis);
svg.append("g").call(xAxisBuySell);
svg.append("g").call(yAxis);
svg.append("g").call(yAxis2);
svg.append('line')
.attr('x1', margin.left)
.attr('y1', buySellY(0))
.attr('x2', width - margin.right)
.attr('y2', buySellY(0))
.attr('stroke', '#1b1e23')
.attr('stroke-opacity', 0.2)
svg.append("g")
.selectAll("rect")
.data(transactions)
.join("rect")
.attr("x", (d, i) => x(d.date))
.attr("y", d => d.value > 0 ? buySellY(d.value) : buySellY(d.value) - Math.abs(buySellY(0) - buySellY(d.value)))
.attr("height", d => Math.abs(buySellY(0) - buySellY(d.value)))
.attr("width", 10)
.attr("fill", d => d.value > 0 ? 'green' : 'red')
.on("click", d => setDatum(d))
// Make price chart
const positionSize = 2
const [notHolding, holding] = _.partition(data, ({date}) =>
buyDatum.quantity > 0 ? date < buyDatum.date : date > buyDatum.date)
const priceChartSegments = [
{color: 'rgba(27, 30, 35, 0.6)', data: notHolding, dashed: true},
{color: 'green', data: holding, dashed: false},
]
priceChartSegments.forEach(({data, color, dashed}) =>
svg.append("path")
.datum(data)
.attr("fill", "none")
.attr("stroke", color)
.attr("stroke-width", dashed ? 1 : positionSize)
.attr("stroke-linejoin", "round")
.attr("stroke-linecap", "round")
.attr("d", d3.line()
.x(d => x(d.date))
.y(d => y(d.value)))
.style('stroke-dasharray', dashed ? '3,3' : null)
)
;[buyDatum].forEach(bD => {
// pre
const preColor = bD.quantity > 0 ? 'green' : 'rgba(27, 30, 35, 0.6)'
svg.append('line')
.attr('x1', margin.left)
.attr('y1', y(bD.value))
.attr('x2', x(bD.date))
.attr('y2', y(bD.value))
.attr('stroke', preColor)
.attr('stroke-width', bD.quantity > 0 ? positionSize : 1)
.style("stroke-dasharray", '3,3')

// post
const postColor = bD.quantity > 0 ? 'rgba(27, 30, 35, 0.6)' : 'green'
svg.append('line')
.attr('x1', x(bD.date))
.attr('y1', y(bD.value))
.attr('x2', width - margin.right)
.attr('y2', y(bD.value))
.attr('stroke', postColor)
.attr('stroke-width', bD.quantity > 0 ? 1 : positionSize)
.style("stroke-dasharray", '3,3')
})
// Make right hand side tag for transaction
if (buyDatum.quantity < 0) {
svg.append("rect")
.attr('x', width - margin.right)
.attr('y', y(buyDatum.value) - 6)
.attr('fill', buyDatum.quantity > 0 ? 'black' : 'green')
.attr('width', `${margin.right}px`)
.attr('height', '12px')

svg.append("text")
.attr('x', width - margin.right + 6)
.attr('y', y(buyDatum.value))
.attr('font-size', '10px')
.attr('fill', 'white')
.attr("dy", ".32em")
.attr('text-anchor', 'start')
.text(format(Math.abs(buyDatum.quantity) * buyDatum.value));
}
// Make left hand side tag for transaction
if (buyDatum.quantity > 0) {
svg.append("rect")
.attr('x', 0)
.attr('y', y(buyDatum.value) - 6)
.attr('fill', 'green')
.attr('width', `${margin.right}px`)
.attr('height', '12px')

svg.append("text")
.attr('x', margin.right - 6)
.attr('y', y(buyDatum.value))
.attr('font-size', '10px')
.attr('fill', 'white')
.attr("dy", ".32em")
.attr('text-anchor', 'end')
.text(format(Math.abs(buyDatum.quantity) * buyDatum.value));
}
// Make tag for security
if (buyDatum.quantity > 0) {
svg.append("rect")
.attr('x', width - margin.right)
.attr('y', y(_.last(data).value) - 6)
.attr('fill', 'green')
.attr('width', `${margin.right}px`)
.attr('height', '12px')

svg.append("text")
.attr('x', width - margin.right + 6)
.attr('y', y(_.last(data).value))
.attr('font-size', '10px')
.attr('fill', 'white')
.attr("dy", ".32em")
.attr('text-anchor', 'start')
.text(format(
buyDatum.quantity * _.last(data).value
));
}
// Make tag for initial holdings
if (buyDatum.quantity < 0) {
svg.append("rect")
.attr('x', 0)
.attr('y', y(data[0].value) - 6)
.attr('fill', 'green')
.attr('width', `${margin.left}px`)
.attr('height', '12px')

svg.append("text")
.attr('x', margin.left - 6)
.attr('text-anchor', 'end')
.attr('y', y(data[0].value))
.attr('font-size', '10px')
.attr('fill', 'white')
.attr("dy", ".32em")
.text(format(
initialHoldings.quantity * initialHoldings.price
));
}
return svg.node();
}
Insert cell
_ = require('lodash')
Insert cell
transactions = {
const parse = d3.timeParse("%Y-%m-%d")
return [
{value: -50, date: parse('2009-06-04')},
{value: 100, date: parse('2010-07-04')},
{value: 100, date: parse('2010-09-13')},
{value: -100, date: parse('2011-01-13')},
]
}
Insert cell
toBuyDatum = t => ({
..._.findLast(data, ({date}) => date <= t.date),
quantity: t.value
})
Insert cell
mutable buyDatum = ({
..._.findLast(data, ({date}) => date <= transactions[1].date),
quantity: transactions[1].value
})
Insert cell
function setDatum(transaction) {
console.log('setting', transaction)
mutable buyDatum = ({
..._.findLast(data, ({date}) => date <= transaction.date),
quantity: transaction.value
})
}
Insert cell
height = 600
Insert cell
bottomBarHeight = 120
Insert cell
margin = ({top: 20, right: 50, bottom: 30, left: 50})
Insert cell
x = d3.scaleUtc()
.domain(d3.extent(data, d => d.date))
.range([margin.left, width - margin.right])
Insert cell
y = d3.scaleLinear()
.domain([d3.min(data, d => d.value), d3.max(data, d => d.value)])
.range([height - margin.bottom, margin.top])
Insert cell
buySellY = {
const extreme = d3.max(transactions, d => Math.abs(d.value))
return d3.scaleLinear()
.domain([-extreme, extreme])
.range([height + bottomBarHeight - margin.bottom, height])
}
Insert cell
buySellX = d3.scaleBand()
.domain(d3.timeDays(data[0].date, _.last(data).date))
.rangeRound([0, width], .1);
Insert cell
y2 = {
const adjVals = data.map(({value}) => Math.abs(buyDatum.quantity) * value)
return d3.scaleLinear()
.domain([d3.min(adjVals), d3.max(adjVals)])
.range([height - margin.bottom, margin.top])
}
Insert cell
xAxis = g => g
.attr("transform", `translate(0,${height - margin.bottom})`)
.call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))
.call(g => g.select(".domain").remove())
Insert cell
xAxisBuySell = g => g
.attr("transform", `translate(0,${height + bottomBarHeight - margin.bottom})`)
.call(d3.axisBottom(x).ticks(width / 80).tickSizeOuter(0))
.call(g => g.select(".domain").remove())
Insert cell
yAxis = g => g
.attr("transform", `translate(${margin.left},0)`)
.call(d3.axisLeft(y)
.tickValues(d3.ticks(...y.domain(), 10))
.tickFormat(x => x))
.call(g => g.selectAll(".tick line").clone()
.attr("stroke-opacity", d => d === 1 ? null : 0.2)
.attr("x2", width - margin.left - margin.right))
.call(g => g.select(".domain").remove())
Insert cell
yAxis2 = {
return g => g
.attr("transform", `translate(${width - margin.right},0)`)
.call(d3.axisRight(y)
.tickValues(d3.ticks(...y.domain(), 10))
.tickFormat(x => x))
.call(g => g.select(".domain").remove())
}
Insert cell
format = {
const nf = Intl.NumberFormat(undefined, {style: 'currency', currency: 'USD'})
return x => {
if (x >= 1e9) return `${nf.format(x / 1e9)}B`
if (x >= 1e6) return `${nf.format(x / 1e6)}M`
if (x >= 1e3) return `${nf.format(x / 1e3)}K`
return nf.format(x)
}
}
Insert cell
data = Object.assign(d3.csvParse(await FileAttachment("aapl.csv").text(), d3.autoType).map(({date, close}) => ({date, value: close})), {y: "$ Close"})
Insert cell
d3 = require("d3@5")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more