Please note this blog was originally published on April 11, 2024.

Algorithmic trading is for everyone whether you are a novice or an expert. AlgoBulls not only supports Web Apps, but also Jupyter Notebooks and CLI for providing the best and seamless algo trading experience to all its users. 

In this article we are going to learn about strategy execution using pyalgotrading in Jupyter Notebook.This blog post is part of a series that is created to enhance your algorithmic trading skills. If this is your first post from the series, we suggest you also read “Building Your Trading Strategy With Phoenix” so you get an overview of how Phoenix helps you create your strategy and progress in your journey for success. 

For this article, we have explained a sample Jupyter Notebook which you can view here or even execute it on binder directly using the link given.

Imports and Connection

To begin with pyalgotrading, you need to set up a Jupyter workspace on your computer. For that you can create a Python virtual environment or you can directly use your global environment to install the “Jupyter”. Right before you install, verify that the python version on your environment is equal to or greater than 3.10.

Follow the steps given below to create your workspace and connect it with your AlgoBulls account.

Check the Python Version:

python3 --version

Create Virtual Environment:

python3 -m venv <name of your environment>

Once the environment is created successfully, you need to activate that environment. There are different commands for activating the environment in different operating systems. To avoid confusion those commands are not mentioned here.

The final step is to install the jupyter and pyalgotrading packages.

pip3 install jupyter

pip3 install pyalgotrading

Great, just ensure that your virtual environment is activated, and type the command shown below to launch Jupyter.

jupyter notebook

To know more about the initial set up, click here.

On launching the Jupyter notebook, you can see a list of folders and files of the current directory. Create a new “ipynb” file and let's get started with the real task.

First, we need to import the pyalgotrading package.

from pyalgotrading.algobulls import AlgoBullsConnection

Next, we need to establish a connection with the AlgoBulls platform.

connection = AlgoBullsConnection()
connection.get_token_url()
API_TOKEN = "0a3f547761154cd89b5616aa3f34603e9902d002"
connection.set_access_token(API_TOKEN)

Note:  Replace this sample token with your own.

Click here to know how to get your access token. Currently, access tokens are completely free to use.

Import or Upload a Strategy

Import Strategies:

Once your connection is established, you can fetch the details of all the saved strategies in your AlgoBulls account using the following code.

all_strategies = connection.get_all_strategies()
all_strategies

You can choose a strategy unique-ID code and use it for executing your strategy. You can even upload your own locally created strategy and upload it, as explained below.

Upload Strategy:

Follow this step if you have coded the strategy on your local machine. You need to save your strategy class in a python file (.py) and save that file in the same folder as that of your Jupyter notebook (.ipynb). Ensure that the below line is added on the top of your .py file and TA-Lib is installed. If not, install it by following the instructions from the TA-Lib Installation Guide.

from pyalgotrading.algobulls import AlgoBullsConnection

Next, come back to your Jupyter notebook and enter the following code to import the strategy class.

from ema_crossover_us import EMARegularOrder as strategy_cls

Now, upload that strategy on the AlgoBulls server that you have made a connection with earlier.

response = connection.create_strategy(strategy_cls, overwrite=True)
response

In the above method, the parameter overwrite=True will overwrite the strategy code on an existing strategy with the same name. Hence, it is a good habit to give a unique name to your strategy wherever necessary.

Extract the strategy unique-ID code from the response, which you can use to execute your strategy.

strategy = response['strategyId']

Search Instruments

Instrument is an asset like stock, commodity, options, index etc. To search for a tradable instrument, you can use the following method. Currently, the available exchanges are NYSE and NASDAQ.

instrument = connection.search_instrument('MSFT', exchange='NASDAQ')[0]['value']
instrument

Strategy Parameters

Strategy parameters are a range of values that can affect the returns, performance, execution time and trade-frequency of your strategy. 

These parameters are fetched and consumed using the “strategy_parameters” dictionary from inside the __init__() method of your strategy code. These values are basically used to tune the output of various methods that are used inside the strategy. 

Now, let’s set up the strategy parameters that can be given as input to your strategy during execution.

The below example shows the strategy parameters used by the EMA Crossover Strategy.

parameters = {
  'TIMEPERIOD1': 12,
  'TIMEPERIOD2': 20,
}
initial_virtual_funds=10000000

Execution

