程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python quantification - how to get real-time stock information

編輯:Python

How to get real-time stock information

There are many interfaces for stock information , Before, Sina was commonly used , But at the beginning of the year , Sina's interface is suddenly unavailable , It has caused a lot of trouble to everyone , For this reason, there are many tutorials on the Internet to teach you how to obtain data from Sina , I can't follow the tutorial for a long time , Simply change to 126( That is, Netease ), I think the speed is pretty good .

First, let's look at the interface address :http://api.money.126.net/data/feed/1000001,money.api

Among them 1000001 It's the stock code , Different from Sina , His first representative is the exchange , Back 6 Bit is the stock code

  • 0: Shanghai
  • 1: The shenzhen stock exchange
  • 2: Beijing stock exchange

First, view the data structure through the browser :

_ntes_quote_callback({
"1000001": {
"code": "1000001",
"percent": 0.002113,
"high": 14.25,
"askvol3": 1026758,
"askvol2": 810700,
"askvol5": 290493,
"askvol4": 461100,
"price": 14.23,
"open": 14.2,
"bid5": 14.18,
"bid4": 14.19,
"bid3": 14.2,
"bid2": 14.21,
"bid1": 14.22,
"low": 14.11,
"updown": 0.03,
"type": "SZ",
"bidvol1": 323600,
"status": 0,
"bidvol3": 244200,
"bidvol2": 673474,
"symbol": "000001",
"update": "2022/06/25 17:59:57",
"bidvol5": 343500,
"bidvol4": 145200,
"volume": 86604061,
"askvol1": 817268,
"ask5": 14.27,
"ask4": 14.26,
"ask1": 14.23,
"name": " Ping An Bank ",
"ask3": 14.25,
"ask2": 14.24,
"arrow": "↑",
"time": "2022/06/24 16:00:58",
"yestclose": 14.2,
"turnover": 1227798687.09
}
});

It can be seen that _ntes_quote_callback() What is in is the standard json data , We just need to use regular expressions to get out .

Let's first define a data structure :

class NetTick:
def __init__(self, dict={}):
self.name = dict.get('name') # The name of the stock
self.yestclose = dict.get('yestclose') # Yesterday's closing price
self.bidvol5 = dict.get('bidvol5') # buy 5 Number
self.bidvol4 = dict.get('bidvol4') # buy 4 Number
self.bidvol3 = dict.get('bidvol3') # buy 3 Number
self.bidvol2 = dict.get('bidvol2') # buy 2 Number
self.bidvol1 = dict.get('bidvol1') # buy 1 Number
self.bid5 = dict.get('bid5') # buy 5 Price
self.bid4 = dict.get('bid4') # buy 4 Price
self.bid3 = dict.get('bid3') # buy 3 Price
self.bid2 = dict.get('bid2') # buy 2 Price
self.bid1 = dict.get('bid1') # buy 1 Price
self.askvol5 = dict.get('askvol5') # sell 5 Number
self.askvol4 = dict.get('askvol4') # sell 4 Number
self.askvol3 = dict.get('askvol3') # sell 3 Number
self.askvol2 = dict.get('askvol2') # sell 2 Number
self.askvol1 = dict.get('askvol1') # sell 1 Number
self.ask5 = dict.get('ask5') # sell 5 Price
self.ask4 = dict.get('ask4') # sell 4 Price
self.ask3 = dict.get('ask3') # sell 3 Price
self.ask2 = dict.get('ask2') # sell 2 Price
self.ask1 = dict.get('ask1') # sell 1 Price
self.symbol = dict.get('symbol') # Stock code first place 1: The shenzhen stock exchange 0: Shanghai 2 Beijing stock exchange
self.volume = dict.get('volume') # volume
self.price = dict.get('price') # Current price
self.open = dict.get('open') # Opening price
self.low = dict.get('low') # The lowest price
self.high = dict.get('high') # Highest price
self.code = dict.get('code') # Remove the stock code marked as
self.turnover = dict.get('turnover') # turnover
self.percent = dict.get('percent') # applies
self.updown = dict.get('updown') # Up and down

