股票期权不匹配的 Python 正则表达式

标签 python regex finance

我正在尝试创建一个正则表达式来查找经纪商数据中的选项符号。每Wikipedia格式为:

  1. 标的股票或 ETF 的根代码,用空格填充至 6 个字符
  2. 到期日期,6 位数字,格式为 yymmdd
  3. 期权类型,P 或 C,用于看跌或看涨
  4. 行权价,即价格 x 1000,前面填充 0 到 8 位数字

所以我创建了这个正则表达式:

option_regex = re.compile(r'''(
(\w{1,6})            # beginning ticker, 1 to 6 word characters
(\s)?                # optional separator
(\d{6})              # 6 digits for yymmdd
([cp])               # C or P for call or put
(\d{8})              # 8 digits for strike price
)''', re.VERBOSE | re.IGNORECASE)

但是当我测试它时,我收到一个错误:

import re

option_regex = re.compile(r'''(
(\w{1,6})            # beginning ticker, 1 to 6 word characters
(\s)?                # optional separator
(\d{6})              # 6 digits for yymmdd
([cp])               # C or P for call or put
(\d{8})              # 8 digits for strike price
)''', re.VERBOSE | re.IGNORECASE)

result = option_regex.search('AAPL  170818C00155000')

result.group()
Traceback (most recent call last):

  File "<ipython-input-4-0273c989d990>", line 1, in <module>
    result.group()

AttributeError: 'NoneType' object has no attribute 'group'

最佳答案

来自python documentation on re.search() :

Scan through string looking for the first location where the regular expression pattern produces a match, and return a corresponding MatchObject instance. Return None if no position in the string matches the pattern; note that this is different from finding a zero-length match at some point in the string.

您的代码抛出此异常,因为子例程没有找到任何内容。基本上,您尝试在 None 上运行 .group()。防御它是个好主意:

if not result:
    ... # Pattern didn't match the string
    return

您的模式与您输入的字符串不匹配,因为它的分隔符比您想象的要长:它有 2 个空格而不是 1 个。您可以通过在规则中添加 +(“至少一次”)来解决此问题:

(\s+)?                # optional separator

关于股票期权不匹配的 Python 正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45571504/

相关文章:

python - 如何使用 lxml 更新 XML 文件

python - 如何使用 python Scrapy 抓取延迟加载图像

python - 具有 Statsmodel ValueError : zero-size array to reduction operation maximum which has no identity 的多重 OLS 回归

python - 基于 Pandas 数据框中列比较的条件累积和

r - 使用 get() 来引用带有 R 的 quantmod 数组中的列?

python - 尝试在 Python 中显示首字母

正则表达式替换 : if not followed by letter or number

php - 如何替换字符串中的第 n 次出现

php - 性能: PHP Error Handling and Regex

wpf - 在 WPF 工具包图表上隐藏周末