Files
quanxiel/course/Full Algorithmic Trading Using Python/03-key-concepts.md
T

30 lines
12 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 03 · Key Concepts(关键概念:时间处理·骨架·Symbol)
- **系列**:Full Algorithmic Trading Using Python
- **频道**:TradeOptionsWithMe | **本集**:Key Concepts(关键概念:时间处理·骨架·Symbol)
- **时长**:10 分 5 秒 | **原视频**:https://youtu.be/28kE5JIi4-0
- **本地视频**:[videos/03-key-concepts.mp4](videos/03-key-concepts.mp4)
## 🎯 本集要点(中文导读)
首集进入 **QuantConnect API**,讲**时间处理**与**算法骨架**、**Symbol**。
- **Lean 引擎**:QuantConnect 基于开源 Lean。理解 Lean 如何处理时间至关重要。
- **前视偏差(Look-ahead Bias)**:回测时若误用未来数据,回测会"看起来很好",实盘必崩。示例:用"当日收盘价"做决策=偷看未来。
- **Lean 的时间规则**:数据是**流式**的;一根 bar **只能在其 end time 及以后**使用。用日线时,用周五收盘价做的决策,要到下一个 bar(周一开盘)才真正发出。
- **数据形状**:tick(单一时间点)vs bar(有区间,含起止时间);支持日/时/分/秒 bar,也可自定义 consolidated bar。同一算法可混用多种分辨率。
- **time frontier(时间前沿)**:不能访问其之后的数据;默认时区为**纽约**。
- **算法骨架**:所有算法继承 `QCAlgorithm`,提供大量辅助函数/属性:
- `Initialize()`:初始化(加数据、设回测参数、初始化变量等)
- `OnData(data)`:每来新数据(tick 或 bar 到达 end time)时触发——最常用
- 还有 `OnEndOfDay`、`OnOrderEvent` 等
- `self.Time`(当前时间)、`self.Securities`、`self.Portfolio`
- **Symbol 对象**(标识证券):形如 `ticker+hash`,编码了 8 个属性:`Value`(ticker)、`SecurityType`、`Market`、`HasUnderlying`、`Date`、`OptionType`/`OptionRight` 等。
- ⚠️ **别直接用 ticker**:ticker 会变、会被不同券商复用,产生歧义。应始终用 **Symbol 对象**:`self.AddEquity("AAPL").Symbol` 保存复用。
## 📝 完整文稿(英文 · 自动转写)
> 由本地 ASR(faster-whisper)从视频音轨转录,未人工校对,供检索/精读使用。原始讲解以上方视频为准。
Welcome back to the third video of this algorithmic trading video series. This video is the first video where we actually start looking at the QuantConnect API. The goal of this video is to present some of the most important key concepts as well as a basic trading algorithm skeleton inside of QuantConnect. With this knowledge, we can then finally start creating our very first basic trading algorithm in the next video lesson. Like last time, I want to start by quickly thanking the sponsor of this video series. QuantConnect has seen some of my algorithmic trading videos and they have offered to sponsor this series. So, thanks for the support. QuantConnect's trading engine is powered by the open source Lean engine. To truly understand how you can develop trading algorithms using QuantConnect and Lean, it is essential to understand how Lean handles time. For this, let's first quickly look at one of the biggest problems related to handling time inside of an algorithmic trading engine. Namely, look ahead bias. When testing your trading algorithm on historical data, you have to simulate the passing of time. If this is done incorrectly, your trading bot might try to access future data to make its trading decisions. Let me give you a very simple example of look ahead bias. Let's say you have a bot that only trades Apple. For its trading decisions, it compares the closing price of the current day to the current price. The problem with this is that the closing price is not yet actually known, so using that to make decisions is like seeing the future. I know this might seem like an obvious mistake, but in more complex algorithms, look ahead bias can be much, much harder to detect. The worst part about look ahead bias is that back testing will work just fine. Only when you switch to live trading, will your bot stop working since it can't actually access the future data anymore. The Lean engine uses streaming technology that allows you to access data from the past or present. This makes life a lot easier since you won't have to worry about look ahead bias anymore. However, it can also lead to some confusion, especially when you're just starting out, which is why I want to put special emphasis on this topic. One Connect has two shapes of data. On the one hand, they have tick data, which is data for a single point in time, and on the other hand, there is bar data, which has a period. Since bar data covers a period, it has both a start time and an end time. For tick data, start and end time are the same. The important thing to understand is that Lean only allows you to use the data of a bar at its end time, so that the start of the next bar or later. This restriction ensures that you don't accidentally use future data and thereby full prey to look ahead bias. This means that, if your algorithm uses the closing price of a given bar to make a trading decision, any orders sent out based on this decision are first sent out at the start of the next bar. So, if you're using daily data and you want to use Friday's closing price, your orders will first be ready at the start of the next bar, which will be on Saturday. But since markets usually are closed on Saturday, they would first be sent out at the open of the following Monday. So the Friday bar includes all ticks from Friday at 0 o'clock to Friday right before midnight. Besides daily bars, QuantConnect also has hourly, minutely and secondly bars. Besides that, you can also create your own custom consolidated bars for custom resolutions. You will learn how to do this in one of the later videos. The same algorithm can also use multiple different bar resolutions for different data. The current time is controlled by the so-called time frontier. To avoid look ahead bias, you cannot access anything behind this time frontier. Note that if you're using custom data, there are a couple of extra things you need to look out for, but more on that in a later lesson. The default time zone inside of a QuantConnect algorithm is New York's time zone, but this can be reconfigured if you want to. Now that you hopefully understand how time is being handled inside of Lean, let's move on to the skeleton of a QuantConnect algorithm. Every algorithm extends the QC algorithm class which provides you with hundreds of helper functions and properties. If for instance, you ever want to access the current time to check where the time frontier is at, you can do so with self.time inside of the QC algorithm class. Besides that, this class implements portfolio, securities, transactions and data subscription management. Let me quickly walk you through a few of the most commonly used properties just to give you a basic idea of this class. But if this all seems a little overwhelming, don't worry, in my opinion the best way to learn this is by creating plenty of example algorithms, which is what we will start doing in the next videos. Probably the most used method of the QC algorithm class is the initialised method. As the name implies, this method is used to initialise your algorithm. You can add what data you want, which models you want to use, edit back testing settings, initialise helper variables and much more. Next up, if a bunch of event handlers, I'd say the most commonly used one is the on data method. This is called every time the algorithm receives new data, so every time a bar reaches its end time or a tick event occurs. Besides that, there also are more specific event handlers such as on end of day or on order event, which are called at the end of each day and in case of an order event like an order being filled. Other important properties of the QC algorithm class include self.securities, which is an array of security objects and self.portfolio, which is used to access the holdings inside of your portfolio. Speaking of securities, let's now take a look at how QuantConnect handles accessing securities. For this, QuantConnect uses symbols that look something like this, a ticker followed by a hash code. This weird looking string encodes all the important information regarding a security in an easy to process fashion. To understand what exactly it encodes, let's take a closer look at the properties of a symbol object. But first, note that a symbol object can not only represent a stock, it can be anything from an equity, option, future, forex pair, cryptocurrency or a CFD. A symbol object has 8 main properties. The first is its value, which is basically the ticker of that security. More exactly, this is the ticker that you referenced when adding the data for this security. So for instance, the value of this symbol would be AAPL. Next up, a symbol object also has a security type, which can be an equity, option, future, forex pair, cryptocurrency or a CFD. Then there also is the market property, which can be used to determine on which market the security trades. For most equities, this would just be the US market. But for forex or cryptos, the same currency can be traded on different markets such as GDAX or Bitfinex. This property helps to distinguish between them. Besides that, the ultra-stable property symbol dot has underlying, which indicates whether this security is a derivative or not. For instance, has underlying would be true for options or futures, but falls for equities. In addition to that, we have symbol dot date, which saves the earliest listing date for equities and the expiration date for futures or options. For options, other relevant properties include symbol dot option type and symbol dot option right, which represent whether the option is an American or European option and whether it is a cool or a poor option. All these properties are encoded into the hash string after the ticker. So why can't we just save the ticker by itself? Usually, QuantConnect does allow you to use the ticker of a security directly to add and access data. However, this is not recommended since tickers do not hold nearly as much information as symbol objects. The problem is that the ticker of a stock can change and it can be reused by different brokerages. This can lead to a lot of unwanted ambiguity, which you definitely want to avoid. That's why you should always use a symbol object instead of a ticker. To create and save a symbol object, you can simply add dot symbol when adding data and save this object into a variable. So for example, let's say you have an algorithm that trades apple. Then you can add apple data by using self dot add equity aapl. You can then save the apple symbol object by appending dot symbol to add equity. You can then later use this save variable when sending out an order for apple instead of using the aapl ticker. But that's just to give you a short taste of a few helper functions that the QC algorithm class provides. In the next video, we will start exploring the API in a more detailed manner and we might even write our first simple trading bot. For now, you should just understand how lean handles time and more specifically you should always remember that events are transmitted at the end time of each bar. So at the end time of the last bar, the on data method of the QC algorithm class is called in which you can analyze the data from this bar and use it to make trading decisions. You can't access any data beyond the time frontier. Furthermore, you now hopefully understand how QuantConnect allows you to identify different securities, namely by using symbol objects. It is highly recommendable to always use the actual symbol object instead of the ticker for this. Like I said, I hope you enjoyed this video and learned something new. If you did, don't forget to subscribe, turn on the notification bell and smash the like button for more content like this. Thanks for watching.