Contents:
Most frameworks go beyond backtesting to include some live trading capabilities. This is convenient if you want to deploy from your backtesting framework, which also works with your preferred broker and data sources. The Python community is well served, with at least six open source backtesting frameworks available. They are however, in various stages of development and documentation. If you enjoy working on a team building an open source backtesting framework, check out their Github repos.
What asset class es are you trading? While most of the frameworks support US Equities data via YahooFinance, if a strategy incorporates derivatives, ETFs, or EM securities, the data needs to be importable or provided by the framework. Asset class coverages goes beyond data.
What about illiquid markets, how realistic an assumption must be made when executing large orders? What data frequency and detail is your STS built on? What order type s does your STS require? At a minimum, limit, stops and OCO should be supported by the framework.
The early stage frameworks have scant documentation, few have support other than community boards. If the framework requires any STS to be recoded before backtesting, then the framework should support canned functions for the most popular technical indicators to speed STS testing. Users determine how long of a historical period to backtest based on what the framework provides, or what they are capable of importing. Most all of the frameworks support a decent number of visualization capabilities, including equity curves and deciled-statistics.
In the context of strategies developed using technical indicators , system developers attempt to find an optimal set of parameters for each indicator. Most simply, optimization might find that a 6 and 10 day moving average crossover STS accumulated more profit over the historic test data than any other combination of time periods between 1 and In a portfolio context , optimization seeks to find the optimal weighting of every asset in the portfolio, including shorted and leveraged instruments.
On a periodic basis, the portfolio is rebalanced, resulting in the purchase and sale of portfolio holdings as required to align with the optimized weights. Position sizing is an additional use of optimization, helping system developers simulate and analyze the impact of leverage and dynamic position sizing on STS and portfolio performance.
PyAlgoTrade is a muture, fully documented backtesting framework along with paper- and live-trading capabilities. Data support includes Yahoo!
The framework is particularly suited to testing portfolio-based STS, with algos for asset weighting and portfolio rebalancing. Modifying a strategy to run over different time frequencies or alternate asset weights involves a minimal code tweak.
This platform is exceptionally well documented, with an accompanying blog and an active on-line community for posting questions and feature requests. Backtrader supports a number of data formats, including CSV files, Pandas DataFrames, blaze iterators and real time data feeds from three brokers. These data feeds can be accessed simultaneously, and can even represent different timeframes. Open source contributors are welcome. It is being adopted widely across all domains, especially in data science, because of its easy syntax, huge community, and third-party support.
You'll need familiarity with Python and statistics in order to make the most of this tutorial. Make sure to brush up on your Python and check out the fundamentals of statistics. In order to extract stock pricing data, we'll be using the Quandl API. But before that, let's set up the work environment.
Here's how:. You can create your first notebook by clicking on the New dropdown on the right. Make sure you have created an account on Quandl. Follow the steps mentioned here to create your API key.
Pandas is going to be the most rigorously used package in this tutorial as we'll be doing a lot of data manipulation and plotting. After the packages are imported, we will make requests to the Quandl API by using the Quandl package:. Here we have Microsoft's EOD stock pricing data of the last 9 years. All you had to do was call the get method from the Quandl package and supply the stock symbol, MSFT, and the timeframe for the data you need.
With the data in our hands, the first thing we should do is understand what it represents and what kind of information does it encapsulate. As seen in the screenshot above, the DataFrame contains DatetimeIndex, which means we're dealing with time-series data. An index can be thought of as a data structure which helps to modify or reference the data. Time-series data is a sequence of snapshots of prices taken at consecutive, equally spaced intervals of time.
In trading, EOD stock pricing data captures the movement of the certain parameters about a stock, such as the stock price, over a specified period of time with data points recorded at regular intervals. We can learn about the summary statistics of the data, which shows us the number of rows, mean, max, standard deviations, etc.
Try running the following line of code in the Ipython cell:. Pandas' resample method is used to facilitate control and flexibility on the frequency conversion of the time series data. We can specify the time intervals to resample the data to monthly, quarterly, or yearly, and perform the required operation over it. A financial return is simply the money made or lost on an investment. A return can be expressed nominally as the change in the amount of an investment over time. A return can be calculated as the percentage derived from the ratio of profit to investment.
Here is how you can calculate returns:. This will print the returns that the stock has been generating on daily basis. Multiplying the number by will give you the percentage change.
Quantopian is a free, community-centered, hosted platform for building and executing trading strategies. It's powered by zipline, a Python library for algorithmic. Python for Finance, Part 2: Intro to Quantitative Trading Strategies. Looking more into quantitative trading strategies and determining returns.
After resampling the data to months for business days , we can get the last day of trading in the month using the apply function. The concept of moving averages is going to build the base for our momentum-based trading strategy. In finance, analysts often have to evaluate statistical metrics continually over a sliding window of time, which is called moving window calculations. Let's see how we can calculate the rolling mean over a window of 50 days, and slide the window by 1 day.
You'll see the rolling mean over a window of 50 days approx. Moving averages help smooth out any fluctuations or spikes in the data, and gives you a smoother curve for the performance of the company. And you can see the difference for yourself, how the spikes in the data are consumed to give a general sentiment around the performance of the stock. Here comes the final and interesting part, designing and making the trading strategy. Momentum-based strategies are based on a technical indicator which capitalizes on the continuance of the market trend. We purchase securities that show an upwards trend and short-sell securities which show a downward trend.
The SMAC strategy is a well-known schematic momentum strategy.
It is a long-only strategy. Momentum, here, is the total return of stock including the dividends over the last n months. This period of n months is called the lookback period. There are 3 main types of lookback periods: short term, intermediate term, and long term.