12 KiB
11 · Forex Trading(外汇 · 均值回归)
- 系列:Full Algorithmic Trading Using Python
- 频道:TradeOptionsWithMe | 本集:Forex Trading(外汇 · 均值回归)
- 时长:13 分 27 秒 | 原视频:https://youtu.be/CoIu-SXDRvY
- 本地视频:videos/11-forex-trading.mp4
🎯 本集要点(中文导读)
本集讲 Forex(外汇)与 CFD 算法,并演示 自定义图表。
- 数据添加:
self.AddForex("EURUSD", resolution, market);市场可选 Oanda(71 组,GMT 时区)或 FXCM(39 组,东部时区);可设杠杆(默认无)。 - CFD:
self.AddCFD(...),数据来自 Oanda(51 个合约);⚠️ 实盘 CFD 目前仅支持非美国居民。 - 数据形态差异:Forex 只有 QuoteBar,没有 TradeBar(QuoteBar 由买卖报价合并;TradeBar 由真实成交合并)。
- 示例 bot:EURUSD 的均值回归策略——价偏离 20 日均线够多就反向入场,回归后平仓;用 Bollinger Bands 辅助判断;用
self.Plot绘制价格、布林带、以及买/卖/平仓的散点标记(entry/exit)。 - 工具:
self.Plot自定义图表可直观核对入场点;回测结果该示例约 +27%(同期 EURUSD 基本横盘)。
📝 完整文稿(英文 · 自动转写)
由本地 ASR(faster-whisper)从视频音轨转录,未人工校对,供检索/精读使用。原始讲解以上方视频为准。
Hello and welcome back to another video of my Python and QuantConnect algorithmic trading course. If you're new to the series make sure to start from the beginning since you otherwise might not be able to follow along properly. In this video you will learn how to create trading algorithms for Forex and CFD trading. In the previous videos all the example trading bots exclusively traded equities. However, all the lessons learned in those videos are just as important for Forex trading. As that, I will show you how to create custom plots when we get to implementing the example Forex trading bot for this video. The main difference between trading equities and Forex inside of QuantConnect is that instead of adding equity data in the initialized method, you add data for the currency pairs or CFDs that you want to trade. This can be done with a simple add Forex statement. When adding currency pairs using the add Forex method, you would usually specify three arguments. The first is the currency pair itself. This could for example be EuroUSD. For a full list of the over 50 supported currency pairs, check out the link documentation page in the description box below. The second argument is the resolution, which can be anything from tick resolution to daily resolution. The third argument is where you specify the market that you want the data for that currency to come from. Currently, QuantConnect supports two markets, namely Oanda and FXCM. Oanda supports 71 pairs and FXCM supports 39 pairs. Note that the Oanda data uses the GMT time zone while FXCM uses Eastern Standard Time. It is also possible to set leverage as another parameter of the add Forex method. By default, there is no leverage though. One of the main differences between Forex and equity data is that Forex data only supports quote bars and no trade bars. The difference is that quote bars are built by consolidating bits and asks from exchanges while trade bars are built from actual trades. For more details on quote bars and trade bars, check out the fourth video of this series. Before we move on to implementing an actual example Forexbot, let me quickly show you how you can add data for CFDs. Since this is very similar to Forex, I will not create an actual trading bot for CFDs in this video. The CFD data also comes from Oanda, which currently supports 51 different contracts. However, note that live trading these contracts is only supported for non-US residents at the moment. To add CFD data, you can simply use the add CFD method, which works pretty much the same as the add Forex method. For a full list of the supported CFDs, check out the documentation page linked below. That said, let's now move on to implementing a Forex trading bot. As always, I will start with a brief theoretical breakdown of the bot that we will code. For this video, we will implement a simple mean reversion strategy on the EuroUSD currency pair. The idea is that we expect the price to stay somewhere around its 20 day mean most of the time. In other words, we do not expect it to deviate from its 20 day moving average too much. However, if it does deviate by more than a certain amount, we take the opposite position and try to profit from the price moving back to its mean. To measure the degree of deviation, we use the standard deviation. If the price moves above its 20 day moving average by more than two standard deviations, we take a short position and if it falls below its 20 day moving average by more than two standard deviations, we open a long position. In either case, we close the position once the price crosses its 20 day moving average. Luckily, we won't have to implement this logic manually since there already is ready to use Indicator that does exactly what I just described. This indicator is known as the Bollinger Bands Indicator. To better understand our algorithm, we will plot the Bollinger Bands Indicator as well as mark the points where the algorithm opened and closed positions on a custom chart. With that said, let us now head over to QuantConnect and start writing the actual code for this trading bot. If you haven't already, make sure to create your free QuantConnect account using the link in the description box below. For the best learning experience, I highly recommend coding along, but I will also post a link in the description box that allows you to clone the finished code from this video. Outside of QuantConnect, we will create a new algorithm in the lab tab. Then we will start off by implementing the initialise method. For this, we first set the backtest time frame to the last 6 years. Thereafter, we leave the starting cash balance to be $100,000 for now. Now, it's already time to add the data for the Forex pair that we want to trade. I will be using the EuroUSD pair for this example, but feel free to try this with other currency pairs as well. To add the data, we use Add Forex. As the first argument, we specify EuroUSD. As the second one, we pass Daily Resolution and as the third, we will use the FXCM market. Note that you could also use another resolution or the Oanda market instead. We then save the symbol of this pair into the self.pair class variable. After adding the data, we want to create a Bollinger band indicator for this currency pair. We can do this with a helper method self.bb which checks 3 arguments. First, we pass our pair so that the indicator knows for which data it is. Then we specify the period that it covers and last but not least, we define the number of standard deviations that the upper and lower bands will deviate from the moving average. The most commonly used parameter values here are 20 days and 2 standard deviations, which is what we will use here as well. Now, let us move on to implementing the onData method. The first thing we do in the onData method is check whether the Bollinger band indicator is ready to use already. If it's not, we just return since we can't use it yet. Then we save the current price of our currency pair into a local variable named price. We can access the price by indexing the current data slice. Next up, we want to decide between two different cases. In the case that we aren't already invested, we check whether the current price is below the lower Bollinger band. If it is, we want to buy as much of EuroUSD as we can. We can accomplish this with set holdings. If instead the price is above the upper 2 standard deviation Bollinger band, we want to establish a short position. To do so, we once again use set holdings. The other case would be that we are already invested. Here, we need to implement the exit logic of the strategy. For this, we first check if we currently have a long position open. If that's the case, we check if the price is crossed above the middle moving average line of the Bollinger band indicator. If it has, we just liquidate the position. If we do not have a long position, we must have a short position. In that case, we need to check if the price has dropped below the moving average. If it has, we once again use self.liquidate to close any open positions. Now we are already finished with implementing the trade logic of this bot. However, before we move on to backtesting this bot, let me show you how you can add and create some custom charts. I will create a chart that plus the price of the currency pair and all three lines of the Bollinger band indicator. Furthermore, I will add symbols to this chart to indicate where this algorithm bought and sold. This can be very helpful when trying to understand when the algorithm made which trades and why. For this, we first head back to the initialised method and create a chart with the name Trade Plot. We save this chart into the variable stock plot. Then we will add three series to this chart. By default, new series will be line plots. However, to mark the entrant exit points of the trades, we want a sketch plot instead. We use Add Series to add a series to the stock plot. To create the series, we use the Series Constructure and pass 5 arguments. The first is the name of the series. The second is the type. The third argument determines whether the label is for the x or y axis. The fourth argument is the color and the final one specifies the shape. For all the details of different types, colors and shapes of these charts, check out the documentation page that I linked below. In total, we add three series for Bias, Shorts and Liquidations. After that, we add the chart to the algorithm. Next up, we have to specify which data we want to plot in the on data method. First, we can add plots for the Bollinger bands and price of the currency pair. We do this with self.plot which I've used many times in the previous videos. Then we need to add the data for the entry and exit markings. For this, we also use self.plot but since we specified that to be three scatter plots in the initialised method, we can use them here. So when buying, we mark the chart with the entry symbol at the price of the entry. We do the same for shorting and when we liquidate any positions. With that, we can now click on Build and Back just to look at the results. As you can see, the results of this time frame seem to look relatively good. The strategy managed to achieve a return of almost 27% which is not bad, especially considering that the EuroUSD currency pair traded pretty much sideways over the same period. On the right hand side, we can select a viewer custom trade plot on which we plotted the price of our pair, the Bollinger bands and the entry and exit markings. With all these plots visible at once, the chart is quite full. However, it is also possible to deselect some of the plots to make it cleaner. If we for example, only select the price, entry and exit plots, you can clearly see when this bot board, shorted and close positions. The green triangle is marked by, the red one is marked short and the blue dot mark exits. If you want to analyze this backed test report in more detail, feel free to clone this algorithm using the link in the description box below. In the next video, I will go over how you can trade options within QuantConnect. That said, I hope you enjoyed this video. If you are a fan of this series, make sure to smash the like button, subscribe and turn on the notification bell. Thanks for watching.