20
loading...
This website collects cookies to deliver better user experience
pip install scrapbook
pip install scrapbook[all]
import scrapbook as sb
x = 1
{
"cell_type": "code",
"execution_count": 1,
"id": "6b5d2b33",
"metadata": {},
"outputs": [],
"source": [
"x = 1"
]
}
scrapbook
to glue
the value of x
to the current notebook.sb.glue("x", x)
{
"cell_type": "code",
"execution_count": 1,
"id": "228fc7d4",
"metadata": {},
"outputs": [
{
"data": {
"application/scrapbook.scrap.json+json": {
"data": 1,
"encoder": "json",
"name": "x",
"version": 1
}
},
"metadata": {
"scrapbook": {
"data": true,
"display": false,
"name": "x"
}
},
"output_type": "display_data"
}
],
"source": [
"sb.glue(\"x\", x)"
]
}
scrapbook
and use it to fetch the value out of the notebook file. Usually, we do this in a different notebook or Python application, but it does work inside the same notebook (as long as it’s been saved to disk).nb = sb.read_notebook("scrapbook_and_jupyter.ipynb")
nb
) has a number of attributes which correspond directly to the JSON schema of a notebook file, just as documented in the nbformat
docs. But it also has a few extra methods for dealing with scraps
, the values that have been glued to the notebook. You can see the scraps directly:nb.scraps
Scraps([('x', Scrap(name='x', data=1, encoder='json', display=None))])
DataFrame
.nb.scrap_dataframe
name data encoder display filename
0 x 1 json None scrapbook_and_jupyter.ipynb
x = nb.scraps['x'].data
x
1
scrapbook
features.length = 1000
symbol = "XYZ"
d = {
"a": 1,
"b": 2,
}
threshold = 0.1 # 10%
import pandas as pd
import numpy as np
import scrapbook as sb
import matplotlib.pyplot as plt
# generate a DataFrame that has synthetic price information
idx = pd.date_range(start='20100101', periods=length, freq='B')
prices = pd.DataFrame({'price' : np.cumsum(np.random.random(length) - .5)}, index=idx)
# normalize to always be above 0
prices['price'] += abs(prices['price'].min())
prices['ATH'] = prices['price'].expanding().max()
distance = 1 - prices.iloc[-1]['price']/prices.iloc[-1]['ATH']
if distance <= threshold:
close_to_ath = True
else:
close_to_ath = False
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(prices['price'])
ax.plot(prices['ATH'])
ax.text(prices.index[-1], prices['price'].iloc[-1], f"{distance * 100: .1f}%");
glue
method for a basic type. If the type passed in can be serialized using one of the built in encoders, it will be. To preserve numeric types, they will be encoded as JSON.sb.glue("length", length) # numeric - int (stored as json)
sb.glue("symbol", symbol) # text
sb.glue("distance", distance) # numeric - float
sb.glue("close_to_ath", close_to_ath) # bool
display
parameter to the glue
function. This determines whether the value is visibile in the notebook when it is glued. By default you will not see the value in the notebook when it is stored.matplotlib.figure.Figure
(so an exception is raised), but since it can be displayed, it can be stored that way.# with display set, this will display the value, see it in the output below?
sb.glue("dj", d, encoder="json", display=True)
sb.glue("prices", prices, encoder="pandas")
sb.glue("message", "This is a message", encoder="text")
try:
sb.glue("chart", fig)
except NotImplementedError as nie:
print(nie)
# but we can store the display result (will also display the value)
sb.glue("chart", fig, encoder="display")
{'a': 1, 'b': 2}
Scrap of type <class 'matplotlib.figure.Figure'> has no supported encoder registered
mkdir tickers
for s in AAA ABC BCD DEF GHI JKL MNO MMN OOP PQD XYZ PDQ
do
papermill -p symbol $s scrapbook_example_source.ipynb tickers/${s}.ipynb
done
read_notebooks
method, which allows us to fetch the notebooks all at once. We’ll iterate through them and display the ticker and distance for each notebook, and show the chart for each that is within the threshold.source_dir = "tickers"
sbook = sb.read_notebooks(source_dir)
sbook
) that we can iterate through.for nb in sbook.notebooks:
print(f"{nb.scraps['symbol'].data: <5} {nb.scraps['distance'].data * 100: .2f}%")
if nb.scraps['close_to_ath'].data:
display(nb.scraps['chart'].display['data'], raw=True)
AAA 49.81%
ABC 60.51%
BCD 0.13%
DEF 94.09%
FB 80.13%
GHI 19.65%
JKL 44.80%
MMN 100.00%
MNO 2.42%
OOP 24.18%
PDQ 93.33%
PQD 18.19%
XYZ 44.14%
reglue
. You can use this method on an existing notebook to “re”-glue a scrap into the current notebook. You can also rename the scrap.reglue
is to display visual elements.nb.reglue("length", "length2") # new name
nb.reglue("chart") # will display chart, just like earlier