Through research , We found that 126 The interface supports multiple stock queries , Then we can define two methods , One by one , Check more than one , The specific implementation is as follows :

import requests
import re
from models.nettick import NetTick
from utils.packages import * class NetEaseData:
@staticmethod
def get_realtime_data(symbol):
"""
Netease's real-time data interface
:param symbol: Stock code
:return: Tick
"""
code = NetEaseData.convert_market(symbol)
try:
response = requests.get("http://api.money.126.net/data/feed/{},money.api".format(code)).text
re_find = NetEaseData.__re_find(response)
if re_find is not None:
find_stock = re_find.get(code)
if find_stock is not None:
return NetTick(find_stock) except Exception as e:
logger.error(' Error requesting Netease interface , error message :{}'.format(e)) return None @staticmethod
def convert_market(other_market_code=str):
"""
Convert the general stock code sz sh bj start + Stock code
"""
if other_market_code[0:2].lower() == 'sh':
return '0' + other_market_code[2:]
elif other_market_code[0:2].lower() == 'sz':
return '1' + other_market_code[2:]
else:
return '2' + other_market_code[2:] @staticmethod
def get_realtime_datas(symbols=[]):
"""
Netease's real-time data interface
:param symbols: Stock code list
:return: Ticks list
"""
codes = [NetEaseData.convert_market(code) for code in symbols]
result = []
try:
response = requests.get("http://api.money.126.net/data/feed/{},money.api".format(','.join(codes))).text
re_find = NetEaseData.__re_find(response)
if re_find is not None:
for code in re_find:
item = re_find[code]
result.append(NetTick(item))
except Exception as e:
logger.error(' Error requesting Netease interface , error message :{}'.format(e)) return result @staticmethod
def __re_find(response):
find = re.findall(r"_ntes_quote_callback\((.*)\);", response)
if len(find) >= 1:
return to_obj(find[-1]) return None if __name__ == '__main__':
ticks = NetEaseData.get_realtime_datas(['sh588000', 'sz000001', 'bj831010'])
[print(tick.symbol, tick.name, tick.price) for tick in ticks]
tick = NetEaseData.get_realtime_data('sz127045')
print(tick.symbol, tick.name, tick.price)

It's very easy to use

  • NetEaseData.get_realtime_data: Acquire individual shares
  • NetEaseData.get_realtime_datas : Get multiple stock data

My stock code here is compatible with the original Sina model , You can make your own changes .

Currently, we are upgrading our own quantification platform , Some of the previous code will also be published , If you like it, please make a recommendation , thank you

