原文:
zh.annas-archive.org/md5/010eca9c9f84c67fe4f8eb1d9bd1d316
译者:飞龙 协议:CC BY-NC-SA 4.0
拥有便捷的金融数据对于进行算法交易至关重要。 金融数据可以是静态的,也可以是动态的。 静态金融数据是在交易时间内不会改变的数据。 静态数据包括金融工具列表、金融工具属性、金融工具的限价和上一个交易日的收盘价格。 动态金融数据是在交易时间内可能持续变化的数据。 动态数据包括市场深度、最后交易价格、金融工具的时间和数量,以及当日的最高和最低价格。 本章包括获取各种类型金融数据的配方。
以下是本章的配方列表:
您将需要以下内容才能成功执行本章的配方:
pyalgotrading
Python 包($ pip install pyalgotrading
)本章的最新 Jupyter 笔记本可以在 GitHub 上找到,网址为github.com/PacktPublishing/Python-Algorithmic-Trading-Cookbook
。
以下代码将帮助您与 Zerodha 建立经纪人连接,这将在本章中的所有配方中使用。 请确保在尝试任何配方之前已经按照这些步骤进行了操作。
与经纪人建立连接的第一步是获取 API 密钥。 经纪人会为每位客户提供唯一的密钥,通常是api-key
和api-secret
密钥对。 这些 API 密钥通常按月订阅收费。 在开始之前,您需要从经纪人网站上获取您的api-key
和api-secret
的副本。 您可以参考附录 I了解更多详细信息。
执行以下步骤:
>>> from pyalgotrading.broker.broker_connection_zerodha import BrokerConnectionZerodha
api_key
和api_secret
密钥。 这些是您独有的,经纪人将用它们来识别您的证券账户:>>> api_key = "<your-api-key>"
>>> api_secret = "<your-api-secret>"
>>> broker_connection = BrokerConnectionZerodha(api_key, \
api_secret)
您将获得以下输出:
Installing package kiteconnect via pip...
Please login to this link to generate your request token: https://kite.trade/connect/login?api_key=<your-api-key>&v=3
如果您是第一次运行此程序,且未安装kiteconnect
,pyalgotrading
会自动为您安装它。第 2 步 的最终输出将是一个链接。点击链接并使用您的 Zerodha 凭据登录。如果身份验证成功,您将在浏览器地址栏中看到一个类似于以下内容的链接:https://127.0.0.1/?request_token=<alphanumeric-token>&action=login&status=success
。
以下是一个示例:
https://127.0.0.1/?request_token=H06I6Ydv95y23D2Dp7NbigFjKweGwRP7&action=login&status=success
request_token
中:>>> request_token = "<your-request-token>"
>>> broker_connection.set_access_token(request_token)
broker_connection
实例现已准备好执行 API 调用。
pyalgotrading
包支持多个经纪人,并为每个经纪人提供一个连接对象类,具有相同的方法。它将经纪人 API 抽象在统一接口后面,因此您不必担心底层经纪人 API 调用,可以直接使用本章中的所有示例。设置经纪人连接的程序将因经纪人而异。如果您不是使用 Zerodha 作为经纪人,则可以参考 pyalgotrading 文档设置经纪人连接。对于 Zerodha 用户,之前的步骤就足够了。
金融工具,也被称为证券,是可以在交易所交易的资产。在交易所中,可能有成千上万种金融工具。金融工具列表在静态性质上是不变的,因为它在实时交易时段不会改变。金融工具可能会随时改变,但绝不会在同一天内发生变化。拥有这些数据是算法交易的第一步。本文介绍如何获取金融工具列表。
确保在 Python 命名空间中有 broker_connection
对象可用。请参考本章的技术要求部分进行设置。
使用 broker_connection
获取并显示所有可用的金融工具:
>>> instruments = broker_connection.get_all_instruments()
>>> instruments
我们得到了以下输出(您的输出可能有所不同):
本文使用 broker_connection
的 get_all_instruments()
方法获取所有可用的金融工具列表,该方法返回一个 pandas.DataFrame
对象。此对象被赋值给一个新属性instruments
,并在输出中显示。由于经常添加新的金融工具并定期更新现有的金融工具,因此此输出可能与您的输出不同。
金融工具具有各种属性,可以更深入地了解该工具,例如交易代码、交易所、交易段、最小变动价位等等。在下单时,也需要一些这些属性。本文列出并解释了经纪人支持的所有属性。所有这些属性都是静态的,意味着它们在实时交易时段不会改变。
确保instruments
对象在你的 Python 命名空间中可用。参考本章的 获取金融工具列表 配方来设置它。
列出经纪人提供的金融工具的所有属性:
>>> list(instruments.columns)
我们得到以下输出:
['instrument_token',
'exchange_token',
trading-symbol,
'name',
'last_price',
'expiry',
'strike',
'tick_size',
'lot_size',
'instrument_type',
'segment',
exchange]
获取金融工具列表 配方将所有工具作为 pandas.DataFrame
对象获取。调用其 columns
属性返回所有可用的列。每一列都是每个金融工具的属性。你可以在kite.trade/docs/connect/v3/market-quotes/#csv-response-columns
找到更多细节。
金融工具可能有固定的到期日,也可能没有。如果有,它们在到期日最后可用于交易。通常,现金段中的工具不会过期,而衍生品工具(来自期货和期权段的工具)具有短暂的有效期,并在指定日期到期。本配方展示了两种类型的工具以及如何获取它们的到期日期。到期日是静态数据,意味着在交易时间内不会更改。
确保broker_connection
和 instruments
对象在你的 Python 命名空间中可用。参考本章的 技术要求 部分来设置 broker_connection
。参考本章的第一个配方来设置 instruments
。
我们对这个配方执行以下步骤:
broker_connection
获取一个工具对象:>>> instrument1 = broker_connection.get_instrument('NSE',
'TATASTEEL')
instrument1
是否会到期:>>> print(f'Instrument expires: {instrument1.will_expire()}')
我们得到以下输出:
Instrument expires: False
broker_connection
获取另一个工具对象:>>> instrument2 = broker_connection.get_instrument('NFO-FUT',
TATASTEEL20AUGFUT)
在这里你不应该得到任何输出。这意味着你已成功获取了这个工具。
请注意,如果在此步骤中正确输入后仍然获得以下输出,请参考本章 获取金融工具列表 配方的输出表格,使用最新可用的 NFO-FUT 段脚本重试此步骤:
ERROR: Instrument not found. Either it is expired and hence not available, or you have misspelled the "segment" and "tradingsymbol" parameters.
这可能是因为带有 tradingsymbol TATASTEEL20AUGFUT
的工具在编写本书时可用,但自那时起已经到期,因此不再可用。
instrument2
是否会到期:>>> print(f'Instrument expires: {instrument2.will_expire()}')
我们得到以下输出:
Instrument expires: True
instrument2
的到期日期:>>> print(f'Expiry date: {instrument2.expiry}')
我们得到以下输出(您的输出可能不同):
Expiry date: 2020-08-27
步骤 1使用BrokerConnectionZerodha
类的get_instrument()
方法获取一个工具并将其分配给一个新属性instrument1
。该对象是Instrument
类的一个实例。调用get_instrument
所需的两个参数是交易所(NSE
)和交易符号(TATASTEEL
)。在步骤 2中,我们使用will_expire()
方法检查该工具是否将过期。此步骤的输出为False
。我们在步骤 3和步骤 4中重复相同的过程,这次是为了另一个工具,分配给一个新属性instrument2
,该方法对will_expire()
方法返回True
。这显示在步骤 4的输出中。最后,在步骤 5中,我们使用expiry
属性获取instrument2
的到期日期。
每种金融工具都有明确定义的价格范围。预计该工具价格在当天的价格范围内。在市场交易时间内,如果工具价格突破价格范围的上限或下限,交易所可能会暂停该工具的交易一段时间或整天。这是为了防止工具价格在一天内的突然上涨或下跌。价格范围的上限称为上限电路限制,下限称为下限电路限制。这些数据是静态的,意味着在一天内不会改变。但是,它们在一天到另一天之间可能会发生显着变化。本配方帮助查找金融工具的电路限制。
确保broker_connection
和instrument1
对象在您的 Python 命名空间中可用。请参阅本章的技术要求部分设置broker_connection
。请参阅本章的金融工具属性配方设置instrument1
。
获取并打印instrument1
的下限和上限电路限制:
>>> lower_circuit_limit, upper_circuit_limit = \
broker_connection.get_circuit_limits(instrument1)
>>> print(f'Lower circuit limit: {lower_circuit_limit}')
>>> print(f'Upper circuit limit: {upper_circuit_limit}')
我们得到以下输出(您的输出可能有所不同):
Lower circuit limit: 315.9
Upper circuit limit: 386
BrokerConnectionZerodha
类的get_circuit_limits()
方法将给定金融工具的下限和上限电路限制作为元组获取。此方法将Instrument
类型的对象作为参数。我们在这里使用instrument1
作为参数。
金融工具的市场深度是市场上买方和卖方的数据的时间顺序列表。买方列表是买方愿意以哪些价格及其相应数量购买该工具的价格和数量列表。类似地,卖方列表是卖方愿意以哪些价格及其相应数量出售该工具的价格和数量列表。如果您对市场深度的概念还不熟悉,本配方的*工作原理…*部分的解释将更清晰地解释。
市场深度有助于预测某一金融工具价格的走向。它还有助于了解具有大数量的订单是否会显著改变价格。市场深度具有动态性,意味着在实时交易时段内不断变化。此示例帮助实时查找金融工具的市场深度。
确保 broker_connection
和 instrument1
对象在您的 Python 命名空间中可用。请参阅本章的 技术要求 部分设置 broker_connection
。请参阅本章的 金融工具属性 部分设置 instrument1
。
获取并打印 instrument1
的买入市场深度和卖出市场深度:
>>> buy_market_depth, sell_market_depth = \
broker_connection.get_market_depth(instrument1)
>>> print(f'Buy Market Depth:\n{buy_market_depth}')
>>> print(f'Sell Market Depth:\n{sell_market_depth}')
我们得到以下输出(您的输出可能会有所不同):
Buy Market Depth:
orders price quantity
0 1 350.05 1
1 16 350.00 43294
2 5 349.95 1250
3 8 349.90 3134
4 5 349.85 1078
Sell Market Depth:
orders price quantity
0 1 350.10 25
1 7 350.15 1367
2 13 350.20 4654
3 13 350.25 2977
4 21 350.30 5798
BrokerConnectionZerodha
类的 get_market_depth()
方法获取给定金融工具的市场深度。此方法以 Instrument
类型的对象作为参数。在此处我们使用 instrument1
作为参数。市场深度显示为买方和卖方的不同表格。
买入市场深度 是一个包含五个条目或竞标的表格,按价格降序排列。每个条目表示市场上某一时刻可用的买家,给出的价格以及该价格可用的数量。
卖出市场深度 是一个包含五个条目或竞标的表格,按价格升序排列。每个条目表示市场上某一时刻已存在的卖家,给出的价格以及该价格可用的数量。
当买家和卖家匹配时,订单在交易所执行,条目从买方和卖方表格中删除。
金融工具的总待买入数量是在某一时刻所有待买入订单数量的总和。此数据具有动态性,并且在实时交易时段内随时可能发生变化。
确保 broker_connection
和 instrument1
对象在您的 Python 命名空间中可用。请参阅本章的 技术要求 部分设置 broker_connection
。请参阅本章的 金融工具属性 部分设置 instrument1
。
获取并打印 instrument1
的总待买入数量:
>>> total_pending_buy_quantity = \
broker_connection.get_total_pending_buy_quantity(instrument1)
>>> print(f'Total pending BUY quantity: {total_pending_buy_quantity}')
我们得到以下输出(您的输出可能会有所不同):
Total pending BUY quantity: 1319590
BrokerConnectionZerodha
类的 get_total_pending_buy_quantity()
方法在任意时刻获取给定金融工具的总买入数量。此方法以 Instrument
类型的对象作为参数。在此处我们使用 instrument1
作为参数。
金融工具的总待售数量是在某一时刻所有待售订单数量的总和。此数据是动态的,可能在交易时间内的任何时刻变化。
确保在你的 Python 命名空间中有broker_connection
和instrument1
对象可用。参考本章的技术要求部分设置broker_connection
。参考本章的金融工具属性配方设置instrument1
。
获取并打印instrument1
的总待售数量:
>>> total_pending_sell_quantity = \
broker_connection.get_total_pending_sell_quantity(instrument1)
>>> print(f'Total pending SELL quantity: {total_pending_sell_quantity}')
我们得到以下输出(你的输出可能不同):
Total pending SELL quantity: 968602
BrokerConnectionZerodha
类的get_total_pending_sell_quantity()
方法在任何给定时刻获取给定金融工具的总卖出数量。此方法将Instrument
类型的对象作为参数。我们在此处使用instrument1
作为参数。
金融工具的一天中总交易量是该天内所有交易数量(买入和卖出,但仅计算一次)的总和。例如,如果交易员 A从交易员 B购买股票X的 10 数量,而交易员 C将相同股票X的 20 数量卖给交易员 D,那么X的总交易量将是 10 + 20 = 30。它不会是 10 + 10 + 20 + 20 = 60,因为交易对总交易量的贡献只计算一次。此数据是动态的,可能在交易时间内的任何时刻增加。
确保在你的 Python 命名空间中有broker_connection
和instrument1
对象可用。参考本章的技术要求部分设置broker_connection
。参考本章的金融工具属性配方设置instrument1
。
获取并打印一天中某个工具的总交易量:
>>> total_volume_day = broker_connection.get_total_volume_day(instrument1)
>>> print(f'Total Volume for the day so far: {total_volume_day}')
我们得到以下输出(你的输出可能不同):
Total Volume for the day so far: 24416975
BrokerConnectionZerodha
类的get_total_volume_day()
方法在一天中的任何给定时刻获取给定金融工具的总交易量。此方法将Instrument
类型的对象作为参数。我们在此处使用instrument1
作为参数。
金融工具的最新交易价格(LTP)是执行该工具的订单的最新价格。它本质上是指可以购买或出售该工具的当前价格(假设流动性良好)。正如描述所示,此数据是动态的,可能在交易时间内持续变化。本配方展示了如何获取金融工具的 LTP。
确保 broker_connection
和 instrument1
对象在你的 Python 命名空间中可用。参考本章的技术要求部分设置 broker_connection
。参考本章的金融工具属性示例设置 instrument1
。
获取并打印 instrument1
的 LTP:
>>> ltp = broker_connection.get_ltp(instrument1)
>>> print(f'Last traded price: {ltp}')
我们得到以下输出(您的输出可能不同):
Last traded price: 350.95
BrokerConnectionZerodha
类的 get_ltp()
方法在任何给定时刻获取给定金融工具的 LTP。此方法将一个 Instrument
类型的对象作为参数。我们在此处使用 instrument1
作为参数。获取的数据类型为 float
。
金融工具的最后交易时间(LTT)是该工具最后一次执行订单的最新时间。此数据具有动态性,因为它在交易时间内可能会持续变化。此示例帮助获取金融工具的 LTT。
确保 broker_connection
和 instrument1
对象在你的 Python 命名空间中可用。参考本章的技术要求部分设置 broker_connection
。参考本章的金融工具属性示例设置 instrument1
。
获取并打印 instrument1
的 LTT:
>>> ltt = broker_connection.get_ltt(instrument1)
>>> print(f'Last traded time: {ltt}')
我们得到以下输出(您的输出可能不同):
Last traded time: 2020-07-17 14:42:54
BrokerConnectionZerodha
类的 get_ltt()
方法在任何给定时刻获取给定金融工具的 LTT。此方法将一个 Instrument
类型的对象作为参数。我们在此处使用 instrument1
作为参数。获取的数据是 datetime.datetime
类的一个实例。
金融工具的最后交易数量(LTQ)是该工具最后一次执行订单时交易的数量。此数据具有动态性,因为它在交易时间内可能会持续变化。此示例演示了如何获取金融工具的 LTQ。
确保 broker_connection
和 instrument1
对象在你的 Python 命名空间中可用。参考本章的技术要求部分设置 broker_connection
。参考本章的金融工具属性示例设置 instrument1
。
获取并打印 instrument1
的 LTQ:
>>> ltq = broker_connection.get_ltq(instrument1)
>>> print(f'Last traded quantity: {ltq}')
我们得到以下输出(您的输出可能不同):
Last traded quantity: 19
BrokerConnectionZerodha
类的 get_ltq()
方法在任何给定时刻获取给定金融工具的 LTQ。此方法将一个 Instrument
类型的对象作为参数。我们在此处使用 instrument1
作为参数。获取的数据类型为 int
。
通常,交易策略在做出新交易决策之前使用金融工具当日的开盘价格作为首要合格条件之一。将当日的开盘价格与前一日的收盘价格进行比较,可能会暗示市场价格在当天对于某个工具是上涨还是下跌。如果开盘价格明显高于前一日的收盘价格,则价格可能会继续上涨。同样,如果开盘价格明显低于前一日的收盘价格,则价格可能会继续下跌。记录的开盘价格数据是静态的,意味着它在交易小时内不会改变。本教程演示了如何获取金融工具当日的开盘价格。
确保在你的 Python 命名空间中可用broker_connection
和instrument1
对象。请参考本章节的 技术要求 部分设置broker_connection
。请参考本章节的 金融工具属性 食谱设置instrument1
。
获取并打印一天中instrument1
的开盘价格:
>>> open_price_day = broker_connection.get_open_price_day(instrument1)
>>> print(f'Open price today: {open_price_day}')
我们得到以下输出(你的输出可能会有所不同):
Open price today: 346
BrokerConnectionZerodha
类的get_open_price_day()
方法获取给定金融工具当日的开盘价格。此方法将Instrument
类型的对象作为参数。我们在这里使用instrument1
作为参数。获取的数据为float
类型。
在做出新交易决策之前,交易策略通常使用金融工具当日的最高价格作为一个合格条件之一。这些数据是动态的,因为它们可能在交易小时内不断变化。本教程演示了如何获取金融工具当日的最高记录价格。
确保在你的 Python 命名空间中可用broker_connection
和instrument1
对象。请参考本章节的 技术要求 部分设置broker_connection
。请参考本章节的 金融工具属性 食谱设置instrument1
。
获取并打印一天中instrument1
的记录最高价格:
>>> high_price_day = broker_connection.get_high_price_day(instrument1)
>>> print(f'Highest price today: {high_price_day}')
我们得到以下输出。你的输出可能会有所不同:
Highest price today: 356.8
BrokerConnectionZerodha
类的get_high_price_day()
方法获取给定金融工具当日的最高记录价格。此方法将Instrument
类型的对象作为参数。我们在这里使用instrument1
作为参数。获取的数据为float
类型。
通常,交易策略在做出新交易决策之前会将金融工具当天最低价格作为符合条件之一。这些数据是动态的,因为它们可能在实时交易时间内持续变化。本文演示了如何获取金融工具当天最低记录价格。
确保 broker_connection
和 instrument1
对象在您的 Python 命名空间中可用。请参考本章的 技术要求 部分设置 broker_connection
。请参考本章的 金融工具属性 配方设置 instrument1
。
获取并打印 instrument1
当天最低价格的记录:
>>> low_price_day = broker_connection.get_low_price_day(instrument1)
>>> print(f'Lowest price today: {low_price_day}')
我们得到以下输出(您的输出可能有所不同):
Lowest price today: 345.15
BrokerConnectionZerodha
类的 get_low_price_day()
方法获取给定金融工具当天的最低记录价格。此方法以 Instrument
类型的对象作为参数。我们在此处将 instrument1
用作参数。获取的数据是 float
类型的。
通常,交易策略在做出交易决策之前会使用前一交易日的金融工具收盘价作为首要条件之一。将当天的开盘价与前一天的收盘价进行比较,可能会暗示市场价格今天是否会上涨或下跌。如果开盘价显著高于前一天的收盘价,则价格可能会继续上涨。同样,如果开盘价显著低于前一天的收盘价,则价格可能会继续下跌。记录的收盘价数据是静态的,意味着在实时交易时间内不会发生变化。本文介绍了如何获取金融工具的前一日收盘价。
确保 broker_connection
和 instrument1
对象在您的 Python 命名空间中可用。请参考本章的 技术要求 部分设置 broker_connection
。请参考本章的 金融工具属性 配方设置 instrument1
。
获取并打印 instrument1
上一交易日的记录收盘价:
>>> close_price_last_day = \
broker_connection.get_close_price_last_day(instrument1)
>>> print(f'Close price of last trading day: {close_price_last_day}')
我们得到以下输出(您的输出可能有所不同):
Close price of last trading day: 341.65
BrokerConnectionZerodha
类的 get_close_price_day()
方法获取给定金融工具的前一交易日收盘价。此方法以 Instrument
类型的对象作为参数。我们在此处将 instrument1
用作参数。获取的数据是 float
类型的。
金融工具的历史数据是指金融工具过去所有买入或卖出价格的数据。算法交易策略总是在历史数据上进行虚拟执行,以评估其在实际投资前的过去表现。这个过程被称为回测。历史数据对于回测至关重要(在第八章,回测策略中有详细介绍)。此外,历史数据还需要用于计算技术指标(在第五章,计算和绘制技术指标中有详细介绍),这有助于在实时进行买卖决策。蜡烛图案是股票分析中广泛使用的工具。分析师通常使用各种类型的蜡烛图案。本章提供了一些示例,展示了如何使用经纪人 API 获取历史数据,如何获取和计算多个蜡烛图案 – 日本(开-高-低-收(OHLC)、线段、Renko 和 Heikin-Ashi – 以及如何使用第三方工具获取历史数据。
在本章中,我们将介绍以下示例:
让我们开始吧!
您将需要以下内容才能成功执行本章中的示例:
pyalgotrading
($ pip install pyalgotrading
)
quandl
($pip install quandl
)这是可选的,仅用于最后一个示例
本章的最新 Jupyter 笔记本可在 GitHub 上找到:github.com/PacktPublishing/Python-Algorithmic-Trading-Cookbook/tree/master/Chapter04
。
以下代码将帮助您设置与 Zerodha 的经纪人连接,这将被本章中的所有示例使用。请确保在尝试任何提供的示例之前已经执行了这些步骤。
设置与经纪人的连接的第一件事是收集所需的 API 密钥。经纪人为每个客户提供唯一的密钥,通常是api-key
和api-secret
密钥对。这些 API 密钥通常是按月付费的。在开始本章之前,您需要从经纪人网站获取您的api-key
和api-secret
的副本。您可以参考附录 I了解更多详情。
执行以下步骤:
>>> from pyalgotrading.broker.broker_connection_zerodha import BrokerConnectionZerodha
api_key
和 api_secret
。这些对你是唯一的,经纪人将使用它们来识别你的证券账户:>>> api_key = "<your-api-key>"
>>> api_secret = "<your-api-secret>"
>>> broker_connection = BrokerConnectionZerodha(api_key,
api_secret)
你将得到以下链接:
Installing package kiteconnect via pip...
Please login to this link to generate your request token: https://kite.trade/connect/login?api_key=<your-api-key>&v=3
如果你是第一次运行此程序,并且尚未安装 kiteconnect
,pyalgotrading
将自动为你安装。步骤 2 的最终输出将是一个链接。点击该链接并使用你的 Zerodha 凭证登录。如果认证成功,你将在浏览器地址栏中看到一个类似于 https://127.0.0.1/?request_token=&action=login&status=success
的链接。
例如:
https://127.0.0.1/?request_token=H06I6Ydv95y23D2Dp7NbigFjKweGwRP7&action=login&status=success
request_token
中:>>> request_token = "<your-request-token>"
>>> broker_connection.set_access_token(request_token)
broker_connection
实例现在已经准备好执行 API 调用了。
pyalgotrading
包支持多个经纪人,并为每个经纪人提供一个连接对象类,其方法相同。它将经纪人 API 抽象在一个统一的接口后面,使用户无需担心底层经纪人 API 调用,并可以直接使用本章中的所有示例。
仅经纪人连接设置的过程会因经纪人而异。如果你不使用 Zerodha 作为你的经纪人,你可以参考 pyalgotrading 文档来学习如何设置经纪人连接。对于 Zerodha 用户,上述步骤就足够了。
金融工具的历史数据是过去时间戳的时间序列数据。可以使用经纪人 API 获取给定时段的历史数据。本篇示例演示了如何建立经纪人连接以及如何为金融工具获取单日历史数据的过程。
确保 broker_connection
对象在你的 Python 命名空间中可用。请参考本章节的技术要求部分了解如何设置它。
执行以下步骤完成本篇示例:
>>> instrument = broker_connection.get_instrument('NSE',
'TATASTEEL')
>>> historical_data = broker_connection.get_historical_data(
instrument=instrument,
candle_interval='minute',
start_date='2020-01-01',
end_date='2020-01-01')
>>> historical_data
你将得到以下输出:
historical_data
DataFrame 的可用列:>>> historical_data.columns
你将得到以下输出:
>>> Index(['timestamp', 'open', 'high', 'low', 'close', 'volume'],
dtype='object')
在 步骤 1 中,你使用 broker_connection
的 get_instrument()
方法来获取一个金融工具,并将其赋值给一个新属性 instrument
。这个对象是 Instrument
类的一个实例。调用 get_instrument()
需要两个参数,交易所('NSE'
)和交易标志('TATASTEEL'
)。接下来,你使用 get_historical_data()
方法获取 instrument
的历史数据。这个方法接受四个参数,描述如下:
instrument
:必须放置历史数据的金融工具。应该是 Instrument
类的一个实例。在这里传递 instrument
。
candle_interval
: 一个有效的字符串,表示历史数据中每个蜡烛图的持续时间。你在这里传递minute
。(可能的值可以是minute
,3minute
,5minute
,10minute
,30minute
,60minute
和day
。)
start_date
: 截取历史数据的开始日期。应该是YYYY-MM-DD
格式的字符串。你在这里传递2020-01-01
。
end_date:
截取历史数据的截止日期,包括该日期。应该是YYYY-MM-DD
格式的字符串。你在这里传递2020-01-01
。
在步骤 2中,你获取并打印historical_data
的可用列。你得到的列是timestamp
、open
、high
、low
、close
和volume
。
更多有关蜡烛图案的信息将在下一篇配方使用日本(OHLC)蜡烛图案获取历史数据以及本章的第三篇配方获取具有蜡烛间隔变化的日本蜡烛图案中介绍。
金融工具的历史数据是一个蜡烛图数组。历史数据中的每个条目都是一个单独的蜡烛图。有各种各样的蜡烛图案。
本配方演示了最常用的蜡烛图案——日本蜡烛图案。它是一种蜡烛图案,每个蜡烛图案持有一个持续时间,并指示在该持续时间内工具可能会取得的所有价格。这些数据使用四个参数表示——开盘价、最高价、最低价和收盘价。可以描述如下:
根据这些参数,日本蜡烛图案也被称为OHLC 蜡烛图案。日本蜡烛图案中的所有时间戳都是等距的(在市场开放时间内)。例如,一个交易日的时间戳看起来像是上午 9:15、9:16、9:17、9:18 等等,对于 1 分钟的蜡烛间隔,每个时间戳都是在 1 分钟的间隔内等距分布的。
确保broker_connection
和historical_data
对象在你的 Python 命名空间中可用。参考本章的技术要求部分设置broker_connection
。参考上一篇配方设置historical_data
。
我们执行以下步骤来进行这个配方:
>>> from pyalgotrading.utils.func import plot_candlestick_chart, PlotType
historical_data
的一行创建一个绿色蜡烛图:>>> candle_green = historical_data.iloc[:1,:]
# Only 1st ROW of historical data
>>> plot_candlestick_chart(candle_green,
PlotType.JAPANESE,
"A 'Green' Japanese Candle")
你将得到以下输出:
historical_data
的一行创建一个红色蜡烛图:# A 'Red' Japanese Candle
>>> candle_red = historical_data.iloc[1:2,:]
# Only 2nd ROW of historical data
>>> plot_candlestick_chart(candle_red,
PlotType.OHLC,
"A 'Red' Japanese Candle")
这将给您以下输出:
>>> plot_candlestick_chart(historical_data,
PlotType.OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'NSE:TATASTEEL | 1st Jan, 2020 | '
'Candle Interval: 1 Minute')
这将给您以下输出:
>>> instrument2 = broker_connection.get_instrument('NSE', 'INFY')
>>> historical_data = \
broker_connection.get_historical_data(instrument2,
'minute',
'2020-01-01',
'2020-01-01')
>>> plot_candlestick_chart(historical_data,
PlotType.OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'NSE:INFY | 1st Jan, 2020 | '
'Candle Interval: 1 Minute')
这将给您以下输出:
>>> instrument3 = broker_connection.get_instrument('NSE',
'ICICIBANK')
>>> historical_data =
broker_connection.get_historical_data(instrument3,
'minute',
'2020-01-01',
'2020-01-01')
>>> plot_candlestick_chart(historical_data, PlotType.OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'NSE:ICICIBANK | 1st Jan, 2020 | '
'Candle Size: 1 Minute')
这将给您以下输出:
在步骤 1中,您导入plot_candlestick_chart
,这是一个用于绘制蜡烛图表的快速实用函数,以及PlotType
,一个用于各种蜡烛图案类型的枚举。接下来的两步介绍了两种蜡烛图,或简称为蜡烛——一个绿色蜡烛和一个红色蜡烛。正如我们之前提到的,历史数据中的每个条目都是一个蜡烛。这两个步骤有选择地从数据中提取绿色和红色蜡烛。(请注意,如果您选择了与使用经纪人 API 获取历史数据配方中不同的持续时间historical_data
,则传递给historical_data.iloc
的索引将不同)。如果一个日本蜡烛的收盘价高于其开盘价,它的颜色将是绿色。绿色蜡烛也称为看涨蜡烛,因为它表明价格在那段时间内看涨,即上涨。如果一个日本蜡烛的收盘价低于其开盘价,它的颜色将是红色。红色蜡烛也称为看跌蜡烛,因为它表明价格在那段时间内看跌,即下跌。
在步骤 4中,您使用plot_candlestick_chart()
函数绘制了historical_data
持有的完整历史数据。图表是多个蜡烛图的组合,每个蜡烛图的长度都不同。因此,这样的图表被称为蜡烛图案图表。请注意,蜡烛间隔为 1 分钟,意味着时间戳在 1 分钟间隔内等间距排列。步骤 5和步骤 6演示了相似的 1 分钟蜡烛间隔蜡烛图案图表,分别用于NSE:INFY
和NSE:ICICIBANK
仪器。
如果您是蜡烛图表的新手,我建议您与本章的 Jupyter Notebook 中的图表进行交互,网址为github.com/PacktPublishing/Python-Algorithmic-Trading-Cookbook/blob/master/Chapter04/CHAPTER%204.ipynb
。尝试悬停在多个蜡烛图上以查看它们的值,并放大/缩小或移动到各种持续时间以更清晰地查看蜡烛图。尝试将这些蜡烛图的颜色与本食谱中的描述联系起来。如果由于某种原因 Jupyter Notebook 中的图表没有自动呈现给您,您可以下载此 html 文件,该文件是相同 Jupyter Notebook 的文件,将其在浏览器中打开并与其进行交互:github.com/PacktPublishing/Python-Algorithmic-Trading-Cookbook/blob/master/Chapter04/CHAPTER%204.ipynb
。
金融工具的历史数据可以以不同的蜡烛图间隔形式进行分析。经纪人通常支持 1 分钟、3 分钟、5 分钟、10 分钟、15 分钟、30 分钟、1 小时、1 天等蜡烛图间隔。较短的蜡烛图间隔暗示着局部价格运动趋势,而较大的蜡烛图间隔则表示整体价格运动趋势。根据算法交易策略的不同,您可能需要较短的蜡烛图间隔或较大的蜡烛图间隔。1 分钟的蜡烛图间隔通常是最小的可用蜡烛图间隔。此示例演示了金融工具一天的历史数据在各种蜡烛图间隔下的情况。
确保broker_connection
对象在您的 Python 命名空间中可用。请参考本章的技术要求部分,了解如何设置broker_connection
。
我们执行此食谱的以下步骤:
>>> from pyalgotrading.utils.func import plot_candlestick_chart, PlotType
>>> instrument = broker_connection.get_instrument('NSE',
'TATASTEEL')
>>> historical_data_1minute = \
broker_connection.get_historical_data(instrument,
'minute',
'2020-01-01',
'2020-01-01')
>>> plot_candlestick_chart(historical_data_1minute,
PlotType.OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 1 Minute')
您将获得以下输出:
>>> historical_data_3minutes = \
broker_connection.get_historical_data(instrument,
'3minute',
'2020-01-01',
'2020-01-01')
>>> plot_candlestick_chart(historical_data_3minutes,
PlotType.OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 3 Minutes')
您将获得以下输出:
>>> historical_data_5minutes = \
broker_connection.get_historical_data(instrument,
'5minute',
'2020-01-01',
'2020-01-01')
>>> plot_candlestick_chart(historical_data_5minutes,
PlotType.OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 5 Minutes')
您将获得以下输出:
>>> historical_data_10minutes = \
broker_connection.get_historical_data(instrument,
'10minute',
'2020-01-01',
'2020-01-01')
>>> plot_candlestick_chart(historical_data_10minutes,
PlotType.OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 10 Minutes')
您将获得以下输出:
>>> historical_data_15minutes = \
broker_connection.get_historical_data(instrument,
'15minute',
'2020-01-01',
'2020-01-01')
>>> plot_candlestick_chart(historical_data_15minutes,
PlotType.OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 15 Minutes')
您将获得以下输出:
>>> historical_data_30minutes = \
broker_connection.get_historical_data(instrument,
'30minute',
'2020-01-01',
'2020-01-01')
>>> plot_candlestick_chart(historical_data_30minutes,
PlotType.OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 30 Minutes')
您将获得以下输出:
>>> historical_data_1hour = \
broker_connection.get_historical_data(instrument,
'hour',
'2020-01-01',
'2020-01-01')
>>> plot_candlestick_chart(historical_data_1hour,
PlotType.OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: 1 Hour')
>>> historical_data_day = \
broker_connection.get_historical_data(instrument,
'day',
'2020-01-01',
'2020-01-01')
>>> plot_candlestick_chart(historical_data_day,
PlotType.OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'NSE:TATASTEEL | '
'1st Jan, 2020 | '
'Candle Interval: Day')
您将获得以下输出,这是一个单一的蜡烛:
在步骤 1 中,您导入了plot_candlestick_chart
,这是一个用于绘制蜡烛图案图表的快速实用函数,以及PlotType
,一个用于各种蜡烛图案类型的枚举。 在步骤 2 中,使用broker_connection
的get_instrument()
方法获取一个仪器并将其分配给一个新属性instrument
。 此对象是Instrument
类的一个实例。 调用get_instrument()
所需的两个参数是交易所('NSE'
)和交易符号('TATASTEEL'
)。 步骤 3 和 4 获取并绘制了蜡烛图间隔的历史数据;即,1 分钟,3 分钟,5 分钟,10 分钟,15 分钟,30 分钟,1 小时和 1 天。 您使用get_historical_data()
方法获取相同仪器和相同开始和结束日期的历史数据,只是蜡烛间隔不同。 您使用plot_candlestick_chart()
函数绘制日本蜡烛图案图表。 随着蜡烛间隔的增加,您可以观察到以下图表之间的差异:
金融工具的历史数据可以以 Line Break 蜡烛图案的形式进行分析,这是一种专注于价格运动的蜡烛图案。这与专注于时间运动的日本蜡烛图案不同。经纪人通常不会通过 API 提供 Line Break 蜡烛图案的历史数据。经纪人通常使用日本蜡烛图案提供历史数据,需要将其转换为 Line Break 蜡烛图案。较短的蜡烛间隔暗示着局部价格运动趋势,而较长的蜡烛间隔则表示整体价格运动趋势。根据你的算法交易策略,你可能需要蜡烛间隔较小或较大。1 分钟的蜡烛间隔通常是最小的可用蜡烛间隔。
Line Break 蜡烛图案的工作方式如下:
open
和close
属性。
线数
(n)设置,通常取为3
。
这个配方展示了我们如何使用经纪人 API 获取历史数据,将历史数据转换为 Line Break 蜡烛图案,并进行绘图。这是针对多个蜡烛间隔进行的。
确保broker_connection
对象在你的 Python 命名空间中可用。参考本章的技术要求部分,了解如何设置broker_connection
。
对于这个配方,我们执行以下步骤:
>>> from pyalgotrading.utils.func import plot_candlestick_chart, PlotType
>>> from pyalgotrading.utils.candlesticks.linebreak import Linebreak
>>> instrument = broker_connection.get_instrument('NSE',
'TATASTEEL')
>>> historical_data_1minute = \
broker_connection.get_historical_data(instrument,
'minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_1minute_linebreak = \
Linebreak(historical_data_1minute)
>>> historical_data_1minute_linebreak
你将得到以下输出:
close open timestamp
0 424.00 424.95 2019-12-02 09:15:00+05:30
1 424.50 424.00 2019-12-02 09:16:00+05:30
2 425.75 424.80 2019-12-02 09:17:00+05:30
3 423.75 424.80 2019-12-02 09:19:00+05:30
4 421.70 423.75 2019-12-02 09:20:00+05:30
… … ....
1058 474.90 474.55 2019-12-31 10:44:00+05:30
1059 471.60 474.55 2019-12-31 11:19:00+05:30
1060 471.50 471.60 2019-12-31 14:19:00+05:30
1061 471.35 471.50 2019-12-31 15:00:00+05:30
1062 471.00 471.35 2019-12-31 15:29:00+05:30
historical_data
的一行创建一个绿色 Line Break 蜡烛:>>> candle_green_linebreak = historical_data_1minute_linebreak.iloc[1:2,:]
# Only 2nd ROW of historical data
>>> plot_candlestick_chart(candle_green_linebreak,
PlotType.LINEBREAK,
"A 'Green' Line Break Candle")
你将得到以下输出:
historical_data
的一行创建一个红色 Line Break 蜡烛:>>> candle_red_linebreak = historical_data_1minute_linebreak.iloc[:1,:]
# Only 1st ROW of historical data
>>> plot_candlestick_chart(candle_red_linebreak,
PlotType.LINEBREAK,
"A 'Red' Line Break Candle")
你将得到以下输出:
>>> plot_candlestick_chart(historical_data_1minute_linebreak,
PlotType.LINEBREAK,
'Historical Data | '
'Line Break Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 1 Minute', True)
你将得到以下输出:
>>> historical_data_3minutes = \
broker_connection.get_historical_data(instrument,
'3minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_3minutes_linebreak = \
Linebreak(historical_data_3minutes)
>>> plot_candlestick_chart(historical_data_3minutes_linebreak,
PlotType.LINEBREAK,
'Historical Data | '
'Line Break Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 3 Minutes', True)
你将得到以下输出:
>>> historical_data_5minutes = \
broker_connection.get_historical_data(instrument,
'5minute',
'2019-12-01',
'2020-01-10')
>>> historical_data_5minutes_linebreak = \
Linebreak(historical_data_5minutes)
>>> plot_candlestick_chart(historical_data_5minutes_linebreak,
PlotType.LINEBREAK,
'Historical Data | '
'Line Break Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 5 Minutes', True)
你将得到以下输出:
>>> historical_data_10minutes = \
broker_connection.get_historical_data(instrument,
'10minute',
'2019-12-01',
'2020-01-10')
>>> historical_data_10minutes_linebreak = \
Linebreak(historical_data_10minutes)
>>> plot_candlestick_chart(historical_data_10minutes_linebreak,
PlotType.LINEBREAK,
'Historical Data | '
'Line Break Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 10 Minutes', True)
你将会得到以下输出:
>>> historical_data_15minutes = \
broker_connection.get_historical_data(instrument,
'15minute',
'2019-12-01',
'2020-01-10')
>>> historical_data_15minutes_linebreak = \
Linebreak(historical_data_15minutes)
>>> plot_candlestick_chart(historical_data_15minutes_linebreak,
PlotType.LINEBREAK,
'Historical Data | '
'Line Break Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 15 Minutes', True)
你将会得到以下输出:
>>> historical_data_30minutes = \
broker_connection.get_historical_data(instrument,
'30minute',
'2019-12-01',
'2020-01-10')
>>> historical_data_30minutes_linebreak = \
Linebreak(historical_data_30minutes)
>>> plot_candlestick_chart(historical_data_30minutes_linebreak,
PlotType.LINEBREAK,
'Historical Data | '
'Line Break Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 30 Minutes', True)
你将会得到以下输出:
>>> historical_data_1hour = \
broker_connection.get_historical_data(instrument,
'hour',
'2019-12-01',
'2020-01-10')
>>> historical_data_1hour_linebreak = \
Linebreak(historical_data_1hour)
>>> plot_candlestick_chart(historical_data_1hour_linebreak,
PlotType.LINEBREAK,
'Historical Data | '
'Line Break Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 1 Hour', True)
你将会得到以下输出:
>>> historical_data_day = \
broker_connection.get_historical_data(instrument,
'day',
'2019-12-01',
'2020-01-10')
>>> historical_data_day_linebreak = \
Linebreak(historical_data_day)
>>> plot_candlestick_chart(historical_data_day_linebreak,
PlotType.LINEBREAK,
'Historical Data | '
'Line Break Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 1 Day', True)
你将会得到以下输出:
在 步骤 1 中,你导入 plot_candlestick_chart
,一个用于绘制蜡烛图表的快捷实用函数,PlotType
,一个用于各种蜡烛图案的枚举,以及 Linebreak
函数,该函数可以将日本蜡烛图案的历史数据转换成线条蜡烛图案。在 步骤 2 中,你使用 broker_connection
的 get_instrument()
方法来获取一个工具,并将其赋值给一个新属性 instrument
。这个对象是 Instrument
类的一个实例。调用 get_instrument()
需要的两个参数是交易所('NSE'
)和交易符号('TATASTEEL'
)。接下来,你使用 broker_connection
对象的 get_historical_data()
方法获取工具的历史数据,时段为 2019 年 12 月,蜡烛间隔为 1 分钟。返回的时间序列数据以日本蜡烛图案的形式呈现。Linebreak()
函数将此数据转换为线条蜡烛图案,另一个 pandas.DataFrame
对象。你将其赋值给 historical_data_1minute_linebreak
。注意到 historical_data_1minute_linebreak
只有 timestamp
、open
和 close
列。另外,请注意时间戳不是等距的,因为线条蜡烛是基于价格变动而不是时间的。在 步骤 3 和 步骤 4 中,你从数据中选择性地提取了一个绿色和一个红色蜡烛。(请注意,如果您选择了第一章中获取的 historical_data
的不同持续时间,传递给 historical_data.iloc
的索引将不同。)请注意,蜡烛没有影子(延伸在主要蜡烛体两侧的线)因为蜡烛只有 open
和 close
属性。在 步骤 5 中,你使用 plot_candlestick_chart()
函数绘制了 historical_data
持有的完整历史数据。
在 步骤 6 到 12 中,您使用日本烛台图案获取历史数据,将其转换为 Line Break 烛台图案,并绘制烛台间隔为 3 分钟、5 分钟、10 分钟、15 分钟、30 分钟、1 小时和 1 天的转换数据。随着烛台间隔的增加,观察以下图表之间的差异和相似之处:
如果您对查找数学和实现 Line Break 烛台感兴趣,请参阅位于 github.com/algobulls/pyalgotrading/blob/master/pyalgotrading/utils/candlesticks/linebreak.py
的 pyalgotrading
包中的源代码。
金融工具的历史数据可以以 Renko 砖块图案的形式进行分析,这是一种关注价格变动的烛台图案。这与关注时间变动的日本烛台图案不同。经纪人通常不通过 API 提供 Renko 砖块图案的历史数据。经纪人通常通过使用需要转换为 Renko 砖块图案的日本烛台图案来提供历史数据。较短的烛台间隔暗示着局部价格变动趋势,而较大的烛台间隔则表示整体价格变动趋势。根据您的算法交易策略,您可能需要烛台间隔小或大。1 分钟的烛台间隔通常是最小的可用烛台间隔。
Renko 砖块图案的工作原理如下:
open
和 close
属性。
b
) 设置,通常设置为 2
。
Brick Count
。因此,此处也将蜡烛称为砖块。
b
个点,则形成绿色砖块。如果价格在单个蜡烛间隔内上涨超过b
个点,将形成足够多的砖块以适应价格变动。
例如,假设价格比前一砖的高点高出 21 个点。如果砖块大小为2
,将形成 10 个具有相同时间戳的砖块以适应 20 点的变动。对于剩余的 1 点变化(21-20),直到价格至少再上涨 1 点之前,不会形成任何砖块。
b
个点,则形成红色蜡烛。如果价格在单个蜡烛间隔内下跌超过b
个点,将形成足够多的砖块以适应价格变动。
例如,假设价格比前一个砖的最高价低 21 个点。如果砖块大小为2
,将形成 10 个具有相同时间戳的砖块以适应 20 点的变动。对于剩余的 1 点变化(21-20),直到价格至少再下跌 1 点之前,不会形成任何砖块。
本食谱展示了如何使用经纪人 API 获取历史数据作为日本蜡烛图案,以及如何使用砖块蜡烛图案转换和绘制不同蜡烛间隔的历史数据。
确保在 Python 命名空间中可用的broker_connection
对象。请参阅本章的技术要求部分,了解如何设置broker_connection
。
我们按照以下步骤执行此处方:
>>> from pyalgotrading.utils.func import plot_candlestick_chart, PlotType
>>> from pyalgotrading.utils.candlesticks.renko import Renko
>>> instrument = broker_connection.get_instrument('NSE',
'TATASTEEL')
>>> historical_data_1minute = \
broker_connection.get_historical_data(instrument,
'minute',
'2019-12-01',
'2020-01-10')
>>> historical_data_1minute_renko = Renko(historical_data_1minute)
>>> historical_data_1minute_renko
您将获得以下输出:
close open timestamp
0 424.0 424.95 2019-12-02 09:15:00+05:30
1 422.0 424.00 2019-12-02 09:20:00+05:30
2 426.0 424.00 2019-12-02 10:00:00+05:30
3 422.0 424.00 2019-12-02 10:12:00+05:30
4 420.0 422.00 2019-12-02 15:28:00+05:30
... ... ... ...
186 490.0 488.00 2020-01-10 10:09:00+05:30
187 492.0 490.00 2020-01-10 11:41:00+05:30
188 488.0 490.00 2020-01-10 13:31:00+05:30
189 486.0 488.00 2020-01-10 13:36:00+05:30
190 484.0 486.00 2020-01-10 14:09:00+05:30
historical_data
的行中创建绿色砖块:>>> candle_green_renko = historical_data_1minute_renko.iloc[2:3,:]
# Only 3rd ROW of historical data
>>> plot_candlestick_chart(candle_green_renko,
PlotType.RENKO,
"A Green 'Renko' Candle")
您将获得以下输出:
historical_data
的行中创建红色砖块:>>> plot_candlestick_chart(historical_data_1minute_renko,
PlotType.RENKO,
'Historical Data | '
'Renko Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 1 Minute', True)
您将获得以下输出:
>>> historical_data_3minutes = \
broker_connection.get_historical_data(instrument,
'3minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_3minutes_renko = \
Renko(historical_data_3minutes)
>>> plot_candlestick_chart(historical_data_3minutes_renko,
PlotType.RENKO,
'Historical Data | '
'Renko Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 3 Minutes', True)
您将获得以下输出:
>>> historical_data_5minutes = \
broker_connection.get_historical_data(instrument,
'5minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_5minutes_renko = \
Renko(historical_data_5minutes)
>>> plot_candlestick_chart(historical_data_5minutes_renko,
PlotType.RENKO,
'Historical Data | '
'Renko Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 5 Minutes', True)
您将获得以下输出:
>>> historical_data_10minutes = \
broker_connection.get_historical_data(instrument,
'10minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_10minutes_renko = \
Renko(historical_data_10minutes)
>>> plot_candlestick_chart(historical_data_10minutes_renko,
PlotType.RENKO,
'Historical Data | '
'Renko Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 10 Minutes', True)
你将会得到以下输出:
>>> historical_data_15minutes = \
broker_connection.get_historical_data(instrument,
'15minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_15minutes_renko = \
Renko(historical_data_15minutes)
>>> plot_candlestick_chart(historical_data_15minutes_renko,
PlotType.RENKO,
'Historical Data | '
'Renko Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 15 Minutes', True)
你将会得到以下输出:
>>> historical_data_15minutes = \
broker_connection.get_historical_data(instrument,
'15minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_15minutes_renko = \
Renko(historical_data_15minutes)
>>> plot_candlestick_chart(historical_data_15minutes_renko,
PlotType.RENKO,
'Historical Data | '
'Renko Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 15 Minutes', True)
你将会得到以下输出:
>>> historical_data_30minutes = \
broker_connection.get_historical_data(instrument,
'30minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_30minutes_renko = \
Renko(historical_data_30minutes)
>>> plot_candlestick_chart(historical_data_30minutes_renko,
PlotType.RENKO,
'Historical Data | '
'Renko Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 30 Minutes', True)
你将会得到以下输出:
>>> historical_data_1hour = \
broker_connection.get_historical_data(instrument,
'hour',
'2019-12-01',
'2019-12-31')
>>> historical_data_1hour_renko = Renko(historical_data_1hour)
>>> plot_candlestick_chart(historical_data_1hour_renko,
PlotType.RENKO,
'Historical Data | '
'Renko Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 1 Hour', True)
你将会得到以下输出:
>>> historical_data_day = \
broker_connection.get_historical_data(instrument,
'day',
'2019-12-01',
'2019-12-31')
>>> historical_data_day_renko = Renko(historical_data_day)
>>> plot_candlestick_chart(historical_data_day_renko,
PlotType.RENKO,
'Historical Data | '
'Renko Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: Day', True)
你将会得到以下输出:
在 步骤 1 中,你导入了plot_candlestick_chart
,一个用于绘制蜡烛图表的快速实用函数,PlotType
,用于各种蜡烛图案的枚举,以及Renko
函数,该函数可以将日本蜡烛图案的历史数据转换为 Renko 蜡烛图案。在 步骤 2 中,你使用broker_connection
的get_instrument()
方法来获取一个工具,并将其赋值给一个新属性instrument
。这个对象是Instrument
类的一个实例。调用 get_instrument()所需的两个参数是交易所('NSE'
)和交易符号('TATASTEEL'
)。接下来,你使用broker_connection
对象的get_historical_data()
方法来获取 2019 年 12 月的历史数据,蜡烛间隔为 1 分钟。返回的时间序列数据以日本蜡烛图案的形式呈现。Renko()
函数将此数据转换为 Renko 蜡烛图案,另一个pandas.DataFrame
对象。你将其赋值给historical_data_1minute_renko
。请注意,historical_data_1minute_renko
具有timestamp
、open
和close
列。同时请注意,时间戳不是等距的,因为 Renko 蜡烛是基于价格变动而不是时间的。在 步骤 3 和 4 中,你选择性地从数据中提取一个绿色蜡烛和一个红色蜡烛(请注意,传递给historical_data.iloc
的索引是从本章第一个配方中获取的)。请注意,蜡烛没有影子(延伸在主要蜡烛体两侧的线),因为蜡烛只有open
和close
属性。在 步骤 5 中,你使用plot_candlestick_chart()
函数绘制historical_data
中保存的完整历史数据。
在步骤 6到12中,您使用日本蜡烛图形态获取历史数据,将其转换为 Renko 蜡烛图形态,并绘制蜡烛间隔为 3 分钟、5 分钟、10 分钟、15 分钟、30 分钟、1 小时和 1 天的转换数据。观察随着蜡烛间隔增加而图表之间的以下差异和相似之处:
如果您对研究 Renko 蜡烛图的数学和实现感兴趣,请参考 github.com/algobulls/pyalgotrading/blob/master/pyalgotrading/utils/candlesticks/renko.py
中 pyalgotrading
包中的源代码。
金融工具的历史数据可以以平均-足烛形态的形式进行分析。经纪人通常不会通过 API 提供使用平均-足烛形态的历史数据。经纪人通常提供使用日本蜡烛图形态的历史数据,需要将其转换为平均-足烛形态。较短的蜡烛间隔暗示着局部价格走势,而较长的蜡烛间隔则表示整体价格走势。根据您的算法交易策略,您可能需要蜡烛间隔较小或较大。1 分钟的蜡烛间隔通常是可用的最小蜡烛间隔。
平均-足蜡烛形态的工作原理如下:
收盘价
、开盘价
、最高价
和 最低价
属性。对于每根蜡烛,会发生以下情况:
收盘价
计算为当前日本蜡烛的 开盘价
、最高价
、最低价
和 收盘价
属性的平均值。
开盘价
为前一个平均-足蜡烛的 开盘价
和 收盘价
属性的平均值。
高
为:
Open
Close
High
Low
是:
Open
Close
Low
Close
高于Open
时形成绿色蜡烛。(与日本蜡烛图案中的绿色蜡烛相同。)
Close
低于Open
时形成红色蜡烛。(与日本蜡烛图案中的红色蜡烛相同。)
此示例向您展示了在使用经纪人 API 时如何使用日本蜡烛图案获取历史数据,以及如何转换和绘制各种蜡烛间隔的历史数据使用平均蜡烛图案。
确保在你的 Python 命名空间中可用 broker_connection
对象。请参考本章的技术要求部分了解如何设置 broker_connection
。
我们对这个配方执行以下步骤:
>>> from pyalgotrading.utils.func import plot_candlestick_chart, PlotType
>>> from pyalgotrading.utils.candlesticks.heikinashi import HeikinAshi
>>> instrument = broker_connection.get_instrument('NSE',
'TATASTEEL')
>>> historical_data_1minute = \
broker_connection.get_historical_data(instrument,
'minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_1minute_heikinashi = \
HeikinAshi(historical_data_1minute)
>>> historical_data_1minute_heikinashi
你将获得以下输出:
>>> candle_green_heikinashi = \
historical_data_1minute_heikinashi.iloc[2:3,:]
# Only 3rd ROW of historical data
>>> plot_candlestick_chart(candle_green_heikinashi,
PlotType.HEIKINASHI,
"A 'Green' HeikinAshi Candle")
你将获得以下输出:
# A 'Red' HeikinAshi Candle
>>> candle_red_heikinashi = \
historical_data_1minute_heikinashi.iloc[4:5,:]
# Only 1st ROW of historical data
>>> plot_candlestick_chart(candle_red_heikinashi,
PlotType.HEIKINASHI,
"A 'Red' HeikinAshi Candle")
你将获得以下输出:
>>> plot_candlestick_chart(historical_data_1minute_heikinashi,
PlotType.HEIKINASHI,
'Historical Data | '
'Heikin-Ashi Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 1 minute', True)
你将获得以下输出:
>>> historical_data_3minutes = \
broker_connection.get_historical_data(instrument,
'3minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_3minutes_heikinashi = \
HeikinAshi(historical_data_3minutes)
>>> plot_candlestick_chart(historical_data_3minutes_heikinashi,
PlotType.HEIKINASHI,
'Historical Data | '
'Heikin-Ashi Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 3 minutes', True)
你将获得以下输出:
>>> historical_data_5minutes = \
broker_connection.get_historical_data(instrument,
'5minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_5minutes_heikinashi = \
HeikinAshi(historical_data_5minutes)
>>> plot_candlestick_chart(historical_data_5minutes_heikinashi,
PlotType.HEIKINASHI,
'Historical Data | '
'Heikin-Ashi Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 5 minutes', True)
你将获得以下输出:
>>> historical_data_10minutes = \
broker_connection.get_historical_data(instrument,
'10minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_10minutes_heikinashi = \
HeikinAshi(historical_data_10minutes)
>>> plot_candlestick_chart(historical_data_10minutes_heikinashi,
PlotType.HEIKINASHI,
'Historical Data | '
'Heikin-Ashi Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 10 minutes', True)
你将获得以下输出:
>>> historical_data_15minutes = \
broker_connection.get_historical_data(instrument,
'15minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_15minutes_heikinashi = \
HeikinAshi(historical_data_15minutes)
>>> plot_candlestick_chart(historical_data_15minutes_heikinashi,
PlotType.HEIKINASHI,
'Historical Data | '
'Heikin-Ashi Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 15 minutes', True)
你将获得以下输出:
>>> historical_data_30minutes = \
broker_connection.get_historical_data(instrument,
'30minute',
'2019-12-01',
'2019-12-31')
>>> historical_data_30minutes_heikinashi = \
HeikinAshi(historical_data_30minutes)
>>> plot_candlestick_chart(historical_data_30minutes_heikinashi,
PlotType.HEIKINASHI,
'Historical Data | '
'Heikin-Ashi Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 30 minutes', True)
你将获得以下输出:
>>> historical_data_1hour =
broker_connection.get_historical_data(instrument,
'hour',
'2019-12-01',
'2019-12-31')
>>> historical_data_1hour_heikinashi = \
HeikinAshi(historical_data_1hour)
>>> plot_candlestick_chart(historical_data_1hour_heikinashi,
PlotType.HEIKINASHI,
'Historical Data | '
'Heikin-Ashi Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: 1 Hour', True)
你将获得以下输出:
>>> historical_data_day = \
broker_connection.get_historical_data(instrument,
'day',
'2019-12-01',
'2019-12-31')
>>> historical_data_day_heikinashi = \
HeikinAshi(historical_data_day)
>>> plot_candlestick_chart(historical_data_day_heikinashi,
PlotType.HEIKINASHI,
'Historical Data | '
'Heikin-Ashi Candlesticks Pattern | '
'NSE:TATASTEEL | '
'Dec, 2019 | '
'Candle Interval: Day', True)
你将获得以下输出:
在步骤 1中,您导入plot_candlestick_chart
,一个用于绘制蜡烛图模式图表的快捷工具函数,PlotType
,一个用于各种蜡烛图模式的枚举,以及HeikinAshi
函数,该函数可以将日本蜡烛图模式的历史数据转换为适用于平均阴阳蜡烛图模式的数据。在步骤 2中,您使用broker_connection
的get_instrument()
方法获取一个工具,并将其分配给一个新属性instrument
。这个对象是Instrument
类的一个实例。调用get_instrument()
所需的两个参数是交易所('NSE'
)和交易符号('TATASTEEL'
)。接下来,您使用broker_connection
对象的get_historical_data()
方法获取 2019 年 12 月的历史数据,蜡烛间隔为 1 分钟。返回的时间序列数据以日本蜡烛图模式的形式返回。HeikinAshi()
函数将这些数据转换为平均阴阳蜡烛图模式,另一个pandas.DataFrame
对象。您将其分配给historical_data_1minute_heikinashi
。注意historical_data_1minute_heikinashi
具有timestamp
、close
、open
、high
和low
列。还请注意,时间戳是等距的,因为平均阴阳蜡烛图是基于日本蜡烛的平均值。在步骤 3和步骤 4中,您从数据中选择性地提取绿色和红色蜡烛。(请注意,如果您选择本章第一个配方中获取的historical_data
的不同持续时间,则传递给historical_data.iloc
的索引将不同。)请注意,蜡烛具有阴影(延伸在主蜡烛体两侧的线),因为蜡烛具有high
和low
属性,以及open
和close
属性。在步骤 5中,您使用plot_candlstick_charts()
函数绘制historical_data
保存的完整历史数据。
在步骤 6到步骤 12之间,您使用日本蜡烛图模式获取历史数据,将其转换为平均阴阳蜡烛图模式,并分别为 3 分钟、5 分钟、10 分钟、15 分钟、30 分钟、1 小时和 1 天的蜡烛间隔绘制转换后的数据图表。随着蜡烛间隔的增加,观察以下图表之间的差异和相似之处:
如果你对 Heikin-Ashi 蜡烛图的数学和实现感兴趣,请参考 pyalgotrading
包中的源代码:github.com/algobulls/pyalgotrading/blob/master/pyalgotrading/utils/candlesticks/heikinashi.py
。
到目前为止,在本章的所有配方中,你都使用了经纪连接来获取历史数据。在这个配方中,你将使用第三方工具 Quandl (www.quandl.com/tools/python
) 来获取历史数据。它有一个免费使用的 Python 版本,可以使用 pip
轻松安装。这个配方演示了使用 quandl
来获取 FAAMG 股票价格(Facebook、亚马逊、苹果、微软和谷歌)的历史数据。
确保你已安装了 Python 的 quandl
包。如果没有,你可以使用以下 pip
命令进行安装:
$ pip install quandl
我们对此配方执行以下步骤:
>>> from pyalgotrading.utils.func import plot_candlestick_chart, PlotType
>>> import quandl
>>> facebook = quandl.get('WIKI/FB',
start_date='2015-1-1',
end_date='2015-3-31')
>>> plot_candlestick_chart(facebook,
PlotType.QUANDL_OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'FACEBOOK | '
'Jan-March 2015 | '
'Candle Interval: Day', True)
你将得到以下输出:
>>> amazon = quandl.get('WIKI/AMZN',
start_date='2015-1-1',
end_date='2015-3-31')
>>> plot_candlestick_chart(amazon,
PlotType.QUANDL_OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'AMAZON | '
'Jan-March 2015 | '
'Candle Interval: Day', True)
你将得到以下输出:
>>> apple = quandl.get('WIKI/AAPL',
start_date='2015-1-1',
end_date='2015-3-31')
>>> plot_candlestick_chart(apple,
PlotType.QUANDL_OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'APPLE | '
'Jan-March 2015 | '
'Candle Interval: Day', True)
你将得到以下输出:
>>> microsoft = quandl.get('WIKI/MSFT',
start_date='2015-1-1',
end_date='2015-3-31')
>>> plot_candlestick_chart(microsoft,
PlotType.QUANDL_OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'MICROSOFT | '
'Jan-March 2015 | '
'Candle Interval: Day', True)
你将得到以下输出:
>>> google = quandl.get('WIKI/GOOGL',
start_date='2015-1-1',
end_date='2015-3-31')
>>> plot_candlestick_chart(google,
PlotType.QUANDL_OHLC,
'Historical Data | '
'Japanese Candlesticks Pattern | '
'GOOGLE | '
'Jan-March 2015 | '
'Candle Interval: Day', True)
你将得到以下输出:
第一步中,你需要导入plot_candlestick_chart
,这是一个用于绘制蜡烛图表的快速实用函数,还有PlotType
,用于表示各种蜡烛图案的枚举,以及quandl
模块。在其余的步骤中,使用quandl.get()
获取 Facebook、Amazon、Apple、Microsoft 和 Google 股票的历史数据,并使用plot_candlestick_chart()
方法进行绘制。quandl
返回的数据格式是 OHLC(开盘价、最高价、最低价、收盘价)格式。
这种第三方模块的好处是它们是免费的,而且你不需要建立经纪人连接来获取历史数据。但缺点是来自免费包的数据有其局限性。例如,无法实时获取数据,也无法获取日内交易的数据(1 分钟蜡烛、3 分钟蜡烛等)。
因此,是否要使用这些数据取决于你的需求。它可能适用于测试或更新现有代码库,但不足以提供实时数据源,这在实际交易会话期间是需要的。