请求为Python代码添加strikePrice、expiryDate、instrumentType过滤功能
为NSE期权链添加过滤功能并提取目标值
以下是添加了过滤功能并支持提取underlyingValue的修改方案,同时兼容原有代码的功能:
import requests import pandas as pd class NseIndia2: def __init__(self): self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.212 Safari/537.36'} self.session = requests.Session() self.session.get("http://nseindia.com", headers=self.headers) def get_option_chain(self, symbol, strike_price=None, expiry_date=None, instrument_type=None): url = 'https://www.nseindia.com/api/option-chain-indices?symbol=' + symbol data = self.session.get(url,headers=self.headers).json()["records"]["data"] my_df = [] for i in data: for k, v in i.items(): if k == "CE" or k == "PE": info = v info["instrumentType"] = k my_df.append(info) df = pd.DataFrame(my_df) # 应用过滤条件 if strike_price is not None: df = df[df['strikePrice'] == strike_price] if expiry_date is not None: df = df[df['expiryDate'] == expiry_date] if instrument_type is not None: df = df[df['instrumentType'] == instrument_type] return df nse = NseIndia2() # 示例:使用指定过滤条件获取结果并提取underlyingValue filtered_result = nse.get_option_chain( "NIFTY", strike_price=8500, expiry_date="29-Dec-2022", instrument_type="PE" ) # 提取underlyingValue(处理无匹配结果的情况) underlying_value = filtered_result['underlyingValue'].iloc[0] if not filtered_result.empty else None print(f"匹配到的underlyingValue: {underlying_value}")
关键修改说明
- 给
get_option_chain方法新增了三个可选参数:strike_price、expiry_date、instrument_type,默认值为None,不传入时返回完整期权链,兼容原有逻辑。 - 在生成DataFrame后,依次应用每个非空的过滤条件,只保留同时满足所有条件的记录。
- 提取
underlyingValue时加入了空值判断,避免没有匹配结果时触发索引错误。
内容的提问来源于stack exchange,提问作者Mohamed Rafi Puthukkudi
相关产品推荐
相关产品推荐

