Just a very quick video to give you an idea on how easy it is to get up and running. This is a Bollinger Band Script that is included in Trend Following Systems: A DIY Project – Batteries Included
Category Archives: Python
Get My Latest Book-TrendFollowing Systems: A DIY Project – Batteries Included
Just wanted to let you know that my latest book has just been published.
Trend Following Systems: A DIY Project – Batteries Included: Can You Reboot and Fix Yesterday’s Algorithms to Work with Today’s Markets?
Trend Following Systems: A DIY Project – Batteries Included
This book introduces my new Python back-tester, TradingSimula-18. It is completely and I mean completely self contained. All you need is the latest version of Python and you will be up and running trading systems in less than 5 minutes. Fifteen years of data on 30 futures is included (data from Quandl). I have included more than 20 scripts that you can test and build on. This back-tester is different than the one I published in the Ultimate Algorithmic Trading System Toolbox. It utilizes what I call the horizontal portfolio spanning paradigm. Instead of sequentially testing different markets in a portfoio:
It process data in the following manner:
This form of testing allows for decisions to be made on a portfolio basis at the end of any historic bar. Things like inputting portfolio performance into an allocation formula is super simple. However, this paradigm opens up a lot of different “what-if” scenarios.
- What If I Limit 2 Markets Per Sector
- What If I Turn Off A Certain Sector
- What If I Liquidate The Largest OTE loser
- What If I Liquidate The Largest OTE winner
- What If I Only Trade The Ten Markets With The Highest ADX Values
All the data and market performance and portfolio performance is right at your fingertips. Your testing is only limited by your creativity.
The best part is you get to learn raw Python without having to install complicated libraries like SciKit, Numpy or Pandas. You don’t even need to install distributions of commercial products – like Anaconda. Don’t get me wrong I think Anaconda is awesome but many times it is overkill. If you want to do machine learning then that is the way to go. If you want to test simple Trend Following algorithms and make portfolio level decisions you don’t need a data science application.
There isn’t a complicated interface to learn. Its all command line driven from Python’s IDLE. 90% of the source code is revealed for the back-testing software. Its like one of those see-thru calculators. You see all the circuits and semiconductors, but in Python. So you will need to flow through the code to get to the sections that pertain to your test. Here is a small sample of how you set up the testing parameters for a Donchian Script.
Everything is batched processed: set up, pick market or portfolio, run. Then examine all of the reports. Here is an example of the sector analysis report.
Plus I include EasyLanguage for the majority of the scripts. Of course without the portfolio level management. I am working on a new website that will support the new book at TrendFollowingSystems.com.
Please take a look at my latest book – it would make an awesome Christmas present.
Python Script To Import List of Trades into TradeStation’s EasyLanguage – Sort of
Converting A List of Trades, Dates and Prices Into EasyLanguage Arrays:
As the old saying goes “a picture is worth a thousand words!” Have you ever been given a list of trades like this:
But really wanted to see this:
I have created a small Python script that will take a list of trades like those listed in table above and create the following EasyLanguage:
This just creates the arrays that you can use to graph the trades on a chart. If you are using exact prices you got to make sure your data aligns with the prices in the list of trades. If you are only entering on the open or the close of the bar then the price array isn’t necessary.
The following Python script will also be helpful if you want to learn how to open a file in csv format, read it into lists, convert it and then save the output to a file.
And here is the EasyLanguage code that will step through the arrays and place the trades accordingly. I noticed that sometimes two trades could occur on the same bar, but only two and you will notice in the code where I programmed this occurrence.
How to Create a Dominant Cycle Class in Python
John Ehlers used the following EasyLanguage code to calculate the Dominant Cycle in a small sample of data. If you are interested in cycles and noise reduction, definitely check out the books by John Ehlers – “Rocket Science for Traders” or “Cybernetic Analysis for Stocks and Futures.” I am doing some research in this area and wanted to share how I programmed the indicator/function in Python. I refer you to his books or online resources for an explanation of the code. I can tell you it involves an elegantly simplified approach using the Hilbert Transform.
In my Python based back tester an indicator of this type is best programmed by using a class. A class is really a simple construct, especially in Python, once you familiarize yourself with the syntax. This indicator requires you to refer to historical values to calculate the next value in the equation: Value1[4], inPhase[1], re[2], etc.,. In EasyLanguage these values are readily accessible as every variable is defined as a BarArray – the complete history of a variable is accessible by using indexing. In my PSB I used lists to store values for those variables most often used such as Open, High, Low, Close. When you need to store the values of let’s say the last five bars its best to just create a list on the fly or build them into a class structure. A Class stores data and data structures and includes the methods (functions) that the data will be pumped into. The follow code describes the class in two sections: 1) data declaration and instantiation and 2) the function to calculate the Dominant Cycle. First off I create the variables that will hold the constant values: imult and qmult. By using the word self I make these variables class members and can access them using “.” notation. I will show you later what this means. I also make the rest of the variables class members, but this time I make them lists and instantiate the first five values to zero. I use list comprehension to create the lists and zero out the first five elements – all in one line of code. This is really just a neat short cut, but can be used for much more powerful applications. Once you create a dominantCycleClass object the object is constructed and all of the data is connected to this particular object. You can create many dominantCycleClass objects and each one would maintain its own data. Remember a class is just a template that is used to create an object.
The second part of the class template contains the method or function for calculating the Dominant Cycle. Notice how I index into the lists to extract prior values. You will also see the word self. preceding the variable names used in the calculations. Initially I felt like this redundancy hurt the readability of the code and in this case it might. But by using self. I know I am dealing with a class member. This is an example of the ” . ” notation I referred to earlier. Basically this ties the variable to the class.
Okay we now have the class template to calculate the Dominant Cycle but how do we us it?
Here I assign domCycle the object created by calling the dominantCycleClass constructor. TempVal1 is assigned the Dominant Cycle when the function or method is called using the objects name (domCycle) and the now familiar ” . ” notation. See how you can also access the imult variable using the same notation.
Here is the code in its entirety. I put this in the indicator module of the PSB.
Pyramiding with Python
A reader of the “UATSTB” asked for an example of how to pyramid in the Python System BackTester (PSB). I had original bug where you couldn’t peel off all of the positions at once. If you tried then the PSB would crash. I have now fixed that problem and here are the necessary lines to add on another position after the initial positions is put on. I am using a simple moving average crossover to initiate the first position and then if the longer term moving average is positive for 4 days in a row I add on another position. That’s it. A max of two position only. The system either gets reversed to the other side, stopped out or takes profits. Attached in this post is the module that fixes the pyramiding problem and the code for this system in its entirety. I will also put the fix in the version 2.0 download.
I only put in the summary of code that will create the initial position and then add 1 more. Notice the highlighted code from line 3 to 7. Here I am using a simple loop to determine if the the 39-day moving average is increasing/decreasing consecutively over the past four days. If the upCnt == 4 then I add a long position. Notice how I test in the Long Pyramid Logic the values of mp and upCnt. I only go long another position if I am already long 1 and upCnt == 4.
Here is a print out of some of the trades:
While I was posting the trades I found something that struck my funny – look at line 5 (highlighted). The short pyramid trade occurs at a higher price than the initial short – at first I thought I had made a programming error. So I thought I would double check the code and then do some debugging. Instead of invoking the debugger which is really cool and easy to use I decided to just print out the results to the console.
As you can see the longer term moving average is moving down event though price has increased. Take a look at this chart and you can see multiple occurrences of this.
Remember to copy and replace the tradeClass.py in you PSB2.0 directory – this fixes the pyramid bug. Also copy the DMAPyra.py to the same directory. If you haven’t as of yet download the PSB from this website and buy the book for a very good description.
Restructuring Trade Entry with PSB
It has been brought to my attention by a very astute reader of the book that the ordering of the buy/sell/longliq/shortliq directives creates a potential error by giving preference to entries. The code in the book and my examples thus far test for a true condition first in the entry logic and then in the exit logic. Let’s say your long exit stop in the Euros is set at 11020, but your reversal is set at 11000. The python back tester will skip the exit at 11020 and reverse at 11000. This only happens if both stops are hit on the same day. If this happens you will incur a 20 point additional loss. You can prevent this by using logic similar to:
Notice bow I compare the price level of stb and stopb [stb – reversal and stopb – liquidation]. I added this to the long entry logic – the code is only executed if the entry is less than the exit (closer to the current market). I am in the process of restructuring the flow so that all orders will be examined on a bar by bar basis and the ones that should take place (chronologically speaking) will do so and be reflected in the performance metrics. This can cause multiple trades on a single bar. This is what happens in real trading and should be reflected in the PSB. This is where the lack of a GOTO creates a small headache in Python. The ESB already takes this into consieration. I will post when I finalize the code.
Version 2.0 of Python System Back-tester Available
I have just wrapped up the latest version of the Python System Back-tester (PSB).
I have added some more portfolio performance metrics and you will see these in the performance reports. The most useful addition is the concept of the .POR file when you run a system. Instead of having to select your data files each time you run a system, you can build a .POR file with a list of files/markets you want to batch run.
Here is an example of a Portfolio file:
TY.CSV
CU.CSV
SB.CSV
S2.CSV
QG.CSV
QM.CSV
C2.CSV
Just make sure you put the .POR file inside the same folder that contains your testing data. I have included a TestPortfolio.por file in version 2.0. I would treat the different versions as completely separate applications. Your existing .py algorithm files will need to be slightly modified to work with version 2.0.
This line of code needs to be modified from this:
systemMarket.setSysMarkInfo(sysName,myComName,listOfTrades,equity)
to this:
systemMarket.setSysMarkInfo(sysName,myComName,listOfTrades,equity,initCapital)
This line is near the bottom of the overall loop. I added the initCapital variable so you could do position sizing and the performance metrics would reflect this initial value.
And set initCapital to a pertinent value. I put it right below the sysName variable:
sysName = ‘BollingerBandSys’ #System Name here
initCapital = 100000 #starting account balance
Also I corrected a small bug in the main loop. You should change this:
for i in range(len(myDate) – numBarsToGoBack,len(myDate)):
to
for i in range(len(myDate) – (numBarsToGoBack-rampUp),len(myDate)):
In another post I will show how the portfolio performance metrics have changed. I hope you like the new version. I will be adding a library of trading systems utilizing this new version in a few days.
If you want to download Version 2.0 – just go the the following link
If You Can Do This – You Can Test Any Algorithm!
All the unnecessary lines of the Python System Back-Testing Module have been hidden. Only the lines that you need to develop the next great algorithm are included. Reads sort of like English. This snippet introduces you to the use of functions and lists – two major components of the Python language. If you buy my latest book – “The Ultimate Algorithmic Trading System Toolbox” then simply email me or sign up through the contact form and you will get version 2.0 for free!
Turtle Volatility Loss in Python Back Tester – Part 3 in Series
The Turtle N or Volatility is basically a 20-day Average True Range in terms of Dollars. This amount is considered the market volatility. In other words the market, based on the average, can either move up or down by this amount. It can move much less or much further; this is just an estimate. If the market moves 2 N against a position, then as a Turtle you were to liquidate your stake in that commodity. The logic indicates that if the market has a break out and then moves 2 N in the opposite direction, then the break out has failed. First the code must be defined to represent the market volatility. This is simple enough by using the sAverage function call and passing it the trueRanges and 20 days. There’s no use in converting this to dollars because what we want is a price offset. Once a position is entered the turtleN is either added to the price [short position] or subtracted from the price [long position] to determine the respective stop levels. Look at lines 2, 8 and 17 to see how this is handled. An additional trade code block must be added to facilitate this stop. Lines 17 to 28 takes care of exiting a long position when the market moves 2 N in the opposite direction. This new stop is in addition to the highest/lowest high/low stops for the past 10 -20 days.
Turtle (Last Trade Was A Loser (LTL)) Filter – Part 2 in Series
How many of you believe if the last trade was a winner, the probability of the next trade being a loser is higher? The Turtles believed this and in this post I introduce the concept of filtering trades based on the prior trade’s success.
Here is a list of trades without the filter:
20090506 Turt20Buy 1 91.75000 0.00 0.00
20090622 Long10-Liq 1 103.14000 11290.00 11290.00
20090702 Turt20Shrt 1 102.26000 0.00 0.00
20090721 Shrt10-Liq 1 100.80000 1360.00 12650.00
20090803 Turt20Buy 1 104.61000 0.00 0.00
20090817 Long10-Liq 1 101.99000 -2720.00 9930.00
20090824 Turt20Buy 1 107.71000 0.00 0.00
20090902 Long10-Liq 1 100.97000 -6840.00 3090.00
20090902 Turt20Shrt 1 100.10000 0.00 0.00
20090917 Shrt10-Liq 1 105.87000 -5870.00 -2780.00
20090924 Turt20Shrt 1 100.02000 0.00 0.00
20091008 Shrt10-Liq 1 104.72000 -4800.00 -7580.00
20091012 Turt20Buy 1 106.13000 0.00 0.00
20091030 Long10-Liq 1 109.43000 3200.00 -4380.00
20091113 Turt20Shrt 1 108.95000 0.00 0.00
20091223 Shrt10-Liq 1 106.03000 2820.00 -1560.00
And here are the trades with filter engaged:
20090506 Turt20Buy 1 91.75000 0.00 0.00
20090622 Long10-Liq 1 103.14000 11290.00 11290.00
20090824 Turt20Buy 1 107.71000 0.00 0.00
20090902 Long10-Liq 1 100.97000 -6840.00 4450.00
20090902 Turt20Shrt 1 100.10000 0.00 0.00
20090917 Shrt10-Liq 1 105.87000 -5870.00 -1420.00
20090924 Turt20Shrt 1 100.02000 0.00 0.00
20091008 Shrt10-Liq 1 104.72000 -4800.00 -6220.00
20091012 Turt20Buy 1 106.13000 0.00 0.00
20091030 Long10-Liq 1 109.43000 3200.00 -3020.00
20100126 Turt20Shrt 1 104.09000 0.00 0.00
20100218 Shrt10-Liq 1 108.12000 -4130.00 -7150.00
20100219 Turt20Buy 1 109.37000 0.00 0.00
20100322 Long10-Liq 1 108.96000 -510.00 -7660.00
Check for yourself – you will notice that a trade after a winner is skipped. Trades are not picked back up until a loser is reported. Trading like this is quite easy but backtesting is quite a bit more difficult. I talk about this in the book where you have to switch between actual trading and simulated trading. The beauty of the Python BackTester is that it is somewhat easy to incorporate this into the testing logic. All you have to do is determine if the prior real or simulated trade is a loser. If it isn’t then you still must keep track of all trades, but don’t book the trades that follow the winner. I have created a testing module that does just that. Here is a snippet of the code:
I will include this in an update to the Python backtester for registered users of this site.