Now comes the most important part of this blog, the execution of strategy. There are various ways to execute any strategy, like “backtesting”, “paper trading” or “real trading”. 

There are mandatory parameters required for strategy execution, apart from the parameters that you want your strategy to consume. For reference, those are shown below. To know more about these strategy parameters, and how to submit a job for strategy execution, click here.

connection.backtest(
    strategy=strategy, 
    start='2021-08-01 09:15 -0400', 
    end='2023-07-31 15:30 -0400', 
    instrument='NASDAQ:MSFT', 
    lots=5,
    parameters=parameters, 
    candle='1 hour',
    initial_funds_virtual=initial_virtual_funds
)

You can monitor the progress of your strategy by querying for the execution status, as shown below

connection.get_backtesting_job_status(strategy)

You can generate detailed logs of your strategy execution in case you need to deep dive into the execution.

logs = connection.get_backtesting_logs(strategy)

The progress bar updates automatically, keeping you informed of the strategy's execution.

Analyzing Strategy Performance

Once the strategy execution is finished, you can analyze the performance of your strategy by fetching the Profit and Loss report.

Note: This report is fetched as a dataframe, and you can use it to perform further analysis.

connection
.get_backtesting_report_pnl_table(strategy)

You can compute industry-standard metrics like Sharpe and Sortino ratios using a simple method. It generates these metrics in a clear tabular format.

Visualisations, in the form of charts, offer insights into your strategy's performance. We offer ‘quantstats’ powered visualization for generating strategy analytics. Here, each chart provides a unique perspective on your trading strategy's behavior.

connection.get_backtesting_report_statistics(
    strategy,          
    report='full',         
    html_dump=True
)

To get detailed information on the charts and metrics, visit our blog and our comprehensive documentation.

You can use the strategy methods described in this blog for all trading types, like “backtesting”, “paper trading” or “real trading”. Know more here.

And that concludes our journey!

I hope this blog has inspired you to explore the world of creating and executing trading strategies with AlgoBulls. 

If you're intrigued by Jupyter Notebooks and wonder if similar tasks can be performed on the AlgoBulls website, the answer is "yes." We have a dedicated blog explaining this process.

Thank you for joining me, and may you conquer the trading world with AlgoBulls by your side. Have a fantastic day!


Options trading is not suitable for all investors due to its inherent high risk, which can potentially result in significant losses. Please read Characteristics and Risks of Standardized Options before investing in options.

Alpaca Securities LLC and AlgoBulls are not affiliated and neither are responsible for the liabilities of the other. 

Please note that this article is for educational and informational purposes only. All screenshots are for illustrative purposes only. The views and opinions expressed are those of the author and do not reflect or represent the views and opinions of Alpaca. Alpaca does not recommend any specific securities or investment strategies.

Alpaca does not prepare, edit, or endorse Third Party Content. Alpaca does not guarantee the accuracy, timeliness, completeness or usefulness of Third Party Content, and is not responsible or liable for any content, advertising, products, or other materials on or available from third party sites.

Securities brokerage services are provided by Alpaca Securities LLC ("Alpaca Securities"), member FINRA/SIPC, a wholly-owned subsidiary of AlpacaDB, Inc. Technology and services are offered by AlpacaDB, Inc.

This is not an offer, solicitation of an offer, or advice to buy or sell securities or open a brokerage account in any jurisdiction where Alpaca Securities are not registered or licensed, as applicable.

All investments involve risk and the past performance of a security, or financial product does not guarantee future results or returns. There is no guarantee that any investment strategy will achieve its objectives. Please note that diversification does not assure a profit, or protect against loss. There is always the potential of losing money when you invest in securities, or other financial products. Investors should consider their investment objectives and risks carefully before investing.

Past hypothetical backtest results do not guarantee future returns, and actual results may vary from the analysis.

The Paper Trading API is offered by AlpacaDB, Inc. and does not require real money or permit a user to transact in real securities in the market. Providing use of the Paper Trading API is not an offer or solicitation to buy or sell securities, securities derivative or futures products of any kind, or any type of trading or investment advice, recommendation or strategy, given or in any manner endorsed by AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate and the information made available through Paper Trading is not an offer or solicitation of any kind in any jurisdiction where AlpacaDB, Inc. or any AlpacaDB, Inc. affiliate is not authorized to do business.