Public
Edited
Jun 8, 2024
Insert cell
md`# Test`
Insert cell
dayjs(1704926102425).toISOString()
Insert cell
Insert cell
Insert cell
dayjs('2024-04-01').endOf('day').unix()
Insert cell
dayjs.unix(1714521600).toString()
Insert cell
{
const { Subject, ReplaySubject } = rxjs
const subject = new ReplaySubject();

subject.subscribe({
next: (v) => console.log(`observerA: ${v}`),
});

subject.next(1);
subject.next(2);

subject.subscribe({
next: (v) => console.log(`observerB: ${v}`),
});

subject.next(3)
}

Insert cell
sma = (period, data) => {
if (data.length < period) {
throw new Error(`sma: data.length ${data.length} must be bigger than ${period}`);
}

const sum = data.slice(0, period).reduce((acc, val) => acc + val, 0);
return sum / period;
}
Insert cell
ma = (length, data) => {
const result = [];
for (let i = 0; i <= data.length - length; i++) {
const slice = data.slice(i, i + length);
const average = slice.reduce((acc, val) => acc + val, 0) / length;
result.push(average);
}
return result;
};
Insert cell
rma = (length, data) => {
const result = [];
let sum = 0;
for (let i = 0; i < length; i++) {
sum += data[i];
}

let average = sum / length;
result.push(average);

for (let i = length + 1; i < data.length; i++) {
average = (average * (length - 1) + data[i]) / length;
result.push(average);
}

return result.reverse();
}
Insert cell
rsi = (len, bars) => {
if (bars.length < len * 2) {
throw new Error(`rsi: bars.length ${bars.length} must be bigger than ${len * 2}`);
}

const c = changes("close", bars)

const max = c.map(val => Math.max(val, 0))
const min = c.map(val => -1 * Math.min(val, 0))
const up = rma(len, max.reverse())
const down = rma(len, min.reverse())

const rsiValues = [];

for (let i = 0; i < up.length; i++) {
const upValue = up[i];
const downValue = down[i];
if (downValue === 0) {
rsiValues.push(100);
} else if (upValue === 0) {
rsiValues.push(0);
} else {
rsiValues.push(100 - (100 / (1 + upValue / downValue)));
}
}
return rsiValues
}
Insert cell
Insert cell
rsi(14, sol.slice(0, 28))
Insert cell
function calculateTargetWeightedIndex(stockPrices) {
const totalValue = stockPrices.reduce((acc, price) => acc + price, 0);
const targetValuePerStock = totalValue / stockPrices.length;

console.log(targetValuePerStock)
let adjustedTotal = 0;
for (let price of stockPrices) {
adjustedTotal += Math.abs(price - targetValuePerStock); // Adjusted for the difference from target value
}

const adjustedIndex = adjustedTotal / stockPrices.length;
return adjustedIndex;
}
Insert cell
function calculateMarketCapWeightedIndex(stocks, shares) {
const marketCaps = stocks.map(s => shares[s.symbol] * s.price);

// Calculate the total market capitalization
const totalMarketCap = R.sum(marketCaps)

// Calculate the weighted index
const weightedIndex = totalMarketCap * 100 / R.sum(Object.values(shares))
return weightedIndex;
}
Insert cell
stockPrices = [100, 0.5, 200, 250]
Insert cell
dayjs("2025-01-22T10:22:03").startOf('second').toISOString()
Insert cell
calculateTargetWeightedIndex(stockPrices)
Insert cell
getShares = () => {
const totalShare = 50000000
const result = {
'BTC/USD': Math.round(totalShare / 35000),
'ETH/USD': Math.round(totalShare/ 1880),
'ADA/USD': Math.round(totalShare / 0.3),
'SOL/USD': Math.round(totalShare / 40),
'LINK/USD': Math.round(totalShare / 11.5)
}

return result
}
Insert cell
stocks = [{symbol: 'BTC/USD', price: 35000}, {symbol: 'ADA/USD', price: 0.65}, {symbol: 'SOL/USD', price: 41}]
Insert cell
calculateMarketCapWeightedIndex(stocks, getShares())
Insert cell
marketDay = ({
"date": '2023-03-17',
"open": '09:30',
"close": '16:00',
"session_open": '0400',
"session_close": '2000'
})
Insert cell
today = dayjs().utc()
Insert cell
dayjs(1707525900000).tz("America/New_York").format("YYYY-MM-DDTHH:mm:ss")
Insert cell
dayjs.utc('2023-04-17T13:30:00').toISOString()
Insert cell
dayjs.utc('2023-04-18').set({ hour: 14 }).toISOString()
Insert cell
dayjs.utc().format("HH:mm Z")
Insert cell
isMarketOpen = (date) => {
const openDate = dayjs.tz(marketDay.date, "America/New_York").set({ hour: 9, minute: 30, second: 0 }).utc()
const closeDate = dayjs.tz(marketDay.date, "America/New_York").set({ hour: 16, minute: 0, second: 0 }).utc()

return dayjs(date).isBetween(openDate, closeDate, 'minute', '[]')
}

