Learning To Code – This Is What I Use It For.

*I decided to spend lockdown learning to code python to create some useful tools for trading*

Welcome back to the blog. In this post I am going to share with you my progress in regards to learning to code in the Python language, why I decided to learn to code and the benefits of doing so and I am also going to show you some cool projects I have been working on. Please feel free to skip the first few paragraphs of this post to get to the trading content if coding does not interest you.

What is Python?

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. https://www.python.org/doc/essays/blurb/

Why I decided to learn python, what I have done to learn (udemy/forums/books).

I am by no means and expert or established Python coder and could not get a job as a software developer but what I do have is the basics and understanding of finance. What I have also found is that online forums and also blog posts are a fantastic resource when trying to code a specific project or task because most of the time, someone has completed the same task or at least one very similar and they know the solution.

A lot of coding is “open source” and this means a software for which the original source code is made freely available and may be redistributed and modified. This allows faster progression and improvements of projects which is great for everyone.

What are the benefits of learning to code?

It’s a language and a widely used one, every piece of technology you use is built on code. On a much simpler level however, it is a powerful tool for data analysis that can compute infinitely more data than the human brain and much faster. I have always been a big fan of using Excel but Python is another step up from that.

For example, I have a basic stock trading system that uses a few technical indicators and daily price data. I download 100 days worth of daily price data for 201 different stocks and indices and apply formula to them to generate trade entry and exit signals. Using Microsoft Excel, this task takes on average just over 7 minutes to download the data and check for any new trade signals.

In Python, this same task takes under 30 seconds.

Project 1: FX Volatility Table & Chart.

This is my favourite project that I have completed so far since learning to code because both volatility and FX currencies feature a lot in my trading. This project was to assist me in determining the levels of volatility in the major FX currencies across multiple timeframes in order to assess whether volatility is at either extreme highs or extreme lows vs a longer term sample. I can then use this to influence my analysis.

The image below shows the output of my code.

FX volatility table and rolling monthly volatility of all FX currencies plotted as a graph.

The FX volatility table is easy to use and understand. It records the one month, three month, one year, three year and five year average daily price volatility of the major currencies vs the other currencies in the table. I have then added a 7th column which is a simple “indicator” that displays HIGH when the current one month (short term) volatility is above the five year (long term) volatility.

I have created the line graph as a way of plotting the monthly rolling price volatility of all the major FX currencies across a much longer period of time (13 years). This is as long as I have “accurate” price data for which is one of the issues I have found when learning to code. I am currently using free price data downloaded from Yahoo Finance and in future I am looking to purchase a data subscription.

I intend to use this graph as my own rudimentary FX VIX or volatility index.

FX volatility table showing average daily volatility for multiple FX currencies and multiple timeframes.

The image above shows a close up view of my FX volatility table as at 09/11/2020. My process for coding both of the volatility table and graph is explained in the notes below.

Project 2: FX Correlations Table.

This project is much simpler than the first but it is just as useful in my opinion. I have created a much larger table of FX data that displays the correlation coefficients of one FX currency pair vs multiple others based on the length of data downloaded as defined by the code.

As you can see in the image below, it is very simple to understand and organised in a grid formate for ease of use.

FX Majors correlation table (3 years of data).

I have used the major FX pairs in this table but the code is completely customisable in order to define what assets/securities you want to calculate the correlation coefficients of and are then displayed in the table. I also applied a basic conditional formatting rule to highlight the least correlated FX currency pairs in any single column for easy identification.

FX Majors correlation table exported to excel.

I have also added a final line of code to export the FX correlations table to excel format on demand which makes it easier to distribute and send to anyone who needs to use it for their own analysis. Again, to reiterate my point earlier in the post about the power of python vs excel, I could do all of this in excel using VBA macros but by using Python I can download the 5 years of price data, sort it and calculate the correlation coefficients of each currency pair and export it to excel in less than 10 seconds.

