I recently ran into an issue that I think might be helpful to share with the broader community. I am currently running a live algorithm which I have developed over the past couple of years. I implemented this algorithm in C#, and because of this, the infrastructure I have been using is naturally in that language. I recently have been looking to add more sophisticated statistical techniques to improve my strategy, and have found the libraries in C# quite limiting. Because python is better suited for this with the libraries QuantConnect supports, I looked to transition my code to Python. For some reason, I could not seem to get my algorithm to translate properly, so I tackled this problem from a different angle: Implementing a python script within my C# algorithm. 

In the attached backtest you will see just how I was able to do it. Now there may be a better way to do this, so feel free to share any input. QuantConnect uses Pythonnet for the C#->Python interpretation so understanding how that package works is helpful. Some things I noticed

  1. You will see that the python portion of the code is indented all the way to the left. For some reason, the python interpreter is extremely sensitive to tabs and spaces and it needs to be written exactly as you would a normal script, including the indents.
  2. Converting the history call from C# to python requires the call to be converted into a list so that it is possible to then convert that into a DataFrame in python. I could not get it to work otherwise. I looked into calling the history function from within the python script but that proved to be too much of a pain to debug.
  3. The function must be called as a dynamic type. It is possible to return any datatype in python, which you can then pass back into a python script (i.e. with how I pass the HMM model back through to update). Most data types convert pretty easily between the two languages. Check out the pythonnet documentation for more regarding conversions.

I would like to give a special thank you to Alex with the QuantConnect support team for giving me the initial C# code to properly write this up, as well as Jack who wrote up the original HMM python code. The original code can be found here: https://www.quantconnect.com/forum/discussion/6878/from-research-to-production-hidden-markov-models/p1

 

Author