Insert cell
Insert cell
positions
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
Insert cell
Insert cell
orders = [{
"symbol": "SPY",
"date": 1677531600000,
"dateFormatted": "2023-02-27T21:00:00.000Z",
"price": 400,
"units": 5,
"action": "sell"
}, {
"symbol": "AAPL",
"date": 1677531600000,
"dateFormatted": "2023-02-27T21:00:00.000Z",
"price": 130,
"units": 2,
"action": "buy"
}]
Insert cell
Insert cell
data
Type Table, then Shift-Enter. Ctrl-space for more options.

Insert cell
dayjs.utc('2023-07-18').toISOString()
Insert cell
dayjs().valueOf()
Insert cell
getYears = data => {
const all = [...new Set(Object.keys(plCurrent).map(v => dayjs(v).year()))]
const min = Math.min(...all)
const max = Math.max(...all)
const res = []

for (let i = min; i <= max; i++) {
res.push(i)
}

return res
}
Insert cell
getMonths = (len) => {
const arr = Array.from(Array(len).keys())
const months = arr.map(
(x) => dayjs()
.set('year', dayjs().subtract(x, 'months').year())
.set('month', dayjs().subtract(x, 'months').month())
.startOf('month')
.format("YYYY-MM")
).reduce((res, val) => ({...res, [val]: 0}), {})

return months
}
Insert cell
Array.from(Array(3).keys()).map(x => {
return dayjs().subtract(x, 'months').month()
})

Insert cell
plCurrent = ({
'2023-09': 80,
'2023-10': 80,
'2023-11': 50,
'2023-12': -20
})
Insert cell
getMonths(6)
Insert cell
curve = (len, data) => {
const now = dayjs().unix()
const months = getMonths(len)

let total = 0
return Object.keys(months).reverse().map(date => {
total = total + (data[date] ?? 0)
return {
date,
value: dayjs(date).unix() > now ? 0 : total
}
})
}
Insert cell
test1 = curve(12, plCurrent)
Insert cell
test1.slice(0, 5)
Insert cell
dateRange = (start, stop, freq = 'd') => {
const dateArray = new Array();
let currentDate = dayjs(start).toDate();
while (currentDate <= dayjs(stop).toDate()) {
dateArray.push(new Date (currentDate));
currentDate = dayjs(currentDate).add(1, freq).toDate()
}
return dateArray;
}
Insert cell
dateRange("2023-11-01", "2023-11-11")
Insert cell
SVGDefsElement


Insert cell
Insert cell
{
const myPromise1 = () => new Promise((resolve, reject) => {
setTimeout(() => {
console.log('p1 resolved');
resolve("p1");
}, 2000);
})

const myPromise2 = () => new Promise((resolve, reject) => {
setTimeout(() => {
console.log('p2 resolved');
resolve("p2");
}, 100);
})

const all = [myPromise1, myPromise2]
// for (const p of all) {
// await p()
// }

const x2 = Promise.allSettled(all.map(x => x()))
}
Insert cell
Insert cell
rxjs = import("https://cdn.skypack.dev/rxjs@7.6.0")
Insert cell
dayjs = {
const dayjs = await require('dayjs')
var utc = await require('dayjs/plugin/utc')
var timezone = await require('dayjs/plugin/timezone')
var isBetween = await require('dayjs/plugin/isBetween')
var objectSupport = await require('dayjs/plugin/objectSupport')
dayjs.extend(utc)
dayjs.extend(timezone)
dayjs.extend(isBetween)
dayjs.extend(objectSupport)
return dayjs
}

Insert cell
R = import("https://cdn.skypack.dev/ramda@0.28.0")
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more