This same task takes more than 60 seconds in excel using the same Yahoo Finance data.

Financial Market Correlations.

I can adjust the code in my FX correlation table to produce multi timeframe price correlation comparisons for any assets or securities so long as there is price data available. For example, I could use Gold and the Australian Dollar in order to determine when there might be adverse market conditions and a potential reversion trade set up is begging to occur. The basic theory behind this type of trade is that when the price of two assets, that normally has strong positive correlation, is showing low positive or even negative correlation then you can buy one asset and sell the other in the hope that the long term price correlation returns.

For more information on market correlations and trading them, please click on the blog post below.

https://diaryofafinancekid.com/2020/01/24/the-market-correlation-divergence-hedge/

Project 3: Investment Portfolio Optimisation.

This project came as part of my Udemy course on python coding in finance and investing. I have tailored the project to my own needs and used the Markowitz Portfolio Optimisation theory to find the most effective weighting for a selection of 3 investment products that I currently have funds invested with.

The idea behind the theory and execution is that the average successful investor looks to get the maximum return on their investment for the minimum amount of risk. Based on various weights of investments in a portfolio you change both the potential returns and volatility of the portfolio and there is an optimum weighting depending on your risk appetite.

Naturally one would assume greater risk = greater returns but this is not always the case as shown by the scatter plot of various portfolio weightings of my 3 investment products. The outer edge of the scatter plot is called the efficient frontier.

Scatter plot showing portfolio volatility vs returns of random using random generated weights.

The efficient frontier is the set of optimal portfolios that offer the highest expected return for a defined level of risk or the lowest risk for a given level of expected return. Portfolios that lie below the efficient frontier are sub-optimal because they do not provide enough return for the level of risk. Portfolios that cluster to the right of the efficient frontier are sub-optimal because they have a higher level of risk for the defined rate of return.

Maximum returns for minimum risk would be the point on the graph on the very left at the edge of the curve.

This code actually uses a Monte Carlo type simulation to run 1000 random weighting combinations to find the various reward:risk ratios and plot them on the scatter chart like as seen above. Therefore every time you re-run this code you will likely get a slightly different scatter graph and optimised weighting. The difference between weights of investments in the portfolio will likely be very small as the random weights generated are to 8 decimal places.

My process for coding the portfolio optimisation, running the simulation of random weights and plotting it on the scatter graph is explained in the notes below.

End note.

I thought I would write this blog post to show you why I have been slightly “more busy” than usual in the past few weeks and why the number of posts I have been publishing has dropped slightly. I also think that coding and algorithmic trading is a very popular topic of discussion amongst traders who all would love to be able to profit from the markets without actually having to place trades themselves.

Everything I have learnt so far about coding, the python language and the projects I have made so far have been from online sources and it has cost me very little except from time dedicated to learning. Anyone can start to learn code just like anyone can learn a new foreign languages.

I will be working on hosting and displaying live versions of my FX Volatility Table & Chart FX Correlations Table on this blog site for you all to be able to see and use in your own analysis.

If you are interested in learning my personal trading strategies, please consider my Mastering The Markets – Retail Trading Course. Head over to my Trading Education page to check out all of my education packages and the deals available.

Useful Links:

All my technical analysis is done using the TradingView platform. You can get access via the link below.

https://tradingview.go2cloud.org/SH3bP

My preferred broker of choice is IC Markets. Low spreads and trading costs really help long term profitability. A link to their site is below.

https://www.icmarkets.com/?camp=38537

FTMO Trader Funding Programme.

https://ftmo.com/?affiliates=335

Thanks for reading and please don’t forget to LIKE, SHARE and FOLLOW my blog to stay up to date with the latest market analysis and trading education posts.

DISCLAIMER: None of the information posted on this site is to be considered investment/financial advice. Trading is high risk and you should only trade with money you can afford to lose.

1 thought on “Learning To Code – This Is What I Use It For.

Comments are closed.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close