Python quantitative - More articles on how to get real-time stock information

  1. python Get real-time stock information

    Python3 Get stock market data ( Chinese stocks / China Index / Global index ) #!/usr/local/bin/python3 #coding=utf-8 #source http://www.cnblogs.co ...

  2. python Quantitative analysis series ---5 Line code implementation 1 Get the real-time transaction data of all stocks once in seconds

    python Quantitative analysis series ---5 Line code implementation 1 Get the real-time transaction data of all stocks once in seconds I've been too busy at work recently , I haven't updated the article for a week , Originally, this issue was intended to share some analysis results of the dragon and tiger list data , At present, the value in the data has not been very good ...

  3. Financial quantitative analysis -python Quantitative analysis series --- Use python Access to stock historical data and real-time transaction data

    Financial data interface package tushare Use ( One ) Tushare Is an open source free financial data interface package , It can be used to get historical data of stocks . Annual and quarterly report data . Real time pen data . Historical data , This paper deals with tushare Usage of , What already exists ...

  4. Python Script : Get stock information

    On Shuimu, I saw someone asking me if I want to use python To get stock information ,sina finance The data above are obtained through js The control of the , Will get real-time information according to the stock code, and then display it in a user-friendly way . First , One of sina's url Let me ...

  5. Face detection and recognition python Implement series (1)—— To configure 、 Get a real-time video stream

    Face detection and recognition python Implement series (1)—— To configure . Get a real-time video stream 1. Preface Spend more than half a day today to QQ A few old articles in the space moved here , It's a blog move .QQ There are still some places left in the space to record their own mathematical learning routes ...

  6. At present, it is more popular Python Quantitative open source framework summary ( transaction + Risk analysis tools )

      notes : Click the frame name to go to Github talib talib Short for Technical Analysis Library, The main function is to calculate the technical analysis index of market data numpy Introduce : One use python Realized ...

  7. China's Python Quantify the chain of trading tools

    I know it :https://www.zhihu.com/question/28557233 As the title , The scope of questions is limited to the tool chain suitable for the financial market in Chinese Mainland , therefore IbPy and Quotopian And so on, mainly for the European and American markets ...

  8. Python Quantitative trading

    Data collation : 1.python A quantitative one github Code 2. principle + python Basics Explain 3. So far, we have found two good quantitative transactions Learning platform : Jukuan and youkuang are both in quantitative trading 15 It's on the line in 2000 , Jukuan is 15 In the new ...

  9. python perform shell Get hardware parameters, write mysql

    Recently, I want to get various parameters of the server , Include cpu. Memory . disk . Model and other information . Tried Hyperic HQ.Nagios and Snmp, They are very powerful , But it doesn't match the demand , Or too heavy. So I thought of using python ...

  10. Application Python Language writing gets Linux Basic system information ( 3、 ... and ):Python And database programming , Store the information in the database

    Application Python Language writing gets Linux Basic system information ( 3、 ... and ):Python And database programming Links to the first two articles : Application Python Language writing gets Linux Basic system information ( One ): get Linux edition . kernel . current time shipment ...

Random recommendation

  1. Photoshop Quickly make the secondary cartoon style effect from ordinary photos

    I want to share with you today Photoshop Quickly make the secondary cartoon style effect from ordinary photos , The tutorial is great , For those who like comics, please refer to this article , I hope it can help you ! When it comes to Japanese animated films , Your first impression must be Hayao Miyazaki , But Japan, apart from Miyazaki ...

  2. page object

    http://www.51testing.com/html/76/316176-849962.html

  3. oracle11gRAC Environment use RMAN Incremental backup solution

    quote :http://blog.itpub.net/29819001/viewspace-1320977/ [[email protected] ~]$ rman target /Recovery Manager: R ...

  4. MVC Calculate the page execution time

    Use  ActionFilterAttribute To achieve : public class PerformanceActionAttribute:ActionFilterAttribute { public ...

  5. Windows Next Android Studio Stay in for a long time Building "Project Name" Gradle project info The solution to the picture

    Problem description : Create one Android After the project ,Android Studio Stay in for a long time Building [Project Name] Gradle project info The picture doesn't move . reason : here And ...

  6. Use POI establish Excel File download

    POIExcelUtils.java: package com.saicfc.pmpf.internal.manage.utils; import java.io.File; import java. ...

  7. start-up apache Service times are wrong 【the requested operation has failed】

    Trying to fix the mistake , First, find out the cause of the mistake . Use ApacheMonitor.exe start-up apache The service doesn't see any reason for the error . Find the cause of the problem :cmd-- Command to end -- Switch to apache Of bin Catalog , Execute the following command : ...

  8. Python National second level examination (2019)

    One . Preface 2018 year 9 With the national computer rank examination subjects to join “ second level Python”, Also established Python Status at home , Brother pig believes Python Language is bound to be like PS So popular . Near future , Who will be Python Who can get the goddess ...

  9. sublime text3 The plug-in enhances the function of the sidebar to copy and paste files

    Shortcut key ctrl + shift +p Input   install package enter , Call up the plug-in searcher , Enter... In the search field  SideBarEnhancements  Enter to install the plug-in . Various operation functions in the sidebar are added ...

  10. django - summary

    0.html-socket import socket def handle_request(client): request_data = client.recv(1024) print(" ...


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved