0

0

使用 Python 的 NSE 期权链数据 - 第二部分 |沙阿·斯塔万

王林

王林

发布时间:2024-08-09 12:31:42

|

985人浏览过

|

来源于dev.to

转载

在上一篇文章中,我们讨论了如何使用 python 获取 nifty 和 bank nifty 数据。那篇文章的反响很好,因此根据大众的需求,这里有一个扩展版本。在本文中,我们将学习如何每 30 秒从 nse 网站获取期权链数据。此内容仅用于学习目的。

在 python 中,我们将使用 asyncio 每 30 秒向 nse 数据发出一次 api 请求。

在python中安装所需的库

pip 安装 aiohttp 异步

代码

import aiohttp
import asyncio
import requests
import json
import math
import time


def strRed(skk):         return "\033[91m {}\033[00m".format(skk)
def strGreen(skk):       return "\033[92m {}\033[00m".format(skk)
def strYellow(skk):      return "\033[93m {}\033[00m".format(skk)
def strLightPurple(skk): return "\033[94m {}\033[00m".format(skk)
def strPurple(skk):      return "\033[95m {}\033[00m".format(skk)
def strCyan(skk):        return "\033[96m {}\033[00m".format(skk)
def strLightGray(skk):   return "\033[97m {}\033[00m".format(skk)
def strBlack(skk):       return "\033[98m {}\033[00m".format(skk)
def strBold(skk):        return "\033[1m {}\033[00m".format(skk)

def round_nearest(x, num=50): return int(math.ceil(float(x)/num)*num)
def nearest_strike_bnf(x): return round_nearest(x, 100)
def nearest_strike_nf(x): return round_nearest(x, 50)

url_oc      = "https://www.nseindia.com/option-chain"
url_bnf     = 'https://www.nseindia.com/api/option-chain-indices?symbol=BANKNIFTY'
url_nf      = 'https://www.nseindia.com/api/option-chain-indices?symbol=NIFTY'
url_indices = "https://www.nseindia.com/api/allIndices"

headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36',
            'accept-language': 'en,gu;q=0.9,hi;q=0.8',
            'accept-encoding': 'gzip, deflate, br'}

cookies = dict()

def set_cookie():
    sess = requests.Session()
    request = sess.get(url_oc, headers=headers, timeout=5)
    return dict(request.cookies)

async def get_data(url, session):
    global cookies
    async with session.get(url, headers=headers, timeout=5, cookies=cookies) as response:
        if response.status == 401:
            cookies = set_cookie()
            async with session.get(url, headers=headers, timeout=5, cookies=cookies) as response:
                return await response.text()
        elif response.status == 200:
            return await response.text()
        return ""

async def fetch_all_data():
    async with aiohttp.ClientSession() as session:
        indices_data = await get_data(url_indices, session)
        bnf_data = await get_data(url_bnf, session)
        nf_data = await get_data(url_nf, session)
    return indices_data, bnf_data, nf_data

# Process the fetched data
def process_indices_data(data):
    global bnf_ul, nf_ul, bnf_nearest, nf_nearest
    data = json.loads(data)
    for index in data["data"]:
        if index["index"] == "NIFTY 50":
            nf_ul = index["last"]
        if index["index"] == "NIFTY BANK":
            bnf_ul = index["last"]
    bnf_nearest = nearest_strike_bnf(bnf_ul)
    nf_nearest = nearest_strike_nf(nf_ul)

def process_oi_data(data, nearest, step, num):
    data = json.loads(data)
    currExpiryDate = data["records"]["expiryDates"][0]
    oi_data = []
    for item in data['records']['data']:
        if item["expiryDate"] == currExpiryDate:
            if nearest - step*num <= item["strikePrice"] <= nearest + step*num:
                oi_data.append((item["strikePrice"], item["CE"]["openInterest"], item["PE"]["openInterest"]))
    return oi_data

def print_oi_data(nifty_data, bank_nifty_data, prev_nifty_data, prev_bank_nifty_data):
    print(strBold(strLightPurple("Nifty Open Interest:")))
    for i, (strike, ce_oi, pe_oi) in enumerate(nifty_data):
        ce_change = ce_oi - prev_nifty_data[i][1] if prev_nifty_data else 0
        pe_change = pe_oi - prev_nifty_data[i][2] if prev_nifty_data else 0
        ce_color = strGreen(ce_oi) if ce_change > 0 else strRed(ce_oi)
        pe_color = strGreen(pe_oi) if pe_change > 0 else strRed(pe_oi)
        print(f"Strike Price: {strike}, Call OI: {ce_color} ({strBold(f'+{ce_change}') if ce_change > 0 else strBold(ce_change) if ce_change < 0 else ce_change}), Put OI: {pe_color} ({strBold(f'+{pe_change}') if pe_change > 0 else strBold(pe_change) if pe_change < 0 else pe_change})")

    print(strBold(strLightPurple("\nBank Nifty Open Interest:")))
    for i, (strike, ce_oi, pe_oi) in enumerate(bank_nifty_data):
        ce_change = ce_oi - prev_bank_nifty_data[i][1] if prev_bank_nifty_data else 0
        pe_change = pe_oi - prev_bank_nifty_data[i][2] if prev_bank_nifty_data else 0
        ce_color = strGreen(ce_oi) if ce_change > 0 else strRed(ce_oi)
        pe_color = strGreen(pe_oi) if pe_change > 0 else strRed(pe_oi)
        print(f"Strike Price: {strike}, Call OI: {ce_color} ({strBold(f'+{ce_change}') if ce_change > 0 else strBold(ce_change) if ce_change < 0 else ce_change}), Put OI: {pe_color} ({strBold(f'+{pe_change}') if pe_change > 0 else strBold(pe_change) if pe_change < 0 else pe_change})")

def calculate_support_resistance(oi_data):
    highest_oi_ce = max(oi_data, key=lambda x: x[1])
    highest_oi_pe = max(oi_data, key=lambda x: x[2])
    return highest_oi_ce[0], highest_oi_pe[0]

async def update_data():
    global cookies
    prev_nifty_data = prev_bank_nifty_data = None
    while True:
        cookies = set_cookie()
        indices_data, bnf_data, nf_data = await fetch_all_data()

        process_indices_data(indices_data)

        nifty_oi_data = process_oi_data(nf_data, nf_nearest, 50, 10)
        bank_nifty_oi_data = process_oi_data(bnf_data, bnf_nearest, 100, 10)

        support_nifty, resistance_nifty = calculate_support_resistance(nifty_oi_data)
        support_bank_nifty, resistance_bank_nifty = calculate_support_resistance(bank_nifty_oi_data)

        print(strBold(strCyan(f"\nMajor Support and Resistance Levels:")))
        print(f"Nifty Support: {strYellow(support_nifty)}, Nifty Resistance: {strYellow(resistance_nifty)}")
        print(f"Bank Nifty Support: {strYellow(support_bank_nifty)}, Bank Nifty Resistance: {strYellow(resistance_bank_nifty)}")

        print_oi_data(nifty_oi_data, bank_nifty_oi_data, prev_nifty_data, prev_bank_nifty_data)

        prev_nifty_data = nifty_oi_data
        prev_bank_nifty_data = bank_nifty_oi_data

        for i in range(30, 0, -1):
            print(strBold(strLightGray(f"\rFetching data in {i} seconds...")), end="")
            time.sleep(1)
        print(strBold(strCyan("\nFetching new data... Please wait.")))
        await asyncio.sleep(1)

async def main():
    await update_data()

asyncio.run(main())

输出:

使用 Python 的 NSE 期权链数据 - 第二部分 |沙阿·斯塔万

使用 Python 的 NSE 期权链数据 - 第二部分 |沙阿·斯塔万

Uni-CourseHelper
Uni-CourseHelper

私人AI助教,高效学习工具

下载

立即学习Python免费学习笔记(深入)”;

您甚至可以通过此链接观看演示视频

