{ "cells": [ { "cell_type": "markdown", "id": "a9f4fa17", "metadata": {}, "source": [ "# Golden Cross with Blankly\n", "\n", "This tutorial goes over how to implement a golden cross using Blankly in a Jupyter Notebook. \n", "\n", "Blankly is like any other package in that it allows users to easily interact with its various functions, explore the data, do processing, and only when they're ready, to fully create a useful `Strategy`. Today we're going to investigate the golden cross strategy using Simple Moving Averages of 50 and 100 \n", "\n", "Author: Brandon Fan" ] }, { "cell_type": "markdown", "id": "a88ebc66", "metadata": {}, "source": [ "## Environment Setup" ] }, { "cell_type": "markdown", "id": "0b139093", "metadata": {}, "source": [ "### `blankly init` \n", "\n", "To easily initialize our codebase and the necessary files, let's simply run `blankly init` in the command line" ] }, { "cell_type": "code", "execution_count": 1, "id": "4780743f", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Initializing...\n", "\n", "██████╗ ██╗ █████╗ ███╗ ██╗██╗ ██╗██╗ ██╗ ██╗ ███████╗██╗███╗ ██╗ █████╗ ███╗ ██╗ ██████╗███████╗\n", "██╔══██╗██║ ██╔══██╗████╗ ██║██║ ██╔╝██║ ╚██╗ ██╔╝ ██╔════╝██║████╗ ██║██╔══██╗████╗ ██║██╔════╝██╔════╝\n", "██████╔╝██║ ███████║██╔██╗ ██║█████╔╝ ██║ ╚████╔╝ █████╗ ██║██╔██╗ ██║███████║██╔██╗ ██║██║ █████╗ \n", "██╔══██╗██║ ██╔══██║██║╚██╗██║██╔═██╗ ██║ ╚██╔╝ ██╔══╝ ██║██║╚██╗██║██╔══██║██║╚██╗██║██║ ██╔══╝ \n", "██████╔╝███████╗██║ ██║██║ ╚████║██║ ██╗███████╗██║ ██║ ██║██║ ╚████║██║ ██║██║ ╚████║╚██████╗███████╗\n", "╚═════╝ ╚══════╝╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝ ╚═╝╚═╝ ╚═══╝ ╚═════╝╚══════╝\n", "\n", "Downloading keys template...\n", "Already exists - skipping...\n", "Downloading settings defaults...\n", "Already exists - skipping...\n", "Downloading backtest defaults...\n", "Already exists - skipping...\n", "Downloading RSI bot example...\n", "Already exists - skipping...\n", "Writing deployment defaults...\n", "Already exists - skipping...\n", "Writing requirements.txt defaults...\n", "Already exists - skipping...\n", "Done!\n" ] } ], "source": [ "!blankly init" ] }, { "cell_type": "markdown", "id": "c7561279", "metadata": {}, "source": [ "As you can see, our directory now has everything that we need :D" ] }, { "cell_type": "code", "execution_count": 2, "id": "b67d2b56", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Golden Cross with Blankly.ipynb keys.json\r\n", "backtest.json \u001b[34mprice_caches\u001b[m\u001b[m\r\n", "blankly.json requirements.txt\r\n", "bot.py settings.json\r\n" ] } ], "source": [ "!ls" ] }, { "cell_type": "markdown", "id": "65e4482d", "metadata": {}, "source": [ "### `keys.json`" ] }, { "cell_type": "markdown", "id": "ad61137a", "metadata": {}, "source": [ "Make sure that you have in the same directory as your jupyter notebook, the necessary `keys.json` that houses all of your API keys that you are going to use. To check out how to get keys setup, look [here](https://docs.blankly.finance/config/keys.json), we will be using Alpaca in this tutorial so make sure you have your Alpaca keys" ] }, { "cell_type": "markdown", "id": "3c0cc7bb", "metadata": {}, "source": [ "## Imports\n", "\n", "The imports are pretty straight forward. Blankly allows you to easily import everything you need almost directly nad houses a variety of [built-in indicators](https://docs.blankly.finance/metrics/indicators) that you can directly use. \n", "\n", "*Note the `bokeh.io` import for `output_notebook`, this is important to allow the graphs to display (such as backtest results)*" ] }, { "cell_type": "code", "execution_count": 3, "id": "25886875", "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", "
" ] }, "metadata": {}, "output_type": "display_data" }, { "data": { "application/javascript": [ "\n", "(function(root) {\n", " function now() {\n", " return new Date();\n", " }\n", "\n", " const force = true;\n", "\n", " if (typeof root._bokeh_onload_callbacks === \"undefined\" || force === true) {\n", " root._bokeh_onload_callbacks = [];\n", " root._bokeh_is_loading = undefined;\n", " }\n", "\n", " const JS_MIME_TYPE = 'application/javascript';\n", " const HTML_MIME_TYPE = 'text/html';\n", " const EXEC_MIME_TYPE = 'application/vnd.bokehjs_exec.v0+json';\n", " const CLASS_NAME = 'output_bokeh rendered_html';\n", "\n", " /**\n", " * Render data to the DOM node\n", " */\n", " function render(props, node) {\n", " const script = document.createElement(\"script\");\n", " node.appendChild(script);\n", " }\n", "\n", " /**\n", " * Handle when an output is cleared or removed\n", " */\n", " function handleClearOutput(event, handle) {\n", " const cell = handle.cell;\n", "\n", " const id = cell.output_area._bokeh_element_id;\n", " const server_id = cell.output_area._bokeh_server_id;\n", " // Clean up Bokeh references\n", " if (id != null && id in Bokeh.index) {\n", " Bokeh.index[id].model.document.clear();\n", " delete Bokeh.index[id];\n", " }\n", "\n", " if (server_id !== undefined) {\n", " // Clean up Bokeh references\n", " const cmd_clean = \"from bokeh.io.state import curstate; print(curstate().uuid_to_server['\" + server_id + \"'].get_sessions()[0].document.roots[0]._id)\";\n", " cell.notebook.kernel.execute(cmd_clean, {\n", " iopub: {\n", " output: function(msg) {\n", " const id = msg.content.text.trim();\n", " if (id in Bokeh.index) {\n", " Bokeh.index[id].model.document.clear();\n", " delete Bokeh.index[id];\n", " }\n", " }\n", " }\n", " });\n", " // Destroy server and session\n", " const cmd_destroy = \"import bokeh.io.notebook as ion; ion.destroy_server('\" + server_id + \"')\";\n", " cell.notebook.kernel.execute(cmd_destroy);\n", " }\n", " }\n", "\n", " /**\n", " * Handle when a new output is added\n", " */\n", " function handleAddOutput(event, handle) {\n", " const output_area = handle.output_area;\n", " const output = handle.output;\n", "\n", " // limit handleAddOutput to display_data with EXEC_MIME_TYPE content only\n", " if ((output.output_type != \"display_data\") || (!Object.prototype.hasOwnProperty.call(output.data, EXEC_MIME_TYPE))) {\n", " return\n", " }\n", "\n", " const toinsert = output_area.element.find(\".\" + CLASS_NAME.split(' ')[0]);\n", "\n", " if (output.metadata[EXEC_MIME_TYPE][\"id\"] !== undefined) {\n", " toinsert[toinsert.length - 1].firstChild.textContent = output.data[JS_MIME_TYPE];\n", " // store reference to embed id on output_area\n", " output_area._bokeh_element_id = output.metadata[EXEC_MIME_TYPE][\"id\"];\n", " }\n", " if (output.metadata[EXEC_MIME_TYPE][\"server_id\"] !== undefined) {\n", " const bk_div = document.createElement(\"div\");\n", " bk_div.innerHTML = output.data[HTML_MIME_TYPE];\n", " const script_attrs = bk_div.children[0].attributes;\n", " for (let i = 0; i < script_attrs.length; i++) {\n", " toinsert[toinsert.length - 1].firstChild.setAttribute(script_attrs[i].name, script_attrs[i].value);\n", " toinsert[toinsert.length - 1].firstChild.textContent = bk_div.children[0].textContent\n", " }\n", " // store reference to server id on output_area\n", " output_area._bokeh_server_id = output.metadata[EXEC_MIME_TYPE][\"server_id\"];\n", " }\n", " }\n", "\n", " function register_renderer(events, OutputArea) {\n", "\n", " function append_mime(data, metadata, element) {\n", " // create a DOM node to render to\n", " const toinsert = this.create_output_subarea(\n", " metadata,\n", " CLASS_NAME,\n", " EXEC_MIME_TYPE\n", " );\n", " this.keyboard_manager.register_events(toinsert);\n", " // Render to node\n", " const props = {data: data, metadata: metadata[EXEC_MIME_TYPE]};\n", " render(props, toinsert[toinsert.length - 1]);\n", " element.append(toinsert);\n", " return toinsert\n", " }\n", "\n", " /* Handle when an output is cleared or removed */\n", " events.on('clear_output.CodeCell', handleClearOutput);\n", " events.on('delete.Cell', handleClearOutput);\n", "\n", " /* Handle when a new output is added */\n", " events.on('output_added.OutputArea', handleAddOutput);\n", "\n", " /**\n", " * Register the mime type and append_mime function with output_area\n", " */\n", " OutputArea.prototype.register_mime_type(EXEC_MIME_TYPE, append_mime, {\n", " /* Is output safe? */\n", " safe: true,\n", " /* Index of renderer in `output_area.display_order` */\n", " index: 0\n", " });\n", " }\n", "\n", " // register the mime type if in Jupyter Notebook environment and previously unregistered\n", " if (root.Jupyter !== undefined) {\n", " const events = require('base/js/events');\n", " const OutputArea = require('notebook/js/outputarea').OutputArea;\n", "\n", " if (OutputArea.prototype.mime_types().indexOf(EXEC_MIME_TYPE) == -1) {\n", " register_renderer(events, OutputArea);\n", " }\n", " }\n", "\n", " \n", " if (typeof (root._bokeh_timeout) === \"undefined\" || force === true) {\n", " root._bokeh_timeout = Date.now() + 5000;\n", " root._bokeh_failed_load = false;\n", " }\n", "\n", " const NB_LOAD_WARNING = {'data': {'text/html':\n", " \"\\n\"+\n", " \"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \\n\"+\n", " \"may be due to a slow or bad network connection. Possible fixes:\\n\"+\n", " \"
\\n\"+\n", " \"\\n\"+\n",
" \"from bokeh.resources import INLINE\\n\"+\n",
" \"output_notebook(resources=INLINE)\\n\"+\n",
" \"
\\n\"+\n",
" \"\\n\"+\n \"BokehJS does not appear to have successfully loaded. If loading BokehJS from CDN, this \\n\"+\n \"may be due to a slow or bad network connection. Possible fixes:\\n\"+\n \"
\\n\"+\n \"\\n\"+\n \"from bokeh.resources import INLINE\\n\"+\n \"output_notebook(resources=INLINE)\\n\"+\n \"
\\n\"+\n \"\n", " | time | \n", "open | \n", "high | \n", "low | \n", "close | \n", "volume | \n", "
---|---|---|---|---|---|---|
0 | \n", "1640754000 | \n", "302.94 | \n", "305.48 | \n", "293.6600 | \n", "299.97 | \n", "32036645.0 | \n", "
1 | \n", "1640840400 | \n", "298.28 | \n", "304.57 | \n", "295.4000 | \n", "295.88 | \n", "29281826.0 | \n", "
2 | \n", "1640926800 | \n", "296.75 | \n", "300.30 | \n", "293.3057 | \n", "294.21 | \n", "24464247.0 | \n", "
3 | \n", "1641186000 | \n", "298.24 | \n", "307.11 | \n", "297.8500 | \n", "301.25 | \n", "35656625.0 | \n", "
4 | \n", "1641272400 | \n", "302.61 | \n", "304.68 | \n", "283.4900 | \n", "292.99 | \n", "49212953.0 | \n", "
\n", " | high | \n", "low | \n", "volume | \n", "close | \n", "open | \n", "time | \n", "
---|---|---|---|---|---|---|
0 | \n", "239.9100 | \n", "236.7200 | \n", "5948415.0 | \n", "239.91 | \n", "238.85 | \n", "1577941200 | \n", "
1 | \n", "237.8300 | \n", "234.1000 | \n", "5145208.0 | \n", "236.07 | \n", "235.00 | \n", "1578027600 | \n", "
2 | \n", "237.2700 | \n", "231.2700 | \n", "6603313.0 | \n", "237.06 | \n", "232.36 | \n", "1578286800 | \n", "
3 | \n", "241.7700 | \n", "236.3900 | \n", "7980144.0 | \n", "239.93 | \n", "238.20 | \n", "1578373200 | \n", "
4 | \n", "242.0400 | \n", "238.1490 | \n", "6931017.0 | \n", "240.38 | \n", "239.76 | \n", "1578459600 | \n", "
5 | \n", "245.9297 | \n", "240.8550 | \n", "6386105.0 | \n", "243.02 | \n", "243.55 | \n", "1578546000 | \n", "
6 | \n", "248.5500 | \n", "243.7500 | \n", "7911735.0 | \n", "244.32 | \n", "247.48 | \n", "1578632400 | \n", "
7 | \n", "252.9884 | \n", "246.7500 | \n", "8008491.0 | \n", "251.98 | \n", "247.66 | \n", "1578891600 | \n", "
8 | \n", "251.2800 | \n", "246.7500 | \n", "8989483.0 | \n", "247.28 | \n", "250.51 | \n", "1578978000 | \n", "
9 | \n", "248.6891 | \n", "244.5300 | \n", "6578446.0 | \n", "245.57 | \n", "247.79 | \n", "1579064400 | \n", "
10 | \n", "249.1700 | \n", "246.7750 | \n", "7104791.0 | \n", "248.93 | \n", "247.63 | \n", "1579150800 | \n", "
11 | \n", "250.0000 | \n", "247.3700 | \n", "6344766.0 | \n", "249.28 | \n", "249.72 | \n", "1579237200 | \n", "
12 | \n", "249.2900 | \n", "246.5703 | \n", "5447938.0 | \n", "247.94 | \n", "247.68 | \n", "1579582800 | \n", "
13 | \n", "253.5900 | \n", "249.0000 | \n", "5980976.0 | \n", "250.05 | \n", "249.76 | \n", "1579669200 | \n", "
14 | \n", "253.2000 | \n", "248.1500 | \n", "6113790.0 | \n", "252.86 | \n", "251.88 | \n", "1579755600 | \n", "
15 | \n", "259.5000 | \n", "248.3000 | \n", "9337839.0 | \n", "250.48 | \n", "257.87 | \n", "1579842000 | \n", "
16 | \n", "242.2500 | \n", "232.2300 | \n", "11764241.0 | \n", "240.20 | \n", "239.00 | \n", "1580101200 | \n", "
17 | \n", "249.2700 | \n", "240.7143 | \n", "7774401.0 | \n", "247.97 | \n", "242.85 | \n", "1580187600 | \n", "
18 | \n", "248.8400 | \n", "243.9400 | \n", "6486300.0 | \n", "245.54 | \n", "247.28 | \n", "1580274000 | \n", "
19 | \n", "246.3500 | \n", "239.4000 | \n", "7262590.0 | \n", "245.81 | \n", "241.67 | \n", "1580360400 | \n", "
20 | \n", "244.4500 | \n", "234.7500 | \n", "9260493.0 | \n", "236.43 | \n", "243.97 | \n", "1580446800 | \n", "