stock-tracker

This commit is contained in:
C菌
2026-07-04 00:17:11 +08:00
commit 6087341a48
6463 changed files with 1929869 additions and 0 deletions
@@ -0,0 +1,6 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2019/10/20 10:57
Desc:
"""
@@ -0,0 +1,23 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2019/10/20 10:58
Desc: 外汇配置文件
"""
# headers
SHORT_HEADERS = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36"
}
# url
FX_SPOT_URL = (
"http://www.chinamoney.com.cn/r/cms/www/chinamoney/data/fx/rfx-sp-quot.json"
)
FX_SWAP_URL = (
"http://www.chinamoney.com.cn/r/cms/www/chinamoney/data/fx/rfx-sw-quot.json"
)
FX_PAIR_URL = (
"http://www.chinamoney.com.cn/r/cms/www/chinamoney/data/fx/cpair-quot.json"
)
# payload
SPOT_PAYLOAD = {"t": {}}
@@ -0,0 +1,80 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2024/6/26 15:33
Desc: 英为财情-外汇-货币对历史数据
https://cn.investing.com/currencies/
https://cn.investing.com/currencies/eur-usd-historical-data
"""
import pandas as pd
import requests
from bs4 import BeautifulSoup
from akshare.utils.tqdm import get_tqdm
def currency_pair_map(symbol: str = "美元") -> pd.DataFrame:
"""
指定货币的所有可获取货币对的数据
https://cn.investing.com/currencies/cny-jmd
:param symbol: 指定货币
:type symbol: str
:return: 指定货币的所有可获取货币对的数据
:rtype: pandas.DataFrame
"""
region_code = []
region_name = []
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
# "Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Host": "cn.investing.com",
"Pragma": "no-cache",
"Referer": "https://cn.investing.com/currencies/single-currency-crosses",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "same-origin",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/79.0.3945.130 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
}
def has_data_sml_id_but_no_id(tag):
return tag.has_attr("data-sml-id") and not tag.has_attr("title")
tqdm = get_tqdm()
for region_id in tqdm(["4", "1", "8", "7", "6"], leave=False):
url = "https://cn.investing.com/currencies/Service/region"
params = {"region_ID": region_id, "currency_ID": "false"}
r = requests.get(url, params=params, headers=headers)
soup = BeautifulSoup(r.text, features="lxml")
region_code.extend(
[
item["continentid"] + "-" + region_id
for item in soup.find_all(has_data_sml_id_but_no_id)
]
)
region_name.extend(
[item.find("i").text for item in soup.find_all(has_data_sml_id_but_no_id)]
)
name_id_map = dict(zip(region_name, region_code))
url = "https://cn.investing.com/currencies/Service/currency"
params = {
"region_ID": name_id_map[symbol].split("-")[1],
"currency_ID": name_id_map[symbol].split("-")[0],
}
r = requests.get(url, params=params, headers=headers)
soup = BeautifulSoup(r.text, features="lxml")
temp_code = [item["href"].split("/")[-1] for item in soup.find_all("a")] # need
temp_name = [item["title"].replace(" ", "-") for item in soup.find_all("a")]
temp_df = pd.DataFrame(data=[temp_name, temp_code], index=["name", "code"]).T
return temp_df
if __name__ == "__main__":
currency_pair_map_df = currency_pair_map(symbol="人民币")
print(currency_pair_map_df)
@@ -0,0 +1,67 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2025/9/9 14:57
Desc: 中国外汇交易中心暨全国银行间同业拆借中心-基准-外汇市场-外汇掉期曲线-外汇掉漆 C-Swap 定盘曲线
https://www.chinamoney.org.cn/chinese/bkcurvfsw
"""
import ssl
import pandas as pd
import requests
from requests.adapters import HTTPAdapter
class LegacySSLAdapter(HTTPAdapter):
def init_poolmanager(self, *args, **kwargs):
context = ssl.create_default_context()
# 允许不安全的 legacy renegotiation
context.options |= ssl.OP_LEGACY_SERVER_CONNECT
kwargs["ssl_context"] = context
return super().init_poolmanager(*args, **kwargs)
def fx_c_swap_cm():
"""
中国外汇交易中心暨全国银行间同业拆借中心-基准-外汇市场-外汇掉期曲线-外汇掉期 C-Swap 定盘曲线
https://www.chinamoney.org.cn/chinese/bkcurvfsw
:return: 外汇掉期 C-Swap 定盘曲线
:rtype: pandas.DataFrame
"""
session = requests.Session()
session.mount(prefix="https://", adapter=LegacySSLAdapter())
url = "https://www.chinamoney.org.cn/r/cms/www/chinamoney/data/fx/fx-c-sw-curv-USD.CNY.json"
payload = {
"t": "1757402201554",
}
r = session.post(url, data=payload)
data_json = r.json()
temp_df = pd.DataFrame(data_json["records"])
temp_df.rename(
columns={
"curveTime": "日期时间",
"tenor": "期限品种",
"swapPnt": "掉期点(Pips)",
"dataSource": "掉期点数据源",
"swapAllPrc": "全价汇率",
},
inplace=True,
)
temp_df = temp_df[
[
"日期时间",
"期限品种",
"掉期点(Pips)",
"掉期点数据源",
"全价汇率",
]
]
temp_df["掉期点(Pips)"] = pd.to_numeric(temp_df["掉期点(Pips)"], errors="coerce")
temp_df["全价汇率"] = pd.to_numeric(temp_df["全价汇率"], errors="coerce")
return temp_df
if __name__ == "__main__":
fx_c_swap_cm_df = fx_c_swap_cm()
print(fx_c_swap_cm_df)
@@ -0,0 +1,113 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2022/6/28 14:57
Desc: 中国外汇交易中心暨全国银行间同业拆借中心-市场数据-市场行情-外汇市场行情
人民币外汇即期报价: fx_spot_quote
人民币外汇远掉报价: fx_swap_quote
外币对即期报价: fx_pair_quote
"""
import time
import pandas as pd
import requests
from akshare.fx.cons import (
SHORT_HEADERS,
FX_SPOT_URL,
FX_SWAP_URL,
FX_PAIR_URL,
)
def fx_spot_quote() -> pd.DataFrame:
"""
中国外汇交易中心暨全国银行间同业拆借中心-市场数据-市场行情-外汇市场行情-人民币外汇即期报价
http://www.chinamoney.com.cn/chinese/mkdatapfx/
:return: 人民币外汇即期报价
:rtype: pandas.DataFrame
"""
payload = {"t": str(int(round(time.time() * 1000)))}
res = requests.post(FX_SPOT_URL, data=payload, headers=SHORT_HEADERS)
temp_df = pd.DataFrame(res.json()["records"])
temp_df = temp_df[["ccyPair", "bidPrc", "askPrc", "midprice", "time"]]
temp_df.columns = [
"货币对",
"买报价",
"卖报价",
"-",
"-",
]
temp_df = temp_df[["货币对", "买报价", "卖报价"]]
temp_df["买报价"] = pd.to_numeric(temp_df["买报价"], errors="coerce")
temp_df["卖报价"] = pd.to_numeric(temp_df["卖报价"], errors="coerce")
return temp_df
def fx_swap_quote() -> pd.DataFrame:
"""
中国外汇交易中心暨全国银行间同业拆借中心-市场数据-市场行情-债券市场行情-人民币外汇远掉报价
https://www.chinamoney.com.cn/chinese/index.html
:return: 人民币外汇远掉报价
:rtype: pandas.DataFrame
"""
payload = {"t": str(int(round(time.time() * 1000)))}
res = requests.post(FX_SWAP_URL, data=payload, headers=SHORT_HEADERS)
temp_df = pd.DataFrame(res.json()["records"])
temp_df = temp_df[
[
"ccyPair",
"label_1W",
"label_1M",
"label_3M",
"label_6M",
"label_9M",
"label_1Y",
]
]
temp_df.columns = [
"货币对",
"1周",
"1月",
"3月",
"6月",
"9月",
"1年",
]
return temp_df
def fx_pair_quote() -> pd.DataFrame:
"""
中国外汇交易中心暨全国银行间同业拆借中心-市场数据-市场行情-债券市场行情-外币对即期报价
http://www.chinamoney.com.cn/chinese/mkdatapfx/
:return: 外币对即期报价
:rtype: pandas.DataFrame
"""
payload = {"t": str(int(round(time.time() * 1000)))}
res = requests.post(FX_PAIR_URL, data=payload, headers=SHORT_HEADERS)
temp_df = pd.DataFrame(res.json()["records"])
temp_df = temp_df[["ccyPair", "bidPrc", "askPrc", "midprice", "time"]]
temp_df.columns = [
"货币对",
"买报价",
"卖报价",
"-",
"-",
]
temp_df = temp_df[["货币对", "买报价", "卖报价"]]
temp_df["买报价"] = pd.to_numeric(temp_df["买报价"], errors="coerce")
temp_df["卖报价"] = pd.to_numeric(temp_df["卖报价"], errors="coerce")
return temp_df
if __name__ == "__main__":
fx_spot_quote_df = fx_spot_quote()
print(fx_spot_quote_df)
fx_swap_quote_df = fx_swap_quote()
print(fx_swap_quote_df)
fx_pair_quote_df = fx_pair_quote()
print(fx_pair_quote_df)
@@ -0,0 +1,86 @@
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2026/5/18 18:12
Desc: 百度股市通-外汇-行情榜单
https://finance.baidu.com/top/foreign-rmb
"""
import pandas as pd
import requests
def fx_quote_baidu(symbol: str = "人民币", token: str = "") -> pd.DataFrame:
"""
百度股市通-外汇-行情榜单
https://finance.baidu.com/top/foreign-rmb
:param symbol: choice of {"人民币", "美元"}
:type symbol: str
:param token: 目标网站复制 acs-token 后传入
:type token: str
:return: 外汇行情数据
:rtype: pandas.DataFrame
"""
symbol_map = {
"人民币": "rmb",
"美元": "dollar",
}
headers = {
"Accept": "application/json, text/plain, */*",
"Accept-Language": "zh-CN,zh;q=0.9",
"Origin": "https://finance.baidu.com",
"Referer": "https://finance.baidu.com/",
"acs-token": token,
}
url = "https://finance.pae.baidu.com/api/getforeignrank"
out_df = pd.DataFrame()
num = 0
while True:
params = {
"type": symbol_map[symbol],
"pn": num,
"rn": "20",
"finClientType": "pc",
}
r = requests.get(url, params=params, headers=headers, timeout=10)
data_json = r.json()
# 显式检查返回码,便于调试
if data_json.get("ResultCode") != "0":
print(f"[pn={num}] 接口返回异常: {data_json}")
break
result = data_json.get("Result")
if not result: # 空列表 → 已到末页
break
temp_df = pd.DataFrame(result)
if temp_df.empty or "list" not in temp_df.columns:
break
temp_list = []
item = None
for item in temp_df["list"]:
temp_list.append(list(pd.DataFrame(item).T.iloc[1, :].values))
if item is None:
break
value_df = pd.DataFrame(
temp_list, columns=pd.DataFrame(item).T.iloc[0, :].values
)
big_df = pd.concat(objs=[temp_df, value_df], axis=1)
for col in ["market", "list", "status", "icon1", "icon2", "financeType"]:
if col in big_df.columns:
del big_df[col]
big_df.columns = ["代码", "名称", "最新价", "涨跌额", "涨跌幅"]
big_df["最新价"] = pd.to_numeric(big_df["最新价"], errors="coerce")
big_df["涨跌额"] = pd.to_numeric(big_df["涨跌额"], errors="coerce")
big_df["涨跌幅"] = (
pd.to_numeric(big_df["涨跌幅"].str.strip("%"), errors="coerce") / 100
)
out_df = pd.concat(objs=[out_df, big_df], ignore_index=True)
# 如果本页返回不足 20 条,说明是最后一页
if len(big_df) < 20:
break
num += 20
return out_df
if __name__ == "__main__":
fx_quote_baidu_df = fx_quote_baidu(symbol="人民币")
print(fx_quote_baidu_df)