Jupyter notebook custom magic

Keywords: cell parameter, line parameter, trading algo, extension jupyter, magic function, pipe, package, load, execute, framework, power. Powered by TextRank.

Jupyter notebooks a great way of prototyping small programs and exploring/visualizing data from scripts. I use them to run back tests on trading algos. One of the most power features is that you can actually pipe the contents of a cell to another python function. This feature came in really handy when I wanted to pipe a trading algo into my backtesting framework. To accomplish this you need to make use of "magics"

First create a function in your __init__.py file in your package

def load_ipython_extension(ipython):
        def rtrade(line, cell):
            parser = argparse.ArgumentParser()
            parser.add_argument("-s", help="start date YYYY-mm-dd", dest="start",
                    action="store", required=False)
            parser.add_argument("-e", help="end date YYYY-mm-dd", dest="end",
                    action='store', required=False)
            parser.add_argument("-o", help="result output file name", dest="output",
                    action='store', required=False, default="result_df.pickle")
            # We create a string buffer containing the
            # contents of the cell.
            args = parser.parse_args(line.split())
            sio = StringIO(cell)
            print("dates",args.start)
            print("end", args.end)
            return Simulator(args.start, args.end, args.output).test(cell)
        ipython.register_magic_function(rtrade, "line_cell", "rtrade")

when we load the extension Jupyter will execute this function for us. The line parameter is the line of the magic function and the cell parameter is the contents of the cell.

Load the extension with (my package is called retrotrade)

%load_ext retrotrade

now execute the magic with

%%rtrade -s 2020-01-01 -e 2021-01-01 -o result.pickle
<some python code>

The line parameter above will contain the first line that starts with %% and the cell parameter will contain the rest of the cell contents.


Metadata

237 words

Similar posts

Powered by TF-IDF/Cosine similarity

First published on 2021-09-01

Generated on 13 Dec 2024 at 12:12 AM

Index

Mobile optimized version. Desktop version.