谢谢!!
我们下一篇富有洞察力的博客见。

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
pip安装使用方法
pip安装使用方法

安装步骤:1、确保Python已经正确安装在您的计算机上;2、下载“get-pip.py”脚本;3、按下Win + R键,然后输入cmd并按下Enter键来打开命令行窗口;4、在命令行窗口中,使用cd命令切换到“get-pip.py”所在的目录;5、执行安装命令;6、验证安装结果即可。大家可以访问本专题下的文章,了解pip安装使用方法的更多内容。

339

2023.10.09

更新pip版本
更新pip版本

更新pip版本方法有使用pip自身更新、使用操作系统自带的包管理工具、使用python包管理工具、手动安装最新版本。想了解更多相关的内容,请阅读专题下面的文章。

412

2024.12.20

pip设置清华源
pip设置清华源

设置方法:1、打开终端或命令提示符窗口;2、运行“touch ~/.pip/pip.conf”命令创建一个名为pip的配置文件;3、打开pip.conf文件,然后添加“[global];index-url = https://pypi.tuna.tsinghua.edu.cn/simple”内容,这将把pip的镜像源设置为清华大学的镜像源;4、保存并关闭文件即可。

761

2024.12.23

python升级pip
python升级pip

本专题整合了python升级pip相关教程,阅读下面的文章了解更多详细内容。

349

2025.07.23

Python 自然语言处理(NLP)基础与实战
Python 自然语言处理(NLP)基础与实战

本专题系统讲解 Python 在自然语言处理(NLP)领域的基础方法与实战应用,涵盖文本预处理(分词、去停用词)、词性标注、命名实体识别、关键词提取、情感分析,以及常用 NLP 库(NLTK、spaCy)的核心用法。通过真实文本案例,帮助学习者掌握 使用 Python 进行文本分析与语言数据处理的完整流程,适用于内容分析、舆情监测与智能文本应用场景。

9

2026.01.27

拼多多赚钱的5种方法 拼多多赚钱的5种方法
拼多多赚钱的5种方法 拼多多赚钱的5种方法

在拼多多上赚钱主要可以通过无货源模式一件代发、精细化运营特色店铺、参与官方高流量活动、利用拼团机制社交裂变,以及成为多多进宝推广员这5种方法实现。核心策略在于通过低成本、高效率的供应链管理与营销,利用平台社交电商红利实现盈利。

105

2026.01.26

edge浏览器怎样设置主页 edge浏览器自定义设置教程
edge浏览器怎样设置主页 edge浏览器自定义设置教程

在Edge浏览器中设置主页,请依次点击右上角“...”图标 > 设置 > 开始、主页和新建标签页。在“Microsoft Edge 启动时”选择“打开以下页面”,点击“添加新页面”并输入网址。若要使用主页按钮,需在“外观”设置中开启“显示主页按钮”并设定网址。

13

2026.01.26

苹果官方查询网站 苹果手机正品激活查询入口
苹果官方查询网站 苹果手机正品激活查询入口

苹果官方查询网站主要通过 checkcoverage.apple.com/cn/zh/ 进行,可用于查询序列号(SN)对应的保修状态、激活日期及技术支持服务。此外,查找丢失设备请使用 iCloud.com/find,购买信息与物流可访问 Apple (中国大陆) 订单状态页面。

111

2026.01.26

npd人格什么意思 npd人格有什么特征
npd人格什么意思 npd人格有什么特征

NPD(Narcissistic Personality Disorder)即自恋型人格障碍,是一种心理健康问题,特点是极度夸大自我重要性、需要过度赞美与关注,同时极度缺乏共情能力,背后常掩藏着低自尊和不安全感,影响人际关系、工作和生活,通常在青少年时期开始显现,需由专业人士诊断。

5

2026.01.26

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
最新Python教程 从入门到精通
最新Python教程 从入门到精通

共4课时 | 22.3万人学习

Django 教程
Django 教程

共28课时 | 3.5万人学习

SciPy 教程
SciPy 教程

共10课时 | 1.3万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号