nwo
stringlengths 10
28
| sha
stringlengths 40
40
| path
stringlengths 11
97
| identifier
stringlengths 1
64
| parameters
stringlengths 2
2.24k
| return_statement
stringlengths 0
2.17k
| docstring
stringlengths 0
5.45k
| docstring_summary
stringlengths 0
3.83k
| func_begin
int64 1
13.4k
| func_end
int64 2
13.4k
| function
stringlengths 28
56.4k
| url
stringlengths 106
209
| project
int64 1
48
| executed_lines
list | executed_lines_pc
float64 0
153
| missing_lines
list | missing_lines_pc
float64 0
100
| covered
bool 2
classes | filecoverage
float64 2.53
100
| function_lines
int64 2
1.46k
| mccabe
int64 1
253
| coverage
float64 0
100
| docstring_lines
int64 0
112
| function_nodoc
stringlengths 9
56.4k
| id
int64 0
29.8k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/symbol_var.py
|
symbol_market
|
(symbol_detail: str = "SC")
|
映射出市场代码
:param symbol_detail:
:return:
|
映射出市场代码
:param symbol_detail:
:return:
| 24 | 33 |
def symbol_market(symbol_detail: str = "SC"):
"""
映射出市场代码
:param symbol_detail:
:return:
"""
var_item = symbol_varieties(symbol_detail)
for market_item, contract_items in cons.market_exchange_symbols.items():
if var_item in contract_items:
return market_item
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/symbol_var.py#L24-L33
| 25 |
[
0,
1,
2,
3,
4,
5
] | 60 |
[
6,
7,
8,
9
] | 40 | false | 25.806452 | 10 | 3 | 60 | 3 |
def symbol_market(symbol_detail: str = "SC"):
var_item = symbol_varieties(symbol_detail)
for market_item, contract_items in cons.market_exchange_symbols.items():
if var_item in contract_items:
return market_item
| 18,134 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/symbol_var.py
|
find_chinese
|
(chinese_string: str)
|
return "".join(res)
|
查找中文字符
:param chinese_string: 中文字符串
:return:
|
查找中文字符
:param chinese_string: 中文字符串
:return:
| 36 | 44 |
def find_chinese(chinese_string: str):
"""
查找中文字符
:param chinese_string: 中文字符串
:return:
"""
p = re.compile(r"[\u4e00-\u9fa5]")
res = re.findall(p, chinese_string)
return "".join(res)
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/symbol_var.py#L36-L44
| 25 |
[
0,
1,
2,
3,
4,
5
] | 66.666667 |
[
6,
7,
8
] | 33.333333 | false | 25.806452 | 9 | 1 | 66.666667 | 3 |
def find_chinese(chinese_string: str):
p = re.compile(r"[\u4e00-\u9fa5]")
res = re.findall(p, chinese_string)
return "".join(res)
| 18,135 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/symbol_var.py
|
chinese_to_english
|
(chinese_var: str)
|
return english_list[pos]
|
映射期货品种中文名称和英文缩写
:param chinese_var: 期货品种中文名称
:return: 对应的英文缩写
|
映射期货品种中文名称和英文缩写
:param chinese_var: 期货品种中文名称
:return: 对应的英文缩写
| 47 | 264 |
def chinese_to_english(chinese_var: str):
"""
映射期货品种中文名称和英文缩写
:param chinese_var: 期货品种中文名称
:return: 对应的英文缩写
"""
chinese_list = [
"橡胶",
"天然橡胶",
"石油沥青",
"沥青",
"沥青仓库",
"沥青(仓库)",
"沥青厂库",
"沥青(厂库)",
"热轧卷板",
"热轧板卷",
"燃料油",
"白银",
"线材",
"螺纹钢",
"铅",
"铜",
"铝",
"锌",
"黄金",
"钯金",
"锡",
"镍",
"纸浆",
"豆一",
"大豆",
"豆二",
"胶合板",
"玉米",
"玉米淀粉",
"聚乙烯",
"LLDPE",
"LDPE",
"豆粕",
"豆油",
"大豆油",
"棕榈油",
"纤维板",
"鸡蛋",
"聚氯乙烯",
"PVC",
"聚丙烯",
"PP",
"焦炭",
"焦煤",
"铁矿石",
"乙二醇",
"强麦",
"强筋小麦",
" 强筋小麦",
"硬冬白麦",
"普麦",
"硬白小麦",
"硬白小麦()",
"皮棉",
"棉花",
"一号棉",
"白糖",
"PTA",
"菜籽油",
"菜油",
"早籼稻",
"早籼",
"甲醇",
"柴油",
"玻璃",
"油菜籽",
"菜籽",
"菜籽粕",
"菜粕",
"动力煤",
"粳稻",
"晚籼稻",
"晚籼",
"硅铁",
"锰硅",
"硬麦",
"棉纱",
"苹果",
"原油",
"中质含硫原油",
"尿素",
"20号胶",
"苯乙烯",
"不锈钢",
"粳米",
"20号胶20",
"红枣",
"不锈钢仓库",
"纯碱",
"液化石油气",
"低硫燃料油",
"纸浆仓库",
"石油沥青厂库",
"石油沥青仓库",
"螺纹钢仓库",
"螺纹钢厂库",
"纸浆厂库",
"低硫燃料油仓库",
"低硫燃料油厂库",
"短纤",
'涤纶短纤',
'生猪',
'花生',
]
english_list = [
"RU",
"RU",
"BU",
"BU",
"BU",
"BU",
"BU2",
"BU2",
"HC",
"HC",
"FU",
"AG",
"WR",
"RB",
"PB",
"CU",
"AL",
"ZN",
"AU",
"AU",
"SN",
"NI",
"SP",
"A",
"A",
"B",
"BB",
"C",
"CS",
"L",
"L",
"L",
"M",
"Y",
"Y",
"P",
"FB",
"JD",
"V",
"V",
"PP",
"PP",
"J",
"JM",
"I",
"EG",
"WH",
"WH",
"WH",
"PM",
"PM",
"PM",
"PM",
"CF",
"CF",
"CF",
"SR",
"TA",
"OI",
"OI",
"RI",
"ER",
"MA",
"MA",
"FG",
"RS",
"RS",
"RM",
"RM",
"ZC",
"JR",
"LR",
"LR",
"SF",
"SM",
"WT",
"CY",
"AP",
"SC",
"SC",
"UR",
"NR",
"EB",
"SS",
"RR",
"NR",
"CJ",
"SS",
"SA",
"PG",
"LU",
"SP",
"BU",
"BU",
"RB",
"RB",
"SP",
"LU",
"LU",
"PF",
"PF",
"LH",
"PK",
]
pos = chinese_list.index(chinese_var)
return english_list[pos]
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/symbol_var.py#L47-L264
| 25 |
[
0,
1,
2,
3,
4,
5
] | 2.752294 |
[
6,
111,
216,
217
] | 1.834862 | false | 25.806452 | 218 | 1 | 98.165138 | 3 |
def chinese_to_english(chinese_var: str):
chinese_list = [
"橡胶",
"天然橡胶",
"石油沥青",
"沥青",
"沥青仓库",
"沥青(仓库)",
"沥青厂库",
"沥青(厂库)",
"热轧卷板",
"热轧板卷",
"燃料油",
"白银",
"线材",
"螺纹钢",
"铅",
"铜",
"铝",
"锌",
"黄金",
"钯金",
"锡",
"镍",
"纸浆",
"豆一",
"大豆",
"豆二",
"胶合板",
"玉米",
"玉米淀粉",
"聚乙烯",
"LLDPE",
"LDPE",
"豆粕",
"豆油",
"大豆油",
"棕榈油",
"纤维板",
"鸡蛋",
"聚氯乙烯",
"PVC",
"聚丙烯",
"PP",
"焦炭",
"焦煤",
"铁矿石",
"乙二醇",
"强麦",
"强筋小麦",
" 强筋小麦",
"硬冬白麦",
"普麦",
"硬白小麦",
"硬白小麦()",
"皮棉",
"棉花",
"一号棉",
"白糖",
"PTA",
"菜籽油",
"菜油",
"早籼稻",
"早籼",
"甲醇",
"柴油",
"玻璃",
"油菜籽",
"菜籽",
"菜籽粕",
"菜粕",
"动力煤",
"粳稻",
"晚籼稻",
"晚籼",
"硅铁",
"锰硅",
"硬麦",
"棉纱",
"苹果",
"原油",
"中质含硫原油",
"尿素",
"20号胶",
"苯乙烯",
"不锈钢",
"粳米",
"20号胶20",
"红枣",
"不锈钢仓库",
"纯碱",
"液化石油气",
"低硫燃料油",
"纸浆仓库",
"石油沥青厂库",
"石油沥青仓库",
"螺纹钢仓库",
"螺纹钢厂库",
"纸浆厂库",
"低硫燃料油仓库",
"低硫燃料油厂库",
"短纤",
'涤纶短纤',
'生猪',
'花生',
]
english_list = [
"RU",
"RU",
"BU",
"BU",
"BU",
"BU",
"BU2",
"BU2",
"HC",
"HC",
"FU",
"AG",
"WR",
"RB",
"PB",
"CU",
"AL",
"ZN",
"AU",
"AU",
"SN",
"NI",
"SP",
"A",
"A",
"B",
"BB",
"C",
"CS",
"L",
"L",
"L",
"M",
"Y",
"Y",
"P",
"FB",
"JD",
"V",
"V",
"PP",
"PP",
"J",
"JM",
"I",
"EG",
"WH",
"WH",
"WH",
"PM",
"PM",
"PM",
"PM",
"CF",
"CF",
"CF",
"SR",
"TA",
"OI",
"OI",
"RI",
"ER",
"MA",
"MA",
"FG",
"RS",
"RS",
"RM",
"RM",
"ZC",
"JR",
"LR",
"LR",
"SF",
"SM",
"WT",
"CY",
"AP",
"SC",
"SC",
"UR",
"NR",
"EB",
"SS",
"RR",
"NR",
"CJ",
"SS",
"SA",
"PG",
"LU",
"SP",
"BU",
"BU",
"RB",
"RB",
"SP",
"LU",
"LU",
"PF",
"PF",
"LH",
"PK",
]
pos = chinese_list.index(chinese_var)
return english_list[pos]
| 18,136 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_warehouse_receipt.py
|
futures_czce_warehouse_receipt
|
(trade_date: str = "20200702")
|
return big_dict
|
郑州商品交易所-交易数据-仓单日报
http://www.czce.com.cn/cn/jysj/cdrb/H770310index_1.htm
:param trade_date: 交易日, e.g., "20200702"
:type trade_date: str
:return: 指定日期的仓单日报数据
:rtype: dict
|
郑州商品交易所-交易数据-仓单日报
http://www.czce.com.cn/cn/jysj/cdrb/H770310index_1.htm
:param trade_date: 交易日, e.g., "20200702"
:type trade_date: str
:return: 指定日期的仓单日报数据
:rtype: dict
| 19 | 51 |
def futures_czce_warehouse_receipt(trade_date: str = "20200702") -> dict:
"""
郑州商品交易所-交易数据-仓单日报
http://www.czce.com.cn/cn/jysj/cdrb/H770310index_1.htm
:param trade_date: 交易日, e.g., "20200702"
:type trade_date: str
:return: 指定日期的仓单日报数据
:rtype: dict
"""
url = f"http://www.czce.com.cn/cn/DFSStaticFiles/Future/{trade_date[:4]}/{trade_date}/FutureDataWhsheet.xls"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
}
r = requests.get(url, verify=False, headers=headers)
temp_df = pd.read_excel(BytesIO(r.content))
index_list = temp_df[
temp_df.iloc[:, 0].str.find("品种") == 0.0
].index.to_list()
index_list.append(len(temp_df))
big_dict = {}
for inner_index in range(len(index_list) - 1):
inner_df = temp_df[
index_list[inner_index] : index_list[inner_index + 1]
]
inner_key = re.findall(r"[a-zA-Z]+", inner_df.iloc[0, 0])[0]
inner_df = inner_df.iloc[1:, :]
inner_df.dropna(axis=0, how="all", inplace=True)
inner_df.dropna(axis=1, how="all", inplace=True)
inner_df.columns = inner_df.iloc[0, :].to_list()
inner_df = inner_df.iloc[1:, :]
inner_df.reset_index(inplace=True, drop=True)
big_dict[inner_key] = inner_df
return big_dict
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_warehouse_receipt.py#L19-L51
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 27.272727 |
[
9,
10,
13,
14,
15,
18,
19,
20,
21,
24,
25,
26,
27,
28,
29,
30,
31,
32
] | 54.545455 | false | 10.588235 | 33 | 2 | 45.454545 | 6 |
def futures_czce_warehouse_receipt(trade_date: str = "20200702") -> dict:
url = f"http://www.czce.com.cn/cn/DFSStaticFiles/Future/{trade_date[:4]}/{trade_date}/FutureDataWhsheet.xls"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
}
r = requests.get(url, verify=False, headers=headers)
temp_df = pd.read_excel(BytesIO(r.content))
index_list = temp_df[
temp_df.iloc[:, 0].str.find("品种") == 0.0
].index.to_list()
index_list.append(len(temp_df))
big_dict = {}
for inner_index in range(len(index_list) - 1):
inner_df = temp_df[
index_list[inner_index] : index_list[inner_index + 1]
]
inner_key = re.findall(r"[a-zA-Z]+", inner_df.iloc[0, 0])[0]
inner_df = inner_df.iloc[1:, :]
inner_df.dropna(axis=0, how="all", inplace=True)
inner_df.dropna(axis=1, how="all", inplace=True)
inner_df.columns = inner_df.iloc[0, :].to_list()
inner_df = inner_df.iloc[1:, :]
inner_df.reset_index(inplace=True, drop=True)
big_dict[inner_key] = inner_df
return big_dict
| 18,138 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_warehouse_receipt.py
|
futures_dce_warehouse_receipt
|
(trade_date: str = "20200702")
|
return big_dict
|
大连商品交易所-行情数据-统计数据-日统计-仓单日报
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/cdrb/index.html
:param trade_date: 交易日, e.g., "20200702"
:type trade_date: str
:return: 指定日期的仓单日报数据
:rtype: dict
|
大连商品交易所-行情数据-统计数据-日统计-仓单日报
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/cdrb/index.html
:param trade_date: 交易日, e.g., "20200702"
:type trade_date: str
:return: 指定日期的仓单日报数据
:rtype: dict
| 54 | 90 |
def futures_dce_warehouse_receipt(trade_date: str = "20200702") -> dict:
"""
大连商品交易所-行情数据-统计数据-日统计-仓单日报
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/cdrb/index.html
:param trade_date: 交易日, e.g., "20200702"
:type trade_date: str
:return: 指定日期的仓单日报数据
:rtype: dict
"""
url = "http://www.dce.com.cn/publicweb/quotesdata/wbillWeeklyQuotes.html"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
}
params = {
"wbillWeeklyQuotes.variety": "all",
"year": trade_date[:4],
"month": str(int(trade_date[4:6]) - 1),
"day": trade_date[6:],
}
r = requests.get(url, params=params, headers=headers)
temp_df = pd.read_html(r.text)[0]
index_list = temp_df[
temp_df.iloc[:, 0].str.contains("小计") == 1
].index.to_list()
index_list.insert(0, 0)
big_dict = {}
for inner_index in range(len(index_list) - 1):
if inner_index == 0:
temp_index = 0
else:
temp_index = index_list[inner_index] + 1
inner_df = temp_df[temp_index : index_list[inner_index + 1] + 1]
inner_key = inner_df.iloc[0, 0]
inner_df.reset_index(inplace=True, drop=True)
inner_df = inner_df.fillna(method="ffill")
big_dict[inner_key] = inner_df
return big_dict
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_warehouse_receipt.py#L54-L90
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 24.324324 |
[
9,
10,
13,
19,
20,
21,
24,
25,
26,
27,
28,
30,
31,
32,
33,
34,
35,
36
] | 48.648649 | false | 10.588235 | 37 | 3 | 51.351351 | 6 |
def futures_dce_warehouse_receipt(trade_date: str = "20200702") -> dict:
url = "http://www.dce.com.cn/publicweb/quotesdata/wbillWeeklyQuotes.html"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
}
params = {
"wbillWeeklyQuotes.variety": "all",
"year": trade_date[:4],
"month": str(int(trade_date[4:6]) - 1),
"day": trade_date[6:],
}
r = requests.get(url, params=params, headers=headers)
temp_df = pd.read_html(r.text)[0]
index_list = temp_df[
temp_df.iloc[:, 0].str.contains("小计") == 1
].index.to_list()
index_list.insert(0, 0)
big_dict = {}
for inner_index in range(len(index_list) - 1):
if inner_index == 0:
temp_index = 0
else:
temp_index = index_list[inner_index] + 1
inner_df = temp_df[temp_index : index_list[inner_index + 1] + 1]
inner_key = inner_df.iloc[0, 0]
inner_df.reset_index(inplace=True, drop=True)
inner_df = inner_df.fillna(method="ffill")
big_dict[inner_key] = inner_df
return big_dict
| 18,139 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_warehouse_receipt.py
|
futures_shfe_warehouse_receipt
|
(trade_date: str = "20200702")
|
return big_dict
|
上海期货交易所指定交割仓库期货仓单日报
http://www.shfe.com.cn/statements/dataview.html?paramid=dailystock¶mdate=20200703
:param trade_date: 交易日, e.g., "20200702"
:type trade_date: str
:return: 指定日期的仓单日报数据
:rtype: dict
|
上海期货交易所指定交割仓库期货仓单日报
http://www.shfe.com.cn/statements/dataview.html?paramid=dailystock¶mdate=20200703
:param trade_date: 交易日, e.g., "20200702"
:type trade_date: str
:return: 指定日期的仓单日报数据
:rtype: dict
| 93 | 146 |
def futures_shfe_warehouse_receipt(trade_date: str = "20200702") -> dict:
"""
上海期货交易所指定交割仓库期货仓单日报
http://www.shfe.com.cn/statements/dataview.html?paramid=dailystock¶mdate=20200703
:param trade_date: 交易日, e.g., "20200702"
:type trade_date: str
:return: 指定日期的仓单日报数据
:rtype: dict
"""
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
}
url = f"http://www.shfe.com.cn/data/dailydata/{trade_date}dailystock.dat"
if trade_date >= "20140519":
r = requests.get(url, headers=headers)
data_json = r.json()
temp_df = pd.DataFrame(data_json["o_cursor"])
temp_df["VARNAME"] = (
temp_df["VARNAME"].str.split(r"$", expand=True).iloc[:, 0]
)
temp_df["REGNAME"] = (
temp_df["REGNAME"].str.split(r"$", expand=True).iloc[:, 0]
)
temp_df["WHABBRNAME"] = (
temp_df["WHABBRNAME"].str.split(r"$", expand=True).iloc[:, 0]
)
big_dict = {}
for item in set(temp_df["VARNAME"]):
big_dict[item] = temp_df[temp_df["VARNAME"] == item]
else:
url = f"http://www.shfe.com.cn/data/dailydata/{trade_date}dailystock.html"
r = requests.get(url, headers=headers)
temp_df = pd.read_html(r.text)[0]
index_list = temp_df[
temp_df.iloc[:, 3].str.contains("单位:") == 1
].index.to_list()
big_dict = {}
for inner_index in range(len(index_list)):
temp_index_start = index_list[inner_index]
if (inner_index + 1) >= len(index_list):
if temp_df.iloc[-1, 0].startswith("注:"):
temp_index_end = len(temp_df) - 1
else:
temp_index_end = len(temp_df)
else:
temp_index_end = index_list[inner_index + 1]
inner_df = temp_df[temp_index_start:temp_index_end]
inner_df.reset_index(inplace=True, drop=True)
inner_key = inner_df.iloc[0, 0]
inner_df.columns = inner_df.iloc[1].to_list()
inner_df = inner_df[2:]
inner_df.reset_index(inplace=True, drop=True)
big_dict[inner_key] = inner_df
return big_dict
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_warehouse_receipt.py#L93-L146
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 16.666667 |
[
9,
12,
13,
14,
15,
16,
17,
20,
23,
26,
27,
28,
30,
31,
32,
33,
36,
37,
38,
39,
40,
41,
43,
45,
46,
47,
48,
49,
50,
51,
52,
53
] | 59.259259 | false | 10.588235 | 54 | 6 | 40.740741 | 6 |
def futures_shfe_warehouse_receipt(trade_date: str = "20200702") -> dict:
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36"
}
url = f"http://www.shfe.com.cn/data/dailydata/{trade_date}dailystock.dat"
if trade_date >= "20140519":
r = requests.get(url, headers=headers)
data_json = r.json()
temp_df = pd.DataFrame(data_json["o_cursor"])
temp_df["VARNAME"] = (
temp_df["VARNAME"].str.split(r"$", expand=True).iloc[:, 0]
)
temp_df["REGNAME"] = (
temp_df["REGNAME"].str.split(r"$", expand=True).iloc[:, 0]
)
temp_df["WHABBRNAME"] = (
temp_df["WHABBRNAME"].str.split(r"$", expand=True).iloc[:, 0]
)
big_dict = {}
for item in set(temp_df["VARNAME"]):
big_dict[item] = temp_df[temp_df["VARNAME"] == item]
else:
url = f"http://www.shfe.com.cn/data/dailydata/{trade_date}dailystock.html"
r = requests.get(url, headers=headers)
temp_df = pd.read_html(r.text)[0]
index_list = temp_df[
temp_df.iloc[:, 3].str.contains("单位:") == 1
].index.to_list()
big_dict = {}
for inner_index in range(len(index_list)):
temp_index_start = index_list[inner_index]
if (inner_index + 1) >= len(index_list):
if temp_df.iloc[-1, 0].startswith("注:"):
temp_index_end = len(temp_df) - 1
else:
temp_index_end = len(temp_df)
else:
temp_index_end = index_list[inner_index + 1]
inner_df = temp_df[temp_index_start:temp_index_end]
inner_df.reset_index(inplace=True, drop=True)
inner_key = inner_df.iloc[0, 0]
inner_df.columns = inner_df.iloc[1].to_list()
inner_df = inner_df[2:]
inner_df.reset_index(inplace=True, drop=True)
big_dict[inner_key] = inner_df
return big_dict
| 18,140 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_inventory_99.py
|
futures_inventory_99
|
(
exchange: str = "大连商品交易所", symbol: str = "豆一"
)
|
99 期货网-大宗商品库存数据
http://www.99qh.com/d/store.aspx
:param exchange: 交易所名称; choice of {"上海期货交易所", "郑州商品交易所", "大连商品交易所", "LME", "NYMEX", "CBOT", "NYBOT", "TOCOM", "上海国际能源交易中心", "OSE"}
:type exchange: str
:param symbol: 交易所对应的具体品种; 如:大连商品交易所的 豆一
:type symbol: str
:return: 大宗商品库存数据
:rtype: pandas.DataFrame
|
99 期货网-大宗商品库存数据
http://www.99qh.com/d/store.aspx
:param exchange: 交易所名称; choice of {"上海期货交易所", "郑州商品交易所", "大连商品交易所", "LME", "NYMEX", "CBOT", "NYBOT", "TOCOM", "上海国际能源交易中心", "OSE"}
:type exchange: str
:param symbol: 交易所对应的具体品种; 如:大连商品交易所的 豆一
:type symbol: str
:return: 大宗商品库存数据
:rtype: pandas.DataFrame
| 18 | 288 |
def futures_inventory_99(
exchange: str = "大连商品交易所", symbol: str = "豆一"
) -> pd.DataFrame:
"""
99 期货网-大宗商品库存数据
http://www.99qh.com/d/store.aspx
:param exchange: 交易所名称; choice of {"上海期货交易所", "郑州商品交易所", "大连商品交易所", "LME", "NYMEX", "CBOT", "NYBOT", "TOCOM", "上海国际能源交易中心", "OSE"}
:type exchange: str
:param symbol: 交易所对应的具体品种; 如:大连商品交易所的 豆一
:type symbol: str
:return: 大宗商品库存数据
:rtype: pandas.DataFrame
"""
data_code = {
"1": [
"1",
"2",
"3",
"12",
"32",
"36",
"37",
"40",
"42",
"47",
"56",
"63",
"69",
"70",
"79",
"85",
],
"2": [
"4",
"14",
"29",
"31",
"33",
"38",
"44",
"45",
"50",
"51",
"52",
"55",
"59",
"64",
"66",
"67",
"75",
"76",
"81",
"82",
"87",
"92",
"95",
],
"3": [
"6",
"7",
"8",
"15",
"30",
"34",
"35",
"39",
"43",
"53",
"57",
"58",
"61",
"62",
"68",
"80",
"84",
"86",
"88",
"89",
"94",
],
"4": ["9", "10", "16", "17", "18", "23", "28"],
"5": ["11", "20", "21"],
"6": ["13", "24", "25", "26", "27"],
"7": ["19"],
"8": ["22"],
"10": ["78", "83", "90", "93"],
"11": ["91"],
}
data_name = {
"1": [
"铜",
"铝",
"橡胶",
"燃料油",
"锌",
"黄金",
"螺纹钢",
"线材",
"铅",
"白银",
"石油沥青",
"热轧卷板",
"锡",
"镍",
"纸浆",
"不锈钢",
],
"2": [
"强麦",
"一号棉",
"白糖",
"PTA",
"菜籽油",
"早籼稻",
"甲醇",
"普麦",
"玻璃",
"油菜籽",
"菜籽粕",
"动力煤",
"粳稻",
"晚籼稻",
"硅铁",
"锰硅",
"棉纱",
"苹果",
"红枣",
"尿素",
"纯碱",
"短纤",
"花生",
],
"3": [
"豆一",
"豆二",
"豆粕",
"玉米",
"豆油",
"聚乙烯",
"棕榈油",
"聚氯乙烯",
"焦炭",
"焦煤",
"铁矿石",
"鸡蛋",
"胶合板",
"聚丙烯",
"玉米淀粉",
"乙二醇",
"粳米",
"苯乙烯",
"纤维板",
"液化石油气",
"生猪",
],
"4": ["LME铜", "LME铝", "LME镍", "LME铅", "LME锌", "LME锡", "LME铝合金"],
"5": ["COMEX铜", "COMEX金", "COMEX银"],
"6": ["CBOT大豆", "CBOT小麦", "CBOT玉米", "CBOT燕麦", "CBOT糙米"],
"7": ["NYBOT2号棉"],
"8": ["TOCOM橡胶"],
"10": ["原油", "20号胶", "低硫燃料油", "国际铜"],
"11": ["OSE橡胶"],
}
temp_out_exchange_name = {
"1": "上海期货交易所",
"2": "郑州商品交易所",
"3": "大连商品交易所",
"4": "LME",
"5": "NYMEX",
"6": "CBOT",
"7": "NYBOT",
"8": "TOCOM",
"10": "上海国际能源交易中心",
"11": "OSE",
}
exchange_map = {
value: key for key, value in temp_out_exchange_name.items()
}
exchange = exchange_map[exchange]
temp_symbol_code_map = dict(zip(data_name[exchange], data_code[exchange]))
symbol = temp_symbol_code_map[symbol]
out_exchange_name = {
"1": "上海期货交易所",
"2": "郑州商品交易所",
"3": "大连商品交易所",
"4": "LME",
"5": "NYMEX",
"6": "CBOT",
"7": "NYBOT",
"8": "TOCOM",
"10": "上海国际能源交易中心",
"11": "OSE",
}
name_temp_dict = {}
code_temp_dict = {}
for num in data_code.keys():
name_temp_dict[out_exchange_name[num]] = dict(
zip(data_code[num], data_name[num])
)
code_temp_dict[num] = dict(zip(data_code[num], data_name[num]))
n = 10
while n != 0:
try:
n -= 1
session = requests.Session()
url = "http://service.99qh.com/Storage/Storage.aspx"
params = {"page": "99qh"}
r = session.post(url, params=params, headers=sample_headers)
cookie = r.cookies.get_dict()
url = "http://service.99qh.com/Storage/Storage.aspx"
params = {"page": "99qh"}
r = requests.post(
url, params=params, headers=sample_headers, cookies=cookie
)
soup = BeautifulSoup(r.text, "lxml")
view_state = soup.find_all(attrs={"id": "__VIEWSTATE"})[0]["value"]
even_validation = soup.find_all(attrs={"id": "__EVENTVALIDATION"})[
0
]["value"]
payload = {
"__EVENTTARGET": "ddlExchName",
"__EVENTARGUMENT": "",
"__LASTFOCUS": "",
"__VIEWSTATE": view_state,
"__VIEWSTATEGENERATOR": "6EAC22FA",
"__EVENTVALIDATION": even_validation,
"ddlExchName": int(exchange),
"ddlGoodsName": 1,
}
res = requests.post(
url,
params={"page": "99qh"},
data=payload,
headers=qh_headers,
cookies=cookie,
)
soup = BeautifulSoup(res.text, "lxml")
view_state = soup.find_all(attrs={"id": "__VIEWSTATE"})[0]["value"]
even_validation = soup.find_all(attrs={"id": "__EVENTVALIDATION"})[
0
]["value"]
payload = {
"__EVENTTARGET": "ddlGoodsName",
"__EVENTARGUMENT": "",
"__LASTFOCUS": "",
"__VIEWSTATE": view_state,
"__VIEWSTATEGENERATOR": "6EAC22FA",
"__EVENTVALIDATION": even_validation,
"ddlExchName": int(exchange),
"ddlGoodsName": int(symbol),
}
res = requests.post(
url,
params=params,
data=payload,
headers=qh_headers,
cookies=cookie,
)
data_df = pd.read_html(res.text)[-1].T
data_df.columns = data_df.iloc[0, :]
data_df = data_df.iloc[1:, :]
data_df.reset_index(inplace=True, drop=True)
data_df.columns.name = None
data_df["日期"] = pd.to_datetime(data_df["日期"]).dt.date
data_df["库存"] = pd.to_numeric(data_df["库存"])
data_df["增减"] = pd.to_numeric(data_df["增减"])
data_df.sort_values("日期", inplace=True)
data_df.reset_index(inplace=True, drop=True)
return data_df
except:
continue
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_inventory_99.py#L18-L288
| 25 |
[
0
] | 0.369004 |
[
13,
88,
163,
175,
178,
179,
180,
181,
193,
194,
195,
196,
199,
200,
201,
202,
203,
204,
205,
206,
207,
208,
209,
210,
211,
214,
215,
216,
219,
229,
236,
237,
238,
241,
251,
258,
259,
260,
261,
262,
263,
264,
265,
266,
267,
268,
269,
270
] | 17.712177 | false | 12.280702 | 271 | 4 | 82.287823 | 8 |
def futures_inventory_99(
exchange: str = "大连商品交易所", symbol: str = "豆一"
) -> pd.DataFrame:
data_code = {
"1": [
"1",
"2",
"3",
"12",
"32",
"36",
"37",
"40",
"42",
"47",
"56",
"63",
"69",
"70",
"79",
"85",
],
"2": [
"4",
"14",
"29",
"31",
"33",
"38",
"44",
"45",
"50",
"51",
"52",
"55",
"59",
"64",
"66",
"67",
"75",
"76",
"81",
"82",
"87",
"92",
"95",
],
"3": [
"6",
"7",
"8",
"15",
"30",
"34",
"35",
"39",
"43",
"53",
"57",
"58",
"61",
"62",
"68",
"80",
"84",
"86",
"88",
"89",
"94",
],
"4": ["9", "10", "16", "17", "18", "23", "28"],
"5": ["11", "20", "21"],
"6": ["13", "24", "25", "26", "27"],
"7": ["19"],
"8": ["22"],
"10": ["78", "83", "90", "93"],
"11": ["91"],
}
data_name = {
"1": [
"铜",
"铝",
"橡胶",
"燃料油",
"锌",
"黄金",
"螺纹钢",
"线材",
"铅",
"白银",
"石油沥青",
"热轧卷板",
"锡",
"镍",
"纸浆",
"不锈钢",
],
"2": [
"强麦",
"一号棉",
"白糖",
"PTA",
"菜籽油",
"早籼稻",
"甲醇",
"普麦",
"玻璃",
"油菜籽",
"菜籽粕",
"动力煤",
"粳稻",
"晚籼稻",
"硅铁",
"锰硅",
"棉纱",
"苹果",
"红枣",
"尿素",
"纯碱",
"短纤",
"花生",
],
"3": [
"豆一",
"豆二",
"豆粕",
"玉米",
"豆油",
"聚乙烯",
"棕榈油",
"聚氯乙烯",
"焦炭",
"焦煤",
"铁矿石",
"鸡蛋",
"胶合板",
"聚丙烯",
"玉米淀粉",
"乙二醇",
"粳米",
"苯乙烯",
"纤维板",
"液化石油气",
"生猪",
],
"4": ["LME铜", "LME铝", "LME镍", "LME铅", "LME锌", "LME锡", "LME铝合金"],
"5": ["COMEX铜", "COMEX金", "COMEX银"],
"6": ["CBOT大豆", "CBOT小麦", "CBOT玉米", "CBOT燕麦", "CBOT糙米"],
"7": ["NYBOT2号棉"],
"8": ["TOCOM橡胶"],
"10": ["原油", "20号胶", "低硫燃料油", "国际铜"],
"11": ["OSE橡胶"],
}
temp_out_exchange_name = {
"1": "上海期货交易所",
"2": "郑州商品交易所",
"3": "大连商品交易所",
"4": "LME",
"5": "NYMEX",
"6": "CBOT",
"7": "NYBOT",
"8": "TOCOM",
"10": "上海国际能源交易中心",
"11": "OSE",
}
exchange_map = {
value: key for key, value in temp_out_exchange_name.items()
}
exchange = exchange_map[exchange]
temp_symbol_code_map = dict(zip(data_name[exchange], data_code[exchange]))
symbol = temp_symbol_code_map[symbol]
out_exchange_name = {
"1": "上海期货交易所",
"2": "郑州商品交易所",
"3": "大连商品交易所",
"4": "LME",
"5": "NYMEX",
"6": "CBOT",
"7": "NYBOT",
"8": "TOCOM",
"10": "上海国际能源交易中心",
"11": "OSE",
}
name_temp_dict = {}
code_temp_dict = {}
for num in data_code.keys():
name_temp_dict[out_exchange_name[num]] = dict(
zip(data_code[num], data_name[num])
)
code_temp_dict[num] = dict(zip(data_code[num], data_name[num]))
n = 10
while n != 0:
try:
n -= 1
session = requests.Session()
url = "http://service.99qh.com/Storage/Storage.aspx"
params = {"page": "99qh"}
r = session.post(url, params=params, headers=sample_headers)
cookie = r.cookies.get_dict()
url = "http://service.99qh.com/Storage/Storage.aspx"
params = {"page": "99qh"}
r = requests.post(
url, params=params, headers=sample_headers, cookies=cookie
)
soup = BeautifulSoup(r.text, "lxml")
view_state = soup.find_all(attrs={"id": "__VIEWSTATE"})[0]["value"]
even_validation = soup.find_all(attrs={"id": "__EVENTVALIDATION"})[
0
]["value"]
payload = {
"__EVENTTARGET": "ddlExchName",
"__EVENTARGUMENT": "",
"__LASTFOCUS": "",
"__VIEWSTATE": view_state,
"__VIEWSTATEGENERATOR": "6EAC22FA",
"__EVENTVALIDATION": even_validation,
"ddlExchName": int(exchange),
"ddlGoodsName": 1,
}
res = requests.post(
url,
params={"page": "99qh"},
data=payload,
headers=qh_headers,
cookies=cookie,
)
soup = BeautifulSoup(res.text, "lxml")
view_state = soup.find_all(attrs={"id": "__VIEWSTATE"})[0]["value"]
even_validation = soup.find_all(attrs={"id": "__EVENTVALIDATION"})[
0
]["value"]
payload = {
"__EVENTTARGET": "ddlGoodsName",
"__EVENTARGUMENT": "",
"__LASTFOCUS": "",
"__VIEWSTATE": view_state,
"__VIEWSTATEGENERATOR": "6EAC22FA",
"__EVENTVALIDATION": even_validation,
"ddlExchName": int(exchange),
"ddlGoodsName": int(symbol),
}
res = requests.post(
url,
params=params,
data=payload,
headers=qh_headers,
cookies=cookie,
)
data_df = pd.read_html(res.text)[-1].T
data_df.columns = data_df.iloc[0, :]
data_df = data_df.iloc[1:, :]
data_df.reset_index(inplace=True, drop=True)
data_df.columns.name = None
data_df["日期"] = pd.to_datetime(data_df["日期"]).dt.date
data_df["库存"] = pd.to_numeric(data_df["库存"])
data_df["增减"] = pd.to_numeric(data_df["增减"])
data_df.sort_values("日期", inplace=True)
data_df.reset_index(inplace=True, drop=True)
return data_df
except:
continue
| 18,141 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_comex.py
|
futures_comex_inventory
|
(symbol: str = "黄金") ->
|
return temp_df
|
东方财富网-数据中心-COMEX库存数据
http://data.eastmoney.com/pmetal/comex/by.html
:param symbol: choice of {"黄金", "白银"}
:type symbol: str
:return: COMEX库存数据
:rtype: pandas.DataFrame
|
东方财富网-数据中心-COMEX库存数据
http://data.eastmoney.com/pmetal/comex/by.html
:param symbol: choice of {"黄金", "白银"}
:type symbol: str
:return: COMEX库存数据
:rtype: pandas.DataFrame
| 13 | 60 |
def futures_comex_inventory(symbol: str = "黄金") -> pd.DataFrame:
"""
东方财富网-数据中心-COMEX库存数据
http://data.eastmoney.com/pmetal/comex/by.html
:param symbol: choice of {"黄金", "白银"}
:type symbol: str
:return: COMEX库存数据
:rtype: pandas.DataFrame
"""
symbol_map = {
"黄金": "(ID='EMI00069026')",
"白银": "(ID='EMI00069027')",
}
url = "http://dcfm.eastmoney.com/em_mutisvcexpandinterface/api/js/get"
params = {
"type": "HJBY_KC",
"token": "70f12f2f4f091e459a279469fe49eca5",
"p": "1",
"ps": "5000",
"st": "DATADATE",
"sr": "-1",
"filter": symbol_map[symbol],
"js": "var hVtWMLwm={pages:(tp),data:(x)}",
"rt": "53367096",
}
r = requests.get(url, params=params)
data_text = r.text
data_json = demjson.decode(data_text[data_text.find("{"):])
temp_df = pd.DataFrame(data_json["data"])
del temp_df["ID"]
temp_df["DATADATE"] = pd.to_datetime(temp_df["DATADATE"]).dt.date
temp_df.reset_index(inplace=True)
temp_df['index'] = range(1, len(temp_df)+1)
if symbol == "黄金":
temp_df.columns = [
'序号',
'日期',
f'COMEX{symbol}库存量_1',
f'COMEX{symbol}库存量_2',
]
elif symbol == "白银":
temp_df.columns = [
'序号',
'日期',
f'COMEX{symbol}库存量_1',
f'COMEX{symbol}库存量_2',
]
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_comex.py#L13-L60
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 18.75 |
[
9,
13,
14,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
40,
41,
47
] | 33.333333 | false | 25 | 48 | 3 | 66.666667 | 6 |
def futures_comex_inventory(symbol: str = "黄金") -> pd.DataFrame:
symbol_map = {
"黄金": "(ID='EMI00069026')",
"白银": "(ID='EMI00069027')",
}
url = "http://dcfm.eastmoney.com/em_mutisvcexpandinterface/api/js/get"
params = {
"type": "HJBY_KC",
"token": "70f12f2f4f091e459a279469fe49eca5",
"p": "1",
"ps": "5000",
"st": "DATADATE",
"sr": "-1",
"filter": symbol_map[symbol],
"js": "var hVtWMLwm={pages:(tp),data:(x)}",
"rt": "53367096",
}
r = requests.get(url, params=params)
data_text = r.text
data_json = demjson.decode(data_text[data_text.find("{"):])
temp_df = pd.DataFrame(data_json["data"])
del temp_df["ID"]
temp_df["DATADATE"] = pd.to_datetime(temp_df["DATADATE"]).dt.date
temp_df.reset_index(inplace=True)
temp_df['index'] = range(1, len(temp_df)+1)
if symbol == "黄金":
temp_df.columns = [
'序号',
'日期',
f'COMEX{symbol}库存量_1',
f'COMEX{symbol}库存量_2',
]
elif symbol == "白银":
temp_df.columns = [
'序号',
'日期',
f'COMEX{symbol}库存量_1',
f'COMEX{symbol}库存量_2',
]
return temp_df
| 18,142 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_comm_qihuo.py
|
_futures_comm_qihuo_process
|
(df: pd.DataFrame, name: str = None)
|
return common_temp_df
|
期货手续费数据细节处理函数
https://www.9qihuo.com/qihuoshouxufei
:param df: 获取到的 pandas.DataFrame 数据
:type df: pandas.DataFrame
:param name: 交易所名称
:type name: str
:return: 处理后的数据
:rtype: pandas.DataFrame
|
期货手续费数据细节处理函数
https://www.9qihuo.com/qihuoshouxufei
:param df: 获取到的 pandas.DataFrame 数据
:type df: pandas.DataFrame
:param name: 交易所名称
:type name: str
:return: 处理后的数据
:rtype: pandas.DataFrame
| 13 | 147 |
def _futures_comm_qihuo_process(df: pd.DataFrame, name: str = None) -> pd.DataFrame:
"""
期货手续费数据细节处理函数
https://www.9qihuo.com/qihuoshouxufei
:param df: 获取到的 pandas.DataFrame 数据
:type df: pandas.DataFrame
:param name: 交易所名称
:type name: str
:return: 处理后的数据
:rtype: pandas.DataFrame
"""
common_temp_df = df.copy()
common_temp_df["合约名称"] = (
common_temp_df["合约品种"].str.split("(", expand=True).iloc[:, 0].str.strip()
)
common_temp_df["合约代码"] = (
common_temp_df["合约品种"].str.split("(", expand=True).iloc[:, 1].str.strip(")")
)
common_temp_df["涨停板"] = (
common_temp_df["涨/跌停板"].str.split("/", expand=True).iloc[:, 0].str.strip()
)
common_temp_df["跌停板"] = (
common_temp_df["涨/跌停板"].str.split("/", expand=True).iloc[:, 1].str.strip()
)
common_temp_df["保证金-买开"] = common_temp_df["保证金-买开"].str.strip("%")
common_temp_df["保证金-卖开"] = common_temp_df["保证金-卖开"].str.strip("%")
common_temp_df["保证金-每手"] = common_temp_df["保证金-保证金/每手"].str.strip("元")
common_temp_df["手续费"] = common_temp_df["手续费(开+平)"].str.strip("元")
try:
temp_df_ratio = (
common_temp_df["手续费标准-开仓"][common_temp_df["手续费标准-开仓"].str.contains("万分之")]
.str.split("/", expand=True)
.iloc[:, 0]
.astype(float)
/ 10000
)
except IndexError as e:
temp_df_ratio = pd.NA
temp_df_yuan = common_temp_df["手续费标准-开仓"][
common_temp_df["手续费标准-开仓"].str.contains("元")
]
common_temp_df["手续费标准-开仓-万分之"] = temp_df_ratio
common_temp_df["手续费标准-开仓-元"] = temp_df_yuan.str.strip("元")
try:
temp_df_ratio = (
common_temp_df["手续费标准-平昨"][common_temp_df["手续费标准-平昨"].str.contains("万分之")]
.str.split("/", expand=True)
.iloc[:, 0]
.astype(float)
/ 10000
)
except IndexError as e:
temp_df_ratio = pd.NA
temp_df_yuan = common_temp_df["手续费标准-平昨"][
common_temp_df["手续费标准-平昨"].str.contains("元")
]
common_temp_df["手续费标准-平昨-万分之"] = temp_df_ratio
common_temp_df["手续费标准-平昨-元"] = temp_df_yuan.str.strip("元")
try:
temp_df_ratio = (
common_temp_df["手续费标准-平今"][common_temp_df["手续费标准-平今"].str.contains("万分之")]
.str.split("/", expand=True)
.iloc[:, 0]
.astype(float)
/ 10000
)
except IndexError as e:
temp_df_ratio = pd.NA
temp_df_yuan = common_temp_df["手续费标准-平今"][
common_temp_df["手续费标准-平今"].str.contains("元")
]
common_temp_df["手续费标准-平今-万分之"] = temp_df_ratio
common_temp_df["手续费标准-平今-元"] = temp_df_yuan.str.strip("元")
del common_temp_df["手续费标准-开仓"]
del common_temp_df["手续费标准-平昨"]
del common_temp_df["手续费标准-平今"]
del common_temp_df["合约品种"]
del common_temp_df["涨/跌停板"]
del common_temp_df["手续费(开+平)"]
del common_temp_df["保证金-保证金/每手"]
common_temp_df['交易所名称'] = name
common_temp_df = common_temp_df[
[
"交易所名称",
"合约名称",
"合约代码",
"现价",
"涨停板",
"跌停板",
"保证金-买开",
"保证金-卖开",
"保证金-每手",
"手续费标准-开仓-万分之",
"手续费标准-开仓-元",
"手续费标准-平昨-万分之",
"手续费标准-平昨-元",
"手续费标准-平今-万分之",
"手续费标准-平今-元",
"每跳毛利",
"手续费",
"每跳净利",
"备注",
]
]
common_temp_df["现价"] = pd.to_numeric(common_temp_df["现价"])
common_temp_df["涨停板"] = pd.to_numeric(common_temp_df["涨停板"])
common_temp_df["跌停板"] = pd.to_numeric(common_temp_df["跌停板"])
common_temp_df["保证金-买开"] = pd.to_numeric(common_temp_df["保证金-买开"])
common_temp_df["保证金-卖开"] = pd.to_numeric(common_temp_df["保证金-卖开"])
common_temp_df["保证金-每手"] = pd.to_numeric(common_temp_df["保证金-每手"])
# common_temp_df["手续费标准-开仓-元"] = pd.to_numeric(common_temp_df["手续费标准-开仓-元"])
# common_temp_df["手续费标准-平昨-元"] = pd.to_numeric(common_temp_df["手续费标准-平昨-元"])
# common_temp_df["手续费标准-平今-元"] = pd.to_numeric(common_temp_df["手续费标准-平今-元"])
common_temp_df["每跳毛利"] = pd.to_numeric(common_temp_df["每跳毛利"])
common_temp_df["手续费"] = pd.to_numeric(common_temp_df["手续费"])
common_temp_df["每跳净利"] = pd.to_numeric(common_temp_df["每跳净利"])
url = "http://www.9qihuo.com/qihuoshouxufei"
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
raw_date_text = soup.find('a', attrs={"id": "dlink"}).previous
comm_update_time = raw_date_text.split(",")[0].strip("(手续费更新时间:")
price_update_time = raw_date_text.split(",")[1].strip("价格更新时间:").strip("。)")
common_temp_df['手续费更新时间'] = comm_update_time
common_temp_df['价格更新时间'] = price_update_time
return common_temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_comm_qihuo.py#L13-L147
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
] | 8.148148 |
[
11,
13,
16,
20,
23,
27,
28,
29,
30,
32,
33,
40,
41,
42,
45,
46,
48,
49,
56,
57,
58,
61,
62,
64,
65,
72,
73,
74,
77,
78,
80,
81,
82,
83,
84,
85,
86,
87,
88,
112,
113,
114,
115,
116,
117,
121,
122,
123,
125,
126,
127,
128,
129,
130,
131,
132,
134
] | 42.222222 | false | 6.862745 | 135 | 4 | 57.777778 | 8 |
def _futures_comm_qihuo_process(df: pd.DataFrame, name: str = None) -> pd.DataFrame:
common_temp_df = df.copy()
common_temp_df["合约名称"] = (
common_temp_df["合约品种"].str.split("(", expand=True).iloc[:, 0].str.strip()
)
common_temp_df["合约代码"] = (
common_temp_df["合约品种"].str.split("(", expand=True).iloc[:, 1].str.strip(")")
)
common_temp_df["涨停板"] = (
common_temp_df["涨/跌停板"].str.split("/", expand=True).iloc[:, 0].str.strip()
)
common_temp_df["跌停板"] = (
common_temp_df["涨/跌停板"].str.split("/", expand=True).iloc[:, 1].str.strip()
)
common_temp_df["保证金-买开"] = common_temp_df["保证金-买开"].str.strip("%")
common_temp_df["保证金-卖开"] = common_temp_df["保证金-卖开"].str.strip("%")
common_temp_df["保证金-每手"] = common_temp_df["保证金-保证金/每手"].str.strip("元")
common_temp_df["手续费"] = common_temp_df["手续费(开+平)"].str.strip("元")
try:
temp_df_ratio = (
common_temp_df["手续费标准-开仓"][common_temp_df["手续费标准-开仓"].str.contains("万分之")]
.str.split("/", expand=True)
.iloc[:, 0]
.astype(float)
/ 10000
)
except IndexError as e:
temp_df_ratio = pd.NA
temp_df_yuan = common_temp_df["手续费标准-开仓"][
common_temp_df["手续费标准-开仓"].str.contains("元")
]
common_temp_df["手续费标准-开仓-万分之"] = temp_df_ratio
common_temp_df["手续费标准-开仓-元"] = temp_df_yuan.str.strip("元")
try:
temp_df_ratio = (
common_temp_df["手续费标准-平昨"][common_temp_df["手续费标准-平昨"].str.contains("万分之")]
.str.split("/", expand=True)
.iloc[:, 0]
.astype(float)
/ 10000
)
except IndexError as e:
temp_df_ratio = pd.NA
temp_df_yuan = common_temp_df["手续费标准-平昨"][
common_temp_df["手续费标准-平昨"].str.contains("元")
]
common_temp_df["手续费标准-平昨-万分之"] = temp_df_ratio
common_temp_df["手续费标准-平昨-元"] = temp_df_yuan.str.strip("元")
try:
temp_df_ratio = (
common_temp_df["手续费标准-平今"][common_temp_df["手续费标准-平今"].str.contains("万分之")]
.str.split("/", expand=True)
.iloc[:, 0]
.astype(float)
/ 10000
)
except IndexError as e:
temp_df_ratio = pd.NA
temp_df_yuan = common_temp_df["手续费标准-平今"][
common_temp_df["手续费标准-平今"].str.contains("元")
]
common_temp_df["手续费标准-平今-万分之"] = temp_df_ratio
common_temp_df["手续费标准-平今-元"] = temp_df_yuan.str.strip("元")
del common_temp_df["手续费标准-开仓"]
del common_temp_df["手续费标准-平昨"]
del common_temp_df["手续费标准-平今"]
del common_temp_df["合约品种"]
del common_temp_df["涨/跌停板"]
del common_temp_df["手续费(开+平)"]
del common_temp_df["保证金-保证金/每手"]
common_temp_df['交易所名称'] = name
common_temp_df = common_temp_df[
[
"交易所名称",
"合约名称",
"合约代码",
"现价",
"涨停板",
"跌停板",
"保证金-买开",
"保证金-卖开",
"保证金-每手",
"手续费标准-开仓-万分之",
"手续费标准-开仓-元",
"手续费标准-平昨-万分之",
"手续费标准-平昨-元",
"手续费标准-平今-万分之",
"手续费标准-平今-元",
"每跳毛利",
"手续费",
"每跳净利",
"备注",
]
]
common_temp_df["现价"] = pd.to_numeric(common_temp_df["现价"])
common_temp_df["涨停板"] = pd.to_numeric(common_temp_df["涨停板"])
common_temp_df["跌停板"] = pd.to_numeric(common_temp_df["跌停板"])
common_temp_df["保证金-买开"] = pd.to_numeric(common_temp_df["保证金-买开"])
common_temp_df["保证金-卖开"] = pd.to_numeric(common_temp_df["保证金-卖开"])
common_temp_df["保证金-每手"] = pd.to_numeric(common_temp_df["保证金-每手"])
# common_temp_df["手续费标准-开仓-元"] = pd.to_numeric(common_temp_df["手续费标准-开仓-元"])
# common_temp_df["手续费标准-平昨-元"] = pd.to_numeric(common_temp_df["手续费标准-平昨-元"])
# common_temp_df["手续费标准-平今-元"] = pd.to_numeric(common_temp_df["手续费标准-平今-元"])
common_temp_df["每跳毛利"] = pd.to_numeric(common_temp_df["每跳毛利"])
common_temp_df["手续费"] = pd.to_numeric(common_temp_df["手续费"])
common_temp_df["每跳净利"] = pd.to_numeric(common_temp_df["每跳净利"])
url = "http://www.9qihuo.com/qihuoshouxufei"
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
raw_date_text = soup.find('a', attrs={"id": "dlink"}).previous
comm_update_time = raw_date_text.split(",")[0].strip("(手续费更新时间:")
price_update_time = raw_date_text.split(",")[1].strip("价格更新时间:").strip("。)")
common_temp_df['手续费更新时间'] = comm_update_time
common_temp_df['价格更新时间'] = price_update_time
return common_temp_df
| 18,143 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_comm_qihuo.py
|
futures_comm_info
|
(symbol: str = "所有") ->
|
九期网-期货手续费
https://www.9qihuo.com/qihuoshouxufei
:param symbol: choice of {"所有", "上海期货交易所", "大连商品交易所", "郑州商品交易所", "上海国际能源交易中心", "中国金融期货交易所", "广州期货交易所"}
:type symbol: str
:return: 期货手续费
:rtype: pandas.DataFrame
|
九期网-期货手续费
https://www.9qihuo.com/qihuoshouxufei
:param symbol: choice of {"所有", "上海期货交易所", "大连商品交易所", "郑州商品交易所", "上海国际能源交易中心", "中国金融期货交易所", "广州期货交易所"}
:type symbol: str
:return: 期货手续费
:rtype: pandas.DataFrame
| 150 | 213 |
def futures_comm_info(symbol: str = "所有") -> pd.DataFrame:
"""
九期网-期货手续费
https://www.9qihuo.com/qihuoshouxufei
:param symbol: choice of {"所有", "上海期货交易所", "大连商品交易所", "郑州商品交易所", "上海国际能源交易中心", "中国金融期货交易所", "广州期货交易所"}
:type symbol: str
:return: 期货手续费
:rtype: pandas.DataFrame
"""
url = "https://www.9qihuo.com/qihuoshouxufei"
r = requests.get(url)
temp_df = pd.read_html(r.text)[0]
temp_df.columns = [
"合约品种",
"现价",
"涨/跌停板",
"保证金-买开",
"保证金-卖开",
"保证金-保证金/每手",
"手续费标准-开仓",
"手续费标准-平昨",
"手续费标准-平今",
"每跳毛利",
"手续费(开+平)",
"每跳净利",
"备注",
"-",
"-",
]
df_0 = temp_df[temp_df["合约品种"].str.contains("上海期货交易所")].index.values[0]
df_1 = temp_df[temp_df["合约品种"].str.contains("大连商品交易所")].index.values[0]
df_2 = temp_df[temp_df["合约品种"].str.contains("郑州商品交易所")].index.values[0]
df_3 = temp_df[temp_df["合约品种"].str.contains("上海国际能源交易中心")].index.values[0]
df_4 = temp_df[temp_df["合约品种"].str.contains("广州期货交易所")].index.values[0]
df_5 = temp_df[temp_df["合约品种"].str.contains("中国金融期货交易所")].index.values[0]
shfe_df = temp_df.iloc[df_0 + 3: df_1, :].reset_index(drop=True)
dce_df = temp_df.iloc[df_1 + 3: df_2, :].reset_index(drop=True)
czce_df = temp_df.iloc[df_2 + 3: df_3, :].reset_index(drop=True)
ine_df = temp_df.iloc[df_3 + 3: df_4, :].reset_index(drop=True)
gfex_df = temp_df.iloc[df_4 + 3: df_5, :].reset_index(drop=True)
cffex_df = temp_df.iloc[df_5 + 3:, :].reset_index(drop=True)
if symbol == "上海期货交易所":
return _futures_comm_qihuo_process(shfe_df, "上海期货交易所")
elif symbol == "大连商品交易所":
return _futures_comm_qihuo_process(dce_df, "大连商品交易所")
elif symbol == "郑州商品交易所":
return _futures_comm_qihuo_process(czce_df, "郑州商品交易所")
elif symbol == "上海国际能源交易中心":
return _futures_comm_qihuo_process(ine_df, "上海国际能源交易中心")
elif symbol == "广州期货交易所":
return _futures_comm_qihuo_process(gfex_df, "广州期货交易所")
elif symbol == "中国金融期货交易所":
return _futures_comm_qihuo_process(cffex_df, "中国金融期货交易所")
else:
big_df = pd.DataFrame()
big_df = pd.concat([big_df, _futures_comm_qihuo_process(shfe_df, "上海期货交易所")], ignore_index=True)
big_df = pd.concat([big_df, _futures_comm_qihuo_process(dce_df, "大连商品交易所")], ignore_index=True)
big_df = pd.concat([big_df, _futures_comm_qihuo_process(czce_df, "郑州商品交易所")], ignore_index=True)
big_df = pd.concat([big_df, _futures_comm_qihuo_process(ine_df, "上海国际能源交易中心")], ignore_index=True)
big_df = pd.concat([big_df, _futures_comm_qihuo_process(gfex_df, "广州期货交易所")], ignore_index=True)
big_df = pd.concat([big_df, _futures_comm_qihuo_process(cffex_df, "中国金融期货交易所")], ignore_index=True)
return big_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_comm_qihuo.py#L150-L213
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 14.0625 |
[
9,
10,
11,
12,
29,
30,
31,
32,
33,
34,
36,
37,
38,
39,
40,
41,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
56,
57,
58,
59,
60,
61,
62,
63
] | 56.25 | false | 6.862745 | 64 | 7 | 43.75 | 6 |
def futures_comm_info(symbol: str = "所有") -> pd.DataFrame:
url = "https://www.9qihuo.com/qihuoshouxufei"
r = requests.get(url)
temp_df = pd.read_html(r.text)[0]
temp_df.columns = [
"合约品种",
"现价",
"涨/跌停板",
"保证金-买开",
"保证金-卖开",
"保证金-保证金/每手",
"手续费标准-开仓",
"手续费标准-平昨",
"手续费标准-平今",
"每跳毛利",
"手续费(开+平)",
"每跳净利",
"备注",
"-",
"-",
]
df_0 = temp_df[temp_df["合约品种"].str.contains("上海期货交易所")].index.values[0]
df_1 = temp_df[temp_df["合约品种"].str.contains("大连商品交易所")].index.values[0]
df_2 = temp_df[temp_df["合约品种"].str.contains("郑州商品交易所")].index.values[0]
df_3 = temp_df[temp_df["合约品种"].str.contains("上海国际能源交易中心")].index.values[0]
df_4 = temp_df[temp_df["合约品种"].str.contains("广州期货交易所")].index.values[0]
df_5 = temp_df[temp_df["合约品种"].str.contains("中国金融期货交易所")].index.values[0]
shfe_df = temp_df.iloc[df_0 + 3: df_1, :].reset_index(drop=True)
dce_df = temp_df.iloc[df_1 + 3: df_2, :].reset_index(drop=True)
czce_df = temp_df.iloc[df_2 + 3: df_3, :].reset_index(drop=True)
ine_df = temp_df.iloc[df_3 + 3: df_4, :].reset_index(drop=True)
gfex_df = temp_df.iloc[df_4 + 3: df_5, :].reset_index(drop=True)
cffex_df = temp_df.iloc[df_5 + 3:, :].reset_index(drop=True)
if symbol == "上海期货交易所":
return _futures_comm_qihuo_process(shfe_df, "上海期货交易所")
elif symbol == "大连商品交易所":
return _futures_comm_qihuo_process(dce_df, "大连商品交易所")
elif symbol == "郑州商品交易所":
return _futures_comm_qihuo_process(czce_df, "郑州商品交易所")
elif symbol == "上海国际能源交易中心":
return _futures_comm_qihuo_process(ine_df, "上海国际能源交易中心")
elif symbol == "广州期货交易所":
return _futures_comm_qihuo_process(gfex_df, "广州期货交易所")
elif symbol == "中国金融期货交易所":
return _futures_comm_qihuo_process(cffex_df, "中国金融期货交易所")
else:
big_df = pd.DataFrame()
big_df = pd.concat([big_df, _futures_comm_qihuo_process(shfe_df, "上海期货交易所")], ignore_index=True)
big_df = pd.concat([big_df, _futures_comm_qihuo_process(dce_df, "大连商品交易所")], ignore_index=True)
big_df = pd.concat([big_df, _futures_comm_qihuo_process(czce_df, "郑州商品交易所")], ignore_index=True)
big_df = pd.concat([big_df, _futures_comm_qihuo_process(ine_df, "上海国际能源交易中心")], ignore_index=True)
big_df = pd.concat([big_df, _futures_comm_qihuo_process(gfex_df, "广州期货交易所")], ignore_index=True)
big_df = pd.concat([big_df, _futures_comm_qihuo_process(cffex_df, "中国金融期货交易所")], ignore_index=True)
return big_df
| 18,144 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cot.py
|
get_rank_sum_daily
|
(
start_day: str = "20210510",
end_day: str = "20210510",
vars_list: list = cons.contract_symbols,
)
|
return records.reset_index(drop=True)
|
采集四个期货交易所前 5、前 10、前 15、前 20 会员持仓排名数据
注1:由于上期所和中金所只公布每个品种内部的标的排名,没有公布品种的总排名;
所以函数输出的品种排名是由品种中的每个标的加总获得,并不是真实的品种排名列表
注2:大商所只公布了品种排名,未公布标的排名
:param start_day: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param end_day: 结束数据 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品
:return: pd.DataFrame
展期收益率数据(DataFrame):
symbol 标的合约 string
var 商品品种 string
vol_top5 成交量前5会员成交量总和 int
vol_chg_top5 成交量前5会员成交量变化总和 int
long_open_interest_top5 持多单前5会员持多单总和 int
long_open_interest_chg_top5 持多单前5会员持多单变化总和 int
short_open_interest_top5 持空单前5会员持空单总和 int
short_open_interest_chg_top5 持空单前5会员持空单变化总和 int
vol_top10 成交量前10会员成交量总和 int
...
date 日期 string YYYYMMDD
|
采集四个期货交易所前 5、前 10、前 15、前 20 会员持仓排名数据
注1:由于上期所和中金所只公布每个品种内部的标的排名,没有公布品种的总排名;
所以函数输出的品种排名是由品种中的每个标的加总获得,并不是真实的品种排名列表
注2:大商所只公布了品种排名,未公布标的排名
:param start_day: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param end_day: 结束数据 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品
:return: pd.DataFrame
展期收益率数据(DataFrame):
symbol 标的合约 string
var 商品品种 string
vol_top5 成交量前5会员成交量总和 int
vol_chg_top5 成交量前5会员成交量变化总和 int
long_open_interest_top5 持多单前5会员持多单总和 int
long_open_interest_chg_top5 持多单前5会员持多单变化总和 int
short_open_interest_top5 持空单前5会员持空单总和 int
short_open_interest_chg_top5 持空单前5会员持空单变化总和 int
vol_top10 成交量前10会员成交量总和 int
...
date 日期 string YYYYMMDD
| 56 | 110 |
def get_rank_sum_daily(
start_day: str = "20210510",
end_day: str = "20210510",
vars_list: list = cons.contract_symbols,
):
"""
采集四个期货交易所前 5、前 10、前 15、前 20 会员持仓排名数据
注1:由于上期所和中金所只公布每个品种内部的标的排名,没有公布品种的总排名;
所以函数输出的品种排名是由品种中的每个标的加总获得,并不是真实的品种排名列表
注2:大商所只公布了品种排名,未公布标的排名
:param start_day: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param end_day: 结束数据 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品
:return: pd.DataFrame
展期收益率数据(DataFrame):
symbol 标的合约 string
var 商品品种 string
vol_top5 成交量前5会员成交量总和 int
vol_chg_top5 成交量前5会员成交量变化总和 int
long_open_interest_top5 持多单前5会员持多单总和 int
long_open_interest_chg_top5 持多单前5会员持多单变化总和 int
short_open_interest_top5 持空单前5会员持空单总和 int
short_open_interest_chg_top5 持空单前5会员持空单变化总和 int
vol_top10 成交量前10会员成交量总和 int
...
date 日期 string YYYYMMDD
"""
start_day = (
cons.convert_date(start_day)
if start_day is not None
else datetime.date.today()
)
end_day = (
cons.convert_date(end_day)
if end_day is not None
else cons.convert_date(
cons.get_latest_data_date(datetime.datetime.now())
)
)
records = pd.DataFrame()
while start_day <= end_day:
print(start_day)
if start_day.strftime("%Y%m%d") in calendar:
data = get_rank_sum(start_day, vars_list)
if data is False:
print(
f"{start_day.strftime('%Y-%m-%d')}日交易所数据连接失败,已超过20次,您的地址被网站墙了,请保存好返回数据,稍后从该日期起重试"
)
return records.reset_index(drop=True)
records = records.append(data)
else:
warnings.warn(f"{start_day.strftime('%Y%m%d')}非交易日")
start_day += datetime.timedelta(days=1)
return records.reset_index(drop=True)
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cot.py#L56-L110
| 25 |
[
0
] | 1.818182 |
[
27,
32,
39,
40,
41,
42,
43,
44,
45,
48,
49,
51,
52,
54
] | 25.454545 | false | 7.692308 | 55 | 4 | 74.545455 | 20 |
def get_rank_sum_daily(
start_day: str = "20210510",
end_day: str = "20210510",
vars_list: list = cons.contract_symbols,
):
start_day = (
cons.convert_date(start_day)
if start_day is not None
else datetime.date.today()
)
end_day = (
cons.convert_date(end_day)
if end_day is not None
else cons.convert_date(
cons.get_latest_data_date(datetime.datetime.now())
)
)
records = pd.DataFrame()
while start_day <= end_day:
print(start_day)
if start_day.strftime("%Y%m%d") in calendar:
data = get_rank_sum(start_day, vars_list)
if data is False:
print(
f"{start_day.strftime('%Y-%m-%d')}日交易所数据连接失败,已超过20次,您的地址被网站墙了,请保存好返回数据,稍后从该日期起重试"
)
return records.reset_index(drop=True)
records = records.append(data)
else:
warnings.warn(f"{start_day.strftime('%Y%m%d')}非交易日")
start_day += datetime.timedelta(days=1)
return records.reset_index(drop=True)
| 18,145 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cot.py
|
get_rank_sum
|
(
date: str = "20210525", vars_list: list = cons.contract_symbols
)
|
return records.reset_index(drop=True)
|
抓取四个期货交易所前5、前10、前15、前20会员持仓排名数据
注1:由于上期所和中金所只公布每个品种内部的标的排名, 没有公布品种的总排名;
所以函数输出的品种排名是由品种中的每个标的加总获得, 并不是真实的品种排名列表
注2:大商所只公布了品种排名, 未公布标的排名
:param date: 日期 format: YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如 RB, AL等列表 为空时为所有商品
:return: pd.DataFrame:
展期收益率数据
symbol 标的合约 string
var 商品品种 string
vol_top5 成交量前5会员成交量总和 int
vol_chg_top5 成交量前5会员成交量变化总和 int
long_open_interest_top5 持多单前5会员持多单总和 int
long_open_interest_chg_top5 持多单前5会员持多单变化总和 int
short_open_interest_top5 持空单前5会员持空单总和 int
short_open_interest_chg_top5 持空单前5会员持空单变化总和 int
vol_top10 成交量前10会员成交量总和 int
...
date 日期 string YYYYMMDD
|
抓取四个期货交易所前5、前10、前15、前20会员持仓排名数据
注1:由于上期所和中金所只公布每个品种内部的标的排名, 没有公布品种的总排名;
所以函数输出的品种排名是由品种中的每个标的加总获得, 并不是真实的品种排名列表
注2:大商所只公布了品种排名, 未公布标的排名
:param date: 日期 format: YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如 RB, AL等列表 为空时为所有商品
:return: pd.DataFrame:
展期收益率数据
symbol 标的合约 string
var 商品品种 string
vol_top5 成交量前5会员成交量总和 int
vol_chg_top5 成交量前5会员成交量变化总和 int
long_open_interest_top5 持多单前5会员持多单总和 int
long_open_interest_chg_top5 持多单前5会员持多单变化总和 int
short_open_interest_top5 持空单前5会员持空单总和 int
short_open_interest_chg_top5 持空单前5会员持空单变化总和 int
vol_top10 成交量前10会员成交量总和 int
...
date 日期 string YYYYMMDD
| 113 | 282 |
def get_rank_sum(
date: str = "20210525", vars_list: list = cons.contract_symbols
):
"""
抓取四个期货交易所前5、前10、前15、前20会员持仓排名数据
注1:由于上期所和中金所只公布每个品种内部的标的排名, 没有公布品种的总排名;
所以函数输出的品种排名是由品种中的每个标的加总获得, 并不是真实的品种排名列表
注2:大商所只公布了品种排名, 未公布标的排名
:param date: 日期 format: YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如 RB, AL等列表 为空时为所有商品
:return: pd.DataFrame:
展期收益率数据
symbol 标的合约 string
var 商品品种 string
vol_top5 成交量前5会员成交量总和 int
vol_chg_top5 成交量前5会员成交量变化总和 int
long_open_interest_top5 持多单前5会员持多单总和 int
long_open_interest_chg_top5 持多单前5会员持多单变化总和 int
short_open_interest_top5 持空单前5会员持空单总和 int
short_open_interest_chg_top5 持空单前5会员持空单变化总和 int
vol_top10 成交量前10会员成交量总和 int
...
date 日期 string YYYYMMDD
"""
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return None
dce_var = [
i for i in vars_list if i in cons.market_exchange_symbols["dce"]
]
shfe_var = [
i for i in vars_list if i in cons.market_exchange_symbols["shfe"]
]
czce_var = [
i for i in vars_list if i in cons.market_exchange_symbols["czce"]
]
cffex_var = [
i for i in vars_list if i in cons.market_exchange_symbols["cffex"]
]
big_dict = {}
if len(dce_var) > 0:
data = get_dce_rank_table(date, dce_var)
if data is False:
return False
big_dict.update(data)
if len(shfe_var) > 0:
data = get_shfe_rank_table(date, shfe_var)
if data is False:
return False
big_dict.update(data)
if len(czce_var) > 0:
data = get_czce_rank_table(date, czce_var)
if data is False:
return False
big_dict.update(data)
if len(cffex_var) > 0:
data = get_cffex_rank_table(date, cffex_var)
if data is False:
return False
big_dict.update(data)
records = pd.DataFrame()
for symbol, table in big_dict.items():
table = table.applymap(lambda x: 0 if x == "" else x)
for symbol_inner in set(table["symbol"]):
var = symbol_varieties(symbol_inner)
if var in vars_list:
if var in czce_var:
for col in [
item
for item in table.columns
if item.find("open_interest") > -1
] + ["vol", "vol_chg"]:
table[col] = [
float(value.replace(",", ""))
if value != "-"
else 0.0
for value in table[col]
]
table_cut = table[table["symbol"] == symbol_inner]
table_cut["rank"] = table_cut["rank"].astype("float")
table_cut_top5 = table_cut[table_cut["rank"] <= 5]
table_cut_top10 = table_cut[table_cut["rank"] <= 10]
table_cut_top15 = table_cut[table_cut["rank"] <= 15]
table_cut_top20 = table_cut[table_cut["rank"] <= 20]
big_dict = {
"symbol": symbol_inner,
"variety": var,
"vol_top5": table_cut_top5["vol"].sum(),
"vol_chg_top5": table_cut_top5["vol_chg"].sum(),
"long_open_interest_top5": table_cut_top5[
"long_open_interest"
].sum(),
"long_open_interest_chg_top5": table_cut_top5[
"long_open_interest_chg"
].sum(),
"short_open_interest_top5": table_cut_top5[
"short_open_interest"
].sum(),
"short_open_interest_chg_top5": table_cut_top5[
"short_open_interest_chg"
].sum(),
"vol_top10": table_cut_top10["vol"].sum(),
"vol_chg_top10": table_cut_top10["vol_chg"].sum(),
"long_open_interest_top10": table_cut_top10[
"long_open_interest"
].sum(),
"long_open_interest_chg_top10": table_cut_top10[
"long_open_interest_chg"
].sum(),
"short_open_interest_top10": table_cut_top10[
"short_open_interest"
].sum(),
"short_open_interest_chg_top10": table_cut_top10[
"short_open_interest_chg"
].sum(),
"vol_top15": table_cut_top15["vol"].sum(),
"vol_chg_top15": table_cut_top15["vol_chg"].sum(),
"long_open_interest_top15": table_cut_top15[
"long_open_interest"
].sum(),
"long_open_interest_chg_top15": table_cut_top15[
"long_open_interest_chg"
].sum(),
"short_open_interest_top15": table_cut_top15[
"short_open_interest"
].sum(),
"short_open_interest_chg_top15": table_cut_top15[
"short_open_interest_chg"
].sum(),
"vol_top20": table_cut_top20["vol"].sum(),
"vol_chg_top20": table_cut_top20["vol_chg"].sum(),
"long_open_interest_top20": table_cut_top20[
"long_open_interest"
].sum(),
"long_open_interest_chg_top20": table_cut_top20[
"long_open_interest_chg"
].sum(),
"short_open_interest_top20": table_cut_top20[
"short_open_interest"
].sum(),
"short_open_interest_chg_top20": table_cut_top20[
"short_open_interest_chg"
].sum(),
"date": date.strftime("%Y%m%d"),
}
records = records.append(pd.DataFrame(big_dict, index=[0]))
if len(big_dict.items()) > 0:
add_vars = [
i
for i in cons.market_exchange_symbols["dce"]
+ cons.market_exchange_symbols["shfe"]
+ cons.market_exchange_symbols["cffex"]
if i in records["variety"].tolist()
]
for var in add_vars:
records_cut = records[records["variety"] == var]
var_record = pd.DataFrame(records_cut.sum()).T
var_record["date"] = date.strftime("%Y%m%d")
var_record.loc[:, ["variety", "symbol"]] = var
records = records.append(var_record)
return records.reset_index(drop=True)
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cot.py#L113-L282
| 25 |
[
0
] | 0.588235 |
[
24,
27,
28,
29,
30,
33,
36,
39,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
60,
61,
62,
63,
65,
66,
67,
69,
70,
71,
72,
77,
84,
85,
86,
87,
88,
89,
91,
152,
154,
155,
162,
163,
164,
165,
166,
167,
169
] | 32.352941 | false | 7.692308 | 170 | 24 | 67.647059 | 19 |
def get_rank_sum(
date: str = "20210525", vars_list: list = cons.contract_symbols
):
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return None
dce_var = [
i for i in vars_list if i in cons.market_exchange_symbols["dce"]
]
shfe_var = [
i for i in vars_list if i in cons.market_exchange_symbols["shfe"]
]
czce_var = [
i for i in vars_list if i in cons.market_exchange_symbols["czce"]
]
cffex_var = [
i for i in vars_list if i in cons.market_exchange_symbols["cffex"]
]
big_dict = {}
if len(dce_var) > 0:
data = get_dce_rank_table(date, dce_var)
if data is False:
return False
big_dict.update(data)
if len(shfe_var) > 0:
data = get_shfe_rank_table(date, shfe_var)
if data is False:
return False
big_dict.update(data)
if len(czce_var) > 0:
data = get_czce_rank_table(date, czce_var)
if data is False:
return False
big_dict.update(data)
if len(cffex_var) > 0:
data = get_cffex_rank_table(date, cffex_var)
if data is False:
return False
big_dict.update(data)
records = pd.DataFrame()
for symbol, table in big_dict.items():
table = table.applymap(lambda x: 0 if x == "" else x)
for symbol_inner in set(table["symbol"]):
var = symbol_varieties(symbol_inner)
if var in vars_list:
if var in czce_var:
for col in [
item
for item in table.columns
if item.find("open_interest") > -1
] + ["vol", "vol_chg"]:
table[col] = [
float(value.replace(",", ""))
if value != "-"
else 0.0
for value in table[col]
]
table_cut = table[table["symbol"] == symbol_inner]
table_cut["rank"] = table_cut["rank"].astype("float")
table_cut_top5 = table_cut[table_cut["rank"] <= 5]
table_cut_top10 = table_cut[table_cut["rank"] <= 10]
table_cut_top15 = table_cut[table_cut["rank"] <= 15]
table_cut_top20 = table_cut[table_cut["rank"] <= 20]
big_dict = {
"symbol": symbol_inner,
"variety": var,
"vol_top5": table_cut_top5["vol"].sum(),
"vol_chg_top5": table_cut_top5["vol_chg"].sum(),
"long_open_interest_top5": table_cut_top5[
"long_open_interest"
].sum(),
"long_open_interest_chg_top5": table_cut_top5[
"long_open_interest_chg"
].sum(),
"short_open_interest_top5": table_cut_top5[
"short_open_interest"
].sum(),
"short_open_interest_chg_top5": table_cut_top5[
"short_open_interest_chg"
].sum(),
"vol_top10": table_cut_top10["vol"].sum(),
"vol_chg_top10": table_cut_top10["vol_chg"].sum(),
"long_open_interest_top10": table_cut_top10[
"long_open_interest"
].sum(),
"long_open_interest_chg_top10": table_cut_top10[
"long_open_interest_chg"
].sum(),
"short_open_interest_top10": table_cut_top10[
"short_open_interest"
].sum(),
"short_open_interest_chg_top10": table_cut_top10[
"short_open_interest_chg"
].sum(),
"vol_top15": table_cut_top15["vol"].sum(),
"vol_chg_top15": table_cut_top15["vol_chg"].sum(),
"long_open_interest_top15": table_cut_top15[
"long_open_interest"
].sum(),
"long_open_interest_chg_top15": table_cut_top15[
"long_open_interest_chg"
].sum(),
"short_open_interest_top15": table_cut_top15[
"short_open_interest"
].sum(),
"short_open_interest_chg_top15": table_cut_top15[
"short_open_interest_chg"
].sum(),
"vol_top20": table_cut_top20["vol"].sum(),
"vol_chg_top20": table_cut_top20["vol_chg"].sum(),
"long_open_interest_top20": table_cut_top20[
"long_open_interest"
].sum(),
"long_open_interest_chg_top20": table_cut_top20[
"long_open_interest_chg"
].sum(),
"short_open_interest_top20": table_cut_top20[
"short_open_interest"
].sum(),
"short_open_interest_chg_top20": table_cut_top20[
"short_open_interest_chg"
].sum(),
"date": date.strftime("%Y%m%d"),
}
records = records.append(pd.DataFrame(big_dict, index=[0]))
if len(big_dict.items()) > 0:
add_vars = [
i
for i in cons.market_exchange_symbols["dce"]
+ cons.market_exchange_symbols["shfe"]
+ cons.market_exchange_symbols["cffex"]
if i in records["variety"].tolist()
]
for var in add_vars:
records_cut = records[records["variety"] == var]
var_record = pd.DataFrame(records_cut.sum()).T
var_record["date"] = date.strftime("%Y%m%d")
var_record.loc[:, ["variety", "symbol"]] = var
records = records.append(var_record)
return records.reset_index(drop=True)
| 18,146 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cot.py
|
get_shfe_rank_table
|
(date=None, vars_list=cons.contract_symbols)
|
return big_dict
|
上海期货交易所前 20 会员持仓排名数据明细
注:该交易所只公布每个品种内部的标的排名,没有公布品种的总排名
数据从20020107开始,每交易日16:30左右更新数据
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品
:return: pd.DataFrame
rank 排名 int
vol_party_name 成交量排序的当前名次会员 string(中文)
vol 该会员成交量 int
vol_chg 该会员成交量变化量 int
long_party_name 持多单排序的当前名次会员 string(中文)
long_open_interest 该会员持多单 int
long_open_interest_chg 该会员持多单变化量 int
short_party_name 持空单排序的当前名次会员 string(中文)
short_open_interest 该会员持空单 int
short_open_interest_chg 该会员持空单变化量 int
symbol 标的合约 string
var 品种 string
date 日期 string YYYYMMDD
|
上海期货交易所前 20 会员持仓排名数据明细
注:该交易所只公布每个品种内部的标的排名,没有公布品种的总排名
数据从20020107开始,每交易日16:30左右更新数据
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品
:return: pd.DataFrame
rank 排名 int
vol_party_name 成交量排序的当前名次会员 string(中文)
vol 该会员成交量 int
vol_chg 该会员成交量变化量 int
long_party_name 持多单排序的当前名次会员 string(中文)
long_open_interest 该会员持多单 int
long_open_interest_chg 该会员持多单变化量 int
short_party_name 持空单排序的当前名次会员 string(中文)
short_open_interest 该会员持空单 int
short_open_interest_chg 该会员持空单变化量 int
symbol 标的合约 string
var 品种 string
date 日期 string YYYYMMDD
| 285 | 367 |
def get_shfe_rank_table(date=None, vars_list=cons.contract_symbols):
"""
上海期货交易所前 20 会员持仓排名数据明细
注:该交易所只公布每个品种内部的标的排名,没有公布品种的总排名
数据从20020107开始,每交易日16:30左右更新数据
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品
:return: pd.DataFrame
rank 排名 int
vol_party_name 成交量排序的当前名次会员 string(中文)
vol 该会员成交量 int
vol_chg 该会员成交量变化量 int
long_party_name 持多单排序的当前名次会员 string(中文)
long_open_interest 该会员持多单 int
long_open_interest_chg 该会员持多单变化量 int
short_party_name 持空单排序的当前名次会员 string(中文)
short_open_interest 该会员持空单 int
short_open_interest_chg 该会员持空单变化量 int
symbol 标的合约 string
var 品种 string
date 日期 string YYYYMMDD
"""
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date < datetime.date(2002, 1, 7):
print("shfe数据源开始日期为20020107,跳过")
return {}
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
url = cons.SHFE_VOL_RANK_URL % (date.strftime("%Y%m%d"))
r = requests_link(url, "utf-8")
try:
context = json.loads(r.text)
except:
return {}
df = pd.DataFrame(context["o_cursor"])
df = df.rename(
columns={
"CJ1": "vol",
"CJ1_CHG": "vol_chg",
"CJ2": "long_open_interest",
"CJ2_CHG": "long_open_interest_chg",
"CJ3": "short_open_interest",
"CJ3_CHG": "short_open_interest_chg",
"PARTICIPANTABBR1": "vol_party_name",
"PARTICIPANTABBR2": "long_party_name",
"PARTICIPANTABBR3": "short_party_name",
"PRODUCTNAME": "product1",
"RANK": "rank",
"INSTRUMENTID": "symbol",
"PRODUCTSORTNO": "product2",
}
)
if len(df.columns) < 3:
return {}
df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
df = df.applymap(lambda x: None if x == "" else x)
df["variety"] = df["symbol"].apply(lambda x: symbol_varieties(x))
df = df[df["rank"] > 0]
for col in [
"PARTICIPANTID1",
"PARTICIPANTID2",
"PARTICIPANTID3",
"product1",
"product2",
]:
try:
del df[col]
except:
pass
get_vars = [var for var in vars_list if var in df["variety"].tolist()]
big_dict = {}
for var in get_vars:
df_var = df[df["variety"] == var]
for symbol in set(df_var["symbol"]):
df_symbol = df_var[df_var["symbol"] == symbol]
big_dict[symbol] = df_symbol.reset_index(drop=True)
return big_dict
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cot.py#L285-L367
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21
] | 26.506024 |
[
22,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
39,
57,
58,
59,
60,
61,
63,
64,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80,
81,
82
] | 40.963855 | false | 7.692308 | 83 | 10 | 59.036145 | 19 |
def get_shfe_rank_table(date=None, vars_list=cons.contract_symbols):
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date < datetime.date(2002, 1, 7):
print("shfe数据源开始日期为20020107,跳过")
return {}
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
url = cons.SHFE_VOL_RANK_URL % (date.strftime("%Y%m%d"))
r = requests_link(url, "utf-8")
try:
context = json.loads(r.text)
except:
return {}
df = pd.DataFrame(context["o_cursor"])
df = df.rename(
columns={
"CJ1": "vol",
"CJ1_CHG": "vol_chg",
"CJ2": "long_open_interest",
"CJ2_CHG": "long_open_interest_chg",
"CJ3": "short_open_interest",
"CJ3_CHG": "short_open_interest_chg",
"PARTICIPANTABBR1": "vol_party_name",
"PARTICIPANTABBR2": "long_party_name",
"PARTICIPANTABBR3": "short_party_name",
"PRODUCTNAME": "product1",
"RANK": "rank",
"INSTRUMENTID": "symbol",
"PRODUCTSORTNO": "product2",
}
)
if len(df.columns) < 3:
return {}
df = df.applymap(lambda x: x.strip() if isinstance(x, str) else x)
df = df.applymap(lambda x: None if x == "" else x)
df["variety"] = df["symbol"].apply(lambda x: symbol_varieties(x))
df = df[df["rank"] > 0]
for col in [
"PARTICIPANTID1",
"PARTICIPANTID2",
"PARTICIPANTID3",
"product1",
"product2",
]:
try:
del df[col]
except:
pass
get_vars = [var for var in vars_list if var in df["variety"].tolist()]
big_dict = {}
for var in get_vars:
df_var = df[df["variety"] == var]
for symbol in set(df_var["symbol"]):
df_symbol = df_var[df_var["symbol"] == symbol]
big_dict[symbol] = df_symbol.reset_index(drop=True)
return big_dict
| 18,147 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cot.py
|
_czce_df_read
|
(url, skip_rows, encoding="utf-8", header=0)
|
return data
|
郑州商品交易所的网页数据
:param header:
:type header:
:param url: 网站 string
:param skip_rows: 去掉前几行 int
:param encoding: utf-8 or gbk or gb2312
:return: pd.DataFrame
|
郑州商品交易所的网页数据
:param header:
:type header:
:param url: 网站 string
:param skip_rows: 去掉前几行 int
:param encoding: utf-8 or gbk or gb2312
:return: pd.DataFrame
| 370 | 403 |
def _czce_df_read(url, skip_rows, encoding="utf-8", header=0):
"""
郑州商品交易所的网页数据
:param header:
:type header:
:param url: 网站 string
:param skip_rows: 去掉前几行 int
:param encoding: utf-8 or gbk or gb2312
:return: pd.DataFrame
"""
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
"Host": "www.czce.com.cn",
"Cookie": "XquW6dFMPxV380S=CAaD3sMkdXv3fUoaJlICIEv0MVegGq5EoMyBcxkOjCgSjmpuovYFuTLtYFcxTZGw; XquW6dFMPxV380T=5QTTjUlA6f6WiDO7fMGmqNxHBWz.hKIc8lb_tc1o4nHrJM4nsXCAI9VHaKyV_jkHh4cIVvD25kGQAh.MvLL1SHRA20HCG9mVVHPhAzktNdPK3evjm0NYbTg2Gu_XGGtPhecxLvdFQ0.JlAxy_z0C15_KdO8kOI18i4K0rFERNPxjXq5qG1Gs.QiOm976wODY.pe8XCQtAsuLYJ.N4DpTgNfHJp04jhMl0SntHhr.jhh3dFjMXBx.JEHngXBzY6gQAhER7uSKAeSktruxFeuKlebse.vrPghHqWvJm4WPTEvDQ8q",
}
r = requests_link(url, encoding, headers=headers)
data = pd.read_html(
r.text,
match=".+",
flavor=None,
header=header,
index_col=0,
skiprows=skip_rows,
attrs=None,
parse_dates=False,
thousands=", ",
encoding="gbk",
decimal=".",
converters=None,
na_values=None,
keep_default_na=True,
)
return data
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cot.py#L370-L403
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 29.411765 |
[
10,
16,
17,
33
] | 11.764706 | false | 7.692308 | 34 | 1 | 88.235294 | 7 |
def _czce_df_read(url, skip_rows, encoding="utf-8", header=0):
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36",
"Host": "www.czce.com.cn",
"Cookie": "XquW6dFMPxV380S=CAaD3sMkdXv3fUoaJlICIEv0MVegGq5EoMyBcxkOjCgSjmpuovYFuTLtYFcxTZGw; XquW6dFMPxV380T=5QTTjUlA6f6WiDO7fMGmqNxHBWz.hKIc8lb_tc1o4nHrJM4nsXCAI9VHaKyV_jkHh4cIVvD25kGQAh.MvLL1SHRA20HCG9mVVHPhAzktNdPK3evjm0NYbTg2Gu_XGGtPhecxLvdFQ0.JlAxy_z0C15_KdO8kOI18i4K0rFERNPxjXq5qG1Gs.QiOm976wODY.pe8XCQtAsuLYJ.N4DpTgNfHJp04jhMl0SntHhr.jhh3dFjMXBx.JEHngXBzY6gQAhER7uSKAeSktruxFeuKlebse.vrPghHqWvJm4WPTEvDQ8q",
}
r = requests_link(url, encoding, headers=headers)
data = pd.read_html(
r.text,
match=".+",
flavor=None,
header=header,
index_col=0,
skiprows=skip_rows,
attrs=None,
parse_dates=False,
thousands=", ",
encoding="gbk",
decimal=".",
converters=None,
na_values=None,
keep_default_na=True,
)
return data
| 18,148 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cot.py
|
get_czce_rank_table
|
(
date: str = "20210428", vars_list: list = cons.contract_symbols
)
|
return new_big_dict
|
郑州商品交易所前 20 会员持仓排名数据明细
注:该交易所既公布了品种排名, 也公布了标的排名
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品, 数据从20050509开始,每交易日16:30左右更新数据
:return: pd.DataFrame
rank 排名 int
vol_party_name 成交量排序的当前名次会员 string(中文)
vol 该会员成交量 int
vol_chg 该会员成交量变化量 int
long_party_name 持多单排序的当前名次会员 string(中文)
long_open_interest 该会员持多单 int
long_open_interest_chg 该会员持多单变化量 int
short_party_name 持空单排序的当前名次会员 string(中文)
short_open_interest 该会员持空单 int
short_open_interest_chg 该会员持空单变化量 int
symbol 标的合约 string
var 品种 string
date 日期 string YYYYMMDD
|
郑州商品交易所前 20 会员持仓排名数据明细
注:该交易所既公布了品种排名, 也公布了标的排名
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品, 数据从20050509开始,每交易日16:30左右更新数据
:return: pd.DataFrame
rank 排名 int
vol_party_name 成交量排序的当前名次会员 string(中文)
vol 该会员成交量 int
vol_chg 该会员成交量变化量 int
long_party_name 持多单排序的当前名次会员 string(中文)
long_open_interest 该会员持多单 int
long_open_interest_chg 该会员持多单变化量 int
short_party_name 持空单排序的当前名次会员 string(中文)
short_open_interest 该会员持空单 int
short_open_interest_chg 该会员持空单变化量 int
symbol 标的合约 string
var 品种 string
date 日期 string YYYYMMDD
| 406 | 501 |
def get_czce_rank_table(
date: str = "20210428", vars_list: list = cons.contract_symbols
):
"""
郑州商品交易所前 20 会员持仓排名数据明细
注:该交易所既公布了品种排名, 也公布了标的排名
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品, 数据从20050509开始,每交易日16:30左右更新数据
:return: pd.DataFrame
rank 排名 int
vol_party_name 成交量排序的当前名次会员 string(中文)
vol 该会员成交量 int
vol_chg 该会员成交量变化量 int
long_party_name 持多单排序的当前名次会员 string(中文)
long_open_interest 该会员持多单 int
long_open_interest_chg 该会员持多单变化量 int
short_party_name 持空单排序的当前名次会员 string(中文)
short_open_interest 该会员持空单 int
short_open_interest_chg 该会员持空单变化量 int
symbol 标的合约 string
var 品种 string
date 日期 string YYYYMMDD
"""
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date < datetime.date(2015, 10, 8):
print("CZCE可获取的数据源开始日期为 20151008, 请输入合适的日期参数")
return {}
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
if date >= datetime.date(2015, 10, 8):
url = f"http://www.czce.com.cn/cn/DFSStaticFiles/Future/{date.year}/{date.isoformat().replace('-', '')}/FutureDataHolding.xls"
r = requests.get(url)
temp_df = pd.read_excel(BytesIO(r.content))
temp_pinzhong_index = [
item + 1
for item in temp_df[
temp_df.iloc[:, 0].str.contains("合计", na=False)
].index.to_list()
]
temp_pinzhong_index.insert(0, 0)
temp_pinzhong_index.pop()
temp_symbol_index = (
temp_df.iloc[temp_pinzhong_index, 0]
.str.split(" ", expand=True)
.iloc[:, 0]
)
symbol_list = [
re.compile(r"[0-9a-zA-Z_]+").findall(item)[0]
for item in temp_symbol_index.values
]
temp_symbol_index_list = temp_symbol_index.index.to_list()
big_dict = {}
for i in range(len(temp_symbol_index_list) - 1):
inner_temp_df = temp_df[
temp_symbol_index_list[i] + 2 : temp_symbol_index_list[i + 1] - 1
]
inner_temp_df.columns = [
"rank",
"vol_party_name",
"vol",
"vol_chg",
"long_party_name",
"long_open_interest",
"long_open_interest_chg",
"short_party_name",
"short_open_interest",
"short_open_interest_chg",
]
inner_temp_df.reset_index(inplace=True, drop=True)
big_dict[symbol_list[i]] = inner_temp_df
inner_temp_df = temp_df[temp_symbol_index_list[i + 1] + 2 : -1]
inner_temp_df.columns = [
"rank",
"vol_party_name",
"vol",
"vol_chg",
"long_party_name",
"long_open_interest",
"long_open_interest_chg",
"short_party_name",
"short_open_interest",
"short_open_interest_chg",
]
inner_temp_df.reset_index(inplace=True, drop=True)
big_dict[symbol_list[-1]] = inner_temp_df
new_big_dict = {}
for key, value in big_dict.items():
value["symbol"] = key
value["variety"] = re.compile(r"[a-zA-Z_]+").findall(key)[0]
new_big_dict[key] = value
return new_big_dict
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cot.py#L406-L501
| 25 |
[
0
] | 1.041667 |
[
23,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
37,
43,
44,
45,
50,
54,
55,
56,
57,
60,
72,
73,
74,
75,
87,
88,
89,
90,
91,
92,
93,
95
] | 34.375 | false | 7.692308 | 96 | 8 | 65.625 | 18 |
def get_czce_rank_table(
date: str = "20210428", vars_list: list = cons.contract_symbols
):
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date < datetime.date(2015, 10, 8):
print("CZCE可获取的数据源开始日期为 20151008, 请输入合适的日期参数")
return {}
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
if date >= datetime.date(2015, 10, 8):
url = f"http://www.czce.com.cn/cn/DFSStaticFiles/Future/{date.year}/{date.isoformat().replace('-', '')}/FutureDataHolding.xls"
r = requests.get(url)
temp_df = pd.read_excel(BytesIO(r.content))
temp_pinzhong_index = [
item + 1
for item in temp_df[
temp_df.iloc[:, 0].str.contains("合计", na=False)
].index.to_list()
]
temp_pinzhong_index.insert(0, 0)
temp_pinzhong_index.pop()
temp_symbol_index = (
temp_df.iloc[temp_pinzhong_index, 0]
.str.split(" ", expand=True)
.iloc[:, 0]
)
symbol_list = [
re.compile(r"[0-9a-zA-Z_]+").findall(item)[0]
for item in temp_symbol_index.values
]
temp_symbol_index_list = temp_symbol_index.index.to_list()
big_dict = {}
for i in range(len(temp_symbol_index_list) - 1):
inner_temp_df = temp_df[
temp_symbol_index_list[i] + 2 : temp_symbol_index_list[i + 1] - 1
]
inner_temp_df.columns = [
"rank",
"vol_party_name",
"vol",
"vol_chg",
"long_party_name",
"long_open_interest",
"long_open_interest_chg",
"short_party_name",
"short_open_interest",
"short_open_interest_chg",
]
inner_temp_df.reset_index(inplace=True, drop=True)
big_dict[symbol_list[i]] = inner_temp_df
inner_temp_df = temp_df[temp_symbol_index_list[i + 1] + 2 : -1]
inner_temp_df.columns = [
"rank",
"vol_party_name",
"vol",
"vol_chg",
"long_party_name",
"long_open_interest",
"long_open_interest_chg",
"short_party_name",
"short_open_interest",
"short_open_interest_chg",
]
inner_temp_df.reset_index(inplace=True, drop=True)
big_dict[symbol_list[-1]] = inner_temp_df
new_big_dict = {}
for key, value in big_dict.items():
value["symbol"] = key
value["variety"] = re.compile(r"[a-zA-Z_]+").findall(key)[0]
new_big_dict[key] = value
return new_big_dict
| 18,149 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cot.py
|
_get_dce_contract_list
|
(date, var)
|
大连商品交易所取消了品种排名,只提供标的合约排名,需要获取标的合约列表
:param date: 日期 datetime.date 对象, 为空时为当天
:param var: 合约品种
:return: list 公布了持仓排名的合约列表
|
大连商品交易所取消了品种排名,只提供标的合约排名,需要获取标的合约列表
:param date: 日期 datetime.date 对象, 为空时为当天
:param var: 合约品种
:return: list 公布了持仓排名的合约列表
| 504 | 554 |
def _get_dce_contract_list(date, var):
"""
大连商品交易所取消了品种排名,只提供标的合约排名,需要获取标的合约列表
:param date: 日期 datetime.date 对象, 为空时为当天
:param var: 合约品种
:return: list 公布了持仓排名的合约列表
"""
url = (
"http://www.dce.com.cn/publicweb/quotesdata/memberDealPosiQuotes.html"
)
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "close",
"Host": "www.dce.com.cn",
"Origin": "http://www.dce.com.cn",
"Pragma": "no-cache",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
}
params = {
"memberDealPosiQuotes.variety": var.lower(),
"memberDealPosiQuotes.trade_type": "0",
"year": date.year,
"month": date.month - 1,
"day": date.day,
"contract.contract_id": "all",
"contract.variety_id": var.lower(),
"contract": "",
}
while 1:
try:
r = requests.post(url, params=params, headers=headers)
soup = BeautifulSoup(r.text, "lxml")
contract_list = [
re.findall(
r"\d+",
item["onclick"]
.strip("javascript:setContract_id('")
.strip("');"),
)[0]
for item in soup.find_all(attrs={"name": "contract"})
]
contract_list = [var.lower() + item for item in contract_list]
return contract_list
except:
time.sleep(5)
continue
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cot.py#L504-L554
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 13.72549 |
[
7,
10,
22,
33,
34,
35,
36,
37,
46,
47,
48,
49,
50
] | 25.490196 | false | 7.692308 | 51 | 5 | 74.509804 | 4 |
def _get_dce_contract_list(date, var):
url = (
"http://www.dce.com.cn/publicweb/quotesdata/memberDealPosiQuotes.html"
)
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "close",
"Host": "www.dce.com.cn",
"Origin": "http://www.dce.com.cn",
"Pragma": "no-cache",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
}
params = {
"memberDealPosiQuotes.variety": var.lower(),
"memberDealPosiQuotes.trade_type": "0",
"year": date.year,
"month": date.month - 1,
"day": date.day,
"contract.contract_id": "all",
"contract.variety_id": var.lower(),
"contract": "",
}
while 1:
try:
r = requests.post(url, params=params, headers=headers)
soup = BeautifulSoup(r.text, "lxml")
contract_list = [
re.findall(
r"\d+",
item["onclick"]
.strip("javascript:setContract_id('")
.strip("');"),
)[0]
for item in soup.find_all(attrs={"name": "contract"})
]
contract_list = [var.lower() + item for item in contract_list]
return contract_list
except:
time.sleep(5)
continue
| 18,150 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cot.py
|
get_dce_rank_table
|
(
date: str = "20210309", vars_list=cons.contract_symbols
)
|
return big_dict
|
大连商品交易所前 20 会员持仓排名数据明细, 由于交易所网站问题, 需要 20200720 之后才有数据
注: 该交易所只公布标的合约排名
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date 对象, 为空时为当天
:param vars_list: 合约品种如 RB、AL 等列表为空时为所有商品, 数据从 20060104 开始,每交易日 16:30 左右更新数据
:return: pandas.DataFrame
rank 排名 int
vol_party_name 成交量排序的当前名次会员 string(中文)
vol 该会员成交量 int
vol_chg 该会员成交量变化量 int
long_party_name 持多单排序的当前名次会员 string(中文)
long_open_interest 该会员持多单 int
long_open_interest_chg 该会员持多单变化量 int
short_party_name 持空单排序的当前名次会员 string(中文)
short_open_interest 该会员持空单 int
short_open_interest_chg 该会员持空单变化量 int
symbol 标的合约 string
var 品种 string
date 日期 string YYYYMMDD
|
大连商品交易所前 20 会员持仓排名数据明细, 由于交易所网站问题, 需要 20200720 之后才有数据
注: 该交易所只公布标的合约排名
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date 对象, 为空时为当天
:param vars_list: 合约品种如 RB、AL 等列表为空时为所有商品, 数据从 20060104 开始,每交易日 16:30 左右更新数据
:return: pandas.DataFrame
rank 排名 int
vol_party_name 成交量排序的当前名次会员 string(中文)
vol 该会员成交量 int
vol_chg 该会员成交量变化量 int
long_party_name 持多单排序的当前名次会员 string(中文)
long_open_interest 该会员持多单 int
long_open_interest_chg 该会员持多单变化量 int
short_party_name 持空单排序的当前名次会员 string(中文)
short_open_interest 该会员持空单 int
short_open_interest_chg 该会员持空单变化量 int
symbol 标的合约 string
var 品种 string
date 日期 string YYYYMMDD
| 557 | 708 |
def get_dce_rank_table(
date: str = "20210309", vars_list=cons.contract_symbols
):
"""
大连商品交易所前 20 会员持仓排名数据明细, 由于交易所网站问题, 需要 20200720 之后才有数据
注: 该交易所只公布标的合约排名
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date 对象, 为空时为当天
:param vars_list: 合约品种如 RB、AL 等列表为空时为所有商品, 数据从 20060104 开始,每交易日 16:30 左右更新数据
:return: pandas.DataFrame
rank 排名 int
vol_party_name 成交量排序的当前名次会员 string(中文)
vol 该会员成交量 int
vol_chg 该会员成交量变化量 int
long_party_name 持多单排序的当前名次会员 string(中文)
long_open_interest 该会员持多单 int
long_open_interest_chg 该会员持多单变化量 int
short_party_name 持空单排序的当前名次会员 string(中文)
short_open_interest 该会员持空单 int
short_open_interest_chg 该会员持空单变化量 int
symbol 标的合约 string
var 品种 string
date 日期 string YYYYMMDD
"""
date_string = date
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date < datetime.date(2006, 1, 4):
print(Exception("大连商品交易所数据源开始日期为 20060104,跳过"))
return {}
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
vars_list = [
i for i in vars_list if i in cons.market_exchange_symbols["dce"]
]
big_dict = {}
for var in vars_list:
# var = 'V'
symbol_list = _get_dce_contract_list(date, var)
for symbol in symbol_list:
# print(symbol)
url = cons.DCE_VOL_RANK_URL_1 % (
var.lower(),
symbol,
var.lower(),
date.year,
date.month - 1,
date.day,
)
try:
temp_df = pd.read_excel(
url[:-3] + "excel", header=0, skiprows=3
)
temp_df.dropna(how="any", axis=0, inplace=True)
temp_df = temp_df.applymap(lambda x: str(x).replace(",", ""))
del temp_df["名次.1"]
del temp_df["名次.2"]
temp_df.rename(
columns={
"名次": "rank",
"会员简称": "vol_party_name",
"成交量": "vol",
"增减": "vol_chg",
"会员简称.1": "long_party_name",
"持买单量": "long_open_interest",
"增减.1": "long_open_interest_chg",
"会员简称.2": "short_party_name",
"持卖单量": "short_open_interest",
"增减.2": "short_open_interest_chg",
},
inplace=True,
)
temp_df["symbol"] = symbol.upper()
temp_df["var"] = var
temp_df["date"] = date_string
temp_df = temp_df.applymap(
lambda x: str(x).replace("-", "0") if x == "-" else x
)
temp_df["rank"] = range(1, len(temp_df) + 1)
temp_df["vol"] = temp_df["vol"].astype(float)
temp_df["vol_chg"] = temp_df["vol_chg"].astype(float)
temp_df["long_open_interest"] = temp_df[
"long_open_interest"
].astype(float)
temp_df["long_open_interest_chg"] = temp_df[
"long_open_interest_chg"
].astype(float)
temp_df["short_open_interest"] = temp_df[
"short_open_interest"
].astype(float)
temp_df["short_open_interest_chg"] = temp_df[
"short_open_interest_chg"
].astype(float)
big_dict[symbol] = temp_df
except:
temp_url = "http://www.dce.com.cn/publicweb/quotesdata/memberDealPosiQuotes.html"
payload = {
"memberDealPosiQuotes.variety": var.lower(),
"memberDealPosiQuotes.trade_type": "0",
"year": date.year,
"month": date.month - 1,
"day": str(date.day).zfill(2),
"contract.contract_id": symbol,
"contract.variety_id": var.lower(),
"contract": "",
}
r = requests.post(temp_url, data=payload)
if r.status_code != 200:
big_dict[symbol] = {}
else:
temp_df = pd.read_html(r.text)[1].iloc[:-1, :]
del temp_df["名次.1"]
del temp_df["名次.2"]
temp_df.rename(
columns={
"名次": "rank",
"会员简称": "vol_party_name",
"成交量": "vol",
"增减": "vol_chg",
"会员简称.1": "long_party_name",
"持买单量": "long_open_interest",
"增减.1": "long_open_interest_chg",
"会员简称.2": "short_party_name",
"持卖单量": "short_open_interest",
"增减.2": "short_open_interest_chg",
},
inplace=True,
)
temp_df["symbol"] = symbol.upper()
temp_df["var"] = var
temp_df["date"] = date_string
temp_df = temp_df.applymap(
lambda x: str(x).replace("-", "0") if x == "-" else x
)
temp_df["rank"] = range(1, len(temp_df) + 1)
temp_df["vol"] = temp_df["vol"].astype(float)
temp_df["vol_chg"] = temp_df["vol_chg"].astype(float)
temp_df["long_open_interest"] = temp_df[
"long_open_interest"
].astype(float)
temp_df["long_open_interest_chg"] = temp_df[
"long_open_interest_chg"
].astype(float)
temp_df["short_open_interest"] = temp_df[
"short_open_interest"
].astype(float)
temp_df["short_open_interest_chg"] = temp_df[
"short_open_interest_chg"
].astype(float)
big_dict[symbol] = temp_df
return big_dict
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cot.py#L557-L708
| 25 |
[
0
] | 0.657895 |
[
23,
24,
27,
28,
29,
30,
31,
32,
33,
36,
37,
39,
40,
42,
50,
51,
54,
55,
56,
57,
58,
73,
74,
75,
76,
79,
80,
81,
82,
85,
88,
91,
94,
95,
96,
97,
107,
108,
109,
111,
112,
113,
114,
129,
130,
131,
132,
135,
136,
137,
138,
141,
144,
147,
150,
151
] | 36.842105 | false | 7.692308 | 152 | 8 | 63.157895 | 18 |
def get_dce_rank_table(
date: str = "20210309", vars_list=cons.contract_symbols
):
date_string = date
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date < datetime.date(2006, 1, 4):
print(Exception("大连商品交易所数据源开始日期为 20060104,跳过"))
return {}
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
vars_list = [
i for i in vars_list if i in cons.market_exchange_symbols["dce"]
]
big_dict = {}
for var in vars_list:
# var = 'V'
symbol_list = _get_dce_contract_list(date, var)
for symbol in symbol_list:
# print(symbol)
url = cons.DCE_VOL_RANK_URL_1 % (
var.lower(),
symbol,
var.lower(),
date.year,
date.month - 1,
date.day,
)
try:
temp_df = pd.read_excel(
url[:-3] + "excel", header=0, skiprows=3
)
temp_df.dropna(how="any", axis=0, inplace=True)
temp_df = temp_df.applymap(lambda x: str(x).replace(",", ""))
del temp_df["名次.1"]
del temp_df["名次.2"]
temp_df.rename(
columns={
"名次": "rank",
"会员简称": "vol_party_name",
"成交量": "vol",
"增减": "vol_chg",
"会员简称.1": "long_party_name",
"持买单量": "long_open_interest",
"增减.1": "long_open_interest_chg",
"会员简称.2": "short_party_name",
"持卖单量": "short_open_interest",
"增减.2": "short_open_interest_chg",
},
inplace=True,
)
temp_df["symbol"] = symbol.upper()
temp_df["var"] = var
temp_df["date"] = date_string
temp_df = temp_df.applymap(
lambda x: str(x).replace("-", "0") if x == "-" else x
)
temp_df["rank"] = range(1, len(temp_df) + 1)
temp_df["vol"] = temp_df["vol"].astype(float)
temp_df["vol_chg"] = temp_df["vol_chg"].astype(float)
temp_df["long_open_interest"] = temp_df[
"long_open_interest"
].astype(float)
temp_df["long_open_interest_chg"] = temp_df[
"long_open_interest_chg"
].astype(float)
temp_df["short_open_interest"] = temp_df[
"short_open_interest"
].astype(float)
temp_df["short_open_interest_chg"] = temp_df[
"short_open_interest_chg"
].astype(float)
big_dict[symbol] = temp_df
except:
temp_url = "http://www.dce.com.cn/publicweb/quotesdata/memberDealPosiQuotes.html"
payload = {
"memberDealPosiQuotes.variety": var.lower(),
"memberDealPosiQuotes.trade_type": "0",
"year": date.year,
"month": date.month - 1,
"day": str(date.day).zfill(2),
"contract.contract_id": symbol,
"contract.variety_id": var.lower(),
"contract": "",
}
r = requests.post(temp_url, data=payload)
if r.status_code != 200:
big_dict[symbol] = {}
else:
temp_df = pd.read_html(r.text)[1].iloc[:-1, :]
del temp_df["名次.1"]
del temp_df["名次.2"]
temp_df.rename(
columns={
"名次": "rank",
"会员简称": "vol_party_name",
"成交量": "vol",
"增减": "vol_chg",
"会员简称.1": "long_party_name",
"持买单量": "long_open_interest",
"增减.1": "long_open_interest_chg",
"会员简称.2": "short_party_name",
"持卖单量": "short_open_interest",
"增减.2": "short_open_interest_chg",
},
inplace=True,
)
temp_df["symbol"] = symbol.upper()
temp_df["var"] = var
temp_df["date"] = date_string
temp_df = temp_df.applymap(
lambda x: str(x).replace("-", "0") if x == "-" else x
)
temp_df["rank"] = range(1, len(temp_df) + 1)
temp_df["vol"] = temp_df["vol"].astype(float)
temp_df["vol_chg"] = temp_df["vol_chg"].astype(float)
temp_df["long_open_interest"] = temp_df[
"long_open_interest"
].astype(float)
temp_df["long_open_interest_chg"] = temp_df[
"long_open_interest_chg"
].astype(float)
temp_df["short_open_interest"] = temp_df[
"short_open_interest"
].astype(float)
temp_df["short_open_interest_chg"] = temp_df[
"short_open_interest_chg"
].astype(float)
big_dict[symbol] = temp_df
return big_dict
| 18,151 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cot.py
|
get_cffex_rank_table
|
(date="20200427", vars_list=cons.contract_symbols)
|
return big_dict
|
中国金融期货交易所前 20 会员持仓排名数据明细
注:该交易所既公布品种排名,也公布标的排名
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品, 数据从20100416开始,每交易日16:30左右更新数据
:return: pd.DataFrame
rank 排名 int
vol_party_name 成交量排序的当前名次会员 string(中文)
vol 该会员成交量 int
vol_chg 该会员成交量变化量 int
long_party_name 持多单排序的当前名次会员 string(中文)
long_open_interest 该会员持多单 int
long_open_interest_chg 该会员持多单变化量 int
short_party_name 持空单排序的当前名次会员 string(中文)
short_open_interest 该会员持空单 int
short_open_interest_chg 该会员持空单变化量 int
symbol 标的合约 string
var 品种 string
date 日期 string YYYYMMDD
|
中国金融期货交易所前 20 会员持仓排名数据明细
注:该交易所既公布品种排名,也公布标的排名
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品, 数据从20100416开始,每交易日16:30左右更新数据
:return: pd.DataFrame
rank 排名 int
vol_party_name 成交量排序的当前名次会员 string(中文)
vol 该会员成交量 int
vol_chg 该会员成交量变化量 int
long_party_name 持多单排序的当前名次会员 string(中文)
long_open_interest 该会员持多单 int
long_open_interest_chg 该会员持多单变化量 int
short_party_name 持空单排序的当前名次会员 string(中文)
short_open_interest 该会员持空单 int
short_open_interest_chg 该会员持空单变化量 int
symbol 标的合约 string
var 品种 string
date 日期 string YYYYMMDD
| 711 | 773 |
def get_cffex_rank_table(date="20200427", vars_list=cons.contract_symbols):
"""
中国金融期货交易所前 20 会员持仓排名数据明细
注:该交易所既公布品种排名,也公布标的排名
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品, 数据从20100416开始,每交易日16:30左右更新数据
:return: pd.DataFrame
rank 排名 int
vol_party_name 成交量排序的当前名次会员 string(中文)
vol 该会员成交量 int
vol_chg 该会员成交量变化量 int
long_party_name 持多单排序的当前名次会员 string(中文)
long_open_interest 该会员持多单 int
long_open_interest_chg 该会员持多单变化量 int
short_party_name 持空单排序的当前名次会员 string(中文)
short_open_interest 该会员持空单 int
short_open_interest_chg 该会员持空单变化量 int
symbol 标的合约 string
var 品种 string
date 日期 string YYYYMMDD
"""
vars_list = [
i for i in vars_list if i in cons.market_exchange_symbols["cffex"]
]
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date < datetime.date(2010, 4, 16):
print(Exception("cffex数据源开始日期为20100416,跳过"))
return {}
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
big_dict = {}
for var in vars_list:
# print(var)
# var = "IF"
url = cons.CFFEX_VOL_RANK_URL % (
date.strftime("%Y%m"),
date.strftime("%d"),
var,
)
r = requests_link(url, encoding="gbk")
if not r:
return False
if "网页错误" not in r.text:
try:
temp_chche = StringIO(r.text.split("\n交易日,")[1])
except:
temp_chche = StringIO(
r.text.split("\n交易日,")[0][4:]
) # 20200316开始数据结构变化,统一格式
table = pd.read_csv(temp_chche)
table = table.dropna(how="any")
table = table.applymap(
lambda x: x.strip() if isinstance(x, str) else x
)
for symbol in set(table["合约"]):
table_cut = table[table["合约"] == symbol]
table_cut.columns = ["symbol", "rank"] + rank_columns
table_cut = _table_cut_cal(pd.DataFrame(table_cut), symbol)
big_dict[symbol] = table_cut.reset_index(drop=True)
return big_dict
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cot.py#L711-L773
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20
] | 33.333333 |
[
21,
24,
27,
28,
29,
30,
31,
32,
33,
34,
37,
42,
43,
44,
45,
46,
47,
48,
49,
52,
53,
54,
57,
58,
59,
60,
61,
62
] | 44.444444 | false | 7.692308 | 63 | 9 | 55.555556 | 18 |
def get_cffex_rank_table(date="20200427", vars_list=cons.contract_symbols):
vars_list = [
i for i in vars_list if i in cons.market_exchange_symbols["cffex"]
]
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date < datetime.date(2010, 4, 16):
print(Exception("cffex数据源开始日期为20100416,跳过"))
return {}
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
big_dict = {}
for var in vars_list:
# print(var)
# var = "IF"
url = cons.CFFEX_VOL_RANK_URL % (
date.strftime("%Y%m"),
date.strftime("%d"),
var,
)
r = requests_link(url, encoding="gbk")
if not r:
return False
if "网页错误" not in r.text:
try:
temp_chche = StringIO(r.text.split("\n交易日,")[1])
except:
temp_chche = StringIO(
r.text.split("\n交易日,")[0][4:]
) # 20200316开始数据结构变化,统一格式
table = pd.read_csv(temp_chche)
table = table.dropna(how="any")
table = table.applymap(
lambda x: x.strip() if isinstance(x, str) else x
)
for symbol in set(table["合约"]):
table_cut = table[table["合约"] == symbol]
table_cut.columns = ["symbol", "rank"] + rank_columns
table_cut = _table_cut_cal(pd.DataFrame(table_cut), symbol)
big_dict[symbol] = table_cut.reset_index(drop=True)
return big_dict
| 18,152 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cot.py
|
_table_cut_cal
|
(table_cut, symbol)
|
return table_cut
|
表格切分
:param table_cut: 需要切分的表格
:type table_cut: pandas.DataFrame
:param symbol: 具体合约的代码
:type symbol: str
:return: 表格切分后的结果
:rtype: pandas.DataFrame
|
表格切分
:param table_cut: 需要切分的表格
:type table_cut: pandas.DataFrame
:param symbol: 具体合约的代码
:type symbol: str
:return: 表格切分后的结果
:rtype: pandas.DataFrame
| 776 | 800 |
def _table_cut_cal(table_cut, symbol):
"""
表格切分
:param table_cut: 需要切分的表格
:type table_cut: pandas.DataFrame
:param symbol: 具体合约的代码
:type symbol: str
:return: 表格切分后的结果
:rtype: pandas.DataFrame
"""
var = symbol_varieties(symbol)
table_cut[intColumns + ["rank"]] = table_cut[intColumns + ["rank"]].astype(
int
)
table_cut_sum = table_cut.sum()
table_cut_sum["rank"] = 999
for col in ["vol_party_name", "long_party_name", "short_party_name"]:
table_cut_sum[col] = None
table_cut = table_cut.append(pd.DataFrame(table_cut_sum).T, sort=True)
table_cut["symbol"] = symbol
table_cut["variety"] = var
table_cut[intColumns + ["rank"]] = table_cut[intColumns + ["rank"]].astype(
int
)
return table_cut
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cot.py#L776-L800
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 40 |
[
10,
11,
14,
15,
16,
17,
18,
19,
20,
21,
24
] | 44 | false | 7.692308 | 25 | 2 | 56 | 7 |
def _table_cut_cal(table_cut, symbol):
var = symbol_varieties(symbol)
table_cut[intColumns + ["rank"]] = table_cut[intColumns + ["rank"]].astype(
int
)
table_cut_sum = table_cut.sum()
table_cut_sum["rank"] = 999
for col in ["vol_party_name", "long_party_name", "short_party_name"]:
table_cut_sum[col] = None
table_cut = table_cut.append(pd.DataFrame(table_cut_sum).T, sort=True)
table_cut["symbol"] = symbol
table_cut["variety"] = var
table_cut[intColumns + ["rank"]] = table_cut[intColumns + ["rank"]].astype(
int
)
return table_cut
| 18,153 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cot.py
|
futures_dce_position_rank
|
(date: str = "20160919")
|
return big_dict
|
大连商品交易所-每日持仓排名-具体合约
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/rcjccpm/index.html
:param date: 指定交易日; e.g., "20200511"
:type date: str
:return: 指定日期的持仓排名数据
:rtype: pandas.DataFrame
|
大连商品交易所-每日持仓排名-具体合约
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/rcjccpm/index.html
:param date: 指定交易日; e.g., "20200511"
:type date: str
:return: 指定日期的持仓排名数据
:rtype: pandas.DataFrame
| 803 | 1,021 |
def futures_dce_position_rank(date: str = "20160919") -> dict:
"""
大连商品交易所-每日持仓排名-具体合约
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/rcjccpm/index.html
:param date: 指定交易日; e.g., "20200511"
:type date: str
:return: 指定日期的持仓排名数据
:rtype: pandas.DataFrame
"""
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
url = "http://www.dce.com.cn/publicweb/quotesdata/exportMemberDealPosiQuotesBatchData.html"
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Content-Length": "160",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "www.dce.com.cn",
"Origin": "http://www.dce.com.cn",
"Pragma": "no-cache",
"Referer": "http://www.dce.com.cn/publicweb/quotesdata/memberDealPosiQuotes.html",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
}
payload = {
"memberDealPosiQuotes.variety": "a",
"memberDealPosiQuotes.trade_type": "0",
"contract.contract_id": "a2009",
"contract.variety_id": "a",
"year": date.year,
"month": date.month - 1,
"day": date.day,
"batchExportFlag": "batch",
}
r = requests.post(url, payload, headers=headers)
big_dict = dict()
with zipfile.ZipFile(BytesIO(r.content), "r") as z:
for i in z.namelist():
file_name = i.encode("cp437").decode("GBK")
if not file_name.startswith(date.strftime("%Y%m%d")):
continue
try:
data = pd.read_table(z.open(i), header=None, sep="\t").iloc[
:-6
]
if len(data) < 12: # 处理没有活跃合约的情况
big_dict[file_name.split("_")[1]] = pd.DataFrame()
continue
temp_filter = data[
data.iloc[:, 0].str.find("名次") == 0
].index.tolist()
if (
temp_filter[1] - temp_filter[0] < 5
): # 过滤有无成交量但是有买卖持仓的数据, 如 20201105_c2011_成交量_买持仓_卖持仓排名.txt
big_dict[file_name.split("_")[1]] = pd.DataFrame()
continue
start_list = data[
data.iloc[:, 0].str.find("名次") == 0
].index.tolist()
data = data.iloc[
start_list[0] :,
data.columns[data.iloc[start_list[0], :].notnull()],
]
data.reset_index(inplace=True, drop=True)
start_list = data[
data.iloc[:, 0].str.find("名次") == 0
].index.tolist()
end_list = data[
data.iloc[:, 0].str.find("总计") == 0
].index.tolist()
part_one = data[start_list[0] : end_list[0]].iloc[1:, :]
part_two = data[start_list[1] : end_list[1]].iloc[1:, :]
part_three = data[start_list[2] : end_list[2]].iloc[1:, :]
temp_df = pd.concat(
[
part_one.reset_index(drop=True),
part_two.reset_index(drop=True),
part_three.reset_index(drop=True),
],
axis=1,
ignore_index=True,
)
temp_df.columns = [
"名次",
"会员简称",
"成交量",
"增减",
"名次",
"会员简称",
"持买单量",
"增减",
"名次",
"会员简称",
"持卖单量",
"增减",
]
temp_df["rank"] = range(1, len(temp_df) + 1)
del temp_df["名次"]
temp_df.columns = [
"vol_party_name",
"vol",
"vol_chg",
"long_party_name",
"long_open_interest",
"long_open_interest_chg",
"short_party_name",
"short_open_interest",
"short_open_interest_chg",
"rank",
]
temp_df["symbol"] = file_name.split("_")[1]
temp_df["variety"] = file_name.split("_")[1][:-4].upper()
temp_df = temp_df[
[
"long_open_interest",
"long_open_interest_chg",
"long_party_name",
"rank",
"short_open_interest",
"short_open_interest_chg",
"short_party_name",
"vol",
"vol_chg",
"vol_party_name",
"symbol",
"variety",
]
]
big_dict[file_name.split("_")[1]] = temp_df
except UnicodeDecodeError as e:
try:
data = pd.read_table(
z.open(i),
header=None,
sep="\\s+",
encoding="gb2312",
skiprows=3,
)
except:
data = pd.read_table(
z.open(i),
header=None,
sep="\\s+",
encoding="gb2312",
skiprows=4,
)
start_list = data[
data.iloc[:, 0].str.find("名次") == 0
].index.tolist()
end_list = data[
data.iloc[:, 0].str.find("总计") == 0
].index.tolist()
part_one = data[start_list[0] : end_list[0]].iloc[1:, :]
part_two = data[start_list[1] : end_list[1]].iloc[1:, :]
part_three = data[start_list[2] : end_list[2]].iloc[1:, :]
temp_df = pd.concat(
[
part_one.reset_index(drop=True),
part_two.reset_index(drop=True),
part_three.reset_index(drop=True),
],
axis=1,
ignore_index=True,
)
temp_df.columns = [
"名次",
"会员简称",
"成交量",
"增减",
"名次",
"会员简称",
"持买单量",
"增减",
"名次",
"会员简称",
"持卖单量",
"增减",
]
temp_df["rank"] = range(1, len(temp_df) + 1)
del temp_df["名次"]
temp_df.columns = [
"vol_party_name",
"vol",
"vol_chg",
"long_party_name",
"long_open_interest",
"long_open_interest_chg",
"short_party_name",
"short_open_interest",
"short_open_interest_chg",
"rank",
]
temp_df["symbol"] = file_name.split("_")[1]
temp_df["variety"] = file_name.split("_")[1][:-4].upper()
temp_df = temp_df[
[
"long_open_interest",
"long_open_interest_chg",
"long_party_name",
"rank",
"short_open_interest",
"short_open_interest_chg",
"short_party_name",
"vol",
"vol_chg",
"vol_party_name",
"symbol",
"variety",
]
]
big_dict[file_name.split("_")[1]] = temp_df
return big_dict
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cot.py#L803-L1021
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 4.109589 |
[
9,
12,
13,
14,
15,
16,
31,
41,
42,
43,
44,
45,
46,
47,
48,
49,
52,
53,
54,
55,
58,
61,
62,
63,
66,
70,
71,
74,
77,
78,
79,
80,
89,
103,
104,
105,
117,
118,
119,
135,
136,
137,
138,
145,
146,
153,
156,
159,
160,
161,
162,
171,
185,
186,
187,
199,
200,
201,
217,
218
] | 27.39726 | false | 7.692308 | 219 | 9 | 72.60274 | 6 |
def futures_dce_position_rank(date: str = "20160919") -> dict:
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
url = "http://www.dce.com.cn/publicweb/quotesdata/exportMemberDealPosiQuotesBatchData.html"
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Content-Length": "160",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "www.dce.com.cn",
"Origin": "http://www.dce.com.cn",
"Pragma": "no-cache",
"Referer": "http://www.dce.com.cn/publicweb/quotesdata/memberDealPosiQuotes.html",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
}
payload = {
"memberDealPosiQuotes.variety": "a",
"memberDealPosiQuotes.trade_type": "0",
"contract.contract_id": "a2009",
"contract.variety_id": "a",
"year": date.year,
"month": date.month - 1,
"day": date.day,
"batchExportFlag": "batch",
}
r = requests.post(url, payload, headers=headers)
big_dict = dict()
with zipfile.ZipFile(BytesIO(r.content), "r") as z:
for i in z.namelist():
file_name = i.encode("cp437").decode("GBK")
if not file_name.startswith(date.strftime("%Y%m%d")):
continue
try:
data = pd.read_table(z.open(i), header=None, sep="\t").iloc[
:-6
]
if len(data) < 12: # 处理没有活跃合约的情况
big_dict[file_name.split("_")[1]] = pd.DataFrame()
continue
temp_filter = data[
data.iloc[:, 0].str.find("名次") == 0
].index.tolist()
if (
temp_filter[1] - temp_filter[0] < 5
): # 过滤有无成交量但是有买卖持仓的数据, 如 20201105_c2011_成交量_买持仓_卖持仓排名.txt
big_dict[file_name.split("_")[1]] = pd.DataFrame()
continue
start_list = data[
data.iloc[:, 0].str.find("名次") == 0
].index.tolist()
data = data.iloc[
start_list[0] :,
data.columns[data.iloc[start_list[0], :].notnull()],
]
data.reset_index(inplace=True, drop=True)
start_list = data[
data.iloc[:, 0].str.find("名次") == 0
].index.tolist()
end_list = data[
data.iloc[:, 0].str.find("总计") == 0
].index.tolist()
part_one = data[start_list[0] : end_list[0]].iloc[1:, :]
part_two = data[start_list[1] : end_list[1]].iloc[1:, :]
part_three = data[start_list[2] : end_list[2]].iloc[1:, :]
temp_df = pd.concat(
[
part_one.reset_index(drop=True),
part_two.reset_index(drop=True),
part_three.reset_index(drop=True),
],
axis=1,
ignore_index=True,
)
temp_df.columns = [
"名次",
"会员简称",
"成交量",
"增减",
"名次",
"会员简称",
"持买单量",
"增减",
"名次",
"会员简称",
"持卖单量",
"增减",
]
temp_df["rank"] = range(1, len(temp_df) + 1)
del temp_df["名次"]
temp_df.columns = [
"vol_party_name",
"vol",
"vol_chg",
"long_party_name",
"long_open_interest",
"long_open_interest_chg",
"short_party_name",
"short_open_interest",
"short_open_interest_chg",
"rank",
]
temp_df["symbol"] = file_name.split("_")[1]
temp_df["variety"] = file_name.split("_")[1][:-4].upper()
temp_df = temp_df[
[
"long_open_interest",
"long_open_interest_chg",
"long_party_name",
"rank",
"short_open_interest",
"short_open_interest_chg",
"short_party_name",
"vol",
"vol_chg",
"vol_party_name",
"symbol",
"variety",
]
]
big_dict[file_name.split("_")[1]] = temp_df
except UnicodeDecodeError as e:
try:
data = pd.read_table(
z.open(i),
header=None,
sep="\\s+",
encoding="gb2312",
skiprows=3,
)
except:
data = pd.read_table(
z.open(i),
header=None,
sep="\\s+",
encoding="gb2312",
skiprows=4,
)
start_list = data[
data.iloc[:, 0].str.find("名次") == 0
].index.tolist()
end_list = data[
data.iloc[:, 0].str.find("总计") == 0
].index.tolist()
part_one = data[start_list[0] : end_list[0]].iloc[1:, :]
part_two = data[start_list[1] : end_list[1]].iloc[1:, :]
part_three = data[start_list[2] : end_list[2]].iloc[1:, :]
temp_df = pd.concat(
[
part_one.reset_index(drop=True),
part_two.reset_index(drop=True),
part_three.reset_index(drop=True),
],
axis=1,
ignore_index=True,
)
temp_df.columns = [
"名次",
"会员简称",
"成交量",
"增减",
"名次",
"会员简称",
"持买单量",
"增减",
"名次",
"会员简称",
"持卖单量",
"增减",
]
temp_df["rank"] = range(1, len(temp_df) + 1)
del temp_df["名次"]
temp_df.columns = [
"vol_party_name",
"vol",
"vol_chg",
"long_party_name",
"long_open_interest",
"long_open_interest_chg",
"short_party_name",
"short_open_interest",
"short_open_interest_chg",
"rank",
]
temp_df["symbol"] = file_name.split("_")[1]
temp_df["variety"] = file_name.split("_")[1][:-4].upper()
temp_df = temp_df[
[
"long_open_interest",
"long_open_interest_chg",
"long_party_name",
"rank",
"short_open_interest",
"short_open_interest_chg",
"short_party_name",
"vol",
"vol_chg",
"vol_party_name",
"symbol",
"variety",
]
]
big_dict[file_name.split("_")[1]] = temp_df
return big_dict
| 18,154 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cot.py
|
futures_dce_position_rank_other
|
(date: str = "20160104")
|
return big_df
| 1,024 | 1,119 |
def futures_dce_position_rank_other(date: str = "20160104"):
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
url = (
"http://www.dce.com.cn/publicweb/quotesdata/memberDealPosiQuotes.html"
)
payload = {
"memberDealPosiQuotes.variety": "c",
"memberDealPosiQuotes.trade_type": "0",
"year": date.year,
"month": date.month - 1,
"day": date.day,
"contract.contract_id": "all",
"contract.variety_id": "c",
"contract": "",
}
r = requests.post(url, data=payload)
soup = BeautifulSoup(r.text, "lxml")
symbol_list = [
item["onclick"].strip("javascript:setVariety(").strip("');")
for item in soup.find_all(attrs={"class": "selBox"})[-3].find_all(
"input"
)
]
big_df = dict()
for symbol in symbol_list:
payload = {
"memberDealPosiQuotes.variety": symbol,
"memberDealPosiQuotes.trade_type": "0",
"year": date.year,
"month": date.month - 1,
"day": date.day,
"contract.contract_id": "all",
"contract.variety_id": symbol,
"contract": "",
}
r = requests.post(url, data=payload)
soup = BeautifulSoup(r.text, "lxml")
contract_list = [
item["onclick"].strip("javascript:setContract_id('").strip("');")
for item in soup.find_all(attrs={"name": "contract"})
]
if contract_list:
if len(contract_list[0]) == 4:
contract_list = [symbol + item for item in contract_list]
for contract in contract_list:
payload = {
"memberDealPosiQuotes.variety": symbol,
"memberDealPosiQuotes.trade_type": "0",
"year": date.year,
"month": date.month - 1,
"day": date.day,
"contract.contract_id": contract,
"contract.variety_id": symbol,
"contract": "",
}
r = requests.post(url, data=payload)
temp_df = pd.read_html(r.text)[1].iloc[:-1, :]
temp_df.columns = [
"rank",
"vol_party_name",
"vol",
"vol_chg",
"_",
"long_party_name",
"long_open_interest",
"long_open_interest_chg",
"_",
"short_party_name",
"short_open_interest",
"short_open_interest_chg",
]
temp_df["variety"] = symbol.upper()
temp_df["symbol"] = contract
temp_df = temp_df[
[
"long_open_interest",
"long_open_interest_chg",
"long_party_name",
"rank",
"short_open_interest",
"short_open_interest_chg",
"short_party_name",
"vol",
"vol_chg",
"vol_party_name",
"symbol",
"variety",
]
]
big_df[contract] = temp_df
return big_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cot.py#L1024-L1119
| 25 |
[
0
] | 1.041667 |
[
1,
4,
5,
6,
7,
10,
20,
21,
22,
28,
29,
30,
40,
41,
42,
46,
47,
48,
49,
50,
60,
61,
62,
76,
77,
78,
94,
95
] | 29.166667 | false | 7.692308 | 96 | 9 | 70.833333 | 0 |
def futures_dce_position_rank_other(date: str = "20160104"):
date = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if date.strftime("%Y%m%d") not in calendar:
warnings.warn("%s非交易日" % date.strftime("%Y%m%d"))
return {}
url = (
"http://www.dce.com.cn/publicweb/quotesdata/memberDealPosiQuotes.html"
)
payload = {
"memberDealPosiQuotes.variety": "c",
"memberDealPosiQuotes.trade_type": "0",
"year": date.year,
"month": date.month - 1,
"day": date.day,
"contract.contract_id": "all",
"contract.variety_id": "c",
"contract": "",
}
r = requests.post(url, data=payload)
soup = BeautifulSoup(r.text, "lxml")
symbol_list = [
item["onclick"].strip("javascript:setVariety(").strip("');")
for item in soup.find_all(attrs={"class": "selBox"})[-3].find_all(
"input"
)
]
big_df = dict()
for symbol in symbol_list:
payload = {
"memberDealPosiQuotes.variety": symbol,
"memberDealPosiQuotes.trade_type": "0",
"year": date.year,
"month": date.month - 1,
"day": date.day,
"contract.contract_id": "all",
"contract.variety_id": symbol,
"contract": "",
}
r = requests.post(url, data=payload)
soup = BeautifulSoup(r.text, "lxml")
contract_list = [
item["onclick"].strip("javascript:setContract_id('").strip("');")
for item in soup.find_all(attrs={"name": "contract"})
]
if contract_list:
if len(contract_list[0]) == 4:
contract_list = [symbol + item for item in contract_list]
for contract in contract_list:
payload = {
"memberDealPosiQuotes.variety": symbol,
"memberDealPosiQuotes.trade_type": "0",
"year": date.year,
"month": date.month - 1,
"day": date.day,
"contract.contract_id": contract,
"contract.variety_id": symbol,
"contract": "",
}
r = requests.post(url, data=payload)
temp_df = pd.read_html(r.text)[1].iloc[:-1, :]
temp_df.columns = [
"rank",
"vol_party_name",
"vol",
"vol_chg",
"_",
"long_party_name",
"long_open_interest",
"long_open_interest_chg",
"_",
"short_party_name",
"short_open_interest",
"short_open_interest_chg",
]
temp_df["variety"] = symbol.upper()
temp_df["symbol"] = contract
temp_df = temp_df[
[
"long_open_interest",
"long_open_interest_chg",
"long_party_name",
"rank",
"short_open_interest",
"short_open_interest_chg",
"short_party_name",
"vol",
"vol_chg",
"vol_party_name",
"symbol",
"variety",
]
]
big_df[contract] = temp_df
return big_df
| 18,155 |
||
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_spot_stock_em.py
|
futures_spot_stock
|
(symbol: str = "能源") ->
|
return temp_df
|
东方财富网-数据中心-现货与股票
http://data.eastmoney.com/ifdata/xhgp.html
:param symbol: choice of {'能源', '化工', '塑料', '纺织', '有色', '钢铁', '建材', '农副'}
:type symbol: str
:return: 现货与股票上下游对应数据
:rtype: pandas.DataFrame
|
东方财富网-数据中心-现货与股票
http://data.eastmoney.com/ifdata/xhgp.html
:param symbol: choice of {'能源', '化工', '塑料', '纺织', '有色', '钢铁', '建材', '农副'}
:type symbol: str
:return: 现货与股票上下游对应数据
:rtype: pandas.DataFrame
| 14 | 88 |
def futures_spot_stock(symbol: str = "能源") -> pd.DataFrame:
"""
东方财富网-数据中心-现货与股票
http://data.eastmoney.com/ifdata/xhgp.html
:param symbol: choice of {'能源', '化工', '塑料', '纺织', '有色', '钢铁', '建材', '农副'}
:type symbol: str
:return: 现货与股票上下游对应数据
:rtype: pandas.DataFrame
"""
map_dict = {
"能源": 0,
"化工": 1,
"塑料": 2,
"纺织": 3,
"有色": 4,
"钢铁": 5,
"建材": 6,
"农副": 7,
}
url = "http://data.eastmoney.com/ifdata/xhgp.html"
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Host": "data.eastmoney.com",
"Pragma": "no-cache",
"Upgrade-Insecure-Requests": "1",
"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",
}
r = requests.get(url, headers=headers)
data_text = r.text
temp_json = demjson.decode(
data_text[
data_text.find("pagedata"): data_text.find(
"/newstatic/js/common/emdataview.js"
)
]
.strip("pagedata= ")
.strip(';\n </script>\n <script src="')
)
date_list = list(temp_json["dates"].values())
temp_json = temp_json["datas"]
temp_df = temp_json[map_dict.get(symbol)]
temp_df = pd.DataFrame(temp_df["list"])
xyyh_list = [
"-" if item == [] else ", ".join([inner_item["name"] for inner_item in item])
for item in temp_df["xyyhs"].tolist()
]
scs_list = [
"-" if item == [] else ", ".join([inner_item["name"] for inner_item in item])
for item in temp_df["scss"].tolist()
]
temp_df["scss"] = scs_list
temp_df["xyyhs"] = xyyh_list
temp_df.columns = [
"商品名称",
date_list[0],
date_list[1],
date_list[2],
date_list[3],
date_list[4],
"最新价格",
"近半年涨跌幅",
"生产商",
"下游用户",
]
temp_df[date_list[0]] = pd.to_numeric(temp_df[date_list[0]])
temp_df[date_list[1]] = pd.to_numeric(temp_df[date_list[1]])
temp_df[date_list[2]] = pd.to_numeric(temp_df[date_list[2]])
temp_df[date_list[3]] = pd.to_numeric(temp_df[date_list[3]])
temp_df['最新价格'] = pd.to_numeric(temp_df['最新价格'])
temp_df['近半年涨跌幅'] = pd.to_numeric(temp_df['近半年涨跌幅'])
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_spot_stock_em.py#L14-L88
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 12 |
[
9,
19,
20,
31,
32,
33,
42,
43,
44,
45,
46,
50,
54,
55,
56,
68,
69,
70,
71,
72,
73,
74
] | 29.333333 | false | 19.354839 | 75 | 5 | 70.666667 | 6 |
def futures_spot_stock(symbol: str = "能源") -> pd.DataFrame:
map_dict = {
"能源": 0,
"化工": 1,
"塑料": 2,
"纺织": 3,
"有色": 4,
"钢铁": 5,
"建材": 6,
"农副": 7,
}
url = "http://data.eastmoney.com/ifdata/xhgp.html"
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Host": "data.eastmoney.com",
"Pragma": "no-cache",
"Upgrade-Insecure-Requests": "1",
"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",
}
r = requests.get(url, headers=headers)
data_text = r.text
temp_json = demjson.decode(
data_text[
data_text.find("pagedata"): data_text.find(
"/newstatic/js/common/emdataview.js"
)
]
.strip("pagedata= ")
.strip(';\n </script>\n <script src="')
)
date_list = list(temp_json["dates"].values())
temp_json = temp_json["datas"]
temp_df = temp_json[map_dict.get(symbol)]
temp_df = pd.DataFrame(temp_df["list"])
xyyh_list = [
"-" if item == [] else ", ".join([inner_item["name"] for inner_item in item])
for item in temp_df["xyyhs"].tolist()
]
scs_list = [
"-" if item == [] else ", ".join([inner_item["name"] for inner_item in item])
for item in temp_df["scss"].tolist()
]
temp_df["scss"] = scs_list
temp_df["xyyhs"] = xyyh_list
temp_df.columns = [
"商品名称",
date_list[0],
date_list[1],
date_list[2],
date_list[3],
date_list[4],
"最新价格",
"近半年涨跌幅",
"生产商",
"下游用户",
]
temp_df[date_list[0]] = pd.to_numeric(temp_df[date_list[0]])
temp_df[date_list[1]] = pd.to_numeric(temp_df[date_list[1]])
temp_df[date_list[2]] = pd.to_numeric(temp_df[date_list[2]])
temp_df[date_list[3]] = pd.to_numeric(temp_df[date_list[3]])
temp_df['最新价格'] = pd.to_numeric(temp_df['最新价格'])
temp_df['近半年涨跌幅'] = pd.to_numeric(temp_df['近半年涨跌幅'])
return temp_df
| 18,156 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_basis.py
|
futures_spot_price_daily
|
(
start_day: str = "20210201",
end_day: str = "20210208",
vars_list=cons.contract_symbols,
)
|
指定时间段内大宗商品现货价格及相应基差
http://www.100ppi.com/sf/
:param start_day: str 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象; 默认为当天
:param end_day: str 结束数据 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象; 默认为当天
:param vars_list: list 合约品种如 [RB, AL]; 默认参数为所有商品
:return: pandas.DataFrame
展期收益率数据:
var 商品品种 string
sp 现货价格 float
near_symbol 临近交割合约 string
near_price 临近交割合约结算价 float
dom_symbol 主力合约 string
dom_price 主力合约结算价 float
near_basis 临近交割合约相对现货的基差 float
dom_basis 主力合约相对现货的基差 float
near_basis_rate 临近交割合约相对现货的基差率 float
dom_basis_rate 主力合约相对现货的基差率 float
date 日期 string YYYYMMDD
|
指定时间段内大宗商品现货价格及相应基差
http://www.100ppi.com/sf/
:param start_day: str 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象; 默认为当天
:param end_day: str 结束数据 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象; 默认为当天
:param vars_list: list 合约品种如 [RB, AL]; 默认参数为所有商品
:return: pandas.DataFrame
展期收益率数据:
var 商品品种 string
sp 现货价格 float
near_symbol 临近交割合约 string
near_price 临近交割合约结算价 float
dom_symbol 主力合约 string
dom_price 主力合约结算价 float
near_basis 临近交割合约相对现货的基差 float
dom_basis 主力合约相对现货的基差 float
near_basis_rate 临近交割合约相对现货的基差率 float
dom_basis_rate 主力合约相对现货的基差率 float
date 日期 string YYYYMMDD
| 30 | 74 |
def futures_spot_price_daily(
start_day: str = "20210201",
end_day: str = "20210208",
vars_list=cons.contract_symbols,
):
"""
指定时间段内大宗商品现货价格及相应基差
http://www.100ppi.com/sf/
:param start_day: str 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象; 默认为当天
:param end_day: str 结束数据 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象; 默认为当天
:param vars_list: list 合约品种如 [RB, AL]; 默认参数为所有商品
:return: pandas.DataFrame
展期收益率数据:
var 商品品种 string
sp 现货价格 float
near_symbol 临近交割合约 string
near_price 临近交割合约结算价 float
dom_symbol 主力合约 string
dom_price 主力合约结算价 float
near_basis 临近交割合约相对现货的基差 float
dom_basis 主力合约相对现货的基差 float
near_basis_rate 临近交割合约相对现货的基差率 float
dom_basis_rate 主力合约相对现货的基差率 float
date 日期 string YYYYMMDD
"""
start_day = (
cons.convert_date(start_day) if start_day is not None else datetime.date.today()
)
end_day = (
cons.convert_date(end_day)
if end_day is not None
else cons.convert_date(cons.get_latest_data_date(datetime.datetime.now()))
)
df_list = []
while start_day <= end_day:
temp_df = futures_spot_price(start_day, vars_list)
if temp_df is False:
return pd.concat(df_list).reset_index(drop=True)
elif temp_df is not None:
df_list.append(temp_df)
start_day += datetime.timedelta(days=1)
if len(df_list) > 0:
temp_df = pd.concat(df_list)
temp_df.reset_index(drop=True, inplace=True)
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_basis.py#L30-L74
| 25 |
[
0
] | 2.222222 |
[
25,
28,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44
] | 31.111111 | false | 13.6 | 45 | 5 | 68.888889 | 18 |
def futures_spot_price_daily(
start_day: str = "20210201",
end_day: str = "20210208",
vars_list=cons.contract_symbols,
):
start_day = (
cons.convert_date(start_day) if start_day is not None else datetime.date.today()
)
end_day = (
cons.convert_date(end_day)
if end_day is not None
else cons.convert_date(cons.get_latest_data_date(datetime.datetime.now()))
)
df_list = []
while start_day <= end_day:
temp_df = futures_spot_price(start_day, vars_list)
if temp_df is False:
return pd.concat(df_list).reset_index(drop=True)
elif temp_df is not None:
df_list.append(temp_df)
start_day += datetime.timedelta(days=1)
if len(df_list) > 0:
temp_df = pd.concat(df_list)
temp_df.reset_index(drop=True, inplace=True)
return temp_df
| 18,157 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_basis.py
|
futures_spot_price
|
(date: str = "20210201", vars_list: list = cons.contract_symbols)
|
指定交易日大宗商品现货价格及相应基差
http://www.100ppi.com/sf/day-2017-09-12.html
:param date: 开始日期 format: YYYY-MM-DD 或 YYYYMMDD 或 datetime.date 对象; 为空时为当天
:param vars_list: 合约品种如 RB、AL 等列表 为空时为所有商品
:return: pandas.DataFrame
展期收益率数据:
var 商品品种 string
sp 现货价格 float
near_symbol 临近交割合约 string
near_price 临近交割合约结算价 float
dom_symbol 主力合约 string
dom_price 主力合约结算价 float
near_basis 临近交割合约相对现货的基差 float
dom_basis 主力合约相对现货的基差 float
near_basis_rate 临近交割合约相对现货的基差率 float
dom_basis_rate 主力合约相对现货的基差率 float
date 日期 string YYYYMMDD
|
指定交易日大宗商品现货价格及相应基差
http://www.100ppi.com/sf/day-2017-09-12.html
:param date: 开始日期 format: YYYY-MM-DD 或 YYYYMMDD 或 datetime.date 对象; 为空时为当天
:param vars_list: 合约品种如 RB、AL 等列表 为空时为所有商品
:return: pandas.DataFrame
展期收益率数据:
var 商品品种 string
sp 现货价格 float
near_symbol 临近交割合约 string
near_price 临近交割合约结算价 float
dom_symbol 主力合约 string
dom_price 主力合约结算价 float
near_basis 临近交割合约相对现货的基差 float
dom_basis 主力合约相对现货的基差 float
near_basis_rate 临近交割合约相对现货的基差率 float
dom_basis_rate 主力合约相对现货的基差率 float
date 日期 string YYYYMMDD
| 77 | 129 |
def futures_spot_price(date: str = "20210201", vars_list: list = cons.contract_symbols) -> pd.DataFrame:
"""
指定交易日大宗商品现货价格及相应基差
http://www.100ppi.com/sf/day-2017-09-12.html
:param date: 开始日期 format: YYYY-MM-DD 或 YYYYMMDD 或 datetime.date 对象; 为空时为当天
:param vars_list: 合约品种如 RB、AL 等列表 为空时为所有商品
:return: pandas.DataFrame
展期收益率数据:
var 商品品种 string
sp 现货价格 float
near_symbol 临近交割合约 string
near_price 临近交割合约结算价 float
dom_symbol 主力合约 string
dom_price 主力合约结算价 float
near_basis 临近交割合约相对现货的基差 float
dom_basis 主力合约相对现货的基差 float
near_basis_rate 临近交割合约相对现货的基差率 float
dom_basis_rate 主力合约相对现货的基差率 float
date 日期 string YYYYMMDD
"""
date = cons.convert_date(date) if date is not None else datetime.date.today()
if date < datetime.date(2011, 1, 4):
raise Exception("数据源开始日期为 20110104, 请将获取数据时间点设置在 20110104 后")
if date.strftime("%Y%m%d") not in calendar:
warnings.warn(f"{date.strftime('%Y%m%d')}非交易日")
return
u1 = cons.SYS_SPOT_PRICE_LATEST_URL
u2 = cons.SYS_SPOT_PRICE_URL.format(date.strftime("%Y-%m-%d"))
i = 1
while True:
for url in [u2, u1]:
try:
# url = u2
r = pandas_read_html_link(url)
string = r[0].loc[1, 1]
news = "".join(re.findall(r"[0-9]", string))
if news[3:11] == date.strftime("%Y%m%d"):
records = _check_information(r[1], date)
records.index = records["symbol"]
var_list_in_market = [i for i in vars_list if i in records.index]
temp_df = records.loc[var_list_in_market, :]
temp_df.reset_index(drop=True, inplace=True)
return temp_df
else:
time.sleep(3)
except:
print(f"{date.strftime('%Y-%m-%d')}日生意社数据连接失败,第{str(i)}次尝试,最多5次")
i += 1
if i > 5:
print(
f"{date.strftime('%Y-%m-%d')}日生意社数据连接失败, 如果当前交易日是 2018-09-12, 由于生意社源数据缺失, 无法访问, 否则为重复访问已超过5次,您的地址被网站墙了,请保存好返回数据,稍后从该日期起重试"
)
return False
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_basis.py#L77-L129
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19
] | 37.735849 |
[
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
44,
45,
46,
47,
48,
49,
52
] | 54.716981 | false | 13.6 | 53 | 9 | 45.283019 | 17 |
def futures_spot_price(date: str = "20210201", vars_list: list = cons.contract_symbols) -> pd.DataFrame:
date = cons.convert_date(date) if date is not None else datetime.date.today()
if date < datetime.date(2011, 1, 4):
raise Exception("数据源开始日期为 20110104, 请将获取数据时间点设置在 20110104 后")
if date.strftime("%Y%m%d") not in calendar:
warnings.warn(f"{date.strftime('%Y%m%d')}非交易日")
return
u1 = cons.SYS_SPOT_PRICE_LATEST_URL
u2 = cons.SYS_SPOT_PRICE_URL.format(date.strftime("%Y-%m-%d"))
i = 1
while True:
for url in [u2, u1]:
try:
# url = u2
r = pandas_read_html_link(url)
string = r[0].loc[1, 1]
news = "".join(re.findall(r"[0-9]", string))
if news[3:11] == date.strftime("%Y%m%d"):
records = _check_information(r[1], date)
records.index = records["symbol"]
var_list_in_market = [i for i in vars_list if i in records.index]
temp_df = records.loc[var_list_in_market, :]
temp_df.reset_index(drop=True, inplace=True)
return temp_df
else:
time.sleep(3)
except:
print(f"{date.strftime('%Y-%m-%d')}日生意社数据连接失败,第{str(i)}次尝试,最多5次")
i += 1
if i > 5:
print(
f"{date.strftime('%Y-%m-%d')}日生意社数据连接失败, 如果当前交易日是 2018-09-12, 由于生意社源数据缺失, 无法访问, 否则为重复访问已超过5次,您的地址被网站墙了,请保存好返回数据,稍后从该日期起重试"
)
return False
| 18,158 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_basis.py
|
_check_information
|
(df_data, date)
|
return records
|
数据验证和计算模块
:param df_data: pandas.DataFrame 采集的数据
:param date: datetime.date 具体某一天 YYYYMMDD
:return: pandas.DataFrame
中间数据
symbol spot_price near_contract ... near_basis_rate dom_basis_rate date
CU 49620.00 cu1811 ... -0.002418 -0.003426 20181108
RB 4551.54 rb1811 ... -0.013521 -0.134359 20181108
ZN 22420.00 zn1811 ... -0.032114 -0.076271 20181108
AL 13900.00 al1812 ... 0.005396 0.003957 20181108
AU 274.10 au1811 ... 0.005655 0.020430 20181108
WR 4806.25 wr1903 ... -0.180026 -0.237035 20181108
RU 10438.89 ru1811 ... -0.020969 0.084406 20181108
PB 18600.00 pb1811 ... -0.001344 -0.010215 20181108
AG 3542.67 ag1811 ... -0.000754 0.009408 20181108
BU 4045.53 bu1811 ... -0.129904 -0.149679 20181108
HC 4043.33 hc1811 ... -0.035449 -0.088128 20...
|
数据验证和计算模块
:param df_data: pandas.DataFrame 采集的数据
:param date: datetime.date 具体某一天 YYYYMMDD
:return: pandas.DataFrame
中间数据
symbol spot_price near_contract ... near_basis_rate dom_basis_rate date
CU 49620.00 cu1811 ... -0.002418 -0.003426 20181108
RB 4551.54 rb1811 ... -0.013521 -0.134359 20181108
ZN 22420.00 zn1811 ... -0.032114 -0.076271 20181108
AL 13900.00 al1812 ... 0.005396 0.003957 20181108
AU 274.10 au1811 ... 0.005655 0.020430 20181108
WR 4806.25 wr1903 ... -0.180026 -0.237035 20181108
RU 10438.89 ru1811 ... -0.020969 0.084406 20181108
PB 18600.00 pb1811 ... -0.001344 -0.010215 20181108
AG 3542.67 ag1811 ... -0.000754 0.009408 20181108
BU 4045.53 bu1811 ... -0.129904 -0.149679 20181108
HC 4043.33 hc1811 ... -0.035449 -0.088128 20...
| 132 | 236 |
def _check_information(df_data, date):
"""
数据验证和计算模块
:param df_data: pandas.DataFrame 采集的数据
:param date: datetime.date 具体某一天 YYYYMMDD
:return: pandas.DataFrame
中间数据
symbol spot_price near_contract ... near_basis_rate dom_basis_rate date
CU 49620.00 cu1811 ... -0.002418 -0.003426 20181108
RB 4551.54 rb1811 ... -0.013521 -0.134359 20181108
ZN 22420.00 zn1811 ... -0.032114 -0.076271 20181108
AL 13900.00 al1812 ... 0.005396 0.003957 20181108
AU 274.10 au1811 ... 0.005655 0.020430 20181108
WR 4806.25 wr1903 ... -0.180026 -0.237035 20181108
RU 10438.89 ru1811 ... -0.020969 0.084406 20181108
PB 18600.00 pb1811 ... -0.001344 -0.010215 20181108
AG 3542.67 ag1811 ... -0.000754 0.009408 20181108
BU 4045.53 bu1811 ... -0.129904 -0.149679 20181108
HC 4043.33 hc1811 ... -0.035449 -0.088128 20...
"""
df_data = df_data.loc[:, [0, 1, 2, 3, 5, 6]]
df_data.columns = [
"symbol",
"spot_price",
"near_contract",
"near_contract_price",
"dominant_contract",
"dominant_contract_price",
]
records = pd.DataFrame()
for string in df_data["symbol"].tolist():
if string == "PTA":
news = "PTA"
else:
news = "".join(re.findall(r"[\u4e00-\u9fa5]", string))
if news != "" and news not in ["商品", "价格", "上海期货交易所", "郑州商品交易所", "大连商品交易所"]:
symbol = chinese_to_english(news)
record = pd.DataFrame(df_data[df_data["symbol"] == string])
record.loc[:, "symbol"] = symbol
record.loc[:, "spot_price"] = record.loc[:, "spot_price"].astype(float)
if (
symbol == "JD"
): # 鸡蛋现货为元/公斤, 鸡蛋期货为元/500千克, 其余元/吨(http://www.100ppi.com/sf/)
record.loc[:, "spot_price"] = float(record["spot_price"]) * 500
elif (
symbol == "FG"
): # 上表中现货单位为元/平方米, 期货单位为元/吨. 换算公式:元/平方米*80=元/吨(http://www.100ppi.com/sf/959.html)
record.loc[:, "spot_price"] = float(record["spot_price"]) * 80
records = records.append(record)
records.loc[
:, ["near_contract_price", "dominant_contract_price", "spot_price"]
] = records.loc[
:, ["near_contract_price", "dominant_contract_price", "spot_price"]
].astype(
"float"
)
records.loc[:, "near_contract"] = records["near_contract"].replace(
r"[^0-9]*(\d*)$", r"\g<1>", regex=True
)
records.loc[:, "dominant_contract"] = records["dominant_contract"].replace(
r"[^0-9]*(\d*)$", r"\g<1>", regex=True
)
records.loc[:, "near_contract"] = records["symbol"] + records.loc[
:, "near_contract"
].astype("int").astype("str")
records.loc[:, "dominant_contract"] = records["symbol"] + records.loc[
:, "dominant_contract"
].astype("int").astype("str")
records["near_contract"] = records["near_contract"].apply(
lambda x: x.lower()
if x[:-4]
in cons.market_exchange_symbols["shfe"] + cons.market_exchange_symbols["dce"]
else x
)
records.loc[:, "dominant_contract"] = records.loc[:, "dominant_contract"].apply(
lambda x: x.lower()
if x[:-4]
in cons.market_exchange_symbols["shfe"] + cons.market_exchange_symbols["dce"]
else x
)
records.loc[:, "near_contract"] = records.loc[:, "near_contract"].apply(
lambda x: x[:-4] + x[-3:]
if x[:-4] in cons.market_exchange_symbols["czce"]
else x
)
records.loc[:, "dominant_contract"] = records.loc[:, "dominant_contract"].apply(
lambda x: x[:-4] + x[-3:]
if x[:-4] in cons.market_exchange_symbols["czce"]
else x
)
records["near_basis"] = records["near_contract_price"] - records["spot_price"]
records["dom_basis"] = records["dominant_contract_price"] - records["spot_price"]
records["near_basis_rate"] = (
records["near_contract_price"] / records["spot_price"] - 1
)
records["dom_basis_rate"] = (
records["dominant_contract_price"] / records["spot_price"] - 1
)
records.loc[:, "date"] = date.strftime("%Y%m%d")
return records
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_basis.py#L132-L236
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19
] | 19.047619 |
[
20,
21,
29,
30,
31,
32,
34,
35,
36,
37,
38,
39,
40,
43,
44,
47,
48,
50,
58,
61,
65,
68,
72,
78,
84,
89,
95,
96,
97,
100,
103,
104
] | 30.47619 | false | 13.6 | 105 | 7 | 69.52381 | 17 |
def _check_information(df_data, date):
df_data = df_data.loc[:, [0, 1, 2, 3, 5, 6]]
df_data.columns = [
"symbol",
"spot_price",
"near_contract",
"near_contract_price",
"dominant_contract",
"dominant_contract_price",
]
records = pd.DataFrame()
for string in df_data["symbol"].tolist():
if string == "PTA":
news = "PTA"
else:
news = "".join(re.findall(r"[\u4e00-\u9fa5]", string))
if news != "" and news not in ["商品", "价格", "上海期货交易所", "郑州商品交易所", "大连商品交易所"]:
symbol = chinese_to_english(news)
record = pd.DataFrame(df_data[df_data["symbol"] == string])
record.loc[:, "symbol"] = symbol
record.loc[:, "spot_price"] = record.loc[:, "spot_price"].astype(float)
if (
symbol == "JD"
): # 鸡蛋现货为元/公斤, 鸡蛋期货为元/500千克, 其余元/吨(http://www.100ppi.com/sf/)
record.loc[:, "spot_price"] = float(record["spot_price"]) * 500
elif (
symbol == "FG"
): # 上表中现货单位为元/平方米, 期货单位为元/吨. 换算公式:元/平方米*80=元/吨(http://www.100ppi.com/sf/959.html)
record.loc[:, "spot_price"] = float(record["spot_price"]) * 80
records = records.append(record)
records.loc[
:, ["near_contract_price", "dominant_contract_price", "spot_price"]
] = records.loc[
:, ["near_contract_price", "dominant_contract_price", "spot_price"]
].astype(
"float"
)
records.loc[:, "near_contract"] = records["near_contract"].replace(
r"[^0-9]*(\d*)$", r"\g<1>", regex=True
)
records.loc[:, "dominant_contract"] = records["dominant_contract"].replace(
r"[^0-9]*(\d*)$", r"\g<1>", regex=True
)
records.loc[:, "near_contract"] = records["symbol"] + records.loc[
:, "near_contract"
].astype("int").astype("str")
records.loc[:, "dominant_contract"] = records["symbol"] + records.loc[
:, "dominant_contract"
].astype("int").astype("str")
records["near_contract"] = records["near_contract"].apply(
lambda x: x.lower()
if x[:-4]
in cons.market_exchange_symbols["shfe"] + cons.market_exchange_symbols["dce"]
else x
)
records.loc[:, "dominant_contract"] = records.loc[:, "dominant_contract"].apply(
lambda x: x.lower()
if x[:-4]
in cons.market_exchange_symbols["shfe"] + cons.market_exchange_symbols["dce"]
else x
)
records.loc[:, "near_contract"] = records.loc[:, "near_contract"].apply(
lambda x: x[:-4] + x[-3:]
if x[:-4] in cons.market_exchange_symbols["czce"]
else x
)
records.loc[:, "dominant_contract"] = records.loc[:, "dominant_contract"].apply(
lambda x: x[:-4] + x[-3:]
if x[:-4] in cons.market_exchange_symbols["czce"]
else x
)
records["near_basis"] = records["near_contract_price"] - records["spot_price"]
records["dom_basis"] = records["dominant_contract_price"] - records["spot_price"]
records["near_basis_rate"] = (
records["near_contract_price"] / records["spot_price"] - 1
)
records["dom_basis_rate"] = (
records["dominant_contract_price"] / records["spot_price"] - 1
)
records.loc[:, "date"] = date.strftime("%Y%m%d")
return records
| 18,159 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_basis.py
|
_join_head
|
(content: pd.DataFrame)
|
return headers
| 239 | 247 |
def _join_head(content: pd.DataFrame) -> List:
headers = []
for s1, s2 in zip(content.iloc[0], content.iloc[1]):
if s1 != s2:
s = f'{s1}{s2}'
else:
s = s1
headers.append(s)
return headers
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_basis.py#L239-L247
| 25 |
[
0
] | 11.111111 |
[
1,
2,
3,
4,
6,
7,
8
] | 77.777778 | false | 13.6 | 9 | 3 | 22.222222 | 0 |
def _join_head(content: pd.DataFrame) -> List:
headers = []
for s1, s2 in zip(content.iloc[0], content.iloc[1]):
if s1 != s2:
s = f'{s1}{s2}'
else:
s = s1
headers.append(s)
return headers
| 18,160 |
||
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_basis.py
|
futures_spot_price_previous
|
(date: str = "20220209")
|
return basis
|
具体交易日大宗商品现货价格及相应基差
http://www.100ppi.com/sf/day-2017-09-12.html
:param date: 交易日; 历史日期
:type date: str
:return: 现货价格及相应基差
:rtype: pandas.DataFrame
|
具体交易日大宗商品现货价格及相应基差
http://www.100ppi.com/sf/day-2017-09-12.html
:param date: 交易日; 历史日期
:type date: str
:return: 现货价格及相应基差
:rtype: pandas.DataFrame
| 250 | 291 |
def futures_spot_price_previous(date: str = "20220209") -> pd.DataFrame:
"""
具体交易日大宗商品现货价格及相应基差
http://www.100ppi.com/sf/day-2017-09-12.html
:param date: 交易日; 历史日期
:type date: str
:return: 现货价格及相应基差
:rtype: pandas.DataFrame
"""
date = cons.convert_date(date) if date is not None else datetime.date.today()
if date < datetime.date(2011, 1, 4):
raise Exception("数据源开始日期为 20110104, 请将获取数据时间点设置在 20110104 后")
if date.strftime("%Y%m%d") not in calendar:
warnings.warn(f"{date.strftime('%Y%m%d')}非交易日")
return
url = date.strftime('http://www.100ppi.com/sf2/day-%Y-%m-%d.html')
content = pandas_read_html_link(url)
main = content[1]
# Header
header = _join_head(main)
# Values
values = main[main[4].str.endswith('%')]
values.columns = header
# Basis
basis = pd.concat(content[2:-1])
basis.columns = ['主力合约基差', '主力合约基差(%)']
basis['商品'] = values['商品'].tolist()
basis = pd.merge(values[["商品", "现货价格", "主力合约代码", "主力合约价格"]], basis)
basis = pd.merge(basis, values[["商品", "180日内主力基差最高", "180日内主力基差最低", "180日内主力基差平均"]])
basis.columns = [
"商品",
"现货价格",
"主力合约代码",
"主力合约价格",
"主力合约基差",
"主力合约变动百分比",
"180日内主力基差最高",
"180日内主力基差最低",
"180日内主力基差平均",
]
basis['主力合约变动百分比'] = basis['主力合约变动百分比'].str.strip("%")
return basis
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_basis.py#L250-L291
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 21.428571 |
[
9,
10,
11,
12,
13,
14,
15,
16,
17,
19,
21,
22,
24,
25,
26,
27,
28,
29,
40,
41
] | 47.619048 | false | 13.6 | 42 | 3 | 52.380952 | 6 |
def futures_spot_price_previous(date: str = "20220209") -> pd.DataFrame:
date = cons.convert_date(date) if date is not None else datetime.date.today()
if date < datetime.date(2011, 1, 4):
raise Exception("数据源开始日期为 20110104, 请将获取数据时间点设置在 20110104 后")
if date.strftime("%Y%m%d") not in calendar:
warnings.warn(f"{date.strftime('%Y%m%d')}非交易日")
return
url = date.strftime('http://www.100ppi.com/sf2/day-%Y-%m-%d.html')
content = pandas_read_html_link(url)
main = content[1]
# Header
header = _join_head(main)
# Values
values = main[main[4].str.endswith('%')]
values.columns = header
# Basis
basis = pd.concat(content[2:-1])
basis.columns = ['主力合约基差', '主力合约基差(%)']
basis['商品'] = values['商品'].tolist()
basis = pd.merge(values[["商品", "现货价格", "主力合约代码", "主力合约价格"]], basis)
basis = pd.merge(basis, values[["商品", "180日内主力基差最高", "180日内主力基差最低", "180日内主力基差平均"]])
basis.columns = [
"商品",
"现货价格",
"主力合约代码",
"主力合约价格",
"主力合约基差",
"主力合约变动百分比",
"180日内主力基差最高",
"180日内主力基差最低",
"180日内主力基差平均",
]
basis['主力合约变动百分比'] = basis['主力合约变动百分比'].str.strip("%")
return basis
| 18,161 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_index_ccidx.py
|
futures_index_ccidx
|
(symbol: str = "中证商品期货指数") -> pd.DataFrame
|
return temp_df
|
中证商品指数-商品指数-日频率
http://www.ccidx.com/index.html
:param symbol: choice of {"中证商品期货指数", "中证商品期货价格指数"}
:type symbol: str
:return: 商品指数-日频率
:rtype: pandas.DataFrame
|
中证商品指数-商品指数-日频率
http://www.ccidx.com/index.html
:param symbol: choice of {"中证商品期货指数", "中证商品期货价格指数"}
:type symbol: str
:return: 商品指数-日频率
:rtype: pandas.DataFrame
| 12 | 55 |
def futures_index_ccidx(symbol: str = "中证商品期货指数") -> pd.DataFrame:
"""
中证商品指数-商品指数-日频率
http://www.ccidx.com/index.html
:param symbol: choice of {"中证商品期货指数", "中证商品期货价格指数"}
:type symbol: str
:return: 商品指数-日频率
:rtype: pandas.DataFrame
"""
futures_index_map = {
"中证商品期货指数": "100001.CCI",
"中证商品期货价格指数": "000001.CCI",
}
url = "http://www.ccidx.com/front/ajax_downZSHQ.do"
params = {"indexCode": futures_index_map[symbol]}
r = requests.get(url, params=params)
temp_df = pd.read_excel(r.content, header=1)
temp_df.columns = [
"日期",
"指数代码",
"指数中文全称",
"指数中文简称",
"指数英文全称",
"指数英文简称",
"开盘",
"最高",
"最低",
"收盘",
"结算",
"涨跌",
"涨跌幅",
]
temp_df["日期"] = pd.to_datetime(temp_df["日期"]).dt.date
temp_df["开盘"] = pd.to_numeric(temp_df["开盘"], errors="coerce")
temp_df["最高"] = pd.to_numeric(temp_df["最高"], errors="coerce")
temp_df["最低"] = pd.to_numeric(temp_df["最低"], errors="coerce")
temp_df["收盘"] = pd.to_numeric(temp_df["收盘"], errors="coerce")
temp_df["结算"] = pd.to_numeric(temp_df["结算"], errors="coerce")
temp_df["涨跌"] = pd.to_numeric(temp_df["涨跌"], errors="coerce")
temp_df["涨跌幅"] = pd.to_numeric(temp_df["涨跌幅"], errors="coerce")
temp_df.sort_values(['日期'], inplace=True)
temp_df.reset_index(inplace=True, drop=True)
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_index_ccidx.py#L12-L55
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 20.454545 |
[
9,
13,
14,
15,
16,
18,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43
] | 38.636364 | false | 15.789474 | 44 | 1 | 61.363636 | 6 |
def futures_index_ccidx(symbol: str = "中证商品期货指数") -> pd.DataFrame:
futures_index_map = {
"中证商品期货指数": "100001.CCI",
"中证商品期货价格指数": "000001.CCI",
}
url = "http://www.ccidx.com/front/ajax_downZSHQ.do"
params = {"indexCode": futures_index_map[symbol]}
r = requests.get(url, params=params)
temp_df = pd.read_excel(r.content, header=1)
temp_df.columns = [
"日期",
"指数代码",
"指数中文全称",
"指数中文简称",
"指数英文全称",
"指数英文简称",
"开盘",
"最高",
"最低",
"收盘",
"结算",
"涨跌",
"涨跌幅",
]
temp_df["日期"] = pd.to_datetime(temp_df["日期"]).dt.date
temp_df["开盘"] = pd.to_numeric(temp_df["开盘"], errors="coerce")
temp_df["最高"] = pd.to_numeric(temp_df["最高"], errors="coerce")
temp_df["最低"] = pd.to_numeric(temp_df["最低"], errors="coerce")
temp_df["收盘"] = pd.to_numeric(temp_df["收盘"], errors="coerce")
temp_df["结算"] = pd.to_numeric(temp_df["结算"], errors="coerce")
temp_df["涨跌"] = pd.to_numeric(temp_df["涨跌"], errors="coerce")
temp_df["涨跌幅"] = pd.to_numeric(temp_df["涨跌幅"], errors="coerce")
temp_df.sort_values(['日期'], inplace=True)
temp_df.reset_index(inplace=True, drop=True)
return temp_df
| 18,162 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_index_ccidx.py
|
futures_index_min_ccidx
|
(symbol: str = "中证监控油脂油料期货指数") -> pd.DataFrame:
|
return temp_df
|
中证商品指数-商品指数-分时数据
http://www.ccidx.com/index.html
:param symbol: choice of {"中证商品期货指数", "中证商品期货价格指数", "中证监控油脂油料期货指数", "中证监控软商品期货指数", "中证监控能化期货指数", "中证监控钢铁期货指数"}
:type symbol: str
:return: 商品指数-分时数据
:rtype: pandas.DataFrame
|
中证商品指数-商品指数-分时数据
http://www.ccidx.com/index.html
:param symbol: choice of {"中证商品期货指数", "中证商品期货价格指数", "中证监控油脂油料期货指数", "中证监控软商品期货指数", "中证监控能化期货指数", "中证监控钢铁期货指数"}
:type symbol: str
:return: 商品指数-分时数据
:rtype: pandas.DataFrame
| 58 | 108 |
def futures_index_min_ccidx(symbol: str = "中证监控油脂油料期货指数") -> pd.DataFrame:
"""
中证商品指数-商品指数-分时数据
http://www.ccidx.com/index.html
:param symbol: choice of {"中证商品期货指数", "中证商品期货价格指数", "中证监控油脂油料期货指数", "中证监控软商品期货指数", "中证监控能化期货指数", "中证监控钢铁期货指数"}
:type symbol: str
:return: 商品指数-分时数据
:rtype: pandas.DataFrame
"""
futures_index_map = {
"中证商品期货指数": ["100001.CCI", "0"],
"中证商品期货价格指数": ["000001.CCI", "1"],
"中证监控油脂油料期货指数": ["606005.CCI", "2"],
"中证监控软商品期货指数": ["606008.CCI", "3"],
"中证监控能化期货指数": ["606010.CCI", "4"],
"中证监控钢铁期货指数": ["606011.CCI", "5"],
}
url = "http://www.ccidx.com/cscidx/csciAction/loadTimeData"
params = {"r": "0.08644997232349438"}
payload = {
"indexCode": futures_index_map[symbol][0],
"indexType": futures_index_map[symbol][1],
"pointer": "all",
}
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Content-Length": "44",
"Connection": "keep-alive",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Host": "www.ccidx.com",
"Origin": "http://www.ccidx.com",
"Pragma": "no-cache",
"Proxy-Connection": "keep-alive",
"Referer": "http://www.ccidx.com/cscidx/quote1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
}
r = requests.post(url, params=params, data=payload, headers=headers)
data_json = r.json()
temp_df = pd.DataFrame(
[data_json["dataMap"]["axisList"], data_json["dataMap"]["lineList"]]
).T
temp_df.columns = [
"datetime",
"value",
]
temp_df["value"] = pd.to_numeric(temp_df["value"])
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_index_ccidx.py#L58-L108
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 17.647059 |
[
9,
17,
18,
19,
24,
40,
41,
42,
45,
49,
50
] | 21.568627 | false | 15.789474 | 51 | 1 | 78.431373 | 6 |
def futures_index_min_ccidx(symbol: str = "中证监控油脂油料期货指数") -> pd.DataFrame:
futures_index_map = {
"中证商品期货指数": ["100001.CCI", "0"],
"中证商品期货价格指数": ["000001.CCI", "1"],
"中证监控油脂油料期货指数": ["606005.CCI", "2"],
"中证监控软商品期货指数": ["606008.CCI", "3"],
"中证监控能化期货指数": ["606010.CCI", "4"],
"中证监控钢铁期货指数": ["606011.CCI", "5"],
}
url = "http://www.ccidx.com/cscidx/csciAction/loadTimeData"
params = {"r": "0.08644997232349438"}
payload = {
"indexCode": futures_index_map[symbol][0],
"indexType": futures_index_map[symbol][1],
"pointer": "all",
}
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Content-Length": "44",
"Connection": "keep-alive",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Host": "www.ccidx.com",
"Origin": "http://www.ccidx.com",
"Pragma": "no-cache",
"Proxy-Connection": "keep-alive",
"Referer": "http://www.ccidx.com/cscidx/quote1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
}
r = requests.post(url, params=params, data=payload, headers=headers)
data_json = r.json()
temp_df = pd.DataFrame(
[data_json["dataMap"]["axisList"], data_json["dataMap"]["lineList"]]
).T
temp_df.columns = [
"datetime",
"value",
]
temp_df["value"] = pd.to_numeric(temp_df["value"])
return temp_df
| 18,163 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_rule.py
|
futures_rule
|
(date: str = "20221027")
|
return big_df
|
国泰君安期货-交易日历数据表
https://www.gtjaqh.com/pc/calendar.html
:param date: 需要指定为交易日, 且是近期的日期
:type date: str
:return: 交易日历数据
:rtype: pandas.DataFrame
|
国泰君安期货-交易日历数据表
https://www.gtjaqh.com/pc/calendar.html
:param date: 需要指定为交易日, 且是近期的日期
:type date: str
:return: 交易日历数据
:rtype: pandas.DataFrame
| 12 | 32 |
def futures_rule(date: str = "20221027") -> pd.DataFrame:
"""
国泰君安期货-交易日历数据表
https://www.gtjaqh.com/pc/calendar.html
:param date: 需要指定为交易日, 且是近期的日期
:type date: str
:return: 交易日历数据
:rtype: pandas.DataFrame
"""
url = " https://www.gtjaqh.com/pc/calendar"
params = {"date": f"{date}"}
r = requests.get(url, params=params)
big_df = pd.read_html(r.text, header=1)[0]
big_df["交易保证金比例"] = big_df["交易保证金比例"].str.strip("%")
big_df["交易保证金比例"] = pd.to_numeric(big_df["交易保证金比例"], errors="coerce")
big_df["涨跌停板幅度"] = big_df["涨跌停板幅度"].str.strip("%")
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["最小变动价位"], errors="coerce")
big_df["限价单每笔最大下单手数"] = pd.to_numeric(big_df["限价单每笔最大下单手数"], errors="coerce")
return big_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_rule.py#L12-L32
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 42.857143 |
[
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20
] | 57.142857 | false | 26.315789 | 21 | 1 | 42.857143 | 6 |
def futures_rule(date: str = "20221027") -> pd.DataFrame:
url = " https://www.gtjaqh.com/pc/calendar"
params = {"date": f"{date}"}
r = requests.get(url, params=params)
big_df = pd.read_html(r.text, header=1)[0]
big_df["交易保证金比例"] = big_df["交易保证金比例"].str.strip("%")
big_df["交易保证金比例"] = pd.to_numeric(big_df["交易保证金比例"], errors="coerce")
big_df["涨跌停板幅度"] = big_df["涨跌停板幅度"].str.strip("%")
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["最小变动价位"], errors="coerce")
big_df["限价单每笔最大下单手数"] = pd.to_numeric(big_df["限价单每笔最大下单手数"], errors="coerce")
return big_df
| 18,164 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_foreign.py
|
futures_foreign_hist
|
(symbol: str = "ZSD")
|
return data_df
|
外盘期货-历史行情数据-日频率
http://finance.sina.com.cn/money/future/hf.html
:param symbol: futures symbol, you can get it from futures_foreign_commodity_subscribe_exchange_symbol
:type symbol: str
:return: historical data from 2010
:rtype: pandas.DataFrame
|
外盘期货-历史行情数据-日频率
http://finance.sina.com.cn/money/future/hf.html
:param symbol: futures symbol, you can get it from futures_foreign_commodity_subscribe_exchange_symbol
:type symbol: str
:return: historical data from 2010
:rtype: pandas.DataFrame
| 16 | 35 |
def futures_foreign_hist(symbol: str = "ZSD") -> pd.DataFrame:
"""
外盘期货-历史行情数据-日频率
http://finance.sina.com.cn/money/future/hf.html
:param symbol: futures symbol, you can get it from futures_foreign_commodity_subscribe_exchange_symbol
:type symbol: str
:return: historical data from 2010
:rtype: pandas.DataFrame
"""
today = f'{datetime.today().year}_{datetime.today().month}_{datetime.today().day}'
url = f"https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_S{today}=/GlobalFuturesService.getGlobalFuturesDailyKLine"
params = {
"symbol": symbol,
"_": today,
"source": "web",
}
r = requests.get(url, params=params)
data_text = r.text
data_df = pd.read_json(data_text[data_text.find("["):-2])
return data_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_foreign.py#L16-L35
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 45 |
[
9,
10,
11,
16,
17,
18,
19
] | 35 | false | 29.62963 | 20 | 1 | 65 | 6 |
def futures_foreign_hist(symbol: str = "ZSD") -> pd.DataFrame:
today = f'{datetime.today().year}_{datetime.today().month}_{datetime.today().day}'
url = f"https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_S{today}=/GlobalFuturesService.getGlobalFuturesDailyKLine"
params = {
"symbol": symbol,
"_": today,
"source": "web",
}
r = requests.get(url, params=params)
data_text = r.text
data_df = pd.read_json(data_text[data_text.find("["):-2])
return data_df
| 18,165 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_foreign.py
|
futures_foreign_detail
|
(symbol: str = "ZSD")
|
return data_df
|
foreign futures contract detail data
:param symbol: futures symbol, you can get it from hf_subscribe_exchange_symbol function
:type symbol: str
:return: contract detail
:rtype: pandas.DataFrame
|
foreign futures contract detail data
:param symbol: futures symbol, you can get it from hf_subscribe_exchange_symbol function
:type symbol: str
:return: contract detail
:rtype: pandas.DataFrame
| 38 | 51 |
def futures_foreign_detail(symbol: str = "ZSD") -> pd.DataFrame:
"""
foreign futures contract detail data
:param symbol: futures symbol, you can get it from hf_subscribe_exchange_symbol function
:type symbol: str
:return: contract detail
:rtype: pandas.DataFrame
"""
url = f"https://finance.sina.com.cn/futures/quotes/{symbol}.shtml"
r = requests.get(url)
r.encoding = "gbk"
data_text = r.text
data_df = pd.read_html(data_text)[6]
return data_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_foreign.py#L38-L51
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 57.142857 |
[
8,
9,
10,
11,
12,
13
] | 42.857143 | false | 29.62963 | 14 | 1 | 57.142857 | 5 |
def futures_foreign_detail(symbol: str = "ZSD") -> pd.DataFrame:
url = f"https://finance.sina.com.cn/futures/quotes/{symbol}.shtml"
r = requests.get(url)
r.encoding = "gbk"
data_text = r.text
data_df = pd.read_html(data_text)[6]
return data_df
| 18,166 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cons.py
|
convert_date
|
(date)
|
return None
|
transform a date string to datetime.date object
:param date, string, e.g. 2016-01-01, 20160101 or 2016/01/01
:return: object of datetime.date(such as 2016-01-01) or None
|
transform a date string to datetime.date object
:param date, string, e.g. 2016-01-01, 20160101 or 2016/01/01
:return: object of datetime.date(such as 2016-01-01) or None
| 432 | 450 |
def convert_date(date):
"""
transform a date string to datetime.date object
:param date, string, e.g. 2016-01-01, 20160101 or 2016/01/01
:return: object of datetime.date(such as 2016-01-01) or None
"""
if isinstance(date, datetime.date):
return date
elif isinstance(date, str):
match = DATE_PATTERN.match(date)
if match:
groups = match.groups()
if len(groups) == 3:
return datetime.date(
year=int(groups[0]),
month=int(groups[1]),
day=int(groups[2]),
)
return None
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cons.py#L432-L450
| 25 |
[
0,
1,
2,
3,
4,
5
] | 31.578947 |
[
6,
7,
8,
9,
10,
11,
12,
13,
18
] | 47.368421 | false | 66.129032 | 19 | 5 | 52.631579 | 3 |
def convert_date(date):
if isinstance(date, datetime.date):
return date
elif isinstance(date, str):
match = DATE_PATTERN.match(date)
if match:
groups = match.groups()
if len(groups) == 3:
return datetime.date(
year=int(groups[0]),
month=int(groups[1]),
day=int(groups[2]),
)
return None
| 18,167 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cons.py
|
get_json_path
|
(name, module_file)
|
return module_json_path
|
获取 JSON 配置文件的路径(从模块所在目录查找)
:param name: 文件名
:param module_file: filename
:return: str json_file_path
|
获取 JSON 配置文件的路径(从模块所在目录查找)
:param name: 文件名
:param module_file: filename
:return: str json_file_path
| 453 | 464 |
def get_json_path(name, module_file):
"""
获取 JSON 配置文件的路径(从模块所在目录查找)
:param name: 文件名
:param module_file: filename
:return: str json_file_path
"""
module_folder = os.path.abspath(
os.path.dirname(os.path.dirname(module_file))
)
module_json_path = os.path.join(module_folder, "file_fold", name)
return module_json_path
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cons.py#L453-L464
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 100 |
[] | 0 | true | 66.129032 | 12 | 1 | 100 | 4 |
def get_json_path(name, module_file):
module_folder = os.path.abspath(
os.path.dirname(os.path.dirname(module_file))
)
module_json_path = os.path.join(module_folder, "file_fold", name)
return module_json_path
| 18,168 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cons.py
|
get_pk_path
|
(name, module_file)
|
return module_json_path
|
获取 pickle 配置文件的路径(从模块所在目录查找)
:param name: 文件名
:param module_file: filename
:return: str json_file_path
|
获取 pickle 配置文件的路径(从模块所在目录查找)
:param name: 文件名
:param module_file: filename
:return: str json_file_path
| 467 | 478 |
def get_pk_path(name, module_file):
"""
获取 pickle 配置文件的路径(从模块所在目录查找)
:param name: 文件名
:param module_file: filename
:return: str json_file_path
"""
module_folder = os.path.abspath(
os.path.dirname(os.path.dirname(module_file))
)
module_json_path = os.path.join(module_folder, "file_fold", name)
return module_json_path
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cons.py#L467-L478
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 58.333333 |
[
7,
10,
11
] | 25 | false | 66.129032 | 12 | 1 | 75 | 4 |
def get_pk_path(name, module_file):
module_folder = os.path.abspath(
os.path.dirname(os.path.dirname(module_file))
)
module_json_path = os.path.join(module_folder, "file_fold", name)
return module_json_path
| 18,169 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cons.py
|
get_pk_data
|
(file_name)
|
return pickle.load(open(setting_file_path, "rb"))
|
获取交易日历至 2019 年结束, 这里的交易日历需要按年更新
:return: json
|
获取交易日历至 2019 年结束, 这里的交易日历需要按年更新
:return: json
| 481 | 488 |
def get_pk_data(file_name):
"""
获取交易日历至 2019 年结束, 这里的交易日历需要按年更新
:return: json
"""
setting_file_name = file_name
setting_file_path = get_pk_path(setting_file_name, __file__)
return pickle.load(open(setting_file_path, "rb"))
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cons.py#L481-L488
| 25 |
[
0,
1,
2,
3,
4
] | 62.5 |
[
5,
6,
7
] | 37.5 | false | 66.129032 | 8 | 1 | 62.5 | 2 |
def get_pk_data(file_name):
setting_file_name = file_name
setting_file_path = get_pk_path(setting_file_name, __file__)
return pickle.load(open(setting_file_path, "rb"))
| 18,170 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cons.py
|
get_calendar
|
()
|
return data_json
|
获取交易日历, 这里的交易日历需要按年更新, 主要是从新浪获取的
:return: 交易日历
:rtype: json
|
获取交易日历, 这里的交易日历需要按年更新, 主要是从新浪获取的
:return: 交易日历
:rtype: json
| 491 | 501 |
def get_calendar():
"""
获取交易日历, 这里的交易日历需要按年更新, 主要是从新浪获取的
:return: 交易日历
:rtype: json
"""
setting_file_name = "calendar.json"
setting_file_path = get_json_path(setting_file_name, __file__)
with open(setting_file_path, "r") as f:
data_json = json.load(f)
return data_json
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cons.py#L491-L501
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
] | 100 |
[] | 0 | true | 66.129032 | 11 | 2 | 100 | 3 |
def get_calendar():
setting_file_name = "calendar.json"
setting_file_path = get_json_path(setting_file_name, __file__)
with open(setting_file_path, "r") as f:
data_json = json.load(f)
return data_json
| 18,171 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/cons.py
|
last_trading_day
|
(day)
|
获取前一个交易日
:param day: "%Y%m%d" or datetime.date()
:return last_day: "%Y%m%d" or datetime.date()
|
获取前一个交易日
:param day: "%Y%m%d" or datetime.date()
:return last_day: "%Y%m%d" or datetime.date()
| 504 | 528 |
def last_trading_day(day):
"""
获取前一个交易日
:param day: "%Y%m%d" or datetime.date()
:return last_day: "%Y%m%d" or datetime.date()
"""
calendar = get_calendar()
if isinstance(day, str):
if day not in calendar:
print("Today is not trading day:" + day)
return False
pos = calendar.index(day)
last_day = calendar[pos - 1]
return last_day
elif isinstance(day, datetime.date):
d_str = day.strftime("%Y%m%d")
if d_str not in calendar:
print("Today is not working day:" + d_str)
return False
pos = calendar.index(d_str)
last_day = calendar[pos - 1]
last_day = datetime.datetime.strptime(last_day, "%Y%m%d").date()
return last_day
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/cons.py#L504-L528
| 25 |
[
0,
1,
2,
3,
4,
5
] | 24 |
[
6,
8,
9,
10,
11,
12,
13,
14,
16,
17,
18,
19,
20,
21,
22,
23,
24
] | 68 | false | 66.129032 | 25 | 5 | 32 | 3 |
def last_trading_day(day):
calendar = get_calendar()
if isinstance(day, str):
if day not in calendar:
print("Today is not trading day:" + day)
return False
pos = calendar.index(day)
last_day = calendar[pos - 1]
return last_day
elif isinstance(day, datetime.date):
d_str = day.strftime("%Y%m%d")
if d_str not in calendar:
print("Today is not working day:" + d_str)
return False
pos = calendar.index(d_str)
last_day = calendar[pos - 1]
last_day = datetime.datetime.strptime(last_day, "%Y%m%d").date()
return last_day
| 18,172 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/requests_fun.py
|
requests_link
|
(url: str, encoding: str = "utf-8", method: str = "get", data: Dict = None, headers: Dict = None)
|
利用 requests 请求网站, 爬取网站内容, 如网站链接失败, 可重复爬取 20 次
:param url: string 网站地址
:param encoding: string 编码类型: "utf-8", "gbk", "gb2312"
:param method: string 访问方法: "get", "post"
:param data: dict 上传数据: 键值对
:param headers: dict 游览器请求头: 键值对
:return: requests.response 爬取返回内容: response
|
利用 requests 请求网站, 爬取网站内容, 如网站链接失败, 可重复爬取 20 次
:param url: string 网站地址
:param encoding: string 编码类型: "utf-8", "gbk", "gb2312"
:param method: string 访问方法: "get", "post"
:param data: dict 上传数据: 键值对
:param headers: dict 游览器请求头: 键值对
:return: requests.response 爬取返回内容: response
| 14 | 42 |
def requests_link(url: str, encoding: str = "utf-8", method: str = "get", data: Dict = None, headers: Dict = None):
"""
利用 requests 请求网站, 爬取网站内容, 如网站链接失败, 可重复爬取 20 次
:param url: string 网站地址
:param encoding: string 编码类型: "utf-8", "gbk", "gb2312"
:param method: string 访问方法: "get", "post"
:param data: dict 上传数据: 键值对
:param headers: dict 游览器请求头: 键值对
:return: requests.response 爬取返回内容: response
"""
i = 0
while True:
try:
if method == "get":
r = requests.get(url, timeout=20)
r.encoding = encoding
return r
elif method == "post":
r = requests.post(url, timeout=20, data=data, headers=headers)
r.encoding = encoding
return r
else:
raise ValueError("请提供正确的请求方式")
except:
i += 1
print(f"第{str(i)}次链接失败, 最多尝试 20 次")
time.sleep(5)
if i > 20:
return None
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/requests_fun.py#L14-L42
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 34.482759 |
[
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
22,
23,
24,
25,
26,
27,
28
] | 62.068966 | false | 15.555556 | 29 | 6 | 37.931034 | 7 |
def requests_link(url: str, encoding: str = "utf-8", method: str = "get", data: Dict = None, headers: Dict = None):
i = 0
while True:
try:
if method == "get":
r = requests.get(url, timeout=20)
r.encoding = encoding
return r
elif method == "post":
r = requests.post(url, timeout=20, data=data, headers=headers)
r.encoding = encoding
return r
else:
raise ValueError("请提供正确的请求方式")
except:
i += 1
print(f"第{str(i)}次链接失败, 最多尝试 20 次")
time.sleep(5)
if i > 20:
return None
| 18,173 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/requests_fun.py
|
pandas_read_html_link
|
(url: str, encoding: str = "utf-8", method: str = "get", data: Dict = None, headers: Dict = None)
|
利用 pandas 提供的 read_html 函数来直接提取网页中的表格内容, 如网站链接失败, 可重复爬取 20 次
:param url: string 网站地址
:param encoding: string 编码类型: "utf-8", "gbk", "gb2312"
:param method: string 访问方法: "get", "post"
:param data: dict 上传数据: 键值对
:param headers: dict 游览器请求头: 键值对
:return: requests.response 爬取返回内容: response
|
利用 pandas 提供的 read_html 函数来直接提取网页中的表格内容, 如网站链接失败, 可重复爬取 20 次
:param url: string 网站地址
:param encoding: string 编码类型: "utf-8", "gbk", "gb2312"
:param method: string 访问方法: "get", "post"
:param data: dict 上传数据: 键值对
:param headers: dict 游览器请求头: 键值对
:return: requests.response 爬取返回内容: response
| 45 | 75 |
def pandas_read_html_link(url: str, encoding: str = "utf-8", method: str = "get", data: Dict = None, headers: Dict = None):
"""
利用 pandas 提供的 read_html 函数来直接提取网页中的表格内容, 如网站链接失败, 可重复爬取 20 次
:param url: string 网站地址
:param encoding: string 编码类型: "utf-8", "gbk", "gb2312"
:param method: string 访问方法: "get", "post"
:param data: dict 上传数据: 键值对
:param headers: dict 游览器请求头: 键值对
:return: requests.response 爬取返回内容: response
"""
i = 0
while True:
try:
if method == "get":
r = requests.get(url, timeout=20)
r.encoding = encoding
r = pd.read_html(r.text, encoding=encoding)
return r
elif method == "post":
r = requests.post(url, timeout=20, data=data, headers=headers)
r.encoding = encoding
r = pd.read_html(r.text, encoding=encoding)
return r
else:
raise ValueError("请提供正确的请求方式")
except requests.exceptions.Timeout as e:
i += 1
print(f"第{str(i)}次链接失败, 最多尝试20次", e)
time.sleep(5)
if i > 20:
return None
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/requests_fun.py#L45-L75
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 32.258065 |
[
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
24,
25,
26,
27,
28,
29,
30
] | 64.516129 | false | 15.555556 | 31 | 6 | 35.483871 | 7 |
def pandas_read_html_link(url: str, encoding: str = "utf-8", method: str = "get", data: Dict = None, headers: Dict = None):
i = 0
while True:
try:
if method == "get":
r = requests.get(url, timeout=20)
r.encoding = encoding
r = pd.read_html(r.text, encoding=encoding)
return r
elif method == "post":
r = requests.post(url, timeout=20, data=data, headers=headers)
r.encoding = encoding
r = pd.read_html(r.text, encoding=encoding)
return r
else:
raise ValueError("请提供正确的请求方式")
except requests.exceptions.Timeout as e:
i += 1
print(f"第{str(i)}次链接失败, 最多尝试20次", e)
time.sleep(5)
if i > 20:
return None
| 18,174 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_contract_detail.py
|
futures_contract_detail
|
(symbol: str = 'AP2101')
|
return temp_df
|
查询期货合约详情
https://finance.sina.com.cn/futures/quotes/V2101.shtml
:param symbol: 合约
:type symbol: str
:return: 期货合约详情
:rtype: pandas.DataFrame
|
查询期货合约详情
https://finance.sina.com.cn/futures/quotes/V2101.shtml
:param symbol: 合约
:type symbol: str
:return: 期货合约详情
:rtype: pandas.DataFrame
| 12 | 32 |
def futures_contract_detail(symbol: str = 'AP2101') -> pd.DataFrame:
"""
查询期货合约详情
https://finance.sina.com.cn/futures/quotes/V2101.shtml
:param symbol: 合约
:type symbol: str
:return: 期货合约详情
:rtype: pandas.DataFrame
"""
url = f"https://finance.sina.com.cn/futures/quotes/{symbol}.shtml"
r = requests.get(url)
r.encoding = 'gb2312'
temp_df = pd.read_html(r.text)[6]
data_one = temp_df.iloc[:, :2]
data_one.columns = ['item', 'value']
data_two = temp_df.iloc[:, 2:4]
data_two.columns = ['item', 'value']
data_three = temp_df.iloc[:, 4:]
data_three.columns = ['item', 'value']
temp_df = pd.concat([data_one, data_two, data_three], axis=0, ignore_index=True)
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_contract_detail.py#L12-L32
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 42.857143 |
[
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20
] | 57.142857 | false | 26.315789 | 21 | 1 | 42.857143 | 6 |
def futures_contract_detail(symbol: str = 'AP2101') -> pd.DataFrame:
url = f"https://finance.sina.com.cn/futures/quotes/{symbol}.shtml"
r = requests.get(url)
r.encoding = 'gb2312'
temp_df = pd.read_html(r.text)[6]
data_one = temp_df.iloc[:, :2]
data_one.columns = ['item', 'value']
data_two = temp_df.iloc[:, 2:4]
data_two.columns = ['item', 'value']
data_three = temp_df.iloc[:, 4:]
data_three.columns = ['item', 'value']
temp_df = pd.concat([data_one, data_two, data_three], axis=0, ignore_index=True)
return temp_df
| 18,175 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_zh_sina.py
|
futures_symbol_mark
|
()
|
return temp_df
|
期货的品种和代码映射
http://vip.stock.finance.sina.com.cn/quotes_service/view/js/qihuohangqing.js
:return: 期货的品种和代码映射
:rtype: pandas.DataFrame
|
期货的品种和代码映射
http://vip.stock.finance.sina.com.cn/quotes_service/view/js/qihuohangqing.js
:return: 期货的品种和代码映射
:rtype: pandas.DataFrame
| 27 | 78 |
def futures_symbol_mark() -> pd.DataFrame:
"""
期货的品种和代码映射
http://vip.stock.finance.sina.com.cn/quotes_service/view/js/qihuohangqing.js
:return: 期货的品种和代码映射
:rtype: pandas.DataFrame
"""
url = "http://vip.stock.finance.sina.com.cn/quotes_service/view/js/qihuohangqing.js"
r = requests.get(url)
r.encoding = "gb2312"
data_text = r.text
raw_json = data_text[data_text.find("{") : data_text.find("}") + 1]
data_json = demjson.decode(raw_json)
czce_mark_list = [item[1] for item in data_json["czce"][1:]]
dce_mark_list = [item[1] for item in data_json["dce"][1:]]
shfe_mark_list = [item[1] for item in data_json["shfe"][1:]]
cffex_mark_list = [item[1] for item in data_json["cffex"][1:]]
all_mark_list = (
czce_mark_list + dce_mark_list + shfe_mark_list + cffex_mark_list
)
czce_market_name_list = [data_json["czce"][0]] * len(czce_mark_list)
dce_market_name_list = [data_json["dce"][0]] * len(dce_mark_list)
shfe_market_name_list = [data_json["shfe"][0]] * len(shfe_mark_list)
cffex_market_name_list = [data_json["cffex"][0]] * len(cffex_mark_list)
all_market_name_list = (
czce_market_name_list
+ dce_market_name_list
+ shfe_market_name_list
+ cffex_market_name_list
)
czce_symbol_list = [item[0] for item in data_json["czce"][1:]]
dce_symbol_list = [item[0] for item in data_json["dce"][1:]]
shfe_symbol_list = [item[0] for item in data_json["shfe"][1:]]
cffex_symbol_list = [item[0] for item in data_json["cffex"][1:]]
all_symbol_list = (
czce_symbol_list
+ dce_symbol_list
+ shfe_symbol_list
+ cffex_symbol_list
)
temp_df = pd.DataFrame(
[all_market_name_list, all_symbol_list, all_mark_list]
).T
temp_df.columns = [
"exchange",
"symbol",
"mark",
]
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_zh_sina.py#L27-L78
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 13.461538 |
[
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
21,
22,
23,
24,
25,
32,
33,
34,
35,
36,
43,
46,
51
] | 46.153846 | false | 8.085106 | 52 | 9 | 53.846154 | 4 |
def futures_symbol_mark() -> pd.DataFrame:
url = "http://vip.stock.finance.sina.com.cn/quotes_service/view/js/qihuohangqing.js"
r = requests.get(url)
r.encoding = "gb2312"
data_text = r.text
raw_json = data_text[data_text.find("{") : data_text.find("}") + 1]
data_json = demjson.decode(raw_json)
czce_mark_list = [item[1] for item in data_json["czce"][1:]]
dce_mark_list = [item[1] for item in data_json["dce"][1:]]
shfe_mark_list = [item[1] for item in data_json["shfe"][1:]]
cffex_mark_list = [item[1] for item in data_json["cffex"][1:]]
all_mark_list = (
czce_mark_list + dce_mark_list + shfe_mark_list + cffex_mark_list
)
czce_market_name_list = [data_json["czce"][0]] * len(czce_mark_list)
dce_market_name_list = [data_json["dce"][0]] * len(dce_mark_list)
shfe_market_name_list = [data_json["shfe"][0]] * len(shfe_mark_list)
cffex_market_name_list = [data_json["cffex"][0]] * len(cffex_mark_list)
all_market_name_list = (
czce_market_name_list
+ dce_market_name_list
+ shfe_market_name_list
+ cffex_market_name_list
)
czce_symbol_list = [item[0] for item in data_json["czce"][1:]]
dce_symbol_list = [item[0] for item in data_json["dce"][1:]]
shfe_symbol_list = [item[0] for item in data_json["shfe"][1:]]
cffex_symbol_list = [item[0] for item in data_json["cffex"][1:]]
all_symbol_list = (
czce_symbol_list
+ dce_symbol_list
+ shfe_symbol_list
+ cffex_symbol_list
)
temp_df = pd.DataFrame(
[all_market_name_list, all_symbol_list, all_mark_list]
).T
temp_df.columns = [
"exchange",
"symbol",
"mark",
]
return temp_df
| 18,176 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_zh_sina.py
|
futures_zh_realtime
|
(symbol: str = "白糖") ->
|
return temp_df
|
期货品种当前时刻所有可交易的合约实时数据
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: 品种名称;可以通过 ak.futures_symbol_mark() 获取所有品种命名表
:type symbol: str
:return: 期货品种当前时刻所有可交易的合约实时数据
:rtype: pandas.DataFrame
|
期货品种当前时刻所有可交易的合约实时数据
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: 品种名称;可以通过 ak.futures_symbol_mark() 获取所有品种命名表
:type symbol: str
:return: 期货品种当前时刻所有可交易的合约实时数据
:rtype: pandas.DataFrame
| 81 | 125 |
def futures_zh_realtime(symbol: str = "白糖") -> pd.DataFrame:
"""
期货品种当前时刻所有可交易的合约实时数据
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: 品种名称;可以通过 ak.futures_symbol_mark() 获取所有品种命名表
:type symbol: str
:return: 期货品种当前时刻所有可交易的合约实时数据
:rtype: pandas.DataFrame
"""
_futures_symbol_mark_df = futures_symbol_mark()
symbol_mark_map = dict(
zip(_futures_symbol_mark_df["symbol"], _futures_symbol_mark_df["mark"])
)
url = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQFuturesData"
params = {
"page": "1",
"sort": "position",
"asc": "0",
"node": symbol_mark_map[symbol],
"base": "futures",
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json)
temp_df["trade"] = pd.to_numeric(temp_df["trade"])
temp_df["settlement"] = pd.to_numeric(temp_df["settlement"])
temp_df["presettlement"] = pd.to_numeric(temp_df["presettlement"])
temp_df["open"] = pd.to_numeric(temp_df["open"])
temp_df["high"] = pd.to_numeric(temp_df["high"])
temp_df["low"] = pd.to_numeric(temp_df["low"])
temp_df["close"] = pd.to_numeric(temp_df["close"])
temp_df["bidprice1"] = pd.to_numeric(temp_df["bidprice1"])
temp_df["askprice1"] = pd.to_numeric(temp_df["askprice1"])
temp_df["bidvol1"] = pd.to_numeric(temp_df["bidvol1"])
temp_df["askvol1"] = pd.to_numeric(temp_df["askvol1"])
temp_df["volume"] = pd.to_numeric(temp_df["volume"])
temp_df["position"] = pd.to_numeric(temp_df["position"])
temp_df["preclose"] = pd.to_numeric(temp_df["preclose"])
temp_df["changepercent"] = pd.to_numeric(temp_df["changepercent"])
temp_df["bid"] = pd.to_numeric(temp_df["bid"])
temp_df["ask"] = pd.to_numeric(temp_df["ask"])
temp_df["prevsettlement"] = pd.to_numeric(temp_df["prevsettlement"])
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_zh_sina.py#L81-L125
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 20 |
[
9,
10,
13,
14,
21,
22,
23,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
44
] | 57.777778 | false | 8.085106 | 45 | 1 | 42.222222 | 6 |
def futures_zh_realtime(symbol: str = "白糖") -> pd.DataFrame:
_futures_symbol_mark_df = futures_symbol_mark()
symbol_mark_map = dict(
zip(_futures_symbol_mark_df["symbol"], _futures_symbol_mark_df["mark"])
)
url = "http://vip.stock.finance.sina.com.cn/quotes_service/api/json_v2.php/Market_Center.getHQFuturesData"
params = {
"page": "1",
"sort": "position",
"asc": "0",
"node": symbol_mark_map[symbol],
"base": "futures",
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json)
temp_df["trade"] = pd.to_numeric(temp_df["trade"])
temp_df["settlement"] = pd.to_numeric(temp_df["settlement"])
temp_df["presettlement"] = pd.to_numeric(temp_df["presettlement"])
temp_df["open"] = pd.to_numeric(temp_df["open"])
temp_df["high"] = pd.to_numeric(temp_df["high"])
temp_df["low"] = pd.to_numeric(temp_df["low"])
temp_df["close"] = pd.to_numeric(temp_df["close"])
temp_df["bidprice1"] = pd.to_numeric(temp_df["bidprice1"])
temp_df["askprice1"] = pd.to_numeric(temp_df["askprice1"])
temp_df["bidvol1"] = pd.to_numeric(temp_df["bidvol1"])
temp_df["askvol1"] = pd.to_numeric(temp_df["askvol1"])
temp_df["volume"] = pd.to_numeric(temp_df["volume"])
temp_df["position"] = pd.to_numeric(temp_df["position"])
temp_df["preclose"] = pd.to_numeric(temp_df["preclose"])
temp_df["changepercent"] = pd.to_numeric(temp_df["changepercent"])
temp_df["bid"] = pd.to_numeric(temp_df["bid"])
temp_df["ask"] = pd.to_numeric(temp_df["ask"])
temp_df["prevsettlement"] = pd.to_numeric(temp_df["prevsettlement"])
return temp_df
| 18,177 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_zh_sina.py
|
zh_subscribe_exchange_symbol
|
(symbol: str = "dce")
|
交易所具体的可交易品种
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: choice of {'czce', 'dce', 'shfe', 'cffex'}
:type symbol: str
:return: 交易所具体的可交易品种
:rtype: dict
|
交易所具体的可交易品种
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: choice of {'czce', 'dce', 'shfe', 'cffex'}
:type symbol: str
:return: 交易所具体的可交易品种
:rtype: dict
| 128 | 154 |
def zh_subscribe_exchange_symbol(symbol: str = "dce") -> dict:
"""
交易所具体的可交易品种
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: choice of {'czce', 'dce', 'shfe', 'cffex'}
:type symbol: str
:return: 交易所具体的可交易品种
:rtype: dict
"""
r = requests.get(zh_subscribe_exchange_symbol_url)
r.encoding = "gbk"
data_text = r.text
data_json = demjson.decode(
data_text[data_text.find("{") : data_text.find("};") + 1]
)
if symbol == "czce":
data_json["czce"].remove("郑州商品交易所")
return pd.DataFrame(data_json["czce"])
if symbol == "dce":
data_json["dce"].remove("大连商品交易所")
return pd.DataFrame(data_json["dce"])
if symbol == "shfe":
data_json["shfe"].remove("上海期货交易所")
return pd.DataFrame(data_json["shfe"])
if symbol == "cffex":
data_json["cffex"].remove("中国金融期货交易所")
return pd.DataFrame(data_json["cffex"])
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_zh_sina.py#L128-L154
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 33.333333 |
[
9,
10,
11,
12,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26
] | 59.259259 | false | 8.085106 | 27 | 5 | 40.740741 | 6 |
def zh_subscribe_exchange_symbol(symbol: str = "dce") -> dict:
r = requests.get(zh_subscribe_exchange_symbol_url)
r.encoding = "gbk"
data_text = r.text
data_json = demjson.decode(
data_text[data_text.find("{") : data_text.find("};") + 1]
)
if symbol == "czce":
data_json["czce"].remove("郑州商品交易所")
return pd.DataFrame(data_json["czce"])
if symbol == "dce":
data_json["dce"].remove("大连商品交易所")
return pd.DataFrame(data_json["dce"])
if symbol == "shfe":
data_json["shfe"].remove("上海期货交易所")
return pd.DataFrame(data_json["shfe"])
if symbol == "cffex":
data_json["cffex"].remove("中国金融期货交易所")
return pd.DataFrame(data_json["cffex"])
| 18,178 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_zh_sina.py
|
match_main_contract
|
(symbol: str = "cffex")
|
return ",".join([item for item in subscribe_exchange_list])
|
新浪财经-期货-主力合约
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: choice of {'czce', 'dce', 'shfe', 'cffex'}
:type symbol: str
:return: 主力合约的字符串
:rtype: str
|
新浪财经-期货-主力合约
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: choice of {'czce', 'dce', 'shfe', 'cffex'}
:type symbol: str
:return: 主力合约的字符串
:rtype: str
| 157 | 190 |
def match_main_contract(symbol: str = "cffex") -> str:
"""
新浪财经-期货-主力合约
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: choice of {'czce', 'dce', 'shfe', 'cffex'}
:type symbol: str
:return: 主力合约的字符串
:rtype: str
"""
subscribe_exchange_list = []
exchange_symbol_list = (
zh_subscribe_exchange_symbol(symbol).iloc[:, 1].tolist()
)
for item in exchange_symbol_list:
# item = 'sngz_qh'
zh_match_main_contract_payload.update({"node": item})
res = requests.get(
zh_match_main_contract_url, params=zh_match_main_contract_payload
)
data_json = demjson.decode(res.text)
data_df = pd.DataFrame(data_json)
try:
main_contract = data_df[data_df.iloc[:, 3:].duplicated()]
print(main_contract["symbol"].values[0])
subscribe_exchange_list.append(main_contract["symbol"].values[0])
except:
if len(data_df) == 1:
subscribe_exchange_list.append(data_df["symbol"].values[0])
print(data_df["symbol"].values[0])
else:
print(item, "无主力合约")
continue
print(f"{symbol}主力合约获取成功")
return ",".join([item for item in subscribe_exchange_list])
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_zh_sina.py#L157-L190
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 26.470588 |
[
9,
10,
13,
15,
16,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
30,
31,
32,
33
] | 55.882353 | false | 8.085106 | 34 | 5 | 44.117647 | 6 |
def match_main_contract(symbol: str = "cffex") -> str:
subscribe_exchange_list = []
exchange_symbol_list = (
zh_subscribe_exchange_symbol(symbol).iloc[:, 1].tolist()
)
for item in exchange_symbol_list:
# item = 'sngz_qh'
zh_match_main_contract_payload.update({"node": item})
res = requests.get(
zh_match_main_contract_url, params=zh_match_main_contract_payload
)
data_json = demjson.decode(res.text)
data_df = pd.DataFrame(data_json)
try:
main_contract = data_df[data_df.iloc[:, 3:].duplicated()]
print(main_contract["symbol"].values[0])
subscribe_exchange_list.append(main_contract["symbol"].values[0])
except:
if len(data_df) == 1:
subscribe_exchange_list.append(data_df["symbol"].values[0])
print(data_df["symbol"].values[0])
else:
print(item, "无主力合约")
continue
print(f"{symbol}主力合约获取成功")
return ",".join([item for item in subscribe_exchange_list])
| 18,179 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_zh_sina.py
|
futures_zh_spot
|
(
symbol: str = "V2209",
market: str = "CF",
adjust: str = "0",
)
|
期货的实时行情数据
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: 合约名称的字符串组合
:type symbol: str
:param market: CF 为商品期货
:type market: str
:param adjust: '1' or '0'; 字符串的 0 或 1
:type adjust: str
:return: 期货的实时行情数据
:rtype: pandas.DataFrame
|
期货的实时行情数据
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: 合约名称的字符串组合
:type symbol: str
:param market: CF 为商品期货
:type market: str
:param adjust: '1' or '0'; 字符串的 0 或 1
:type adjust: str
:return: 期货的实时行情数据
:rtype: pandas.DataFrame
| 193 | 599 |
def futures_zh_spot(
symbol: str = "V2209",
market: str = "CF",
adjust: str = "0",
) -> pd.DataFrame:
"""
期货的实时行情数据
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: 合约名称的字符串组合
:type symbol: str
:param market: CF 为商品期货
:type market: str
:param adjust: '1' or '0'; 字符串的 0 或 1
:type adjust: str
:return: 期货的实时行情数据
:rtype: pandas.DataFrame
"""
file_data = "Math.round(Math.random() * 2147483648).toString(16)"
ctx = py_mini_racer.MiniRacer()
rn_code = ctx.eval(file_data)
subscribe_list = ",".join(
["nf_" + item.strip() for item in symbol.split(",")]
)
url = f"https://hq.sinajs.cn/rn={rn_code}&list={subscribe_list}"
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Host": "hq.sinajs.cn",
"Pragma": "no-cache",
"Proxy-Connection": "keep-alive",
"Referer": "http://vip.stock.finance.sina.com.cn/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
}
r = requests.get(url, headers=headers)
data_df = pd.DataFrame(
[
item.strip().split("=")[1].split(",")
for item in r.text.split(";")
if item.strip() != ""
]
)
data_df.iloc[:, 0] = data_df.iloc[:, 0].str.replace('"', "")
data_df.iloc[:, -1] = data_df.iloc[:, -1].str.replace('"', "")
if adjust == "1":
contract_name_list = [
item.split("_")[1] for item in subscribe_list.split(",")
]
contract_min_list = []
contract_exchange_list = []
for contract_name in contract_name_list:
temp_df = futures_contract_detail(symbol=contract_name)
exchange_name = temp_df[temp_df["item"] == "上市交易所"][
"value"
].values[0]
contract_exchange_list.append(exchange_name)
contract_min = temp_df[temp_df["item"] == "最小变动价位"][
"value"
].values[0]
contract_min_list.append(contract_min)
if market == "CF":
data_df.columns = [
"symbol",
"time",
"open",
"high",
"low",
"last_close",
"bid_price",
"ask_price",
"current_price",
"avg_price",
"last_settle_price",
"buy_vol",
"sell_vol",
"hold",
"volume",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
]
data_df = data_df[
[
"symbol",
"time",
"open",
"high",
"low",
"current_price",
"bid_price",
"ask_price",
"buy_vol",
"sell_vol",
"hold",
"volume",
"avg_price",
"last_close",
"last_settle_price",
]
]
data_df["exchange"] = contract_exchange_list
data_df["contract"] = contract_name_list
data_df["contract_min_change"] = contract_min_list
data_df["open"] = pd.to_numeric(data_df["open"])
data_df["high"] = pd.to_numeric(data_df["high"])
data_df["low"] = pd.to_numeric(data_df["low"])
data_df["current_price"] = pd.to_numeric(data_df["current_price"])
data_df["bid_price"] = pd.to_numeric(data_df["bid_price"])
data_df["ask_price"] = pd.to_numeric(data_df["ask_price"])
data_df["buy_vol"] = pd.to_numeric(data_df["buy_vol"])
data_df["sell_vol"] = pd.to_numeric(data_df["sell_vol"])
data_df["hold"] = pd.to_numeric(data_df["hold"])
data_df["volume"] = pd.to_numeric(data_df["volume"])
data_df["avg_price"] = pd.to_numeric(data_df["avg_price"])
data_df["last_close"] = pd.to_numeric(data_df["last_close"])
data_df["last_settle_price"] = pd.to_numeric(
data_df["last_settle_price"]
)
data_df.dropna(subset=["current_price"], inplace=True)
return data_df
else:
data_df.columns = [
"open",
"high",
"low",
"current_price",
"volume",
"amount",
"hold",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_" "_",
"time",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"symbol",
]
data_df = data_df[
[
"symbol",
"time",
"open",
"high",
"low",
"current_price",
"hold",
"volume",
"amount",
]
]
data_df["exchange"] = contract_exchange_list
data_df["contract"] = contract_name_list
data_df["contract_min_change"] = contract_min_list
data_df["open"] = pd.to_numeric(data_df["open"])
data_df["high"] = pd.to_numeric(data_df["high"])
data_df["low"] = pd.to_numeric(data_df["low"])
data_df["current_price"] = pd.to_numeric(data_df["current_price"])
data_df["hold"] = pd.to_numeric(data_df["hold"])
data_df["volume"] = pd.to_numeric(data_df["volume"])
data_df["amount"] = pd.to_numeric(data_df["amount"])
data_df.dropna(subset=["current_price"], inplace=True)
return data_df
else:
if market == "CF":
# 此处由于 20220601 接口变动,增加了字段,此处增加异常判断,except 后为新代码
try:
data_df.columns = [
"symbol",
"time",
"open",
"high",
"low",
"last_close",
"bid_price",
"ask_price",
"current_price",
"avg_price",
"last_settle_price",
"buy_vol",
"sell_vol",
"hold",
"volume",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
]
except:
data_df.columns = [
"symbol",
"time",
"open",
"high",
"low",
"last_close",
"bid_price",
"ask_price",
"current_price",
"avg_price",
"last_settle_price",
"buy_vol",
"sell_vol",
"hold",
"volume",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
]
data_df = data_df[
[
"symbol",
"time",
"open",
"high",
"low",
"current_price",
"bid_price",
"ask_price",
"buy_vol",
"sell_vol",
"hold",
"volume",
"avg_price",
"last_close",
"last_settle_price",
]
]
data_df["open"] = pd.to_numeric(data_df["open"])
data_df["high"] = pd.to_numeric(data_df["high"])
data_df["low"] = pd.to_numeric(data_df["low"])
data_df["current_price"] = pd.to_numeric(data_df["current_price"])
data_df["bid_price"] = pd.to_numeric(data_df["bid_price"])
data_df["ask_price"] = pd.to_numeric(data_df["ask_price"])
data_df["buy_vol"] = pd.to_numeric(data_df["buy_vol"])
data_df["sell_vol"] = pd.to_numeric(data_df["sell_vol"])
data_df["hold"] = pd.to_numeric(data_df["hold"])
data_df["volume"] = pd.to_numeric(data_df["volume"])
data_df["avg_price"] = pd.to_numeric(data_df["avg_price"])
data_df["last_close"] = pd.to_numeric(data_df["last_close"])
data_df["last_settle_price"] = pd.to_numeric(
data_df["last_settle_price"]
)
data_df.dropna(subset=["current_price"], inplace=True)
return data_df
else:
data_df.columns = [
"open",
"high",
"low",
"current_price",
"volume",
"amount",
"hold",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_" "_",
"time",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"symbol",
]
data_df = data_df[
[
"symbol",
"time",
"open",
"high",
"low",
"current_price",
"hold",
"volume",
"amount",
]
]
data_df["open"] = pd.to_numeric(data_df["open"])
data_df["high"] = pd.to_numeric(data_df["high"])
data_df["low"] = pd.to_numeric(data_df["low"])
data_df["current_price"] = pd.to_numeric(data_df["current_price"])
data_df["hold"] = pd.to_numeric(data_df["hold"])
data_df["volume"] = pd.to_numeric(data_df["volume"])
data_df["amount"] = pd.to_numeric(data_df["amount"])
data_df.dropna(subset=["current_price"], inplace=True)
return data_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_zh_sina.py#L193-L599
| 25 |
[
0
] | 0.2457 |
[
17,
18,
19,
20,
23,
24,
35,
36,
43,
44,
45,
46,
49,
50,
51,
52,
53,
56,
57,
60,
61,
62,
92,
111,
112,
113,
115,
116,
117,
118,
119,
120,
121,
122,
123,
124,
125,
126,
127,
130,
131,
133,
185,
198,
199,
200,
202,
203,
204,
205,
206,
207,
208,
210,
211,
213,
215,
216,
246,
247,
293,
313,
314,
315,
316,
317,
318,
319,
320,
321,
322,
323,
324,
325,
329,
330,
332,
384,
397,
398,
399,
400,
401,
402,
403,
405,
406
] | 21.375921 | false | 8.085106 | 407 | 9 | 78.624079 | 10 |
def futures_zh_spot(
symbol: str = "V2209",
market: str = "CF",
adjust: str = "0",
) -> pd.DataFrame:
file_data = "Math.round(Math.random() * 2147483648).toString(16)"
ctx = py_mini_racer.MiniRacer()
rn_code = ctx.eval(file_data)
subscribe_list = ",".join(
["nf_" + item.strip() for item in symbol.split(",")]
)
url = f"https://hq.sinajs.cn/rn={rn_code}&list={subscribe_list}"
headers = {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Host": "hq.sinajs.cn",
"Pragma": "no-cache",
"Proxy-Connection": "keep-alive",
"Referer": "http://vip.stock.finance.sina.com.cn/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36",
}
r = requests.get(url, headers=headers)
data_df = pd.DataFrame(
[
item.strip().split("=")[1].split(",")
for item in r.text.split(";")
if item.strip() != ""
]
)
data_df.iloc[:, 0] = data_df.iloc[:, 0].str.replace('"', "")
data_df.iloc[:, -1] = data_df.iloc[:, -1].str.replace('"', "")
if adjust == "1":
contract_name_list = [
item.split("_")[1] for item in subscribe_list.split(",")
]
contract_min_list = []
contract_exchange_list = []
for contract_name in contract_name_list:
temp_df = futures_contract_detail(symbol=contract_name)
exchange_name = temp_df[temp_df["item"] == "上市交易所"][
"value"
].values[0]
contract_exchange_list.append(exchange_name)
contract_min = temp_df[temp_df["item"] == "最小变动价位"][
"value"
].values[0]
contract_min_list.append(contract_min)
if market == "CF":
data_df.columns = [
"symbol",
"time",
"open",
"high",
"low",
"last_close",
"bid_price",
"ask_price",
"current_price",
"avg_price",
"last_settle_price",
"buy_vol",
"sell_vol",
"hold",
"volume",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
]
data_df = data_df[
[
"symbol",
"time",
"open",
"high",
"low",
"current_price",
"bid_price",
"ask_price",
"buy_vol",
"sell_vol",
"hold",
"volume",
"avg_price",
"last_close",
"last_settle_price",
]
]
data_df["exchange"] = contract_exchange_list
data_df["contract"] = contract_name_list
data_df["contract_min_change"] = contract_min_list
data_df["open"] = pd.to_numeric(data_df["open"])
data_df["high"] = pd.to_numeric(data_df["high"])
data_df["low"] = pd.to_numeric(data_df["low"])
data_df["current_price"] = pd.to_numeric(data_df["current_price"])
data_df["bid_price"] = pd.to_numeric(data_df["bid_price"])
data_df["ask_price"] = pd.to_numeric(data_df["ask_price"])
data_df["buy_vol"] = pd.to_numeric(data_df["buy_vol"])
data_df["sell_vol"] = pd.to_numeric(data_df["sell_vol"])
data_df["hold"] = pd.to_numeric(data_df["hold"])
data_df["volume"] = pd.to_numeric(data_df["volume"])
data_df["avg_price"] = pd.to_numeric(data_df["avg_price"])
data_df["last_close"] = pd.to_numeric(data_df["last_close"])
data_df["last_settle_price"] = pd.to_numeric(
data_df["last_settle_price"]
)
data_df.dropna(subset=["current_price"], inplace=True)
return data_df
else:
data_df.columns = [
"open",
"high",
"low",
"current_price",
"volume",
"amount",
"hold",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_" "_",
"time",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"symbol",
]
data_df = data_df[
[
"symbol",
"time",
"open",
"high",
"low",
"current_price",
"hold",
"volume",
"amount",
]
]
data_df["exchange"] = contract_exchange_list
data_df["contract"] = contract_name_list
data_df["contract_min_change"] = contract_min_list
data_df["open"] = pd.to_numeric(data_df["open"])
data_df["high"] = pd.to_numeric(data_df["high"])
data_df["low"] = pd.to_numeric(data_df["low"])
data_df["current_price"] = pd.to_numeric(data_df["current_price"])
data_df["hold"] = pd.to_numeric(data_df["hold"])
data_df["volume"] = pd.to_numeric(data_df["volume"])
data_df["amount"] = pd.to_numeric(data_df["amount"])
data_df.dropna(subset=["current_price"], inplace=True)
return data_df
else:
if market == "CF":
# 此处由于 20220601 接口变动,增加了字段,此处增加异常判断,except 后为新代码
try:
data_df.columns = [
"symbol",
"time",
"open",
"high",
"low",
"last_close",
"bid_price",
"ask_price",
"current_price",
"avg_price",
"last_settle_price",
"buy_vol",
"sell_vol",
"hold",
"volume",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
]
except:
data_df.columns = [
"symbol",
"time",
"open",
"high",
"low",
"last_close",
"bid_price",
"ask_price",
"current_price",
"avg_price",
"last_settle_price",
"buy_vol",
"sell_vol",
"hold",
"volume",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
]
data_df = data_df[
[
"symbol",
"time",
"open",
"high",
"low",
"current_price",
"bid_price",
"ask_price",
"buy_vol",
"sell_vol",
"hold",
"volume",
"avg_price",
"last_close",
"last_settle_price",
]
]
data_df["open"] = pd.to_numeric(data_df["open"])
data_df["high"] = pd.to_numeric(data_df["high"])
data_df["low"] = pd.to_numeric(data_df["low"])
data_df["current_price"] = pd.to_numeric(data_df["current_price"])
data_df["bid_price"] = pd.to_numeric(data_df["bid_price"])
data_df["ask_price"] = pd.to_numeric(data_df["ask_price"])
data_df["buy_vol"] = pd.to_numeric(data_df["buy_vol"])
data_df["sell_vol"] = pd.to_numeric(data_df["sell_vol"])
data_df["hold"] = pd.to_numeric(data_df["hold"])
data_df["volume"] = pd.to_numeric(data_df["volume"])
data_df["avg_price"] = pd.to_numeric(data_df["avg_price"])
data_df["last_close"] = pd.to_numeric(data_df["last_close"])
data_df["last_settle_price"] = pd.to_numeric(
data_df["last_settle_price"]
)
data_df.dropna(subset=["current_price"], inplace=True)
return data_df
else:
data_df.columns = [
"open",
"high",
"low",
"current_price",
"volume",
"amount",
"hold",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_" "_",
"time",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"_",
"symbol",
]
data_df = data_df[
[
"symbol",
"time",
"open",
"high",
"low",
"current_price",
"hold",
"volume",
"amount",
]
]
data_df["open"] = pd.to_numeric(data_df["open"])
data_df["high"] = pd.to_numeric(data_df["high"])
data_df["low"] = pd.to_numeric(data_df["low"])
data_df["current_price"] = pd.to_numeric(data_df["current_price"])
data_df["hold"] = pd.to_numeric(data_df["hold"])
data_df["volume"] = pd.to_numeric(data_df["volume"])
data_df["amount"] = pd.to_numeric(data_df["amount"])
data_df.dropna(subset=["current_price"], inplace=True)
return data_df
| 18,180 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_zh_sina.py
|
futures_zh_minute_sina
|
(
symbol: str = "IF2008", period: str = "5"
)
|
return temp_df
|
中国各品种期货分钟频率数据
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_3
:param symbol: 可以通过 match_main_contract(symbol="cffex") 获取, 或者访问网页获取
:type symbol: str
:param period: choice of {"1": "1分钟", "5": "5分钟", "15": "15分钟", "30": "30分钟", "60": "60分钟"}
:type period: str
:return: 指定 symbol 和 period 的数据
:rtype: pandas.DataFrame
|
中国各品种期货分钟频率数据
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_3
:param symbol: 可以通过 match_main_contract(symbol="cffex") 获取, 或者访问网页获取
:type symbol: str
:param period: choice of {"1": "1分钟", "5": "5分钟", "15": "15分钟", "30": "30分钟", "60": "60分钟"}
:type period: str
:return: 指定 symbol 和 period 的数据
:rtype: pandas.DataFrame
| 602 | 637 |
def futures_zh_minute_sina(
symbol: str = "IF2008", period: str = "5"
) -> pd.DataFrame:
"""
中国各品种期货分钟频率数据
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_3
:param symbol: 可以通过 match_main_contract(symbol="cffex") 获取, 或者访问网页获取
:type symbol: str
:param period: choice of {"1": "1分钟", "5": "5分钟", "15": "15分钟", "30": "30分钟", "60": "60分钟"}
:type period: str
:return: 指定 symbol 和 period 的数据
:rtype: pandas.DataFrame
"""
url = "https://stock2.finance.sina.com.cn/futures/api/jsonp.php/=/InnerFuturesNewService.getFewMinLine"
params = {
"symbol": symbol,
"type": period,
}
r = requests.get(url, params=params)
temp_df = pd.DataFrame(json.loads(r.text.split("=(")[1].split(");")[0]))
temp_df.columns = [
"datetime",
"open",
"high",
"low",
"close",
"volume",
"hold",
]
temp_df["open"] = pd.to_numeric(temp_df["open"])
temp_df["high"] = pd.to_numeric(temp_df["high"])
temp_df["low"] = pd.to_numeric(temp_df["low"])
temp_df["close"] = pd.to_numeric(temp_df["close"])
temp_df["volume"] = pd.to_numeric(temp_df["volume"])
temp_df["hold"] = pd.to_numeric(temp_df["hold"])
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_zh_sina.py#L602-L637
| 25 |
[
0
] | 2.777778 |
[
13,
14,
18,
19,
20,
29,
30,
31,
32,
33,
34,
35
] | 33.333333 | false | 8.085106 | 36 | 1 | 66.666667 | 8 |
def futures_zh_minute_sina(
symbol: str = "IF2008", period: str = "5"
) -> pd.DataFrame:
url = "https://stock2.finance.sina.com.cn/futures/api/jsonp.php/=/InnerFuturesNewService.getFewMinLine"
params = {
"symbol": symbol,
"type": period,
}
r = requests.get(url, params=params)
temp_df = pd.DataFrame(json.loads(r.text.split("=(")[1].split(");")[0]))
temp_df.columns = [
"datetime",
"open",
"high",
"low",
"close",
"volume",
"hold",
]
temp_df["open"] = pd.to_numeric(temp_df["open"])
temp_df["high"] = pd.to_numeric(temp_df["high"])
temp_df["low"] = pd.to_numeric(temp_df["low"])
temp_df["close"] = pd.to_numeric(temp_df["close"])
temp_df["volume"] = pd.to_numeric(temp_df["volume"])
temp_df["hold"] = pd.to_numeric(temp_df["hold"])
return temp_df
| 18,181 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_zh_sina.py
|
futures_zh_daily_sina
|
(symbol: str = "V2105")
|
return temp_df
|
中国各品种期货日频率数据
https://finance.sina.com.cn/futures/quotes/V2105.shtml
:param symbol: 可以通过 match_main_contract(symbol="cffex") 获取, 或者访问网页获取
:type symbol: str
:return: 指定 symbol 和 period 的数据
:rtype: pandas.DataFrame
|
中国各品种期货日频率数据
https://finance.sina.com.cn/futures/quotes/V2105.shtml
:param symbol: 可以通过 match_main_contract(symbol="cffex") 获取, 或者访问网页获取
:type symbol: str
:return: 指定 symbol 和 period 的数据
:rtype: pandas.DataFrame
| 640 | 674 |
def futures_zh_daily_sina(symbol: str = "V2105") -> pd.DataFrame:
"""
中国各品种期货日频率数据
https://finance.sina.com.cn/futures/quotes/V2105.shtml
:param symbol: 可以通过 match_main_contract(symbol="cffex") 获取, 或者访问网页获取
:type symbol: str
:return: 指定 symbol 和 period 的数据
:rtype: pandas.DataFrame
"""
date = "20210412"
url = "https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_V21052021_4_12=/InnerFuturesNewService.getDailyKLine"
params = {
"symbol": symbol,
"type": "_".join([date[:4], date[4:6], date[6:]]),
}
r = requests.get(url, params=params)
temp_df = pd.DataFrame(json.loads(r.text.split("=(")[1].split(");")[0]))
temp_df.columns = [
"date",
"open",
"high",
"low",
"close",
"volume",
"hold",
"settle",
]
temp_df["open"] = pd.to_numeric(temp_df["open"])
temp_df["high"] = pd.to_numeric(temp_df["high"])
temp_df["low"] = pd.to_numeric(temp_df["low"])
temp_df["close"] = pd.to_numeric(temp_df["close"])
temp_df["volume"] = pd.to_numeric(temp_df["volume"])
temp_df["hold"] = pd.to_numeric(temp_df["hold"])
temp_df["settle"] = pd.to_numeric(temp_df["settle"])
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_zh_sina.py#L640-L674
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 25.714286 |
[
9,
10,
11,
15,
16,
17,
27,
28,
29,
30,
31,
32,
33,
34
] | 40 | false | 8.085106 | 35 | 1 | 60 | 6 |
def futures_zh_daily_sina(symbol: str = "V2105") -> pd.DataFrame:
date = "20210412"
url = "https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_V21052021_4_12=/InnerFuturesNewService.getDailyKLine"
params = {
"symbol": symbol,
"type": "_".join([date[:4], date[4:6], date[6:]]),
}
r = requests.get(url, params=params)
temp_df = pd.DataFrame(json.loads(r.text.split("=(")[1].split(");")[0]))
temp_df.columns = [
"date",
"open",
"high",
"low",
"close",
"volume",
"hold",
"settle",
]
temp_df["open"] = pd.to_numeric(temp_df["open"])
temp_df["high"] = pd.to_numeric(temp_df["high"])
temp_df["low"] = pd.to_numeric(temp_df["low"])
temp_df["close"] = pd.to_numeric(temp_df["close"])
temp_df["volume"] = pd.to_numeric(temp_df["volume"])
temp_df["hold"] = pd.to_numeric(temp_df["hold"])
temp_df["settle"] = pd.to_numeric(temp_df["settle"])
return temp_df
| 18,182 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_daily_bar.py
|
_futures_daily_czce
|
(
date: str = "20100824", dataset: str = "datahistory2010"
)
|
return temp_df
|
郑州商品交易所-交易数据-历史行情下载
http://www.czce.com.cn/cn/jysj/lshqxz/H770319index_1.htm
:param date: 需要的日期
:type date: str
:param dataset: 数据集的名称; 此处只需要替换 datahistory2010 中的 2010 即可
:type dataset: str
:return: 指定日期的所有品种行情数据
:rtype: pandas.DataFrame
|
郑州商品交易所-交易数据-历史行情下载
http://www.czce.com.cn/cn/jysj/lshqxz/H770319index_1.htm
:param date: 需要的日期
:type date: str
:param dataset: 数据集的名称; 此处只需要替换 datahistory2010 中的 2010 即可
:type dataset: str
:return: 指定日期的所有品种行情数据
:rtype: pandas.DataFrame
| 22 | 105 |
def _futures_daily_czce(
date: str = "20100824", dataset: str = "datahistory2010"
) -> pd.DataFrame:
"""
郑州商品交易所-交易数据-历史行情下载
http://www.czce.com.cn/cn/jysj/lshqxz/H770319index_1.htm
:param date: 需要的日期
:type date: str
:param dataset: 数据集的名称; 此处只需要替换 datahistory2010 中的 2010 即可
:type dataset: str
:return: 指定日期的所有品种行情数据
:rtype: pandas.DataFrame
"""
url = f"http://www.czce.com.cn/cn/exchange/{dataset}.zip"
r = requests.get(url)
with zipfile.ZipFile(BytesIO(r.content)) as file:
with file.open(f"{dataset}.txt") as my_file:
data = my_file.read().decode("gb2312")
data_df = pd.read_table(StringIO(data), sep=r"|", header=1)
data_df.columns = [item.strip() for item in data_df.columns]
data_df.dropna(axis=1, inplace=True)
for column in data_df.columns:
try:
data_df[column] = data_df[column].str.strip("\t")
data_df[column] = data_df[column].str.replace(",", "")
except:
data_df[column] = data_df[column]
data_df["昨结算"] = pd.to_numeric(data_df["昨结算"])
data_df["今开盘"] = pd.to_numeric(data_df["今开盘"])
data_df["最高价"] = pd.to_numeric(data_df["最高价"])
data_df["最低价"] = pd.to_numeric(data_df["最低价"])
data_df["今收盘"] = pd.to_numeric(data_df["今收盘"])
data_df["今结算"] = pd.to_numeric(data_df["今结算"])
data_df["涨跌1"] = pd.to_numeric(data_df["涨跌1"])
data_df["涨跌2"] = pd.to_numeric(data_df["涨跌2"])
data_df["成交量(手)"] = pd.to_numeric(data_df["成交量(手)"])
data_df["空盘量"] = pd.to_numeric(data_df["空盘量"])
data_df["增减量"] = pd.to_numeric(data_df["增减量"])
data_df["成交额(万元)"] = pd.to_numeric(data_df["成交额(万元)"])
data_df["交割结算价"] = pd.to_numeric(data_df["交割结算价"])
data_df["交易日期"] = pd.to_datetime(data_df["交易日期"])
data_df.columns = [
"date",
"symbol",
"pre_settle",
"open",
"high",
"low",
"close",
"settle",
"-",
"-",
"volume",
"open_interest",
"-",
"turnover",
"-",
]
variety_list = [
re.compile(r"[a-zA-Z_]+").findall(item)[0]
for item in data_df["symbol"]
]
data_df["variety"] = variety_list
data_df = data_df[
[
"symbol",
"date",
"open",
"high",
"low",
"close",
"volume",
"open_interest",
"turnover",
"settle",
"pre_settle",
"variety",
]
]
temp_df = data_df[data_df["date"] == pd.Timestamp(date)].copy()
temp_df["date"] = date
temp_df.reset_index(inplace=True, drop=True)
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_daily_bar.py#L22-L105
| 25 |
[
0
] | 1.190476 |
[
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
59,
63,
64,
80,
81,
82,
83
] | 42.857143 | false | 6.64557 | 84 | 7 | 57.142857 | 8 |
def _futures_daily_czce(
date: str = "20100824", dataset: str = "datahistory2010"
) -> pd.DataFrame:
url = f"http://www.czce.com.cn/cn/exchange/{dataset}.zip"
r = requests.get(url)
with zipfile.ZipFile(BytesIO(r.content)) as file:
with file.open(f"{dataset}.txt") as my_file:
data = my_file.read().decode("gb2312")
data_df = pd.read_table(StringIO(data), sep=r"|", header=1)
data_df.columns = [item.strip() for item in data_df.columns]
data_df.dropna(axis=1, inplace=True)
for column in data_df.columns:
try:
data_df[column] = data_df[column].str.strip("\t")
data_df[column] = data_df[column].str.replace(",", "")
except:
data_df[column] = data_df[column]
data_df["昨结算"] = pd.to_numeric(data_df["昨结算"])
data_df["今开盘"] = pd.to_numeric(data_df["今开盘"])
data_df["最高价"] = pd.to_numeric(data_df["最高价"])
data_df["最低价"] = pd.to_numeric(data_df["最低价"])
data_df["今收盘"] = pd.to_numeric(data_df["今收盘"])
data_df["今结算"] = pd.to_numeric(data_df["今结算"])
data_df["涨跌1"] = pd.to_numeric(data_df["涨跌1"])
data_df["涨跌2"] = pd.to_numeric(data_df["涨跌2"])
data_df["成交量(手)"] = pd.to_numeric(data_df["成交量(手)"])
data_df["空盘量"] = pd.to_numeric(data_df["空盘量"])
data_df["增减量"] = pd.to_numeric(data_df["增减量"])
data_df["成交额(万元)"] = pd.to_numeric(data_df["成交额(万元)"])
data_df["交割结算价"] = pd.to_numeric(data_df["交割结算价"])
data_df["交易日期"] = pd.to_datetime(data_df["交易日期"])
data_df.columns = [
"date",
"symbol",
"pre_settle",
"open",
"high",
"low",
"close",
"settle",
"-",
"-",
"volume",
"open_interest",
"-",
"turnover",
"-",
]
variety_list = [
re.compile(r"[a-zA-Z_]+").findall(item)[0]
for item in data_df["symbol"]
]
data_df["variety"] = variety_list
data_df = data_df[
[
"symbol",
"date",
"open",
"high",
"low",
"close",
"volume",
"open_interest",
"turnover",
"settle",
"pre_settle",
"variety",
]
]
temp_df = data_df[data_df["date"] == pd.Timestamp(date)].copy()
temp_df["date"] = date
temp_df.reset_index(inplace=True, drop=True)
return temp_df
| 18,183 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_daily_bar.py
|
get_cffex_daily
|
(date: str = "20100416")
|
return data_df
|
中国金融期货交易所-日频率交易数据
http://www.cffex.com.cn/rtj/
:param date: 交易日; 数据开始时间为 20100416
:type date: str
:return: 日频率交易数据
:rtype: pandas.DataFrame
|
中国金融期货交易所-日频率交易数据
http://www.cffex.com.cn/rtj/
:param date: 交易日; 数据开始时间为 20100416
:type date: str
:return: 日频率交易数据
:rtype: pandas.DataFrame
| 108 | 196 |
def get_cffex_daily(date: str = "20100416") -> pd.DataFrame:
"""
中国金融期货交易所-日频率交易数据
http://www.cffex.com.cn/rtj/
:param date: 交易日; 数据开始时间为 20100416
:type date: str
:return: 日频率交易数据
:rtype: pandas.DataFrame
"""
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn("%s非交易日" % day.strftime("%Y%m%d"))
return None
url = (
f"http://www.cffex.com.cn/sj/historysj/{date[:-2]}/zip/{date[:-2]}.zip"
)
r = requests.get(url)
try:
with zipfile.ZipFile(BytesIO(r.content)) as file:
with file.open(f"{date}_1.csv") as my_file:
data = my_file.read().decode("gb2312")
data_df = pd.read_csv(StringIO(data))
except:
return None
data_df = data_df[data_df["合约代码"] != "小计"]
data_df = data_df[data_df["合约代码"] != "合计"]
data_df = data_df[~data_df["合约代码"].str.contains("IO")]
data_df.reset_index(inplace=True, drop=True)
data_df["合约代码"] = data_df["合约代码"].str.strip()
symbol_list = data_df["合约代码"].to_list()
variety_list = [
re.compile(r"[a-zA-Z_]+").findall(item)[0] for item in symbol_list
]
if data_df.shape[1] == 15:
data_df.columns = [
"symbol",
"open",
"high",
"low",
"volume",
"turnover",
"open_interest",
"_",
"close",
"settle",
"pre_settle",
"_",
"_",
"_",
"_",
]
else:
data_df.columns = [
"symbol",
"open",
"high",
"low",
"volume",
"turnover",
"open_interest",
"_",
"close",
"settle",
"pre_settle",
"_",
"_",
"_",
]
data_df["date"] = date
data_df["variety"] = variety_list
data_df = data_df[
[
"symbol",
"date",
"open",
"high",
"low",
"close",
"volume",
"open_interest",
"turnover",
"settle",
"pre_settle",
"variety",
]
]
return data_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_daily_bar.py#L108-L196
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 10.11236 |
[
9,
12,
14,
15,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
35,
36,
54,
70,
71,
72,
88
] | 29.213483 | false | 6.64557 | 89 | 7 | 70.786517 | 6 |
def get_cffex_daily(date: str = "20100416") -> pd.DataFrame:
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn("%s非交易日" % day.strftime("%Y%m%d"))
return None
url = (
f"http://www.cffex.com.cn/sj/historysj/{date[:-2]}/zip/{date[:-2]}.zip"
)
r = requests.get(url)
try:
with zipfile.ZipFile(BytesIO(r.content)) as file:
with file.open(f"{date}_1.csv") as my_file:
data = my_file.read().decode("gb2312")
data_df = pd.read_csv(StringIO(data))
except:
return None
data_df = data_df[data_df["合约代码"] != "小计"]
data_df = data_df[data_df["合约代码"] != "合计"]
data_df = data_df[~data_df["合约代码"].str.contains("IO")]
data_df.reset_index(inplace=True, drop=True)
data_df["合约代码"] = data_df["合约代码"].str.strip()
symbol_list = data_df["合约代码"].to_list()
variety_list = [
re.compile(r"[a-zA-Z_]+").findall(item)[0] for item in symbol_list
]
if data_df.shape[1] == 15:
data_df.columns = [
"symbol",
"open",
"high",
"low",
"volume",
"turnover",
"open_interest",
"_",
"close",
"settle",
"pre_settle",
"_",
"_",
"_",
"_",
]
else:
data_df.columns = [
"symbol",
"open",
"high",
"low",
"volume",
"turnover",
"open_interest",
"_",
"close",
"settle",
"pre_settle",
"_",
"_",
"_",
]
data_df["date"] = date
data_df["variety"] = variety_list
data_df = data_df[
[
"symbol",
"date",
"open",
"high",
"low",
"close",
"volume",
"open_interest",
"turnover",
"settle",
"pre_settle",
"variety",
]
]
return data_df
| 18,184 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_daily_bar.py
|
get_gfex_daily
|
(date: str = "20221223")
|
return result_df
|
广州期货交易所-日频率-量价数据
广州期货交易所: 工业硅(上市时间: 20221222)
http://www.gfex.com.cn/gfex/rihq/hqsj_tjsj.shtml
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象,默认为当前交易日
:type date: str or datetime.date
:return: 广州期货交易所-日频率-量价数据
:rtype: pandas.DataFrame
|
广州期货交易所-日频率-量价数据
广州期货交易所: 工业硅(上市时间: 20221222)
http://www.gfex.com.cn/gfex/rihq/hqsj_tjsj.shtml
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象,默认为当前交易日
:type date: str or datetime.date
:return: 广州期货交易所-日频率-量价数据
:rtype: pandas.DataFrame
| 199 | 260 |
def get_gfex_daily(date: str = "20221223") -> pd.DataFrame:
"""
广州期货交易所-日频率-量价数据
广州期货交易所: 工业硅(上市时间: 20221222)
http://www.gfex.com.cn/gfex/rihq/hqsj_tjsj.shtml
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象,默认为当前交易日
:type date: str or datetime.date
:return: 广州期货交易所-日频率-量价数据
:rtype: pandas.DataFrame
"""
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn(f"{day.strftime('%Y%m%d')}非交易日")
return
url = f"http://www.gfex.com.cn/u/interfacesWebTiDayQuotes/loadList"
payload = {
'trade_date': date,
'trade_type': '0'
}
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Content-Length": "32",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Host": "www.gfex.com.cn",
"Origin": "http://www.gfex.com.cn",
"Pragma": "no-cache",
"Proxy-Connection": "keep-alive",
"Referer": "http://www.gfex.com.cn/gfex/rihq/hqsj_tjsj.shtml",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
"content-type": "application/x-www-form-urlencoded"
}
r = requests.post(url, data=payload, headers=headers)
try:
data_json = r.json()
except:
return
result_df = pd.DataFrame(data_json['data'])
result_df = result_df[~result_df['variety'].str.contains("小计")]
result_df = result_df[~result_df['variety'].str.contains("总计")]
result_df['symbol'] = result_df['varietyOrder'].str.upper() + result_df['delivMonth']
result_df['date'] = date
result_df['open'] = pd.to_numeric(result_df['open'], errors="coerce")
result_df['high'] = pd.to_numeric(result_df['high'], errors="coerce")
result_df['low'] = pd.to_numeric(result_df['low'], errors="coerce")
result_df['close'] = pd.to_numeric(result_df['close'], errors="coerce")
result_df['volume'] = pd.to_numeric(result_df['volumn'], errors="coerce")
result_df['open_interest'] = pd.to_numeric(result_df['openInterest'], errors="coerce")
result_df['turnover'] = pd.to_numeric(result_df['turnover'], errors="coerce")
result_df['settle'] = pd.to_numeric(result_df['clearPrice'], errors="coerce")
result_df['pre_settle'] = pd.to_numeric(result_df['lastClear'], errors="coerce")
result_df['variety'] = result_df['varietyOrder'].str.upper()
result_df = result_df[
['symbol', 'date', 'open', 'high', 'low', 'close', 'volume',
'open_interest', 'turnover', 'settle', 'pre_settle', 'variety']
]
return result_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_daily_bar.py#L199-L260
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 16.129032 |
[
10,
13,
15,
16,
17,
21,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
61
] | 45.16129 | false | 6.64557 | 62 | 3 | 54.83871 | 7 |
def get_gfex_daily(date: str = "20221223") -> pd.DataFrame:
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn(f"{day.strftime('%Y%m%d')}非交易日")
return
url = f"http://www.gfex.com.cn/u/interfacesWebTiDayQuotes/loadList"
payload = {
'trade_date': date,
'trade_type': '0'
}
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Content-Length": "32",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
"Host": "www.gfex.com.cn",
"Origin": "http://www.gfex.com.cn",
"Pragma": "no-cache",
"Proxy-Connection": "keep-alive",
"Referer": "http://www.gfex.com.cn/gfex/rihq/hqsj_tjsj.shtml",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
"content-type": "application/x-www-form-urlencoded"
}
r = requests.post(url, data=payload, headers=headers)
try:
data_json = r.json()
except:
return
result_df = pd.DataFrame(data_json['data'])
result_df = result_df[~result_df['variety'].str.contains("小计")]
result_df = result_df[~result_df['variety'].str.contains("总计")]
result_df['symbol'] = result_df['varietyOrder'].str.upper() + result_df['delivMonth']
result_df['date'] = date
result_df['open'] = pd.to_numeric(result_df['open'], errors="coerce")
result_df['high'] = pd.to_numeric(result_df['high'], errors="coerce")
result_df['low'] = pd.to_numeric(result_df['low'], errors="coerce")
result_df['close'] = pd.to_numeric(result_df['close'], errors="coerce")
result_df['volume'] = pd.to_numeric(result_df['volumn'], errors="coerce")
result_df['open_interest'] = pd.to_numeric(result_df['openInterest'], errors="coerce")
result_df['turnover'] = pd.to_numeric(result_df['turnover'], errors="coerce")
result_df['settle'] = pd.to_numeric(result_df['clearPrice'], errors="coerce")
result_df['pre_settle'] = pd.to_numeric(result_df['lastClear'], errors="coerce")
result_df['variety'] = result_df['varietyOrder'].str.upper()
result_df = result_df[
['symbol', 'date', 'open', 'high', 'low', 'close', 'volume',
'open_interest', 'turnover', 'settle', 'pre_settle', 'variety']
]
return result_df
| 18,185 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_daily_bar.py
|
get_ine_daily
|
(date: str = "20220208")
|
return result_df
|
上海国际能源交易中心-日频率-量价数据
上海国际能源交易中心: 原油期货(上市时间: 20180326); 20号胶期货(上市时间: 20190812)
trade_price: http://www.ine.cn/statements/daily/?paramid=kx
trade_note: http://www.ine.cn/data/datanote.dat
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象,默认为当前交易日
:type date: str or datetime.date
:return: 上海国际能源交易中心-日频率-量价数据
:rtype: pandas.DataFrame or None
|
上海国际能源交易中心-日频率-量价数据
上海国际能源交易中心: 原油期货(上市时间: 20180326); 20号胶期货(上市时间: 20190812)
trade_price: http://www.ine.cn/statements/daily/?paramid=kx
trade_note: http://www.ine.cn/data/datanote.dat
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象,默认为当前交易日
:type date: str or datetime.date
:return: 上海国际能源交易中心-日频率-量价数据
:rtype: pandas.DataFrame or None
| 263 | 331 |
def get_ine_daily(date: str = "20220208") -> pd.DataFrame:
"""
上海国际能源交易中心-日频率-量价数据
上海国际能源交易中心: 原油期货(上市时间: 20180326); 20号胶期货(上市时间: 20190812)
trade_price: http://www.ine.cn/statements/daily/?paramid=kx
trade_note: http://www.ine.cn/data/datanote.dat
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象,默认为当前交易日
:type date: str or datetime.date
:return: 上海国际能源交易中心-日频率-量价数据
:rtype: pandas.DataFrame or None
"""
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn(f"{day.strftime('%Y%m%d')}非交易日")
return
url = f"http://www.ine.cn/data/dailydata/kx/kx{day.strftime('%Y%m%d')}.dat"
r = requests.get(url)
result_df = pd.DataFrame()
try:
data_json = r.json()
except:
return
temp_df = pd.DataFrame(data_json["o_curinstrument"]).iloc[:-1, :]
temp_df = temp_df[temp_df["DELIVERYMONTH"] != "小计"]
temp_df = temp_df[~temp_df["PRODUCTNAME"].str.contains("总计")]
try:
result_df["symbol"] = (
temp_df["PRODUCTGROUPID"].str.upper().str.strip()
+ temp_df["DELIVERYMONTH"]
)
except:
result_df["symbol"] = (
temp_df["PRODUCTID"]
.str.upper()
.str.strip()
.str.split("_", expand=True)
.iloc[:, 0]
+ temp_df["DELIVERYMONTH"]
)
result_df["date"] = day.strftime("%Y%m%d")
result_df["open"] = temp_df["OPENPRICE"]
result_df["high"] = temp_df["HIGHESTPRICE"]
result_df["low"] = temp_df["LOWESTPRICE"]
result_df["close"] = temp_df["CLOSEPRICE"]
result_df["volume"] = temp_df["VOLUME"]
result_df["open_interest"] = temp_df["OPENINTEREST"]
try:
result_df["turnover"] = temp_df["TURNOVER"]
except:
result_df["turnover"] = 0
result_df["settle"] = temp_df["SETTLEMENTPRICE"]
result_df["pre_settle"] = temp_df["PRESETTLEMENTPRICE"]
try:
result_df["variety"] = (
temp_df["PRODUCTGROUPID"].str.upper().str.strip()
)
except:
result_df["variety"] = (
temp_df["PRODUCTID"]
.str.upper()
.str.strip()
.str.split("_", expand=True)
.iloc[:, 0]
)
result_df = result_df[result_df["symbol"] != "总计"]
result_df = result_df[~result_df["symbol"].str.contains("efp")]
return result_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_daily_bar.py#L263-L331
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
] | 15.942029 |
[
11,
14,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
32,
33,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
58,
59,
66,
67,
68
] | 53.623188 | false | 6.64557 | 69 | 6 | 46.376812 | 8 |
def get_ine_daily(date: str = "20220208") -> pd.DataFrame:
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn(f"{day.strftime('%Y%m%d')}非交易日")
return
url = f"http://www.ine.cn/data/dailydata/kx/kx{day.strftime('%Y%m%d')}.dat"
r = requests.get(url)
result_df = pd.DataFrame()
try:
data_json = r.json()
except:
return
temp_df = pd.DataFrame(data_json["o_curinstrument"]).iloc[:-1, :]
temp_df = temp_df[temp_df["DELIVERYMONTH"] != "小计"]
temp_df = temp_df[~temp_df["PRODUCTNAME"].str.contains("总计")]
try:
result_df["symbol"] = (
temp_df["PRODUCTGROUPID"].str.upper().str.strip()
+ temp_df["DELIVERYMONTH"]
)
except:
result_df["symbol"] = (
temp_df["PRODUCTID"]
.str.upper()
.str.strip()
.str.split("_", expand=True)
.iloc[:, 0]
+ temp_df["DELIVERYMONTH"]
)
result_df["date"] = day.strftime("%Y%m%d")
result_df["open"] = temp_df["OPENPRICE"]
result_df["high"] = temp_df["HIGHESTPRICE"]
result_df["low"] = temp_df["LOWESTPRICE"]
result_df["close"] = temp_df["CLOSEPRICE"]
result_df["volume"] = temp_df["VOLUME"]
result_df["open_interest"] = temp_df["OPENINTEREST"]
try:
result_df["turnover"] = temp_df["TURNOVER"]
except:
result_df["turnover"] = 0
result_df["settle"] = temp_df["SETTLEMENTPRICE"]
result_df["pre_settle"] = temp_df["PRESETTLEMENTPRICE"]
try:
result_df["variety"] = (
temp_df["PRODUCTGROUPID"].str.upper().str.strip()
)
except:
result_df["variety"] = (
temp_df["PRODUCTID"]
.str.upper()
.str.strip()
.str.split("_", expand=True)
.iloc[:, 0]
)
result_df = result_df[result_df["symbol"] != "总计"]
result_df = result_df[~result_df["symbol"].str.contains("efp")]
return result_df
| 18,186 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_daily_bar.py
|
get_czce_daily
|
(date: str = "20050525")
|
郑州商品交易所-日频率-量价数据
http://www.czce.com.cn/cn/jysj/mrhq/H770301index_1.htm
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date 对象,默认为当前交易日; 日期需要大于 20100824
:type date: str or datetime.date
:return: 郑州商品交易所-日频率-量价数据
:rtype: pandas.DataFrame or None
|
郑州商品交易所-日频率-量价数据
http://www.czce.com.cn/cn/jysj/mrhq/H770301index_1.htm
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date 对象,默认为当前交易日; 日期需要大于 20100824
:type date: str or datetime.date
:return: 郑州商品交易所-日频率-量价数据
:rtype: pandas.DataFrame or None
| 334 | 444 |
def get_czce_daily(date: str = "20050525") -> pd.DataFrame:
"""
郑州商品交易所-日频率-量价数据
http://www.czce.com.cn/cn/jysj/mrhq/H770301index_1.htm
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date 对象,默认为当前交易日; 日期需要大于 20100824
:type date: str or datetime.date
:return: 郑州商品交易所-日频率-量价数据
:rtype: pandas.DataFrame or None
"""
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn(f"{day.strftime('%Y%m%d')}非交易日")
return
if day > datetime.date(2010, 8, 24):
if day > datetime.date(2015, 11, 11):
u = cons.CZCE_DAILY_URL_3
url = u % (day.strftime("%Y"), day.strftime("%Y%m%d"))
elif day <= datetime.date(2015, 11, 11):
u = cons.CZCE_DAILY_URL_2
url = u % (day.strftime("%Y"), day.strftime("%Y%m%d"))
listed_columns = cons.CZCE_COLUMNS
output_columns = cons.OUTPUT_COLUMNS
try:
r = requests.get(url)
if (
datetime.date(2015, 11, 12)
<= day
<= datetime.date(2017, 12, 27)
):
html = str(r.content, encoding="gbk")
else:
html = r.text
except requests.exceptions.HTTPError as reason:
if reason.response.status_code != 404:
print(
cons.CZCE_DAILY_URL_3
% (day.strftime("%Y"), day.strftime("%Y%m%d")),
reason,
)
return
if html.find("您的访问出错了") >= 0 or html.find("无期权每日行情交易记录") >= 0:
return
html = [
i.replace(" ", "").split("|")
for i in html.split("\n")[:-4]
if i[0][0] != "小"
]
if day > datetime.date(2015, 11, 11):
if html[1][0] not in ["品种月份", "品种代码", "合约代码"]:
return
dict_data = list()
day_const = int(day.strftime("%Y%m%d"))
for row in html[2:]:
m = cons.FUTURES_SYMBOL_PATTERN.match(row[0])
if not m:
continue
row_dict = {
"date": day_const,
"symbol": row[0],
"variety": m.group(1),
}
for i, field in enumerate(listed_columns):
if row[i + 1] == "\r" or row[i + 1] == "":
row_dict[field] = 0.0
elif field in [
"volume",
"open_interest",
"oi_chg",
"exercise_volume",
]:
row[i + 1] = row[i + 1].replace(",", "")
row_dict[field] = int(row[i + 1])
else:
row[i + 1] = row[i + 1].replace(",", "")
row_dict[field] = float(row[i + 1])
dict_data.append(row_dict)
return pd.DataFrame(dict_data)[output_columns]
elif day <= datetime.date(2015, 11, 11):
dict_data = list()
day_const = int(day.strftime("%Y%m%d"))
for row in html[1:]:
row = row[0].split(",")
m = cons.FUTURES_SYMBOL_PATTERN.match(row[0])
if not m:
continue
row_dict = {
"date": day_const,
"symbol": row[0],
"variety": m.group(1),
}
for i, field in enumerate(listed_columns):
if row[i + 1] == "\r":
row_dict[field] = 0.0
elif field in [
"volume",
"open_interest",
"oi_chg",
"exercise_volume",
]:
row_dict[field] = int(float(row[i + 1]))
else:
row_dict[field] = float(row[i + 1])
dict_data.append(row_dict)
return pd.DataFrame(dict_data)[output_columns]
if day <= datetime.date(2010, 8, 24):
_futures_daily_czce_df = _futures_daily_czce(date)
return _futures_daily_czce_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_daily_bar.py#L334-L444
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 8.108108 |
[
9,
12,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
31,
33,
34,
35,
36,
41,
42,
43,
44,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59,
64,
65,
66,
67,
73,
74,
76,
77,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
93,
94,
95,
96,
102,
104,
105,
106,
108,
109,
110
] | 57.657658 | false | 6.64557 | 111 | 26 | 42.342342 | 6 |
def get_czce_daily(date: str = "20050525") -> pd.DataFrame:
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn(f"{day.strftime('%Y%m%d')}非交易日")
return
if day > datetime.date(2010, 8, 24):
if day > datetime.date(2015, 11, 11):
u = cons.CZCE_DAILY_URL_3
url = u % (day.strftime("%Y"), day.strftime("%Y%m%d"))
elif day <= datetime.date(2015, 11, 11):
u = cons.CZCE_DAILY_URL_2
url = u % (day.strftime("%Y"), day.strftime("%Y%m%d"))
listed_columns = cons.CZCE_COLUMNS
output_columns = cons.OUTPUT_COLUMNS
try:
r = requests.get(url)
if (
datetime.date(2015, 11, 12)
<= day
<= datetime.date(2017, 12, 27)
):
html = str(r.content, encoding="gbk")
else:
html = r.text
except requests.exceptions.HTTPError as reason:
if reason.response.status_code != 404:
print(
cons.CZCE_DAILY_URL_3
% (day.strftime("%Y"), day.strftime("%Y%m%d")),
reason,
)
return
if html.find("您的访问出错了") >= 0 or html.find("无期权每日行情交易记录") >= 0:
return
html = [
i.replace(" ", "").split("|")
for i in html.split("\n")[:-4]
if i[0][0] != "小"
]
if day > datetime.date(2015, 11, 11):
if html[1][0] not in ["品种月份", "品种代码", "合约代码"]:
return
dict_data = list()
day_const = int(day.strftime("%Y%m%d"))
for row in html[2:]:
m = cons.FUTURES_SYMBOL_PATTERN.match(row[0])
if not m:
continue
row_dict = {
"date": day_const,
"symbol": row[0],
"variety": m.group(1),
}
for i, field in enumerate(listed_columns):
if row[i + 1] == "\r" or row[i + 1] == "":
row_dict[field] = 0.0
elif field in [
"volume",
"open_interest",
"oi_chg",
"exercise_volume",
]:
row[i + 1] = row[i + 1].replace(",", "")
row_dict[field] = int(row[i + 1])
else:
row[i + 1] = row[i + 1].replace(",", "")
row_dict[field] = float(row[i + 1])
dict_data.append(row_dict)
return pd.DataFrame(dict_data)[output_columns]
elif day <= datetime.date(2015, 11, 11):
dict_data = list()
day_const = int(day.strftime("%Y%m%d"))
for row in html[1:]:
row = row[0].split(",")
m = cons.FUTURES_SYMBOL_PATTERN.match(row[0])
if not m:
continue
row_dict = {
"date": day_const,
"symbol": row[0],
"variety": m.group(1),
}
for i, field in enumerate(listed_columns):
if row[i + 1] == "\r":
row_dict[field] = 0.0
elif field in [
"volume",
"open_interest",
"oi_chg",
"exercise_volume",
]:
row_dict[field] = int(float(row[i + 1]))
else:
row_dict[field] = float(row[i + 1])
dict_data.append(row_dict)
return pd.DataFrame(dict_data)[output_columns]
if day <= datetime.date(2010, 8, 24):
_futures_daily_czce_df = _futures_daily_czce(date)
return _futures_daily_czce_df
| 18,187 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_daily_bar.py
|
get_shfe_v_wap
|
(date: str = "20131017")
|
上期所日成交均价数据
Parameters
------
date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
Return
-------
DataFrame
郑商所日交易数据(DataFrame):
symbol 合约代码
date 日期
time_range v_wap时段,分09:00-10:15和09:00-15:00两类
v_wap 加权平均成交均价
或 None(给定日期没有数据)
|
上期所日成交均价数据
Parameters
------
date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
Return
-------
DataFrame
郑商所日交易数据(DataFrame):
symbol 合约代码
date 日期
time_range v_wap时段,分09:00-10:15和09:00-15:00两类
v_wap 加权平均成交均价
或 None(给定日期没有数据)
| 447 | 490 |
def get_shfe_v_wap(date: str = "20131017") -> pd.DataFrame:
"""
上期所日成交均价数据
Parameters
------
date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
Return
-------
DataFrame
郑商所日交易数据(DataFrame):
symbol 合约代码
date 日期
time_range v_wap时段,分09:00-10:15和09:00-15:00两类
v_wap 加权平均成交均价
或 None(给定日期没有数据)
"""
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn("%s非交易日" % day.strftime("%Y%m%d"))
return None
try:
json_data = json.loads(
requests_link(
cons.SHFE_V_WAP_URL % (day.strftime("%Y%m%d")),
headers=cons.headers,
encoding="utf-8",
).text
)
except:
return None
if len(json_data["o_currefprice"]) == 0:
return None
try:
df = pd.DataFrame(json_data["o_currefprice"])
df["INSTRUMENTID"] = df["INSTRUMENTID"].str.strip()
df[":B1"].astype("int16")
return df.rename(columns=cons.SHFE_V_WAP_COLUMNS)[
list(cons.SHFE_V_WAP_COLUMNS.values())
]
except:
return None
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_daily_bar.py#L447-L490
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
] | 36.363636 |
[
16,
19,
21,
22,
23,
30,
31,
33,
34,
35,
36,
37,
38,
39,
42,
43
] | 36.363636 | false | 6.64557 | 44 | 5 | 63.636364 | 13 |
def get_shfe_v_wap(date: str = "20131017") -> pd.DataFrame:
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn("%s非交易日" % day.strftime("%Y%m%d"))
return None
try:
json_data = json.loads(
requests_link(
cons.SHFE_V_WAP_URL % (day.strftime("%Y%m%d")),
headers=cons.headers,
encoding="utf-8",
).text
)
except:
return None
if len(json_data["o_currefprice"]) == 0:
return None
try:
df = pd.DataFrame(json_data["o_currefprice"])
df["INSTRUMENTID"] = df["INSTRUMENTID"].str.strip()
df[":B1"].astype("int16")
return df.rename(columns=cons.SHFE_V_WAP_COLUMNS)[
list(cons.SHFE_V_WAP_COLUMNS.values())
]
except:
return None
| 18,188 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_daily_bar.py
|
get_shfe_daily
|
(date: str = "20220415")
|
return df[cons.OUTPUT_COLUMNS]
|
上海期货交易所-日频率-量价数据
http://www.shfe.com.cn/statements/dataview.html?paramid=kx
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象, 默认为当前交易日
:type date: str or datetime.date
:return: 上海期货交易所-日频率-量价数据
:rtype: pandas.DataFrame or None
上期所日交易数据(DataFrame):
symbol 合约代码
date 日期
open 开盘价
high 最高价
low 最低价
close 收盘价
volume 成交量
open_interest 持仓量
turnover 成交额
settle 结算价
pre_settle 前结算价
variety 合约类别
或 None(给定交易日没有交易数据)
|
上海期货交易所-日频率-量价数据
http://www.shfe.com.cn/statements/dataview.html?paramid=kx
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象, 默认为当前交易日
:type date: str or datetime.date
:return: 上海期货交易所-日频率-量价数据
:rtype: pandas.DataFrame or None
上期所日交易数据(DataFrame):
symbol 合约代码
date 日期
open 开盘价
high 最高价
low 最低价
close 收盘价
volume 成交量
open_interest 持仓量
turnover 成交额
settle 结算价
pre_settle 前结算价
variety 合约类别
或 None(给定交易日没有交易数据)
| 493 | 571 |
def get_shfe_daily(date: str = "20220415") -> pd.DataFrame:
"""
上海期货交易所-日频率-量价数据
http://www.shfe.com.cn/statements/dataview.html?paramid=kx
:param date: 日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象, 默认为当前交易日
:type date: str or datetime.date
:return: 上海期货交易所-日频率-量价数据
:rtype: pandas.DataFrame or None
上期所日交易数据(DataFrame):
symbol 合约代码
date 日期
open 开盘价
high 最高价
low 最低价
close 收盘价
volume 成交量
open_interest 持仓量
turnover 成交额
settle 结算价
pre_settle 前结算价
variety 合约类别
或 None(给定交易日没有交易数据)
"""
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn("%s非交易日" % day.strftime("%Y%m%d"))
return
try:
json_data = json.loads(
requests_link(
cons.SHFE_DAILY_URL % (day.strftime("%Y%m%d")),
headers=cons.shfe_headers,
).text
)
except requests.HTTPError as reason:
if reason.response != 404:
print(cons.SHFE_DAILY_URL % (day.strftime("%Y%m%d")), reason)
return
if len(json_data["o_curinstrument"]) == 0:
return
df = pd.DataFrame(
[
row
for row in json_data["o_curinstrument"]
if row["DELIVERYMONTH"] not in ["小计", "合计"]
and row["DELIVERYMONTH"] != ""
]
)
try:
df["variety"] = df["PRODUCTGROUPID"].str.upper().str.strip()
except KeyError as e:
df["variety"] = (
df["PRODUCTID"]
.str.upper()
.str.split("_", expand=True)
.iloc[:, 0]
.str.strip()
)
df["symbol"] = df["variety"] + df["DELIVERYMONTH"]
df["date"] = day.strftime("%Y%m%d")
v_wap_df = get_shfe_v_wap(day)
if v_wap_df is not None:
df = pd.merge(
df,
v_wap_df[v_wap_df.time_range == "9:00-15:00"],
on=["date", "symbol"],
how="left",
)
df["turnover"] = df.v_wap * df.VOLUME
else:
df["VOLUME"] = df["VOLUME"].apply(lambda x: 0 if x == "" else x)
df["turnover"] = df["VOLUME"] * df["SETTLEMENTPRICE"]
df.rename(columns=cons.SHFE_COLUMNS, inplace=True)
df = df[~df["symbol"].str.contains("efp")]
return df[cons.OUTPUT_COLUMNS]
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_daily_bar.py#L493-L571
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22
] | 29.113924 |
[
23,
26,
28,
29,
30,
36,
37,
38,
39,
41,
42,
44,
52,
53,
54,
55,
62,
63,
64,
65,
66,
72,
74,
75,
76,
77,
78
] | 34.177215 | false | 6.64557 | 79 | 9 | 65.822785 | 20 |
def get_shfe_daily(date: str = "20220415") -> pd.DataFrame:
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn("%s非交易日" % day.strftime("%Y%m%d"))
return
try:
json_data = json.loads(
requests_link(
cons.SHFE_DAILY_URL % (day.strftime("%Y%m%d")),
headers=cons.shfe_headers,
).text
)
except requests.HTTPError as reason:
if reason.response != 404:
print(cons.SHFE_DAILY_URL % (day.strftime("%Y%m%d")), reason)
return
if len(json_data["o_curinstrument"]) == 0:
return
df = pd.DataFrame(
[
row
for row in json_data["o_curinstrument"]
if row["DELIVERYMONTH"] not in ["小计", "合计"]
and row["DELIVERYMONTH"] != ""
]
)
try:
df["variety"] = df["PRODUCTGROUPID"].str.upper().str.strip()
except KeyError as e:
df["variety"] = (
df["PRODUCTID"]
.str.upper()
.str.split("_", expand=True)
.iloc[:, 0]
.str.strip()
)
df["symbol"] = df["variety"] + df["DELIVERYMONTH"]
df["date"] = day.strftime("%Y%m%d")
v_wap_df = get_shfe_v_wap(day)
if v_wap_df is not None:
df = pd.merge(
df,
v_wap_df[v_wap_df.time_range == "9:00-15:00"],
on=["date", "symbol"],
how="left",
)
df["turnover"] = df.v_wap * df.VOLUME
else:
df["VOLUME"] = df["VOLUME"].apply(lambda x: 0 if x == "" else x)
df["turnover"] = df["VOLUME"] * df["SETTLEMENTPRICE"]
df.rename(columns=cons.SHFE_COLUMNS, inplace=True)
df = df[~df["symbol"].str.contains("efp")]
return df[cons.OUTPUT_COLUMNS]
| 18,189 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_daily_bar.py
|
get_dce_daily
|
(date: str = "20220308")
|
return data_df
|
大连商品交易所日交易数据
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/rxq/index.html
:param date: 交易日, e.g., 20200416
:type date: str
:return: 具体交易日的个品种行情数据
:rtype: pandas.DataFrame
|
大连商品交易所日交易数据
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/rxq/index.html
:param date: 交易日, e.g., 20200416
:type date: str
:return: 具体交易日的个品种行情数据
:rtype: pandas.DataFrame
| 574 | 671 |
def get_dce_daily(date: str = "20220308") -> pd.DataFrame:
"""
大连商品交易所日交易数据
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/rtj/rxq/index.html
:param date: 交易日, e.g., 20200416
:type date: str
:return: 具体交易日的个品种行情数据
:rtype: pandas.DataFrame
"""
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn("%s非交易日" % day.strftime("%Y%m%d"))
return None
url = (
"http://www.dce.com.cn/publicweb/quotesdata/exportDayQuotesChData.html"
)
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Content-Length": "86",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "www.dce.com.cn",
"Origin": "http://www.dce.com.cn",
"Pragma": "no-cache",
"Referer": "http://www.dce.com.cn/publicweb/quotesdata/dayQuotesCh.html",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36",
}
params = {
"dayQuotes.variety": "all",
"dayQuotes.trade_type": "0",
"year": date[:4],
"month": str(int(date[4:6]) - 1),
"day": date[6:],
"exportFlag": "excel",
}
r = requests.post(url, data=params, headers=headers)
data_df = pd.read_excel(BytesIO(r.content))
data_df = data_df[~data_df["商品名称"].str.contains("小计")]
data_df = data_df[~data_df["商品名称"].str.contains("总计")]
data_df["variety"] = data_df["商品名称"].map(lambda x: cons.DCE_MAP[x])
data_df["symbol"] = data_df["合约名称"]
del data_df["商品名称"]
del data_df["合约名称"]
data_df.columns = [
"open",
"high",
"low",
"close",
"pre_settle",
"settle",
"_",
"_",
"volume",
"open_interest",
"_",
"turnover",
"variety",
"symbol",
]
data_df["date"] = date
data_df = data_df[
[
"symbol",
"date",
"open",
"high",
"low",
"close",
"volume",
"open_interest",
"turnover",
"settle",
"pre_settle",
"variety",
]
]
data_df = data_df.applymap(lambda x: x.replace(",", ""))
data_df = data_df.astype(
{
"open": "float",
"high": "float",
"low": "float",
"close": "float",
"volume": "float",
"open_interest": "float",
"turnover": "float",
"settle": "float",
"pre_settle": "float",
}
)
data_df.reset_index(inplace=True, drop=True)
return data_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_daily_bar.py#L574-L671
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 9.183673 |
[
9,
12,
14,
15,
18,
33,
41,
42,
43,
44,
45,
46,
47,
48,
49,
65,
66,
82,
83,
96,
97
] | 21.428571 | false | 6.64557 | 98 | 2 | 78.571429 | 6 |
def get_dce_daily(date: str = "20220308") -> pd.DataFrame:
day = (
cons.convert_date(date) if date is not None else datetime.date.today()
)
if day.strftime("%Y%m%d") not in calendar:
# warnings.warn("%s非交易日" % day.strftime("%Y%m%d"))
return None
url = (
"http://www.dce.com.cn/publicweb/quotesdata/exportDayQuotesChData.html"
)
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Content-Length": "86",
"Content-Type": "application/x-www-form-urlencoded",
"Host": "www.dce.com.cn",
"Origin": "http://www.dce.com.cn",
"Pragma": "no-cache",
"Referer": "http://www.dce.com.cn/publicweb/quotesdata/dayQuotesCh.html",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.105 Safari/537.36",
}
params = {
"dayQuotes.variety": "all",
"dayQuotes.trade_type": "0",
"year": date[:4],
"month": str(int(date[4:6]) - 1),
"day": date[6:],
"exportFlag": "excel",
}
r = requests.post(url, data=params, headers=headers)
data_df = pd.read_excel(BytesIO(r.content))
data_df = data_df[~data_df["商品名称"].str.contains("小计")]
data_df = data_df[~data_df["商品名称"].str.contains("总计")]
data_df["variety"] = data_df["商品名称"].map(lambda x: cons.DCE_MAP[x])
data_df["symbol"] = data_df["合约名称"]
del data_df["商品名称"]
del data_df["合约名称"]
data_df.columns = [
"open",
"high",
"low",
"close",
"pre_settle",
"settle",
"_",
"_",
"volume",
"open_interest",
"_",
"turnover",
"variety",
"symbol",
]
data_df["date"] = date
data_df = data_df[
[
"symbol",
"date",
"open",
"high",
"low",
"close",
"volume",
"open_interest",
"turnover",
"settle",
"pre_settle",
"variety",
]
]
data_df = data_df.applymap(lambda x: x.replace(",", ""))
data_df = data_df.astype(
{
"open": "float",
"high": "float",
"low": "float",
"close": "float",
"volume": "float",
"open_interest": "float",
"turnover": "float",
"settle": "float",
"pre_settle": "float",
}
)
data_df.reset_index(inplace=True, drop=True)
return data_df
| 18,190 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_daily_bar.py
|
get_futures_daily
|
(
start_date: str = "20220208",
end_date: str = "20220208",
market: str = "CFFEX",
)
|
交易所日交易数据
:param start_date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type start_date: str
:param end_date: 结束数据 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type end_date: str
:param market: 'CFFEX' 中金所, 'CZCE' 郑商所, 'SHFE' 上期所, 'DCE' 大商所 之一, 'INE' 上海国际能源交易中心, "GFEX" 广州期货交易所。默认为中金所
:type market: str
:return: 交易所日交易数据
:rtype: pandas.DataFrame
|
交易所日交易数据
:param start_date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type start_date: str
:param end_date: 结束数据 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type end_date: str
:param market: 'CFFEX' 中金所, 'CZCE' 郑商所, 'SHFE' 上期所, 'DCE' 大商所 之一, 'INE' 上海国际能源交易中心, "GFEX" 广州期货交易所。默认为中金所
:type market: str
:return: 交易所日交易数据
:rtype: pandas.DataFrame
| 674 | 729 |
def get_futures_daily(
start_date: str = "20220208",
end_date: str = "20220208",
market: str = "CFFEX",
) -> pd.DataFrame:
"""
交易所日交易数据
:param start_date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type start_date: str
:param end_date: 结束数据 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type end_date: str
:param market: 'CFFEX' 中金所, 'CZCE' 郑商所, 'SHFE' 上期所, 'DCE' 大商所 之一, 'INE' 上海国际能源交易中心, "GFEX" 广州期货交易所。默认为中金所
:type market: str
:return: 交易所日交易数据
:rtype: pandas.DataFrame
"""
if market.upper() == "CFFEX":
f = get_cffex_daily
elif market.upper() == "CZCE":
f = get_czce_daily
elif market.upper() == "SHFE":
f = get_shfe_daily
elif market.upper() == "DCE":
f = get_dce_daily
elif market.upper() == "INE":
f = get_ine_daily
elif market.upper() == "GFEX":
f = get_gfex_daily
else:
print("Invalid Market Symbol")
return
start_date = (
cons.convert_date(start_date)
if start_date is not None
else datetime.date.today()
)
end_date = (
cons.convert_date(end_date)
if end_date is not None
else cons.convert_date(
cons.get_latest_data_date(datetime.datetime.now())
)
)
df_list = list()
while start_date <= end_date:
df = f(date=str(start_date).replace("-", ""))
if df is not None:
df_list.append(df)
start_date += datetime.timedelta(days=1)
if len(df_list) > 0:
temp_df = pd.concat(df_list).reset_index(drop=True)
temp_df = temp_df[~temp_df["symbol"].str.contains("efp")]
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_daily_bar.py#L674-L729
| 25 |
[
0
] | 1.785714 |
[
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
29,
30,
32,
37,
45,
46,
47,
48,
49,
50,
52,
53,
54,
55
] | 46.428571 | false | 6.64557 | 56 | 10 | 53.571429 | 9 |
def get_futures_daily(
start_date: str = "20220208",
end_date: str = "20220208",
market: str = "CFFEX",
) -> pd.DataFrame:
if market.upper() == "CFFEX":
f = get_cffex_daily
elif market.upper() == "CZCE":
f = get_czce_daily
elif market.upper() == "SHFE":
f = get_shfe_daily
elif market.upper() == "DCE":
f = get_dce_daily
elif market.upper() == "INE":
f = get_ine_daily
elif market.upper() == "GFEX":
f = get_gfex_daily
else:
print("Invalid Market Symbol")
return
start_date = (
cons.convert_date(start_date)
if start_date is not None
else datetime.date.today()
)
end_date = (
cons.convert_date(end_date)
if end_date is not None
else cons.convert_date(
cons.get_latest_data_date(datetime.datetime.now())
)
)
df_list = list()
while start_date <= end_date:
df = f(date=str(start_date).replace("-", ""))
if df is not None:
df_list.append(df)
start_date += datetime.timedelta(days=1)
if len(df_list) > 0:
temp_df = pd.concat(df_list).reset_index(drop=True)
temp_df = temp_df[~temp_df["symbol"].str.contains("efp")]
return temp_df
| 18,191 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/receipt.py
|
get_dce_receipt
|
(date: str = None, vars_list: List = cons.contract_symbols)
|
return records.reset_index(drop=True)
|
大连商品交易所-注册仓单数据
:param date: 开始日期: YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象, 为空时为当天
:type date: str
:param vars_list: 合约品种如 RB, AL等列表, 为空时为所有商品数据从 20060106开始,每周五更新仓单数据。直到20090407起,每交易日都更新仓单数据
:type vars_list: list
:return: 注册仓单数据
:rtype: pandas.DataFrame
|
大连商品交易所-注册仓单数据
:param date: 开始日期: YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象, 为空时为当天
:type date: str
:param vars_list: 合约品种如 RB, AL等列表, 为空时为所有商品数据从 20060106开始,每周五更新仓单数据。直到20090407起,每交易日都更新仓单数据
:type vars_list: list
:return: 注册仓单数据
:rtype: pandas.DataFrame
| 28 | 64 |
def get_dce_receipt(date: str = None, vars_list: List = cons.contract_symbols):
"""
大连商品交易所-注册仓单数据
:param date: 开始日期: YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象, 为空时为当天
:type date: str
:param vars_list: 合约品种如 RB, AL等列表, 为空时为所有商品数据从 20060106开始,每周五更新仓单数据。直到20090407起,每交易日都更新仓单数据
:type vars_list: list
:return: 注册仓单数据
:rtype: pandas.DataFrame
"""
if not isinstance(vars_list, list):
return warnings.warn("vars_list: 必须是列表")
date = cons.convert_date(date) if date is not None else datetime.date.today()
if date.strftime('%Y%m%d') not in calendar:
warnings.warn(f"{date.strftime('%Y%m%d')}非交易日")
return None
payload = {
"weekQuotes.variety": "all",
"year": date.year,
"month": date.month - 1, # 网站月份描述少 1 个月, 属于网站问题
"day": date.day
}
data = pandas_read_html_link(cons.DCE_RECEIPT_URL, method="post", data=payload, headers=cons.dce_headers)[0]
records = pd.DataFrame()
for x in data.to_dict(orient='records'):
if isinstance(x['品种'], str):
if x['品种'][-2:] == '小计':
var = x['品种'][:-2]
temp_data = {'var': chinese_to_english(var), 'receipt': int(x['今日仓单量']), 'receipt_chg': int(x['增减']),
'date': date.strftime('%Y%m%d')}
records = pd.concat([records, pd.DataFrame(temp_data, index=[0])])
if len(records.index) != 0:
records.index = records['var']
vars_in_market = [i for i in vars_list if i in records.index]
records = records.loc[vars_in_market, :]
return records.reset_index(drop=True)
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/receipt.py#L28-L64
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 27.027027 |
[
10,
11,
12,
13,
14,
15,
16,
22,
23,
24,
25,
26,
27,
28,
30,
32,
33,
34,
35,
36
] | 54.054054 | false | 7.971014 | 37 | 8 | 45.945946 | 7 |
def get_dce_receipt(date: str = None, vars_list: List = cons.contract_symbols):
if not isinstance(vars_list, list):
return warnings.warn("vars_list: 必须是列表")
date = cons.convert_date(date) if date is not None else datetime.date.today()
if date.strftime('%Y%m%d') not in calendar:
warnings.warn(f"{date.strftime('%Y%m%d')}非交易日")
return None
payload = {
"weekQuotes.variety": "all",
"year": date.year,
"month": date.month - 1, # 网站月份描述少 1 个月, 属于网站问题
"day": date.day
}
data = pandas_read_html_link(cons.DCE_RECEIPT_URL, method="post", data=payload, headers=cons.dce_headers)[0]
records = pd.DataFrame()
for x in data.to_dict(orient='records'):
if isinstance(x['品种'], str):
if x['品种'][-2:] == '小计':
var = x['品种'][:-2]
temp_data = {'var': chinese_to_english(var), 'receipt': int(x['今日仓单量']), 'receipt_chg': int(x['增减']),
'date': date.strftime('%Y%m%d')}
records = pd.concat([records, pd.DataFrame(temp_data, index=[0])])
if len(records.index) != 0:
records.index = records['var']
vars_in_market = [i for i in vars_list if i in records.index]
records = records.loc[vars_in_market, :]
return records.reset_index(drop=True)
| 18,192 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/receipt.py
|
get_shfe_receipt_1
|
(date: str = None, vars_list: List = cons.contract_symbols)
|
return records.reset_index(drop=True)
|
上海期货交易所-注册仓单数据-类型1
适用 20081006 至 20140518(包括)、20100126、20101029日期交易所格式混乱,直接回复脚本中 pandas.DataFrame, 20100416、20130821日期交易所数据丢失
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品
:type vars_list: list
:return: 注册仓单数据-类型1
:rtype: pandas.DataFrame
|
上海期货交易所-注册仓单数据-类型1
适用 20081006 至 20140518(包括)、20100126、20101029日期交易所格式混乱,直接回复脚本中 pandas.DataFrame, 20100416、20130821日期交易所数据丢失
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品
:type vars_list: list
:return: 注册仓单数据-类型1
:rtype: pandas.DataFrame
| 67 | 115 |
def get_shfe_receipt_1(date: str = None, vars_list: List = cons.contract_symbols) -> pd.DataFrame:
"""
上海期货交易所-注册仓单数据-类型1
适用 20081006 至 20140518(包括)、20100126、20101029日期交易所格式混乱,直接回复脚本中 pandas.DataFrame, 20100416、20130821日期交易所数据丢失
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: 合约品种如RB、AL等列表 为空时为所有商品
:type vars_list: list
:return: 注册仓单数据-类型1
:rtype: pandas.DataFrame
"""
if not isinstance(vars_list, list):
return warnings.warn(f"symbol_list: 必须是列表")
date = cons.convert_date(date).strftime('%Y%m%d') if date is not None else datetime.date.today()
if date not in calendar:
warnings.warn(f"{date.strftime('%Y%m%d')}非交易日")
return None
if date == '20100126':
shfe_20100126['date'] = date
return shfe_20100126
elif date == '20101029':
shfe_20101029['date'] = date
return shfe_20101029
elif date in ['20100416', '20130821']:
return warnings.warn('20100416、20130821交易所数据丢失')
else:
var_list = ['天然橡胶', '沥青仓库', '沥青厂库', '热轧卷板', '燃料油', '白银', '线材', '螺纹钢', '铅', '铜', '铝', '锌', '黄金', '锡', '镍']
url = cons.SHFE_RECEIPT_URL_1 % date
data = pandas_read_html_link(url)[0]
indexes = [x for x in data.index if (data[0].tolist()[x] in var_list)]
last_index = [x for x in data.index if '注' in str(data[0].tolist()[x])][0] - 1
records = pd.DataFrame()
for i in list(range(len(indexes))):
if i != len(indexes) - 1:
data_cut = data.loc[indexes[i]:indexes[i + 1] - 1, :]
else:
data_cut = data.loc[indexes[i]:last_index, :]
data_cut = data_cut.fillna(method='pad')
data_dict = dict()
data_dict['var'] = chinese_to_english(data_cut[0].tolist()[0])
data_dict['receipt'] = int(data_cut[2].tolist()[-1])
data_dict['receipt_chg'] = int(data_cut[3].tolist()[-1])
data_dict['date'] = date
records = pd.concat([records, pd.DataFrame(data_dict, index=[0])])
if len(records.index) != 0:
records.index = records['var']
vars_in_market = [i for i in vars_list if i in records.index]
records = records.loc[vars_in_market, :]
return records.reset_index(drop=True)
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/receipt.py#L67-L115
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
] | 22.44898 |
[
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
26,
27,
28,
29,
30,
31,
32,
33,
34,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48
] | 73.469388 | false | 7.971014 | 49 | 12 | 26.530612 | 8 |
def get_shfe_receipt_1(date: str = None, vars_list: List = cons.contract_symbols) -> pd.DataFrame:
if not isinstance(vars_list, list):
return warnings.warn(f"symbol_list: 必须是列表")
date = cons.convert_date(date).strftime('%Y%m%d') if date is not None else datetime.date.today()
if date not in calendar:
warnings.warn(f"{date.strftime('%Y%m%d')}非交易日")
return None
if date == '20100126':
shfe_20100126['date'] = date
return shfe_20100126
elif date == '20101029':
shfe_20101029['date'] = date
return shfe_20101029
elif date in ['20100416', '20130821']:
return warnings.warn('20100416、20130821交易所数据丢失')
else:
var_list = ['天然橡胶', '沥青仓库', '沥青厂库', '热轧卷板', '燃料油', '白银', '线材', '螺纹钢', '铅', '铜', '铝', '锌', '黄金', '锡', '镍']
url = cons.SHFE_RECEIPT_URL_1 % date
data = pandas_read_html_link(url)[0]
indexes = [x for x in data.index if (data[0].tolist()[x] in var_list)]
last_index = [x for x in data.index if '注' in str(data[0].tolist()[x])][0] - 1
records = pd.DataFrame()
for i in list(range(len(indexes))):
if i != len(indexes) - 1:
data_cut = data.loc[indexes[i]:indexes[i + 1] - 1, :]
else:
data_cut = data.loc[indexes[i]:last_index, :]
data_cut = data_cut.fillna(method='pad')
data_dict = dict()
data_dict['var'] = chinese_to_english(data_cut[0].tolist()[0])
data_dict['receipt'] = int(data_cut[2].tolist()[-1])
data_dict['receipt_chg'] = int(data_cut[3].tolist()[-1])
data_dict['date'] = date
records = pd.concat([records, pd.DataFrame(data_dict, index=[0])])
if len(records.index) != 0:
records.index = records['var']
vars_in_market = [i for i in vars_list if i in records.index]
records = records.loc[vars_in_market, :]
return records.reset_index(drop=True)
| 18,193 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/receipt.py
|
get_shfe_receipt_2
|
(date: str = None, vars_list: List = cons.contract_symbols)
|
return records.reset_index(drop=True)
|
上海商品交易所-注册仓单数据-类型2
适用 20140519(包括)-至今
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: 合约品种如 RB、AL 等列表 为空时为所有商品
:type vars_list: list
:return: 注册仓单数据
:rtype: pandas.DataFrame
|
上海商品交易所-注册仓单数据-类型2
适用 20140519(包括)-至今
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: 合约品种如 RB、AL 等列表 为空时为所有商品
:type vars_list: list
:return: 注册仓单数据
:rtype: pandas.DataFrame
| 118 | 165 |
def get_shfe_receipt_2(date: str = None, vars_list: List = cons.contract_symbols) -> pd.DataFrame:
"""
上海商品交易所-注册仓单数据-类型2
适用 20140519(包括)-至今
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: 合约品种如 RB、AL 等列表 为空时为所有商品
:type vars_list: list
:return: 注册仓单数据
:rtype: pandas.DataFrame
"""
if not isinstance(vars_list, list):
return warnings.warn(f"symbol_list: 必须是列表")
date = cons.convert_date(date).strftime('%Y%m%d') if date is not None else datetime.date.today()
if date not in calendar:
warnings.warn('%s非交易日' % date.strftime('%Y%m%d'))
return None
url = cons.SHFE_RECEIPT_URL_2 % date
r = requests_link(url, encoding='utf-8')
try:
context = r.json()
except:
return pd.DataFrame()
data = pd.DataFrame(context['o_cursor'])
if len(data.columns) < 1:
return pd.DataFrame()
records = pd.DataFrame()
for var in set(data['VARNAME'].tolist()):
data_cut = data[data['VARNAME'] == var]
if "BC" in var:
data_dict = {'var': "BC",
'receipt': int(data_cut['WRTWGHTS'].tolist()[-1]),
'receipt_chg': int(data_cut['WRTCHANGE'].tolist()[-1]),
'date': date}
else:
data_dict = {'var': chinese_to_english(re.sub(r"\W|[a-zA-Z]", "", var)),
'receipt': int(data_cut['WRTWGHTS'].tolist()[-1]),
'receipt_chg': int(data_cut['WRTCHANGE'].tolist()[-1]),
'date': date}
records = pd.concat([records, pd.DataFrame(data_dict, index=[0])])
temp_records = records.groupby('var')[['receipt', 'receipt_chg']].sum().reset_index()
temp_records['date'] = date
records = temp_records
if len(records.index) != 0:
records.index = records['var']
vars_in_market = [i for i in vars_list if i in records.index]
records = records.loc[vars_in_market, :]
return records.reset_index(drop=True)
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/receipt.py#L118-L165
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
] | 22.916667 |
[
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
35,
39,
40,
41,
42,
43,
44,
45,
46,
47
] | 62.5 | false | 7.971014 | 48 | 9 | 37.5 | 8 |
def get_shfe_receipt_2(date: str = None, vars_list: List = cons.contract_symbols) -> pd.DataFrame:
if not isinstance(vars_list, list):
return warnings.warn(f"symbol_list: 必须是列表")
date = cons.convert_date(date).strftime('%Y%m%d') if date is not None else datetime.date.today()
if date not in calendar:
warnings.warn('%s非交易日' % date.strftime('%Y%m%d'))
return None
url = cons.SHFE_RECEIPT_URL_2 % date
r = requests_link(url, encoding='utf-8')
try:
context = r.json()
except:
return pd.DataFrame()
data = pd.DataFrame(context['o_cursor'])
if len(data.columns) < 1:
return pd.DataFrame()
records = pd.DataFrame()
for var in set(data['VARNAME'].tolist()):
data_cut = data[data['VARNAME'] == var]
if "BC" in var:
data_dict = {'var': "BC",
'receipt': int(data_cut['WRTWGHTS'].tolist()[-1]),
'receipt_chg': int(data_cut['WRTCHANGE'].tolist()[-1]),
'date': date}
else:
data_dict = {'var': chinese_to_english(re.sub(r"\W|[a-zA-Z]", "", var)),
'receipt': int(data_cut['WRTWGHTS'].tolist()[-1]),
'receipt_chg': int(data_cut['WRTCHANGE'].tolist()[-1]),
'date': date}
records = pd.concat([records, pd.DataFrame(data_dict, index=[0])])
temp_records = records.groupby('var')[['receipt', 'receipt_chg']].sum().reset_index()
temp_records['date'] = date
records = temp_records
if len(records.index) != 0:
records.index = records['var']
vars_in_market = [i for i in vars_list if i in records.index]
records = records.loc[vars_in_market, :]
return records.reset_index(drop=True)
| 18,194 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/receipt.py
|
get_czce_receipt_1
|
(date: str = None, vars_list: List = cons.contract_symbols)
|
return records.reset_index(drop=True)
|
郑州商品交易所-注册仓单数据
适用 20080222 至 20100824(包括)
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: list
:type vars_list: 合约品种如 CF、TA 等列表 为空时为所有商品
:return: 注册仓单数据
:rtype: pandas.DataFrame
|
郑州商品交易所-注册仓单数据
适用 20080222 至 20100824(包括)
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: list
:type vars_list: 合约品种如 CF、TA 等列表 为空时为所有商品
:return: 注册仓单数据
:rtype: pandas.DataFrame
| 168 | 215 |
def get_czce_receipt_1(date: str = None, vars_list: List = cons.contract_symbols):
"""
郑州商品交易所-注册仓单数据
适用 20080222 至 20100824(包括)
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: list
:type vars_list: 合约品种如 CF、TA 等列表 为空时为所有商品
:return: 注册仓单数据
:rtype: pandas.DataFrame
"""
date = cons.convert_date(date).strftime('%Y%m%d') if date is not None else datetime.date.today()
if date not in calendar:
warnings.warn('%s非交易日' % date.strftime('%Y%m%d'))
return None
if date == '20090820':
return pd.DataFrame()
url = cons.CZCE_RECEIPT_URL_1 % date
r = requests_link(url, encoding='utf-8')
context = r.text
data = pd.read_html(context)[1]
records = pd.DataFrame()
indexes = [x for x in data.index if '品种:' in str(data[0].tolist()[x])]
ends = [x for x in data.index if '总计' in str(data[0].tolist()[x])]
for i in list(range(len(indexes))):
if i != len(indexes) - 1:
data_cut = data.loc[indexes[i]:ends[i], :]
data_cut = data_cut.fillna(method='pad')
else:
data_cut = data.loc[indexes[i]:, :]
data_cut = data_cut.fillna(method='pad')
if 'PTA' in data_cut[0].tolist()[0]:
var = 'TA'
else:
var = chinese_to_english(re.sub(r'[A-Z]+', '', data_cut[0].tolist()[0][3:]))
if var == 'CF':
receipt = data_cut[6].tolist()[-1]
receipt_chg = data_cut[7].tolist()[-1]
else:
receipt = data_cut[5].tolist()[-1]
receipt_chg = data_cut[6].tolist()[-1]
data_dict = {'var': var, 'receipt': int(receipt), 'receipt_chg': int(receipt_chg), 'date': date}
records = pd.concat([records, pd.DataFrame(data_dict, index=[0])])
if len(records.index) != 0:
records.index = records['var']
vars_in_market = [i for i in vars_list if i in records.index]
records = records.loc[vars_in_market, :]
return records.reset_index(drop=True)
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/receipt.py#L168-L215
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
] | 22.916667 |
[
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
29,
30,
31,
32,
34,
35,
36,
37,
39,
40,
41,
42,
43,
44,
45,
46,
47
] | 70.833333 | false | 7.971014 | 48 | 11 | 29.166667 | 8 |
def get_czce_receipt_1(date: str = None, vars_list: List = cons.contract_symbols):
date = cons.convert_date(date).strftime('%Y%m%d') if date is not None else datetime.date.today()
if date not in calendar:
warnings.warn('%s非交易日' % date.strftime('%Y%m%d'))
return None
if date == '20090820':
return pd.DataFrame()
url = cons.CZCE_RECEIPT_URL_1 % date
r = requests_link(url, encoding='utf-8')
context = r.text
data = pd.read_html(context)[1]
records = pd.DataFrame()
indexes = [x for x in data.index if '品种:' in str(data[0].tolist()[x])]
ends = [x for x in data.index if '总计' in str(data[0].tolist()[x])]
for i in list(range(len(indexes))):
if i != len(indexes) - 1:
data_cut = data.loc[indexes[i]:ends[i], :]
data_cut = data_cut.fillna(method='pad')
else:
data_cut = data.loc[indexes[i]:, :]
data_cut = data_cut.fillna(method='pad')
if 'PTA' in data_cut[0].tolist()[0]:
var = 'TA'
else:
var = chinese_to_english(re.sub(r'[A-Z]+', '', data_cut[0].tolist()[0][3:]))
if var == 'CF':
receipt = data_cut[6].tolist()[-1]
receipt_chg = data_cut[7].tolist()[-1]
else:
receipt = data_cut[5].tolist()[-1]
receipt_chg = data_cut[6].tolist()[-1]
data_dict = {'var': var, 'receipt': int(receipt), 'receipt_chg': int(receipt_chg), 'date': date}
records = pd.concat([records, pd.DataFrame(data_dict, index=[0])])
if len(records.index) != 0:
records.index = records['var']
vars_in_market = [i for i in vars_list if i in records.index]
records = records.loc[vars_in_market, :]
return records.reset_index(drop=True)
| 18,195 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/receipt.py
|
get_czce_receipt_2
|
(date: str = None, vars_list: List = cons.contract_symbols)
|
return records.reset_index(drop=True)
|
郑州商品交易所-注册仓单数据
http://www.czce.com.cn/cn/jysj/cdrb/H770310index_1.htm
适用 20100825(包括) - 20151111(包括)
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: 合约品种如 CF、TA 等列表为空时为所有商品
:type vars_list: list
:return: 注册仓单数据
:rtype: pandas.DataFrame
|
郑州商品交易所-注册仓单数据
http://www.czce.com.cn/cn/jysj/cdrb/H770310index_1.htm
适用 20100825(包括) - 20151111(包括)
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: 合约品种如 CF、TA 等列表为空时为所有商品
:type vars_list: list
:return: 注册仓单数据
:rtype: pandas.DataFrame
| 218 | 262 |
def get_czce_receipt_2(date: str = None, vars_list: List = cons.contract_symbols):
"""
郑州商品交易所-注册仓单数据
http://www.czce.com.cn/cn/jysj/cdrb/H770310index_1.htm
适用 20100825(包括) - 20151111(包括)
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: 合约品种如 CF、TA 等列表为空时为所有商品
:type vars_list: list
:return: 注册仓单数据
:rtype: pandas.DataFrame
"""
if not isinstance(vars_list, list):
return warnings.warn(f"symbol_list: 必须是列表")
date = cons.convert_date(date).strftime('%Y%m%d') if date is not None else datetime.date.today()
if date not in calendar:
warnings.warn('%s非交易日' % date.strftime('%Y%m%d'))
return None
url = cons.CZCE_RECEIPT_URL_2 % (date[:4], date)
r = requests.get(url)
r.encoding = 'utf-8'
data = pd.read_html(r.text)[3:]
records = pd.DataFrame()
for data_cut in data:
if len(data_cut.columns) > 3:
last_indexes = [x for x in data_cut.index if '注:' in str(data_cut[0].tolist()[x])]
if len(last_indexes) > 0:
last_index = last_indexes[0] - 1
data_cut = data_cut.loc[:last_index, :]
if 'PTA' in data_cut[0].tolist()[0]:
var = 'TA'
else:
strings = data_cut[0].tolist()[0]
string = strings.split(' ')[0][3:]
var = chinese_to_english(re.sub(r'[A-Z]+', '', string))
data_cut.columns = data_cut.T[1].tolist()
receipt = data_cut['仓单数量'].tolist()[-1]
receipt_chg = data_cut['当日增减'].tolist()[-1]
data_dict = {'var': var, 'receipt': int(receipt), 'receipt_chg': int(receipt_chg), 'date': date}
records = pd.concat([records, pd.DataFrame(data_dict, index=[0])])
if len(records.index) != 0:
records.index = records['var']
vars_in_market = [i for i in vars_list if i in records.index]
records = records.loc[vars_in_market, :]
return records.reset_index(drop=True)
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/receipt.py#L218-L262
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 26.666667 |
[
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44
] | 71.111111 | false | 7.971014 | 45 | 10 | 28.888889 | 9 |
def get_czce_receipt_2(date: str = None, vars_list: List = cons.contract_symbols):
if not isinstance(vars_list, list):
return warnings.warn(f"symbol_list: 必须是列表")
date = cons.convert_date(date).strftime('%Y%m%d') if date is not None else datetime.date.today()
if date not in calendar:
warnings.warn('%s非交易日' % date.strftime('%Y%m%d'))
return None
url = cons.CZCE_RECEIPT_URL_2 % (date[:4], date)
r = requests.get(url)
r.encoding = 'utf-8'
data = pd.read_html(r.text)[3:]
records = pd.DataFrame()
for data_cut in data:
if len(data_cut.columns) > 3:
last_indexes = [x for x in data_cut.index if '注:' in str(data_cut[0].tolist()[x])]
if len(last_indexes) > 0:
last_index = last_indexes[0] - 1
data_cut = data_cut.loc[:last_index, :]
if 'PTA' in data_cut[0].tolist()[0]:
var = 'TA'
else:
strings = data_cut[0].tolist()[0]
string = strings.split(' ')[0][3:]
var = chinese_to_english(re.sub(r'[A-Z]+', '', string))
data_cut.columns = data_cut.T[1].tolist()
receipt = data_cut['仓单数量'].tolist()[-1]
receipt_chg = data_cut['当日增减'].tolist()[-1]
data_dict = {'var': var, 'receipt': int(receipt), 'receipt_chg': int(receipt_chg), 'date': date}
records = pd.concat([records, pd.DataFrame(data_dict, index=[0])])
if len(records.index) != 0:
records.index = records['var']
vars_in_market = [i for i in vars_list if i in records.index]
records = records.loc[vars_in_market, :]
return records.reset_index(drop=True)
| 18,196 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/receipt.py
|
get_czce_receipt_3
|
(date: str = None, vars_list: List = cons.contract_symbols)
|
return records.reset_index(drop=True)
|
郑州商品交易所-注册仓单数据
适用 20151008-至今
http://www.czce.com.cn/cn/jysj/cdrb/H770310index_1.htm
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: 合约品种如 CF、TA 等列表为空时为所有商品
:type vars_list: list
:return: 注册仓单数据
:rtype: pandas.DataFrame
|
郑州商品交易所-注册仓单数据
适用 20151008-至今
http://www.czce.com.cn/cn/jysj/cdrb/H770310index_1.htm
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: 合约品种如 CF、TA 等列表为空时为所有商品
:type vars_list: list
:return: 注册仓单数据
:rtype: pandas.DataFrame
| 265 | 335 |
def get_czce_receipt_3(date: str = None, vars_list: List = cons.contract_symbols) -> pd.DataFrame:
"""
郑州商品交易所-注册仓单数据
适用 20151008-至今
http://www.czce.com.cn/cn/jysj/cdrb/H770310index_1.htm
:param date: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type date: str
:param vars_list: 合约品种如 CF、TA 等列表为空时为所有商品
:type vars_list: list
:return: 注册仓单数据
:rtype: pandas.DataFrame
"""
if not isinstance(vars_list, list):
return warnings.warn("vars_list: 必须是列表")
date = cons.convert_date(date).strftime('%Y%m%d') if date is not None else datetime.date.today()
if date not in calendar:
warnings.warn('%s非交易日' % date.strftime('%Y%m%d'))
return None
url = f"http://www.czce.com.cn/cn/DFSStaticFiles/Future/{date[:4]}/{date}/FutureDataWhsheet.xls"
r = requests_link(url, encoding='utf-8')
temp_df = pd.read_excel(BytesIO(r.content))
temp_df = temp_df[[bool(1-item) for item in [item if item is not pd.NA else False for item in temp_df.iloc[:, 0].str.contains("非农产品")]]]
temp_df.reset_index(inplace=True, drop=True)
range_list_one = list(temp_df[[item if not pd.isnull(item) else False for item in temp_df.iloc[:, 0].str.contains("品种")]].index)
range_list_two = list(temp_df[[item if not pd.isnull(item) else False for item in temp_df.iloc[:, 0].str.contains("品种")]].index)[1:]
range_list_two.append(None)
symbol_list = []
receipt_list = []
receipt_chg_list = []
for page in range(len(range_list_one)):
inner_df = temp_df[range_list_one[page]: range_list_two[page]]
reg = re.compile(r'[A-Z]+')
try:
symbol = reg.findall(inner_df.iloc[0, 0])[0]
except:
continue
symbol_list.append(symbol)
inner_df.columns = inner_df.iloc[1, :]
inner_df = inner_df.iloc[2:, :]
inner_df = inner_df.dropna(axis=1, how='all')
if symbol == "PTA":
try:
receipt_list.append(inner_df['仓单数量(完税)'].iloc[-1] + inner_df['仓单数量(保税)'].iloc[-1]) # 20210316 TA 分为保税和完税
except:
receipt_list.append(0)
elif symbol == "MA":
try:
try:
receipt_list.append(inner_df['仓单数量(完税)'].iloc[-2] + inner_df['仓单数量(保税)'].iloc[-2]) # 20210316 MA 分为保税和完税
except:
receipt_list.append(inner_df['仓单数量(完税)'].iloc[-2]) # 处理 MA 的特殊格式
except:
receipt_list.append(0)
else:
try:
receipt_list.append(inner_df['仓单数量'].iloc[-1])
except:
receipt_list.append(0)
if symbol == "MA":
receipt_chg_list.append(inner_df['当日增减'].iloc[-2])
else:
receipt_chg_list.append(inner_df['当日增减'].iloc[-1])
data_df = pd.DataFrame([symbol_list, receipt_list, receipt_chg_list, [date]*len(receipt_chg_list)]).T
data_df.columns = ['var', 'receipt', 'receipt_chg', 'date']
temp_list = data_df['var'].tolist()
data_df['var'] = [item if item != "PTA" else "TA" for item in temp_list]
if len(data_df.index) != 0:
data_df.index = data_df['var']
vars_in_market = [i for i in vars_list if i in data_df.index]
records = data_df.loc[vars_in_market, :]
return records.reset_index(drop=True)
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/receipt.py#L265-L335
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 16.901408 |
[
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
54,
55,
56,
57,
58,
59,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70
] | 80.28169 | false | 7.971014 | 71 | 19 | 19.71831 | 9 |
def get_czce_receipt_3(date: str = None, vars_list: List = cons.contract_symbols) -> pd.DataFrame:
if not isinstance(vars_list, list):
return warnings.warn("vars_list: 必须是列表")
date = cons.convert_date(date).strftime('%Y%m%d') if date is not None else datetime.date.today()
if date not in calendar:
warnings.warn('%s非交易日' % date.strftime('%Y%m%d'))
return None
url = f"http://www.czce.com.cn/cn/DFSStaticFiles/Future/{date[:4]}/{date}/FutureDataWhsheet.xls"
r = requests_link(url, encoding='utf-8')
temp_df = pd.read_excel(BytesIO(r.content))
temp_df = temp_df[[bool(1-item) for item in [item if item is not pd.NA else False for item in temp_df.iloc[:, 0].str.contains("非农产品")]]]
temp_df.reset_index(inplace=True, drop=True)
range_list_one = list(temp_df[[item if not pd.isnull(item) else False for item in temp_df.iloc[:, 0].str.contains("品种")]].index)
range_list_two = list(temp_df[[item if not pd.isnull(item) else False for item in temp_df.iloc[:, 0].str.contains("品种")]].index)[1:]
range_list_two.append(None)
symbol_list = []
receipt_list = []
receipt_chg_list = []
for page in range(len(range_list_one)):
inner_df = temp_df[range_list_one[page]: range_list_two[page]]
reg = re.compile(r'[A-Z]+')
try:
symbol = reg.findall(inner_df.iloc[0, 0])[0]
except:
continue
symbol_list.append(symbol)
inner_df.columns = inner_df.iloc[1, :]
inner_df = inner_df.iloc[2:, :]
inner_df = inner_df.dropna(axis=1, how='all')
if symbol == "PTA":
try:
receipt_list.append(inner_df['仓单数量(完税)'].iloc[-1] + inner_df['仓单数量(保税)'].iloc[-1]) # 20210316 TA 分为保税和完税
except:
receipt_list.append(0)
elif symbol == "MA":
try:
try:
receipt_list.append(inner_df['仓单数量(完税)'].iloc[-2] + inner_df['仓单数量(保税)'].iloc[-2]) # 20210316 MA 分为保税和完税
except:
receipt_list.append(inner_df['仓单数量(完税)'].iloc[-2]) # 处理 MA 的特殊格式
except:
receipt_list.append(0)
else:
try:
receipt_list.append(inner_df['仓单数量'].iloc[-1])
except:
receipt_list.append(0)
if symbol == "MA":
receipt_chg_list.append(inner_df['当日增减'].iloc[-2])
else:
receipt_chg_list.append(inner_df['当日增减'].iloc[-1])
data_df = pd.DataFrame([symbol_list, receipt_list, receipt_chg_list, [date]*len(receipt_chg_list)]).T
data_df.columns = ['var', 'receipt', 'receipt_chg', 'date']
temp_list = data_df['var'].tolist()
data_df['var'] = [item if item != "PTA" else "TA" for item in temp_list]
if len(data_df.index) != 0:
data_df.index = data_df['var']
vars_in_market = [i for i in vars_list if i in data_df.index]
records = data_df.loc[vars_in_market, :]
return records.reset_index(drop=True)
| 18,197 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/receipt.py
|
get_receipt
|
(start_day: str = None, end_day: str = None, vars_list: List = cons.contract_symbols)
|
return records
|
大宗商品-注册仓单数据
:param start_day: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type start_day: str
:param end_day: 结束数据 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type end_day: str
:param vars_list: 合约品种如 RB、AL 等列表为空时为所有商品
:type vars_list: str
:return: 展期收益率数据
:rtype: pandas.DataFrame
|
大宗商品-注册仓单数据
:param start_day: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type start_day: str
:param end_day: 结束数据 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type end_day: str
:param vars_list: 合约品种如 RB、AL 等列表为空时为所有商品
:type vars_list: str
:return: 展期收益率数据
:rtype: pandas.DataFrame
| 338 | 397 |
def get_receipt(start_day: str = None, end_day: str = None, vars_list: List = cons.contract_symbols):
"""
大宗商品-注册仓单数据
:param start_day: 开始日期 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type start_day: str
:param end_day: 结束数据 format:YYYY-MM-DD 或 YYYYMMDD 或 datetime.date对象 为空时为当天
:type end_day: str
:param vars_list: 合约品种如 RB、AL 等列表为空时为所有商品
:type vars_list: str
:return: 展期收益率数据
:rtype: pandas.DataFrame
"""
if not isinstance(vars_list, list):
return warnings.warn(f"vars_list: 必须是列表")
start_day = cons.convert_date(start_day) if start_day is not None else datetime.date.today()
end_day = cons.convert_date(end_day) if end_day is not None else cons.convert_date(
cons.get_latest_data_date(datetime.datetime.now()))
records = pd.DataFrame()
while start_day <= end_day:
if start_day.strftime('%Y%m%d') not in calendar:
warnings.warn(f"{start_day.strftime('%Y%m%d')}非交易日")
else:
print(start_day)
for market, market_vars in cons.market_exchange_symbols.items():
if market == 'dce':
if start_day >= datetime.date(2009, 4, 7):
f = get_dce_receipt
else:
print('20090407 起,大连商品交易所每个交易日更新仓单数据')
f = None
elif market == 'shfe':
if datetime.date(2008, 10, 6) <= start_day <= datetime.date(2014, 5, 16):
f = get_shfe_receipt_1
elif start_day > datetime.date(2014, 5, 16):
f = get_shfe_receipt_2
else:
f = None
print('20081006 起,上海期货交易所每个交易日更新仓单数据')
elif market == 'czce':
if datetime.date(2008, 3, 3) <= start_day <= datetime.date(2010, 8, 24):
f = get_czce_receipt_1
elif datetime.date(2010, 8, 24) < start_day <= datetime.date(2015, 11, 11):
f = get_czce_receipt_2
elif start_day > datetime.date(2015, 11, 11):
f = get_czce_receipt_3
else:
f = None
print('20080303 起,郑州商品交易所每个交易日更新仓单数据')
get_vars = [var for var in vars_list if var in market_vars]
if market != 'cffex' and get_vars != []:
if f is not None:
records = pd.concat([records, f(start_day, get_vars)])
start_day += datetime.timedelta(days=1)
records.reset_index(drop=True, inplace=True)
if records.empty:
return records
if "MA" in records["var"].to_list():
replace_index = records[records["var"] == "MA"]["receipt"].astype(str).str.split("0", expand=True)[0].index
records.loc[replace_index, "receipt"] = records[records["var"] == "MA"]["receipt"].astype(str).str.split("0", expand=True)[0]
return records
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/receipt.py#L338-L397
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 20 |
[
12,
13,
14,
15,
17,
18,
19,
20,
22,
23,
24,
25,
26,
28,
29,
30,
31,
32,
33,
34,
36,
37,
38,
39,
40,
41,
42,
43,
44,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
57,
58,
59
] | 71.666667 | false | 7.971014 | 60 | 20 | 28.333333 | 9 |
def get_receipt(start_day: str = None, end_day: str = None, vars_list: List = cons.contract_symbols):
if not isinstance(vars_list, list):
return warnings.warn(f"vars_list: 必须是列表")
start_day = cons.convert_date(start_day) if start_day is not None else datetime.date.today()
end_day = cons.convert_date(end_day) if end_day is not None else cons.convert_date(
cons.get_latest_data_date(datetime.datetime.now()))
records = pd.DataFrame()
while start_day <= end_day:
if start_day.strftime('%Y%m%d') not in calendar:
warnings.warn(f"{start_day.strftime('%Y%m%d')}非交易日")
else:
print(start_day)
for market, market_vars in cons.market_exchange_symbols.items():
if market == 'dce':
if start_day >= datetime.date(2009, 4, 7):
f = get_dce_receipt
else:
print('20090407 起,大连商品交易所每个交易日更新仓单数据')
f = None
elif market == 'shfe':
if datetime.date(2008, 10, 6) <= start_day <= datetime.date(2014, 5, 16):
f = get_shfe_receipt_1
elif start_day > datetime.date(2014, 5, 16):
f = get_shfe_receipt_2
else:
f = None
print('20081006 起,上海期货交易所每个交易日更新仓单数据')
elif market == 'czce':
if datetime.date(2008, 3, 3) <= start_day <= datetime.date(2010, 8, 24):
f = get_czce_receipt_1
elif datetime.date(2010, 8, 24) < start_day <= datetime.date(2015, 11, 11):
f = get_czce_receipt_2
elif start_day > datetime.date(2015, 11, 11):
f = get_czce_receipt_3
else:
f = None
print('20080303 起,郑州商品交易所每个交易日更新仓单数据')
get_vars = [var for var in vars_list if var in market_vars]
if market != 'cffex' and get_vars != []:
if f is not None:
records = pd.concat([records, f(start_day, get_vars)])
start_day += datetime.timedelta(days=1)
records.reset_index(drop=True, inplace=True)
if records.empty:
return records
if "MA" in records["var"].to_list():
replace_index = records[records["var"] == "MA"]["receipt"].astype(str).str.split("0", expand=True)[0].index
records.loc[replace_index, "receipt"] = records[records["var"] == "MA"]["receipt"].astype(str).str.split("0", expand=True)[0]
return records
| 18,198 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_inventory_em.py
|
futures_inventory_em
|
(symbol: str = "沪铝") ->
|
return temp_df
|
东方财富网-数据中心-期货库存数据
https://data.eastmoney.com/ifdata/kcsj.html
:param symbol: https://data.eastmoney.com/ifdata/kcsj.html 对应的中文名称, 如: 沪铝
:type symbol: str
:return: 指定品种的库存数据
:rtype: pandas.DataFrame
|
东方财富网-数据中心-期货库存数据
https://data.eastmoney.com/ifdata/kcsj.html
:param symbol: https://data.eastmoney.com/ifdata/kcsj.html 对应的中文名称, 如: 沪铝
:type symbol: str
:return: 指定品种的库存数据
:rtype: pandas.DataFrame
| 12 | 61 |
def futures_inventory_em(symbol: str = "沪铝") -> pd.DataFrame:
"""
东方财富网-数据中心-期货库存数据
https://data.eastmoney.com/ifdata/kcsj.html
:param symbol: https://data.eastmoney.com/ifdata/kcsj.html 对应的中文名称, 如: 沪铝
:type symbol: str
:return: 指定品种的库存数据
:rtype: pandas.DataFrame
"""
url = "https://datacenter-web.eastmoney.com/api/data/v1/get"
params = {
"reportName": "RPT_FUTU_POSITIONCODE",
"columns": "TRADE_MARKET_CODE,TRADE_CODE,TRADE_TYPE",
"filter": '(IS_MAINCODE="1")',
"pageNumber": "1",
"pageSize": "500",
"source": "WEB",
"client": "WEB",
"_": "1669352163467",
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json["result"]["data"])
symbol_dict = dict(zip(temp_df["TRADE_TYPE"], temp_df["TRADE_CODE"]))
url = "https://datacenter-web.eastmoney.com/api/data/v1/get"
params = {
"reportName": "RPT_FUTU_STOCKDATA",
"columns": "SECURITY_CODE,TRADE_DATE,ON_WARRANT_NUM,ADDCHANGE",
"filter": f"""(SECURITY_CODE="{symbol_dict[symbol]}")(TRADE_DATE>='2020-10-28')""",
"pageNumber": "1",
"pageSize": "500",
"sortTypes": "-1",
"sortColumns": "TRADE_DATE",
"source": "WEB",
"client": "WEB",
"_": "1669352163467",
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json["result"]["data"])
temp_df.columns = ["-", "日期", "库存", "增减"]
temp_df = temp_df[["日期", "库存", "增减"]]
temp_df.sort_values(["日期"], inplace=True)
temp_df.reset_index(inplace=True, drop=True)
temp_df["库存"] = pd.to_numeric(temp_df["库存"], errors="coerce")
temp_df["增减"] = pd.to_numeric(temp_df["增减"], errors="coerce")
temp_df["日期"] = pd.to_datetime(temp_df["日期"]).dt.date
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_inventory_em.py#L12-L61
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 18 |
[
9,
10,
20,
21,
22,
23,
25,
26,
38,
39,
40,
42,
43,
44,
45,
46,
47,
48,
49
] | 38 | false | 19.230769 | 50 | 1 | 62 | 6 |
def futures_inventory_em(symbol: str = "沪铝") -> pd.DataFrame:
url = "https://datacenter-web.eastmoney.com/api/data/v1/get"
params = {
"reportName": "RPT_FUTU_POSITIONCODE",
"columns": "TRADE_MARKET_CODE,TRADE_CODE,TRADE_TYPE",
"filter": '(IS_MAINCODE="1")',
"pageNumber": "1",
"pageSize": "500",
"source": "WEB",
"client": "WEB",
"_": "1669352163467",
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json["result"]["data"])
symbol_dict = dict(zip(temp_df["TRADE_TYPE"], temp_df["TRADE_CODE"]))
url = "https://datacenter-web.eastmoney.com/api/data/v1/get"
params = {
"reportName": "RPT_FUTU_STOCKDATA",
"columns": "SECURITY_CODE,TRADE_DATE,ON_WARRANT_NUM,ADDCHANGE",
"filter": f"""(SECURITY_CODE="{symbol_dict[symbol]}")(TRADE_DATE>='2020-10-28')""",
"pageNumber": "1",
"pageSize": "500",
"sortTypes": "-1",
"sortColumns": "TRADE_DATE",
"source": "WEB",
"client": "WEB",
"_": "1669352163467",
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json["result"]["data"])
temp_df.columns = ["-", "日期", "库存", "增减"]
temp_df = temp_df[["日期", "库存", "增减"]]
temp_df.sort_values(["日期"], inplace=True)
temp_df.reset_index(inplace=True, drop=True)
temp_df["库存"] = pd.to_numeric(temp_df["库存"], errors="coerce")
temp_df["增减"] = pd.to_numeric(temp_df["增减"], errors="coerce")
temp_df["日期"] = pd.to_datetime(temp_df["日期"]).dt.date
return temp_df
| 18,199 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_to_spot.py
|
futures_to_spot_shfe
|
(date: str = "202101")
|
return temp_df
|
上海期货交易所-期转现
http://www.shfe.com.cn/statements/dataview.html?paramid=kx
1、铜、铜(BC)、铝、锌、铅、镍、锡、螺纹钢、线材、热轧卷板、天然橡胶、20号胶、低硫燃料油、燃料油、石油沥青、纸浆、不锈钢的数量单位为:吨;黄金的数量单位为:克;白银的数量单位为:千克;原油的数量单位为:桶。
2、交割量、期转现量为单向计算。
:param date: 年月
:type date: str
:return: 上海期货交易所期转现
:rtype: pandas.DataFrame
|
上海期货交易所-期转现
http://www.shfe.com.cn/statements/dataview.html?paramid=kx
1、铜、铜(BC)、铝、锌、铅、镍、锡、螺纹钢、线材、热轧卷板、天然橡胶、20号胶、低硫燃料油、燃料油、石油沥青、纸浆、不锈钢的数量单位为:吨;黄金的数量单位为:克;白银的数量单位为:千克;原油的数量单位为:桶。
2、交割量、期转现量为单向计算。
:param date: 年月
:type date: str
:return: 上海期货交易所期转现
:rtype: pandas.DataFrame
| 11 | 44 |
def futures_to_spot_shfe(date: str = "202101") -> pd.DataFrame:
"""
上海期货交易所-期转现
http://www.shfe.com.cn/statements/dataview.html?paramid=kx
1、铜、铜(BC)、铝、锌、铅、镍、锡、螺纹钢、线材、热轧卷板、天然橡胶、20号胶、低硫燃料油、燃料油、石油沥青、纸浆、不锈钢的数量单位为:吨;黄金的数量单位为:克;白银的数量单位为:千克;原油的数量单位为:桶。
2、交割量、期转现量为单向计算。
:param date: 年月
:type date: str
:return: 上海期货交易所期转现
:rtype: pandas.DataFrame
"""
url = f"http://www.shfe.com.cn/data/instrument/ExchangeDelivery{date}.dat"
r = requests.get(url)
data_json = r.json()
temp_df = pd.DataFrame(data_json["ExchangeDelivery"])
temp_df.columns = [
"_",
"日期",
"交割量",
"_",
"期转现量",
"合约",
"_",
"_",
]
temp_df = temp_df[
[
"日期",
"合约",
"交割量",
"期转现量",
]
]
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_to_spot.py#L11-L44
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
] | 32.352941 |
[
11,
12,
13,
14,
15,
25,
33
] | 20.588235 | false | 11.320755 | 34 | 1 | 79.411765 | 8 |
def futures_to_spot_shfe(date: str = "202101") -> pd.DataFrame:
url = f"http://www.shfe.com.cn/data/instrument/ExchangeDelivery{date}.dat"
r = requests.get(url)
data_json = r.json()
temp_df = pd.DataFrame(data_json["ExchangeDelivery"])
temp_df.columns = [
"_",
"日期",
"交割量",
"_",
"期转现量",
"合约",
"_",
"_",
]
temp_df = temp_df[
[
"日期",
"合约",
"交割量",
"期转现量",
]
]
return temp_df
| 18,200 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_to_spot.py
|
futures_delivery_dce
|
(date: str = "202101")
|
return temp_df
|
大连商品交易所-交割统计
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/jgtj/jgsj/index.html
:param date: 交割日期
:type date: str
:return: 大连商品交易所-交割统计
:rtype: pandas.DataFrame
|
大连商品交易所-交割统计
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/jgtj/jgsj/index.html
:param date: 交割日期
:type date: str
:return: 大连商品交易所-交割统计
:rtype: pandas.DataFrame
| 47 | 79 |
def futures_delivery_dce(date: str = "202101") -> pd.DataFrame:
"""
大连商品交易所-交割统计
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/jgtj/jgsj/index.html
:param date: 交割日期
:type date: str
:return: 大连商品交易所-交割统计
:rtype: pandas.DataFrame
"""
url = "http://www.dce.com.cn/publicweb/quotesdata/delivery.html"
params = {
"deliveryQuotes.variety": "all",
"year": "",
"month": "",
"deliveryQuotes.begin_month": date,
"deliveryQuotes.end_month": str(int(date) + 1),
}
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
}
r = requests.post(url, params=params, headers=headers)
temp_df = pd.read_html(r.text)[0]
temp_df["交割日期"] = (
temp_df["交割日期"].astype(str).str.split(".", expand=True).iloc[:, 0]
)
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_to_spot.py#L47-L79
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 27.272727 |
[
9,
10,
17,
27,
28,
29,
32
] | 21.212121 | false | 11.320755 | 33 | 1 | 78.787879 | 6 |
def futures_delivery_dce(date: str = "202101") -> pd.DataFrame:
url = "http://www.dce.com.cn/publicweb/quotesdata/delivery.html"
params = {
"deliveryQuotes.variety": "all",
"year": "",
"month": "",
"deliveryQuotes.begin_month": date,
"deliveryQuotes.end_month": str(int(date) + 1),
}
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Pragma": "no-cache",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
}
r = requests.post(url, params=params, headers=headers)
temp_df = pd.read_html(r.text)[0]
temp_df["交割日期"] = (
temp_df["交割日期"].astype(str).str.split(".", expand=True).iloc[:, 0]
)
return temp_df
| 18,201 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_to_spot.py
|
futures_to_spot_dce
|
(date: str = "202102")
|
return temp_df
|
大连商品交易所-期转现
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/jgtj/qzxcx/index.html
:param date: 期转现日期
:type date: str
:return: 大连商品交易所-期转现
:rtype: pandas.DataFrame
|
大连商品交易所-期转现
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/jgtj/qzxcx/index.html
:param date: 期转现日期
:type date: str
:return: 大连商品交易所-期转现
:rtype: pandas.DataFrame
| 82 | 104 |
def futures_to_spot_dce(date: str = "202102") -> pd.DataFrame:
"""
大连商品交易所-期转现
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/jgtj/qzxcx/index.html
:param date: 期转现日期
:type date: str
:return: 大连商品交易所-期转现
:rtype: pandas.DataFrame
"""
url = "http://www.dce.com.cn/publicweb/quotesdata/ftsDeal.html"
params = {
"ftsDealQuotes.variety": "all",
"year": "",
"month": "",
"ftsDealQuotes.begin_month": date,
"ftsDealQuotes.end_month": date,
}
r = requests.post(url, params=params)
temp_df = pd.read_html(r.text)[0]
temp_df["期转现发生日期"] = (
temp_df["期转现发生日期"].astype(str).str.split(".", expand=True).iloc[:, 0]
)
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_to_spot.py#L82-L104
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 39.130435 |
[
9,
10,
17,
18,
19,
22
] | 26.086957 | false | 11.320755 | 23 | 1 | 73.913043 | 6 |
def futures_to_spot_dce(date: str = "202102") -> pd.DataFrame:
url = "http://www.dce.com.cn/publicweb/quotesdata/ftsDeal.html"
params = {
"ftsDealQuotes.variety": "all",
"year": "",
"month": "",
"ftsDealQuotes.begin_month": date,
"ftsDealQuotes.end_month": date,
}
r = requests.post(url, params=params)
temp_df = pd.read_html(r.text)[0]
temp_df["期转现发生日期"] = (
temp_df["期转现发生日期"].astype(str).str.split(".", expand=True).iloc[:, 0]
)
return temp_df
| 18,202 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_to_spot.py
|
futures_delivery_match_dce
|
(symbol: str = "a")
|
return temp_df
|
大连商品交易所-交割配对表
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/jgtj/jgsj/index.html
:param symbol: 交割品种
:type symbol: str
:return: 大连商品交易所-交割配对表
:rtype: pandas.DataFrame
|
大连商品交易所-交割配对表
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/jgtj/jgsj/index.html
:param symbol: 交割品种
:type symbol: str
:return: 大连商品交易所-交割配对表
:rtype: pandas.DataFrame
| 107 | 127 |
def futures_delivery_match_dce(symbol: str = "a") -> pd.DataFrame:
"""
大连商品交易所-交割配对表
http://www.dce.com.cn/dalianshangpin/xqsj/tjsj26/jgtj/jgsj/index.html
:param symbol: 交割品种
:type symbol: str
:return: 大连商品交易所-交割配对表
:rtype: pandas.DataFrame
"""
url = "http://www.dce.com.cn/publicweb/quotesdata/deliveryMatch.html"
params = {
"deliveryMatchQuotes.variety": symbol,
"contract.contract_id": "all",
"contract.variety_id": symbol,
}
r = requests.post(url, params=params)
temp_df = pd.read_html(r.text)[0]
temp_df["配对日期"] = (
temp_df["配对日期"].astype(str).str.split(".", expand=True).iloc[:, 0]
)
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_to_spot.py#L107-L127
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 42.857143 |
[
9,
10,
15,
16,
17,
20
] | 28.571429 | false | 11.320755 | 21 | 1 | 71.428571 | 6 |
def futures_delivery_match_dce(symbol: str = "a") -> pd.DataFrame:
url = "http://www.dce.com.cn/publicweb/quotesdata/deliveryMatch.html"
params = {
"deliveryMatchQuotes.variety": symbol,
"contract.contract_id": "all",
"contract.variety_id": symbol,
}
r = requests.post(url, params=params)
temp_df = pd.read_html(r.text)[0]
temp_df["配对日期"] = (
temp_df["配对日期"].astype(str).str.split(".", expand=True).iloc[:, 0]
)
return temp_df
| 18,203 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_to_spot.py
|
futures_to_spot_czce
|
(date: str = "20210112")
|
return temp_df
|
郑州商品交易所-期转现统计
http://www.czce.com.cn/cn/jysj/qzxtj/H770311index_1.htm
:param date: 年月日
:type date: str
:return: 郑州商品交易所-期转现统计
:rtype: pandas.DataFrame
|
郑州商品交易所-期转现统计
http://www.czce.com.cn/cn/jysj/qzxtj/H770311index_1.htm
:param date: 年月日
:type date: str
:return: 郑州商品交易所-期转现统计
:rtype: pandas.DataFrame
| 130 | 168 |
def futures_to_spot_czce(date: str = "20210112") -> pd.DataFrame:
"""
郑州商品交易所-期转现统计
http://www.czce.com.cn/cn/jysj/qzxtj/H770311index_1.htm
:param date: 年月日
:type date: str
:return: 郑州商品交易所-期转现统计
:rtype: pandas.DataFrame
"""
url = f"http://www.czce.com.cn/cn/DFSStaticFiles/Future/{date[:4]}/{date}/FutureDataTrdtrades.xls"
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Host": "www.czce.com.cn",
"Pragma": "no-cache",
"Referer": "http://www.czce.com.cn/",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
}
r = requests.get(url, headers=headers)
r.encoding = "utf-8"
temp_df = pd.read_excel(r.content, skiprows=1)
temp_df.columns = [
"合约代码",
"合约数量",
]
temp_df = temp_df[
[
"合约代码",
"合约数量",
]
]
temp_df["合约数量"] = temp_df["合约数量"].str.replace(",", "")
temp_df["合约数量"] = pd.to_numeric(temp_df["合约数量"])
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_to_spot.py#L130-L168
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 23.076923 |
[
9,
10,
22,
23,
24,
26,
30,
36,
37,
38
] | 25.641026 | false | 11.320755 | 39 | 1 | 74.358974 | 6 |
def futures_to_spot_czce(date: str = "20210112") -> pd.DataFrame:
url = f"http://www.czce.com.cn/cn/DFSStaticFiles/Future/{date[:4]}/{date}/FutureDataTrdtrades.xls"
headers = {
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Host": "www.czce.com.cn",
"Pragma": "no-cache",
"Referer": "http://www.czce.com.cn/",
"Upgrade-Insecure-Requests": "1",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36",
}
r = requests.get(url, headers=headers)
r.encoding = "utf-8"
temp_df = pd.read_excel(r.content, skiprows=1)
temp_df.columns = [
"合约代码",
"合约数量",
]
temp_df = temp_df[
[
"合约代码",
"合约数量",
]
]
temp_df["合约数量"] = temp_df["合约数量"].str.replace(",", "")
temp_df["合约数量"] = pd.to_numeric(temp_df["合约数量"])
return temp_df
| 18,204 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_to_spot.py
|
futures_delivery_match_czce
|
(date: str = "20210106")
|
return big_df
|
郑州商品交易所-交割配对
http://www.czce.com.cn/cn/jysj/jgpd/H770308index_1.htm
:param date: 年月日
:type date: str
:return: 郑州商品交易所-交割配对
:rtype: pandas.DataFrame
|
郑州商品交易所-交割配对
http://www.czce.com.cn/cn/jysj/jgpd/H770308index_1.htm
:param date: 年月日
:type date: str
:return: 郑州商品交易所-交割配对
:rtype: pandas.DataFrame
| 171 | 216 |
def futures_delivery_match_czce(date: str = "20210106") -> pd.DataFrame:
"""
郑州商品交易所-交割配对
http://www.czce.com.cn/cn/jysj/jgpd/H770308index_1.htm
:param date: 年月日
:type date: str
:return: 郑州商品交易所-交割配对
:rtype: pandas.DataFrame
"""
url = f"http://www.czce.com.cn/cn/DFSStaticFiles/Future/{date[:4]}/{date}/FutureDataDelsettle.xls"
r = requests.get(url)
r.encoding = "utf-8"
temp_df = pd.read_excel(r.content, skiprows=0)
index_flag = temp_df[temp_df.iloc[:, 0].str.contains("配对日期")].index.values
big_df = pd.DataFrame()
for i, item in enumerate(index_flag):
try:
temp_inner_df = temp_df[index_flag[i] + 1 : index_flag[i + 1]]
except:
temp_inner_df = temp_df[index_flag[i] + 1 :]
temp_inner_df.columns = temp_inner_df.iloc[0, :]
temp_inner_df = temp_inner_df.iloc[1:-1, :]
temp_inner_df.reset_index(drop=True, inplace=True)
date_contract_str = (
temp_df[temp_df.iloc[:, 0].str.contains("配对日期")]
.iloc[:, 0]
.values[i]
)
inner_date = date_contract_str.split(":")[1].split(" ")[0]
symbol = date_contract_str.split(":")[-1]
temp_inner_df["配对日期"] = inner_date
temp_inner_df["合约代码"] = symbol
big_df = pd.concat([big_df, temp_inner_df], ignore_index=True)
big_df.columns = [
"卖方会员",
"卖方会员-会员简称",
"买方会员",
"买方会员-会员简称",
"交割量",
"配对日期",
"合约代码",
]
big_df["交割量"] = big_df["交割量"].str.replace(",", "")
big_df["交割量"] = pd.to_numeric(big_df["交割量"])
return big_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_to_spot.py#L171-L216
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 19.565217 |
[
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
28,
29,
30,
31,
32,
34,
43,
44,
45
] | 52.173913 | false | 11.320755 | 46 | 3 | 47.826087 | 6 |
def futures_delivery_match_czce(date: str = "20210106") -> pd.DataFrame:
url = f"http://www.czce.com.cn/cn/DFSStaticFiles/Future/{date[:4]}/{date}/FutureDataDelsettle.xls"
r = requests.get(url)
r.encoding = "utf-8"
temp_df = pd.read_excel(r.content, skiprows=0)
index_flag = temp_df[temp_df.iloc[:, 0].str.contains("配对日期")].index.values
big_df = pd.DataFrame()
for i, item in enumerate(index_flag):
try:
temp_inner_df = temp_df[index_flag[i] + 1 : index_flag[i + 1]]
except:
temp_inner_df = temp_df[index_flag[i] + 1 :]
temp_inner_df.columns = temp_inner_df.iloc[0, :]
temp_inner_df = temp_inner_df.iloc[1:-1, :]
temp_inner_df.reset_index(drop=True, inplace=True)
date_contract_str = (
temp_df[temp_df.iloc[:, 0].str.contains("配对日期")]
.iloc[:, 0]
.values[i]
)
inner_date = date_contract_str.split(":")[1].split(" ")[0]
symbol = date_contract_str.split(":")[-1]
temp_inner_df["配对日期"] = inner_date
temp_inner_df["合约代码"] = symbol
big_df = pd.concat([big_df, temp_inner_df], ignore_index=True)
big_df.columns = [
"卖方会员",
"卖方会员-会员简称",
"买方会员",
"买方会员-会员简称",
"交割量",
"配对日期",
"合约代码",
]
big_df["交割量"] = big_df["交割量"].str.replace(",", "")
big_df["交割量"] = pd.to_numeric(big_df["交割量"])
return big_df
| 18,205 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_to_spot.py
|
futures_delivery_czce
|
(date: str = "20210112")
|
return temp_df
|
郑州商品交易所-月度交割查询
http://www.czce.com.cn/cn/jysj/ydjgcx/H770316index_1.htm
:param date: 年月日
:type date: str
:return: 郑州商品交易所-月度交割查询
:rtype: pandas.DataFrame
|
郑州商品交易所-月度交割查询
http://www.czce.com.cn/cn/jysj/ydjgcx/H770316index_1.htm
:param date: 年月日
:type date: str
:return: 郑州商品交易所-月度交割查询
:rtype: pandas.DataFrame
| 219 | 242 |
def futures_delivery_czce(date: str = "20210112") -> pd.DataFrame:
"""
郑州商品交易所-月度交割查询
http://www.czce.com.cn/cn/jysj/ydjgcx/H770316index_1.htm
:param date: 年月日
:type date: str
:return: 郑州商品交易所-月度交割查询
:rtype: pandas.DataFrame
"""
url = f"http://www.czce.com.cn/cn/DFSStaticFiles/Future/{date[:4]}/{date}/FutureDataSettlematched.xls"
r = requests.get(url)
r.encoding = "utf-8"
temp_df = pd.read_excel(r.content, skiprows=1)
temp_df.columns = [
"品种",
"交割数量",
"交割额",
]
temp_df["交割数量"] = temp_df["交割数量"].str.replace(",", "")
temp_df["交割额"] = temp_df["交割额"].str.replace(",", "")
temp_df["交割数量"] = pd.to_numeric(temp_df["交割数量"])
temp_df["交割额"] = pd.to_numeric(temp_df["交割额"])
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_to_spot.py#L219-L242
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 37.5 |
[
9,
10,
11,
12,
13,
18,
19,
21,
22,
23
] | 41.666667 | false | 11.320755 | 24 | 1 | 58.333333 | 6 |
def futures_delivery_czce(date: str = "20210112") -> pd.DataFrame:
url = f"http://www.czce.com.cn/cn/DFSStaticFiles/Future/{date[:4]}/{date}/FutureDataSettlematched.xls"
r = requests.get(url)
r.encoding = "utf-8"
temp_df = pd.read_excel(r.content, skiprows=1)
temp_df.columns = [
"品种",
"交割数量",
"交割额",
]
temp_df["交割数量"] = temp_df["交割数量"].str.replace(",", "")
temp_df["交割额"] = temp_df["交割额"].str.replace(",", "")
temp_df["交割数量"] = pd.to_numeric(temp_df["交割数量"])
temp_df["交割额"] = pd.to_numeric(temp_df["交割额"])
return temp_df
| 18,206 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_to_spot.py
|
futures_delivery_shfe
|
(date: str = "202003")
|
return temp_df
|
上海期货交易所-交割情况表
http://www.shfe.com.cn/statements/dataview.html?paramid=kx
注意: 日期 -> 月度统计 -> 下拉到交割情况表
:param date: 年月日
:type date: str
:return: 上海期货交易所-交割情况表
:rtype: pandas.DataFrame
|
上海期货交易所-交割情况表
http://www.shfe.com.cn/statements/dataview.html?paramid=kx
注意: 日期 -> 月度统计 -> 下拉到交割情况表
:param date: 年月日
:type date: str
:return: 上海期货交易所-交割情况表
:rtype: pandas.DataFrame
| 245 | 278 |
def futures_delivery_shfe(date: str = "202003") -> pd.DataFrame:
"""
上海期货交易所-交割情况表
http://www.shfe.com.cn/statements/dataview.html?paramid=kx
注意: 日期 -> 月度统计 -> 下拉到交割情况表
:param date: 年月日
:type date: str
:return: 上海期货交易所-交割情况表
:rtype: pandas.DataFrame
"""
url = f"http://www.shfe.com.cn/data/dailydata/{date}monthvarietystatistics.dat"
r = requests.get(url)
r.encoding = "utf-8"
data_json = r.json()
temp_df = pd.DataFrame(data_json["o_curdelivery"])
temp_df.columns = [
"品种",
"品种代码",
"_",
"交割量-本月",
"交割量-比重",
"交割量-本年累计",
"交割量-累计同比",
]
temp_df = temp_df[
[
"品种",
"交割量-本月",
"交割量-比重",
"交割量-本年累计",
"交割量-累计同比",
]
]
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_to_spot.py#L245-L278
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 29.411765 |
[
10,
11,
12,
13,
14,
15,
24,
33
] | 23.529412 | false | 11.320755 | 34 | 1 | 76.470588 | 7 |
def futures_delivery_shfe(date: str = "202003") -> pd.DataFrame:
url = f"http://www.shfe.com.cn/data/dailydata/{date}monthvarietystatistics.dat"
r = requests.get(url)
r.encoding = "utf-8"
data_json = r.json()
temp_df = pd.DataFrame(data_json["o_curdelivery"])
temp_df.columns = [
"品种",
"品种代码",
"_",
"交割量-本月",
"交割量-比重",
"交割量-本年累计",
"交割量-累计同比",
]
temp_df = temp_df[
[
"品种",
"交割量-本月",
"交割量-比重",
"交割量-本年累计",
"交割量-累计同比",
]
]
return temp_df
| 18,207 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_hq_sina.py
|
_get_real_name_list
|
()
|
return name_list
|
新浪-外盘期货所有品种的中文名称
:return: 外盘期货所有品种的中文名称
:rtype: list
|
新浪-外盘期货所有品种的中文名称
:return: 外盘期货所有品种的中文名称
:rtype: list
| 17 | 32 |
def _get_real_name_list() -> list:
"""
新浪-外盘期货所有品种的中文名称
:return: 外盘期货所有品种的中文名称
:rtype: list
"""
url = "http://finance.sina.com.cn/money/future/hf.html"
r = requests.get(url)
r.encoding = "gb2312"
data_text = r.text
need_text = data_text[
data_text.find("var oHF_1 = ") + 12: data_text.find("var oHF_2") - 2
].replace("\n\t", "")
data_json = demjson.decode(need_text)
name_list = [item[0].strip() for item in data_json.values()]
return name_list
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_hq_sina.py#L17-L32
| 25 |
[
0,
1,
2,
3,
4,
5
] | 37.5 |
[
6,
7,
8,
9,
10,
13,
14,
15
] | 50 | false | 12.941176 | 16 | 2 | 50 | 3 |
def _get_real_name_list() -> list:
url = "http://finance.sina.com.cn/money/future/hf.html"
r = requests.get(url)
r.encoding = "gb2312"
data_text = r.text
need_text = data_text[
data_text.find("var oHF_1 = ") + 12: data_text.find("var oHF_2") - 2
].replace("\n\t", "")
data_json = demjson.decode(need_text)
name_list = [item[0].strip() for item in data_json.values()]
return name_list
| 18,208 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_hq_sina.py
|
futures_foreign_commodity_subscribe_exchange_symbol
|
()
|
return code_list
|
需要订阅的行情的代码
:return: 需要订阅的行情的代码
:rtype: list
|
需要订阅的行情的代码
:return: 需要订阅的行情的代码
:rtype: list
| 35 | 51 |
def futures_foreign_commodity_subscribe_exchange_symbol() -> list:
"""
需要订阅的行情的代码
:return: 需要订阅的行情的代码
:rtype: list
"""
url = "http://finance.sina.com.cn/money/future/hf.html"
r = requests.get(url)
r.encoding = "gb2312"
data_text = r.text
data_json = demjson.decode(
data_text[
data_text.find("var oHF_1 = ") + 12: data_text.find("var oHF_2 = ") - 2
]
)
code_list = list(data_json.keys())
return code_list
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_hq_sina.py#L35-L51
| 25 |
[
0,
1,
2,
3,
4,
5
] | 35.294118 |
[
6,
7,
8,
9,
10,
15,
16
] | 41.176471 | false | 12.941176 | 17 | 1 | 58.823529 | 3 |
def futures_foreign_commodity_subscribe_exchange_symbol() -> list:
url = "http://finance.sina.com.cn/money/future/hf.html"
r = requests.get(url)
r.encoding = "gb2312"
data_text = r.text
data_json = demjson.decode(
data_text[
data_text.find("var oHF_1 = ") + 12: data_text.find("var oHF_2 = ") - 2
]
)
code_list = list(data_json.keys())
return code_list
| 18,209 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_hq_sina.py
|
futures_hq_subscribe_exchange_symbol
|
()
|
return temp_df
|
将品种字典转化为 pandas.DataFrame
https://finance.sina.com.cn/money/future/hf.html
:return: 品种对应表
:rtype: pandas.DataFrame
|
将品种字典转化为 pandas.DataFrame
https://finance.sina.com.cn/money/future/hf.html
:return: 品种对应表
:rtype: pandas.DataFrame
| 54 | 92 |
def futures_hq_subscribe_exchange_symbol() -> pd.DataFrame:
"""
将品种字典转化为 pandas.DataFrame
https://finance.sina.com.cn/money/future/hf.html
:return: 品种对应表
:rtype: pandas.DataFrame
"""
inner_dict = {
"NYBOT-棉花": 'CT',
"LME镍3个月": 'NID',
"LME铅3个月": 'PBD',
"LME锡3个月": 'SND',
"LME锌3个月": 'ZSD',
"LME铝3个月": 'AHD',
"LME铜3个月": 'CAD',
"CBOT-黄豆": 'S',
"CBOT-小麦": 'W',
"CBOT-玉米": 'C',
"CBOT-黄豆油": 'BO',
"CBOT-黄豆粉": 'SM',
"日本橡胶": 'TRB',
"COMEX铜": 'HG',
"NYMEX天然气": 'NG',
"NYMEX原油": 'CL',
"COMEX白银": 'SI',
"COMEX黄金": 'GC',
"CME-瘦肉猪": 'LHC',
"布伦特原油": 'OIL',
"伦敦金": 'XAU',
"伦敦银": 'XAG',
"伦敦铂金": 'XPT',
"伦敦钯金": 'XPD',
"马棕油": 'FCPO',
"欧洲碳排放": 'EUA',
}
temp_df = pd.DataFrame.from_dict(inner_dict, orient='index')
temp_df.reset_index(inplace=True)
temp_df.columns = ['symbol', 'code']
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_hq_sina.py#L54-L92
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 17.948718 |
[
7,
35,
36,
37,
38
] | 12.820513 | false | 12.941176 | 39 | 1 | 87.179487 | 4 |
def futures_hq_subscribe_exchange_symbol() -> pd.DataFrame:
inner_dict = {
"NYBOT-棉花": 'CT',
"LME镍3个月": 'NID',
"LME铅3个月": 'PBD',
"LME锡3个月": 'SND',
"LME锌3个月": 'ZSD',
"LME铝3个月": 'AHD',
"LME铜3个月": 'CAD',
"CBOT-黄豆": 'S',
"CBOT-小麦": 'W',
"CBOT-玉米": 'C',
"CBOT-黄豆油": 'BO',
"CBOT-黄豆粉": 'SM',
"日本橡胶": 'TRB',
"COMEX铜": 'HG',
"NYMEX天然气": 'NG',
"NYMEX原油": 'CL',
"COMEX白银": 'SI',
"COMEX黄金": 'GC',
"CME-瘦肉猪": 'LHC',
"布伦特原油": 'OIL',
"伦敦金": 'XAU',
"伦敦银": 'XAG',
"伦敦铂金": 'XPT',
"伦敦钯金": 'XPD',
"马棕油": 'FCPO',
"欧洲碳排放": 'EUA',
}
temp_df = pd.DataFrame.from_dict(inner_dict, orient='index')
temp_df.reset_index(inplace=True)
temp_df.columns = ['symbol', 'code']
return temp_df
| 18,210 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures/futures_hq_sina.py
|
futures_foreign_commodity_realtime
|
(subscribe_list: list)
|
return data_df
|
新浪-外盘期货-行情数据
https://finance.sina.com.cn/money/future/hf.html
:param subscribe_list: 通过调用 ak.futures_hq_subscribe_exchange_symbol() 函数来获取
:type subscribe_list: list
:return: 行情数据
:rtype: pandas.DataFrame
|
新浪-外盘期货-行情数据
https://finance.sina.com.cn/money/future/hf.html
:param subscribe_list: 通过调用 ak.futures_hq_subscribe_exchange_symbol() 函数来获取
:type subscribe_list: list
:return: 行情数据
:rtype: pandas.DataFrame
| 95 | 245 |
def futures_foreign_commodity_realtime(subscribe_list: list) -> pd.DataFrame:
"""
新浪-外盘期货-行情数据
https://finance.sina.com.cn/money/future/hf.html
:param subscribe_list: 通过调用 ak.futures_hq_subscribe_exchange_symbol() 函数来获取
:type subscribe_list: list
:return: 行情数据
:rtype: pandas.DataFrame
"""
payload = "?list=" + ",".join(["hf_" + item for item in subscribe_list])
url = "http://hq.sinajs.cn/" + payload
headers = {
'Accept': '*/*',
'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': 'hq.sinajs.cn',
'Pragma': 'no-cache',
'Referer': 'https://finance.sina.com.cn/',
'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'Sec-Fetch-Dest': 'script',
'Sec-Fetch-Mode': 'no-cors',
'Sec-Fetch-Site': 'cross-site',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
}
r = requests.get(url, headers=headers)
data_text = r.text
data_df = pd.DataFrame(
[
item.strip().split("=")[1].split(",")
for item in data_text.split(";")
if item.strip() != ""
]
)
data_df.iloc[:, 0] = data_df.iloc[:, 0].str.replace('"', "")
data_df.iloc[:, -1] = data_df.iloc[:, -1].str.replace('"', "")
data_df.columns = [
"current_price",
"-",
"bid",
"ask",
"high",
"low",
"time",
"last_settle_price",
"open",
"hold",
"-",
"-",
"date",
"symbol",
"current_price_rmb",
]
temp_symbol_code_df = futures_hq_subscribe_exchange_symbol()
temp_symbol_code_dict = dict(zip(temp_symbol_code_df['code'], temp_symbol_code_df['symbol']))
data_df["symbol"] = [temp_symbol_code_dict[subscribe] for subscribe in subscribe_list]
data_df = data_df[
[
"symbol",
"current_price",
"current_price_rmb",
"bid",
"ask",
"high",
"low",
"time",
"last_settle_price",
"open",
"hold",
"date",
]
]
data_df.columns = [
"名称",
"最新价",
"人民币报价",
"买价",
"卖价",
"最高价",
"最低价",
"行情时间",
"昨日结算价",
"开盘价",
"持仓量",
"日期",
]
data_df.dropna(how="all", inplace=True)
data_df["最新价"] = pd.to_numeric(data_df["最新价"])
data_df["人民币报价"] = pd.to_numeric(data_df["人民币报价"])
data_df["买价"] = pd.to_numeric(data_df["买价"])
data_df["卖价"] = pd.to_numeric(data_df["卖价"])
data_df["最高价"] = pd.to_numeric(data_df["最高价"])
data_df["最低价"] = pd.to_numeric(data_df["最低价"])
data_df["昨日结算价"] = pd.to_numeric(data_df["昨日结算价"])
data_df["开盘价"] = pd.to_numeric(data_df["开盘价"])
data_df["持仓量"] = pd.to_numeric(data_df["持仓量"])
data_df["涨跌额"] = data_df["最新价"] - data_df["昨日结算价"]
data_df["涨跌幅"] = (data_df["最新价"] - data_df["昨日结算价"]) / data_df["昨日结算价"] * 100
data_df = data_df[
[
"名称",
"最新价",
"人民币报价",
"涨跌额",
"涨跌幅",
"开盘价",
"最高价",
"最低价",
"昨日结算价",
"持仓量",
"买价",
"卖价",
"行情时间",
"日期",
]
]
# 获取转换比例数据
url = "https://finance.sina.com.cn/money/future/hf.html"
r = requests.get(url)
r.encoding = "gb2312"
soup = BeautifulSoup(r.text, "lxml")
data_text = soup.find_all("script", attrs={"type": "text/javascript"})[
-2
].string.strip()
raw_text = data_text[data_text.find("oHF_1 = "): data_text.find("oHF_2")]
need_text = raw_text[raw_text.find("{"): raw_text.rfind("}") + 1]
data_json = demjson.decode(need_text)
price_mul = pd.DataFrame(
[
[item[0] for item in data_json.values()],
[item[1][0] for item in data_json.values()],
]
).T
price_mul.columns = ["symbol", "price"]
# 获取汇率数据
url = "https://hq.sinajs.cn/?list=USDCNY"
r = requests.get(url, headers=headers)
data_text = r.text
usd_rmb = float(
data_text[data_text.find('"') + 1: data_text.find(",美元人民币")].split(",")[-1]
)
# 计算人民币报价
data_df["人民币报价"] = data_df["最新价"] * price_mul["price"] * usd_rmb
data_df.dropna(thresh=4, inplace=True)
return data_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures/futures_hq_sina.py#L95-L245
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 5.960265 |
[
9,
10,
11,
28,
29,
30,
37,
38,
39,
56,
57,
58,
59,
75,
89,
90,
91,
92,
93,
94,
95,
96,
97,
98,
99,
100,
101,
121,
122,
123,
124,
125,
128,
129,
130,
131,
137,
140,
141,
142,
143,
148,
149,
150
] | 29.139073 | false | 12.941176 | 151 | 6 | 70.860927 | 6 |
def futures_foreign_commodity_realtime(subscribe_list: list) -> pd.DataFrame:
payload = "?list=" + ",".join(["hf_" + item for item in subscribe_list])
url = "http://hq.sinajs.cn/" + payload
headers = {
'Accept': '*/*',
'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': 'hq.sinajs.cn',
'Pragma': 'no-cache',
'Referer': 'https://finance.sina.com.cn/',
'sec-ch-ua': '" Not;A Brand";v="99", "Google Chrome";v="97", "Chromium";v="97"',
'sec-ch-ua-mobile': '?0',
'sec-ch-ua-platform': '"Windows"',
'Sec-Fetch-Dest': 'script',
'Sec-Fetch-Mode': 'no-cors',
'Sec-Fetch-Site': 'cross-site',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36'
}
r = requests.get(url, headers=headers)
data_text = r.text
data_df = pd.DataFrame(
[
item.strip().split("=")[1].split(",")
for item in data_text.split(";")
if item.strip() != ""
]
)
data_df.iloc[:, 0] = data_df.iloc[:, 0].str.replace('"', "")
data_df.iloc[:, -1] = data_df.iloc[:, -1].str.replace('"', "")
data_df.columns = [
"current_price",
"-",
"bid",
"ask",
"high",
"low",
"time",
"last_settle_price",
"open",
"hold",
"-",
"-",
"date",
"symbol",
"current_price_rmb",
]
temp_symbol_code_df = futures_hq_subscribe_exchange_symbol()
temp_symbol_code_dict = dict(zip(temp_symbol_code_df['code'], temp_symbol_code_df['symbol']))
data_df["symbol"] = [temp_symbol_code_dict[subscribe] for subscribe in subscribe_list]
data_df = data_df[
[
"symbol",
"current_price",
"current_price_rmb",
"bid",
"ask",
"high",
"low",
"time",
"last_settle_price",
"open",
"hold",
"date",
]
]
data_df.columns = [
"名称",
"最新价",
"人民币报价",
"买价",
"卖价",
"最高价",
"最低价",
"行情时间",
"昨日结算价",
"开盘价",
"持仓量",
"日期",
]
data_df.dropna(how="all", inplace=True)
data_df["最新价"] = pd.to_numeric(data_df["最新价"])
data_df["人民币报价"] = pd.to_numeric(data_df["人民币报价"])
data_df["买价"] = pd.to_numeric(data_df["买价"])
data_df["卖价"] = pd.to_numeric(data_df["卖价"])
data_df["最高价"] = pd.to_numeric(data_df["最高价"])
data_df["最低价"] = pd.to_numeric(data_df["最低价"])
data_df["昨日结算价"] = pd.to_numeric(data_df["昨日结算价"])
data_df["开盘价"] = pd.to_numeric(data_df["开盘价"])
data_df["持仓量"] = pd.to_numeric(data_df["持仓量"])
data_df["涨跌额"] = data_df["最新价"] - data_df["昨日结算价"]
data_df["涨跌幅"] = (data_df["最新价"] - data_df["昨日结算价"]) / data_df["昨日结算价"] * 100
data_df = data_df[
[
"名称",
"最新价",
"人民币报价",
"涨跌额",
"涨跌幅",
"开盘价",
"最高价",
"最低价",
"昨日结算价",
"持仓量",
"买价",
"卖价",
"行情时间",
"日期",
]
]
# 获取转换比例数据
url = "https://finance.sina.com.cn/money/future/hf.html"
r = requests.get(url)
r.encoding = "gb2312"
soup = BeautifulSoup(r.text, "lxml")
data_text = soup.find_all("script", attrs={"type": "text/javascript"})[
-2
].string.strip()
raw_text = data_text[data_text.find("oHF_1 = "): data_text.find("oHF_2")]
need_text = raw_text[raw_text.find("{"): raw_text.rfind("}") + 1]
data_json = demjson.decode(need_text)
price_mul = pd.DataFrame(
[
[item[0] for item in data_json.values()],
[item[1][0] for item in data_json.values()],
]
).T
price_mul.columns = ["symbol", "price"]
# 获取汇率数据
url = "https://hq.sinajs.cn/?list=USDCNY"
r = requests.get(url, headers=headers)
data_text = r.text
usd_rmb = float(
data_text[data_text.find('"') + 1: data_text.find(",美元人民币")].split(",")[-1]
)
# 计算人民币报价
data_df["人民币报价"] = data_df["最新价"] * price_mul["price"] * usd_rmb
data_df.dropna(thresh=4, inplace=True)
return data_df
| 18,211 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/reits/reits_basic.py
|
reits_realtime_em
|
()
|
return temp_df
|
东方财富网-行情中心-REITs-沪深 REITs
http://quote.eastmoney.com/center/gridlist.html#fund_reits_all
:return: 沪深 REITs-实时行情
:rtype: pandas.DataFrame
|
东方财富网-行情中心-REITs-沪深 REITs
http://quote.eastmoney.com/center/gridlist.html#fund_reits_all
:return: 沪深 REITs-实时行情
:rtype: pandas.DataFrame
| 13 | 73 |
def reits_realtime_em() -> pd.DataFrame:
"""
东方财富网-行情中心-REITs-沪深 REITs
http://quote.eastmoney.com/center/gridlist.html#fund_reits_all
:return: 沪深 REITs-实时行情
:rtype: pandas.DataFrame
"""
url = "http://95.push2.eastmoney.com/api/qt/clist/get"
params = {
"pn": "1",
"pz": "20",
"po": "1",
"np": "1",
"ut": "bd1d9ddb04089700cf9c27f6f7426281",
"fltt": "2",
"invt": "2",
"fid": "f3",
"fs": "m:1 t:9 e:97,m:0 t:10 e:97",
"fields": "f2,f3,f4,f5,f6,f12,f14,f15,f16,f17,f18",
"_": "1630048369992",
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json["data"]["diff"])
temp_df.reset_index(inplace=True)
temp_df["index"] = range(1, len(temp_df) + 1)
temp_df.rename(
{
"index": "序号",
"f2": "最新价",
"f3": "涨跌幅",
"f4": "涨跌额",
"f5": "成交量",
"f6": "成交额",
"f12": "代码",
"f14": "名称",
"f15": "最高价",
"f16": "最低价",
"f17": "开盘价",
"f18": "昨收",
},
axis=1,
inplace=True,
)
temp_df = temp_df[
[
"序号",
"代码",
"名称",
"最新价",
"涨跌额",
"涨跌幅",
"成交量",
"成交额",
"开盘价",
"最高价",
"最低价",
"昨收",
]
]
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/reits/reits_basic.py#L13-L73
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 11.47541 |
[
7,
8,
21,
22,
23,
24,
25,
26,
44,
60
] | 16.393443 | false | 16.666667 | 61 | 1 | 83.606557 | 4 |
def reits_realtime_em() -> pd.DataFrame:
url = "http://95.push2.eastmoney.com/api/qt/clist/get"
params = {
"pn": "1",
"pz": "20",
"po": "1",
"np": "1",
"ut": "bd1d9ddb04089700cf9c27f6f7426281",
"fltt": "2",
"invt": "2",
"fid": "f3",
"fs": "m:1 t:9 e:97,m:0 t:10 e:97",
"fields": "f2,f3,f4,f5,f6,f12,f14,f15,f16,f17,f18",
"_": "1630048369992",
}
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(data_json["data"]["diff"])
temp_df.reset_index(inplace=True)
temp_df["index"] = range(1, len(temp_df) + 1)
temp_df.rename(
{
"index": "序号",
"f2": "最新价",
"f3": "涨跌幅",
"f4": "涨跌额",
"f5": "成交量",
"f6": "成交额",
"f12": "代码",
"f14": "名称",
"f15": "最高价",
"f16": "最低价",
"f17": "开盘价",
"f18": "昨收",
},
axis=1,
inplace=True,
)
temp_df = temp_df[
[
"序号",
"代码",
"名称",
"最新价",
"涨跌额",
"涨跌幅",
"成交量",
"成交额",
"开盘价",
"最高价",
"最低价",
"昨收",
]
]
return temp_df
| 18,212 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/reits/reits_basic.py
|
reits_info_jsl
|
()
|
return temp_df
|
集思录-实时数据-REITs-A 股 REITs
https://www.jisilu.cn/data/cnreits/#CnReits
:return: A股 REITs
:rtype: pandas.DataFrame
|
集思录-实时数据-REITs-A 股 REITs
https://www.jisilu.cn/data/cnreits/#CnReits
:return: A股 REITs
:rtype: pandas.DataFrame
| 76 | 137 |
def reits_info_jsl() -> pd.DataFrame:
"""
集思录-实时数据-REITs-A 股 REITs
https://www.jisilu.cn/data/cnreits/#CnReits
:return: A股 REITs
:rtype: pandas.DataFrame
"""
url = "https://www.jisilu.cn/data/cnreits/list/"
params = {"___jsl": "LST___t=1630052485199"}
payload = {"rp": "50", "page": "1"}
r = requests.get(url, params=params, json=payload)
data_json = r.json()
temp_df = pd.DataFrame([item["cell"] for item in data_json["rows"]])
temp_df.rename(
{
"fund_id": "代码",
"fund_nm": "简称",
"full_nm": "全称",
"project_type": "项目类型",
"price": "现价",
"increase_rt": "涨幅",
"volume": "成交额",
"nav": "净值",
"nav_dt": "净值日期",
"discount_rt": "折价率",
"maturity_dt": "到期日",
"fund_company": "基金公司",
"urls": "链接地址",
"last_dt": "更新日期",
"last_time": "更新时间",
"unit_total": "规模",
"left_year": "剩余年限",
},
axis=1,
inplace=True,
)
temp_df = temp_df[
[
"代码",
"简称",
"现价",
"涨幅",
"成交额",
"净值",
"净值日期",
"折价率",
"规模",
"到期日",
"剩余年限",
"全称",
"项目类型",
"基金公司",
]
]
temp_df['现价'] = pd.to_numeric(temp_df['现价'])
temp_df['涨幅'] = pd.to_numeric(temp_df['涨幅'])
temp_df['成交额'] = pd.to_numeric(temp_df['成交额'])
temp_df['净值'] = pd.to_numeric(temp_df['净值'])
temp_df['折价率'] = pd.to_numeric(temp_df['折价率'])
temp_df['规模'] = pd.to_numeric(temp_df['规模'])
temp_df['剩余年限'] = pd.to_numeric(temp_df['剩余年限'])
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/reits/reits_basic.py#L76-L137
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 11.290323 |
[
7,
8,
9,
10,
11,
12,
13,
36,
54,
55,
56,
57,
58,
59,
60,
61
] | 25.806452 | false | 16.666667 | 62 | 2 | 74.193548 | 4 |
def reits_info_jsl() -> pd.DataFrame:
url = "https://www.jisilu.cn/data/cnreits/list/"
params = {"___jsl": "LST___t=1630052485199"}
payload = {"rp": "50", "page": "1"}
r = requests.get(url, params=params, json=payload)
data_json = r.json()
temp_df = pd.DataFrame([item["cell"] for item in data_json["rows"]])
temp_df.rename(
{
"fund_id": "代码",
"fund_nm": "简称",
"full_nm": "全称",
"project_type": "项目类型",
"price": "现价",
"increase_rt": "涨幅",
"volume": "成交额",
"nav": "净值",
"nav_dt": "净值日期",
"discount_rt": "折价率",
"maturity_dt": "到期日",
"fund_company": "基金公司",
"urls": "链接地址",
"last_dt": "更新日期",
"last_time": "更新时间",
"unit_total": "规模",
"left_year": "剩余年限",
},
axis=1,
inplace=True,
)
temp_df = temp_df[
[
"代码",
"简称",
"现价",
"涨幅",
"成交额",
"净值",
"净值日期",
"折价率",
"规模",
"到期日",
"剩余年限",
"全称",
"项目类型",
"基金公司",
]
]
temp_df['现价'] = pd.to_numeric(temp_df['现价'])
temp_df['涨幅'] = pd.to_numeric(temp_df['涨幅'])
temp_df['成交额'] = pd.to_numeric(temp_df['成交额'])
temp_df['净值'] = pd.to_numeric(temp_df['净值'])
temp_df['折价率'] = pd.to_numeric(temp_df['折价率'])
temp_df['规模'] = pd.to_numeric(temp_df['规模'])
temp_df['剩余年限'] = pd.to_numeric(temp_df['剩余年限'])
return temp_df
| 18,213 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/fx/currency_investing.py
|
_currency_name_url
|
()
|
return name_code_dict
|
货币键值对
:return: 货币键值对
:rtype: dict
|
货币键值对
:return: 货币键值对
:rtype: dict
| 20 | 39 |
def _currency_name_url() -> dict:
"""
货币键值对
:return: 货币键值对
:rtype: dict
"""
url = "https://cn.investing.com/currencies/"
res = requests.post(url, headers=short_headers)
data_table = pd.read_html(res.text)[0].iloc[:, 1:] # 实时货币行情
data_table.columns = ["中文名称", "英文名称", "最新", "最高", "最低", "涨跌额", "涨跌幅", "时间"]
name_code_dict = dict(
zip(
data_table["中文名称"].tolist(),
[
item.lower().replace("/", "-")
for item in data_table["英文名称"].tolist()
],
)
)
return name_code_dict
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/fx/currency_investing.py#L20-L39
| 25 |
[
0,
1,
2,
3,
4,
5
] | 30 |
[
6,
7,
8,
9,
10,
19
] | 30 | false | 13.392857 | 20 | 2 | 70 | 3 |
def _currency_name_url() -> dict:
url = "https://cn.investing.com/currencies/"
res = requests.post(url, headers=short_headers)
data_table = pd.read_html(res.text)[0].iloc[:, 1:] # 实时货币行情
data_table.columns = ["中文名称", "英文名称", "最新", "最高", "最低", "涨跌额", "涨跌幅", "时间"]
name_code_dict = dict(
zip(
data_table["中文名称"].tolist(),
[
item.lower().replace("/", "-")
for item in data_table["英文名称"].tolist()
],
)
)
return name_code_dict
| 18,214 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/fx/currency_investing.py
|
currency_hist_area_index_name_code
|
(symbol: str = "usd-jpy")
|
return code
|
指定 symbol 的所有指数和代码
https://cn.investing.com/indices/
:param symbol: 指定的国家或地区;ak._get_global_country_name_url() 函数返回的国家或地区的名称
:type symbol: str
:return: 指定 area 的所有指数和代码
:rtype: dict
|
指定 symbol 的所有指数和代码
https://cn.investing.com/indices/
:param symbol: 指定的国家或地区;ak._get_global_country_name_url() 函数返回的国家或地区的名称
:type symbol: str
:return: 指定 area 的所有指数和代码
:rtype: dict
| 42 | 61 |
def currency_hist_area_index_name_code(symbol: str = "usd-jpy") -> dict:
"""
指定 symbol 的所有指数和代码
https://cn.investing.com/indices/
:param symbol: 指定的国家或地区;ak._get_global_country_name_url() 函数返回的国家或地区的名称
:type symbol: str
:return: 指定 area 的所有指数和代码
:rtype: dict
"""
scraper = cfscrape.create_scraper(delay=10)
pd.set_option("mode.chained_assignment", None)
url = f"https://cn.investing.com/currencies/{symbol}-historical-data"
r = scraper.get(url)
soup = BeautifulSoup(r.text, "lxml")
data_text = soup.find("script", attrs={"id": "__NEXT_DATA__"}).text
data_json = json.loads(data_text)
code = json.loads(data_json["props"]["pageProps"]["state"])["dataStore"][
"pageInfoStore"
]["identifiers"]["instrument_id"]
return code
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/fx/currency_investing.py#L42-L61
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 45 |
[
9,
10,
11,
12,
13,
14,
15,
16,
19
] | 45 | false | 13.392857 | 20 | 1 | 55 | 6 |
def currency_hist_area_index_name_code(symbol: str = "usd-jpy") -> dict:
scraper = cfscrape.create_scraper(delay=10)
pd.set_option("mode.chained_assignment", None)
url = f"https://cn.investing.com/currencies/{symbol}-historical-data"
r = scraper.get(url)
soup = BeautifulSoup(r.text, "lxml")
data_text = soup.find("script", attrs={"id": "__NEXT_DATA__"}).text
data_json = json.loads(data_text)
code = json.loads(data_json["props"]["pageProps"]["state"])["dataStore"][
"pageInfoStore"
]["identifiers"]["instrument_id"]
return code
| 18,215 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/fx/currency_investing.py
|
currency_hist
|
(
symbol: str = "usd-jpy",
period: str = "每日",
start_date: str = "20030101",
end_date: str = "20220808",
)
|
return df_data
|
外汇历史数据, 注意获取数据区间的长短, 输入任意货币对, 具体能否获取, 通过 currency_name_code_dict 查询
:param symbol: 货币对
:type symbol: str
:param period: choice of {"每日", "每周", "每月"}
:type period: str
:param start_date: 日期
:type start_date: str
:param end_date: 日期
:type end_date: str
:return: 货币对历史数据
:rtype: pandas.DataFrame
|
外汇历史数据, 注意获取数据区间的长短, 输入任意货币对, 具体能否获取, 通过 currency_name_code_dict 查询
:param symbol: 货币对
:type symbol: str
:param period: choice of {"每日", "每周", "每月"}
:type period: str
:param start_date: 日期
:type start_date: str
:param end_date: 日期
:type end_date: str
:return: 货币对历史数据
:rtype: pandas.DataFrame
| 64 | 142 |
def currency_hist(
symbol: str = "usd-jpy",
period: str = "每日",
start_date: str = "20030101",
end_date: str = "20220808",
) -> pd.DataFrame:
"""
外汇历史数据, 注意获取数据区间的长短, 输入任意货币对, 具体能否获取, 通过 currency_name_code_dict 查询
:param symbol: 货币对
:type symbol: str
:param period: choice of {"每日", "每周", "每月"}
:type period: str
:param start_date: 日期
:type start_date: str
:param end_date: 日期
:type end_date: str
:return: 货币对历史数据
:rtype: pandas.DataFrame
"""
start_date = "-".join([start_date[:4], start_date[4:6], start_date[6:]])
end_date = "-".join([end_date[:4], end_date[4:6], end_date[6:]])
code = currency_hist_area_index_name_code(symbol)
url = f"https://api.investing.com/api/financialdata/historical/{code}"
period_map = {"每日": "Daily", "每周": "Weekly", "每月": "Monthly"}
params = {
"start-date": start_date,
"end-date": end_date,
"time-frame": period_map[period],
"add-missing-rows": "false",
}
headers = {
"accept": "application/json, text/plain, */*",
"accept-encoding": "gzip, deflate, br",
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
"cache-control": "no-cache",
"domain-id": "cn",
"origin": "https://cn.investing.com",
"pragma": "no-cache",
"referer": "https://cn.investing.com/",
"sec-ch-ua": '"Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"',
"sec-ch-ua-mobile": '"?0"',
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36",
}
r = requests.get(url, params=params, headers=headers)
data_json = r.json()
df_data = pd.DataFrame(data_json["data"])
df_data.columns = [
"-",
"-",
"-",
"日期",
"-",
"-",
"-",
"-",
"-",
"交易量",
"-",
"收盘",
"开盘",
"高",
"低",
"涨跌幅",
]
df_data = df_data[["日期", "收盘", "开盘", "高", "低", "交易量", "涨跌幅"]]
df_data["日期"] = pd.to_datetime(df_data["日期"]).dt.date
df_data["收盘"] = pd.to_numeric(df_data["收盘"])
df_data["开盘"] = pd.to_numeric(df_data["开盘"])
df_data["高"] = pd.to_numeric(df_data["高"])
df_data["低"] = pd.to_numeric(df_data["低"])
df_data["交易量"] = pd.to_numeric(df_data["交易量"])
df_data["涨跌幅"] = pd.to_numeric(df_data["涨跌幅"])
df_data.sort_values("日期", inplace=True)
df_data.reset_index(inplace=True, drop=True)
return df_data
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/fx/currency_investing.py#L64-L142
| 25 |
[
0
] | 1.265823 |
[
19,
20,
21,
22,
23,
24,
30,
47,
48,
49,
50,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78
] | 27.848101 | false | 13.392857 | 79 | 1 | 72.151899 | 11 |
def currency_hist(
symbol: str = "usd-jpy",
period: str = "每日",
start_date: str = "20030101",
end_date: str = "20220808",
) -> pd.DataFrame:
start_date = "-".join([start_date[:4], start_date[4:6], start_date[6:]])
end_date = "-".join([end_date[:4], end_date[4:6], end_date[6:]])
code = currency_hist_area_index_name_code(symbol)
url = f"https://api.investing.com/api/financialdata/historical/{code}"
period_map = {"每日": "Daily", "每周": "Weekly", "每月": "Monthly"}
params = {
"start-date": start_date,
"end-date": end_date,
"time-frame": period_map[period],
"add-missing-rows": "false",
}
headers = {
"accept": "application/json, text/plain, */*",
"accept-encoding": "gzip, deflate, br",
"accept-language": "zh-CN,zh;q=0.9,en;q=0.8",
"cache-control": "no-cache",
"domain-id": "cn",
"origin": "https://cn.investing.com",
"pragma": "no-cache",
"referer": "https://cn.investing.com/",
"sec-ch-ua": '"Google Chrome";v="105", "Not)A;Brand";v="8", "Chromium";v="105"',
"sec-ch-ua-mobile": '"?0"',
"sec-ch-ua-platform": '"Windows"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-site",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.0.0 Safari/537.36",
}
r = requests.get(url, params=params, headers=headers)
data_json = r.json()
df_data = pd.DataFrame(data_json["data"])
df_data.columns = [
"-",
"-",
"-",
"日期",
"-",
"-",
"-",
"-",
"-",
"交易量",
"-",
"收盘",
"开盘",
"高",
"低",
"涨跌幅",
]
df_data = df_data[["日期", "收盘", "开盘", "高", "低", "交易量", "涨跌幅"]]
df_data["日期"] = pd.to_datetime(df_data["日期"]).dt.date
df_data["收盘"] = pd.to_numeric(df_data["收盘"])
df_data["开盘"] = pd.to_numeric(df_data["开盘"])
df_data["高"] = pd.to_numeric(df_data["高"])
df_data["低"] = pd.to_numeric(df_data["低"])
df_data["交易量"] = pd.to_numeric(df_data["交易量"])
df_data["涨跌幅"] = pd.to_numeric(df_data["涨跌幅"])
df_data.sort_values("日期", inplace=True)
df_data.reset_index(inplace=True, drop=True)
return df_data
| 18,216 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/fx/currency_investing.py
|
_currency_single
|
()
|
return temp_df
|
英为财情-外汇-单种货币兑换汇率-单种货币列表
:return: 单种货币列表
:rtype: pandas.DataFrame
|
英为财情-外汇-单种货币兑换汇率-单种货币列表
:return: 单种货币列表
:rtype: pandas.DataFrame
| 145 | 164 |
def _currency_single() -> pd.DataFrame:
"""
英为财情-外汇-单种货币兑换汇率-单种货币列表
:return: 单种货币列表
:rtype: pandas.DataFrame
"""
url = "https://cn.investing.com/currencies/single-currency-crosses"
res = requests.post(url, headers=short_headers)
soup = BeautifulSoup(res.text, "lxml")
name_url_option_list = soup.find(
"select", attrs={"class": "newInput selectBox"}
).find_all("option")
temp_df = pd.DataFrame(
[item.get_text().split("-", 1) for item in name_url_option_list]
)
temp_df.columns = ["short_name", "name"]
temp_df["short_name"] = temp_df["short_name"].str.strip()
temp_df["name"] = temp_df["name"].str.strip()
temp_df["code"] = [item["value"] for item in name_url_option_list]
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/fx/currency_investing.py#L145-L164
| 25 |
[
0,
1,
2,
3,
4,
5
] | 30 |
[
6,
7,
8,
9,
12,
15,
16,
17,
18,
19
] | 50 | false | 13.392857 | 20 | 3 | 50 | 3 |
def _currency_single() -> pd.DataFrame:
url = "https://cn.investing.com/currencies/single-currency-crosses"
res = requests.post(url, headers=short_headers)
soup = BeautifulSoup(res.text, "lxml")
name_url_option_list = soup.find(
"select", attrs={"class": "newInput selectBox"}
).find_all("option")
temp_df = pd.DataFrame(
[item.get_text().split("-", 1) for item in name_url_option_list]
)
temp_df.columns = ["short_name", "name"]
temp_df["short_name"] = temp_df["short_name"].str.strip()
temp_df["name"] = temp_df["name"].str.strip()
temp_df["code"] = [item["value"] for item in name_url_option_list]
return temp_df
| 18,217 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/fx/currency_investing.py
|
currency_name_code
|
(symbol: str = "usd/jpy")
|
return temp_df
|
当前所有可兑换货币对
:param symbol: "usd/jpy"
:type symbol: str
:return: 中英文货币对
:rtype: pandas.DataFrame
name code
0 欧元/美元 eur-usd
1 英镑/美元 gbp-usd
2 美元/日元 usd-jpy
3 美元/瑞士法郎 usd-chf
4 澳大利亚元/美元 aud-usd
.. ... ...
268 日元/新加坡元 jpy-sgd
269 科威特第纳尔/日元 kwd-jpy
270 日元/白俄罗斯卢布 jpy-byn
271 日元/乌克兰赫里纳 jpy-uah
272 日元/土耳其里拉 jpy-try
|
当前所有可兑换货币对
:param symbol: "usd/jpy"
:type symbol: str
:return: 中英文货币对
:rtype: pandas.DataFrame
name code
0 欧元/美元 eur-usd
1 英镑/美元 gbp-usd
2 美元/日元 usd-jpy
3 美元/瑞士法郎 usd-chf
4 澳大利亚元/美元 aud-usd
.. ... ...
268 日元/新加坡元 jpy-sgd
269 科威特第纳尔/日元 kwd-jpy
270 日元/白俄罗斯卢布 jpy-byn
271 日元/乌克兰赫里纳 jpy-uah
272 日元/土耳其里拉 jpy-try
| 167 | 260 |
def currency_name_code(symbol: str = "usd/jpy") -> pd.DataFrame:
"""
当前所有可兑换货币对
:param symbol: "usd/jpy"
:type symbol: str
:return: 中英文货币对
:rtype: pandas.DataFrame
name code
0 欧元/美元 eur-usd
1 英镑/美元 gbp-usd
2 美元/日元 usd-jpy
3 美元/瑞士法郎 usd-chf
4 澳大利亚元/美元 aud-usd
.. ... ...
268 日元/新加坡元 jpy-sgd
269 科威特第纳尔/日元 kwd-jpy
270 日元/白俄罗斯卢布 jpy-byn
271 日元/乌克兰赫里纳 jpy-uah
272 日元/土耳其里拉 jpy-try
"""
symbol = symbol.upper()
currency_df = _currency_single()
url = "https://cn.investing.com/currencies/Service/ChangeCurrency"
params = {
"session_uniq_id": "53bee677662a2336ec07b40738753fc1",
"currencies": currency_df[
currency_df["short_name"] == symbol.split("/")[0]
]["code"].values[0],
}
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"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",
}
r = requests.get(url, params=params, headers=headers)
temp_df = pd.read_html(r.json()["HTML"])[0].iloc[:, 1:]
temp_df.rename(columns={"名称.1": "简称"}, inplace=True)
temp_df["pids"] = [item[:-1] for item in r.json()["pids"]]
name_code_dict_one = dict(
zip(
temp_df["名称"].tolist(),
[
item.lower().replace("/", "-")
for item in temp_df["简称"].tolist()
],
)
)
params = {
"session_uniq_id": "53bee677662a2336ec07b40738753fc1",
"currencies": currency_df[
currency_df["short_name"] == symbol.split("/")[1]
]["code"].values[0],
}
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",
}
r = requests.get(url, params=params, headers=headers)
temp_df = pd.read_html(r.json()["HTML"])[0].iloc[:, 1:]
temp_df.rename(columns={"名称.1": "简称"}, inplace=True)
temp_df["pids"] = [item[:-1] for item in r.json()["pids"]]
name_code_dict_two = dict(
zip(
temp_df["名称"].tolist(),
[
item.lower().replace("/", "-")
for item in temp_df["简称"].tolist()
],
)
)
name_code_dict_one.update(name_code_dict_two)
temp_df = pd.DataFrame.from_dict(
name_code_dict_one, orient="index"
).reset_index()
temp_df.columns = ["name", "code"]
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/fx/currency_investing.py#L167-L260
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19
] | 21.276596 |
[
20,
21,
22,
23,
29,
42,
43,
44,
45,
46,
55,
61,
75,
76,
77,
78,
79,
88,
89,
92,
93
] | 22.340426 | false | 13.392857 | 94 | 5 | 77.659574 | 17 |
def currency_name_code(symbol: str = "usd/jpy") -> pd.DataFrame:
symbol = symbol.upper()
currency_df = _currency_single()
url = "https://cn.investing.com/currencies/Service/ChangeCurrency"
params = {
"session_uniq_id": "53bee677662a2336ec07b40738753fc1",
"currencies": currency_df[
currency_df["short_name"] == symbol.split("/")[0]
]["code"].values[0],
}
headers = {
"Accept": "application/json, text/javascript, */*; q=0.01",
"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",
}
r = requests.get(url, params=params, headers=headers)
temp_df = pd.read_html(r.json()["HTML"])[0].iloc[:, 1:]
temp_df.rename(columns={"名称.1": "简称"}, inplace=True)
temp_df["pids"] = [item[:-1] for item in r.json()["pids"]]
name_code_dict_one = dict(
zip(
temp_df["名称"].tolist(),
[
item.lower().replace("/", "-")
for item in temp_df["简称"].tolist()
],
)
)
params = {
"session_uniq_id": "53bee677662a2336ec07b40738753fc1",
"currencies": currency_df[
currency_df["short_name"] == symbol.split("/")[1]
]["code"].values[0],
}
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",
}
r = requests.get(url, params=params, headers=headers)
temp_df = pd.read_html(r.json()["HTML"])[0].iloc[:, 1:]
temp_df.rename(columns={"名称.1": "简称"}, inplace=True)
temp_df["pids"] = [item[:-1] for item in r.json()["pids"]]
name_code_dict_two = dict(
zip(
temp_df["名称"].tolist(),
[
item.lower().replace("/", "-")
for item in temp_df["简称"].tolist()
],
)
)
name_code_dict_one.update(name_code_dict_two)
temp_df = pd.DataFrame.from_dict(
name_code_dict_one, orient="index"
).reset_index()
temp_df.columns = ["name", "code"]
return temp_df
| 18,218 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/fx/currency_investing.py
|
currency_pair_map
|
(symbol: str = "美元") ->
|
return temp_df
|
指定货币的所有可获取货币对的数据
https://cn.investing.com/currencies/cny-jmd
:param symbol: 指定货币
:type symbol: str
:return: 指定货币的所有可获取货币对的数据
:rtype: pandas.DataFrame
|
指定货币的所有可获取货币对的数据
https://cn.investing.com/currencies/cny-jmd
:param symbol: 指定货币
:type symbol: str
:return: 指定货币的所有可获取货币对的数据
:rtype: pandas.DataFrame
| 263 | 326 |
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 = []
def has_data_sml_id_but_no_id(tag):
return tag.has_attr("data-sml-id") and not tag.has_attr("title")
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"}
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",
}
r = requests.get(url, params=params, headers=headers)
soup = BeautifulSoup(r.text, "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, "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([temp_name, temp_code], index=["name", "code"]).T
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/fx/currency_investing.py#L263-L326
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 14.0625 |
[
9,
10,
12,
13,
15,
16,
17,
18,
32,
33,
34,
40,
47,
48,
49,
53,
54,
56,
59,
62,
63
] | 32.8125 | false | 13.392857 | 64 | 8 | 67.1875 | 6 |
def currency_pair_map(symbol: str = "美元") -> pd.DataFrame:
region_code = []
region_name = []
def has_data_sml_id_but_no_id(tag):
return tag.has_attr("data-sml-id") and not tag.has_attr("title")
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"}
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",
}
r = requests.get(url, params=params, headers=headers)
soup = BeautifulSoup(r.text, "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, "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([temp_name, temp_code], index=["name", "code"]).T
return temp_df
| 18,219 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/fx/fx_quote.py
|
fx_spot_quote
|
()
|
return temp_df
|
中国外汇交易中心暨全国银行间同业拆借中心-市场数据-市场行情-外汇市场行情-人民币外汇即期报价
http://www.chinamoney.com.cn/chinese/mkdatapfx/
:return: 人民币外汇即期报价
:rtype: pandas.DataFrame
|
中国外汇交易中心暨全国银行间同业拆借中心-市场数据-市场行情-外汇市场行情-人民币外汇即期报价
http://www.chinamoney.com.cn/chinese/mkdatapfx/
:return: 人民币外汇即期报价
:rtype: pandas.DataFrame
| 23 | 44 |
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
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/fx/fx_quote.py#L23-L44
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 31.818182 |
[
7,
8,
9,
10,
11,
18,
19,
20,
21
] | 40.909091 | false | 23.076923 | 22 | 1 | 59.090909 | 4 |
def fx_spot_quote() -> pd.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
| 18,220 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/fx/fx_quote.py
|
fx_swap_quote
|
()
|
return temp_df
|
中国外汇交易中心暨全国银行间同业拆借中心-市场数据-市场行情-债券市场行情-人民币外汇远掉报价
https://www.chinamoney.com.cn/chinese/index.html
:return: 人民币外汇远掉报价
:return: pandas.DataFrame
|
中国外汇交易中心暨全国银行间同业拆借中心-市场数据-市场行情-债券市场行情-人民币外汇远掉报价
https://www.chinamoney.com.cn/chinese/index.html
:return: 人民币外汇远掉报价
:return: pandas.DataFrame
| 47 | 77 |
def fx_swap_quote() -> pd.DataFrame:
"""
中国外汇交易中心暨全国银行间同业拆借中心-市场数据-市场行情-债券市场行情-人民币外汇远掉报价
https://www.chinamoney.com.cn/chinese/index.html
:return: 人民币外汇远掉报价
:return: 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
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/fx/fx_quote.py#L47-L77
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 22.580645 |
[
7,
8,
9,
10,
21,
30
] | 19.354839 | false | 23.076923 | 31 | 1 | 80.645161 | 4 |
def fx_swap_quote() -> pd.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
| 18,221 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/fx/fx_quote.py
|
fx_pair_quote
|
()
|
return temp_df
|
中国外汇交易中心暨全国银行间同业拆借中心-市场数据-市场行情-债券市场行情-外币对即期报价
http://www.chinamoney.com.cn/chinese/mkdatapfx/
:return: 外币对即期报价
:return: pandas.DataFrame
|
中国外汇交易中心暨全国银行间同业拆借中心-市场数据-市场行情-债券市场行情-外币对即期报价
http://www.chinamoney.com.cn/chinese/mkdatapfx/
:return: 外币对即期报价
:return: pandas.DataFrame
| 80 | 101 |
def fx_pair_quote() -> pd.DataFrame:
"""
中国外汇交易中心暨全国银行间同业拆借中心-市场数据-市场行情-债券市场行情-外币对即期报价
http://www.chinamoney.com.cn/chinese/mkdatapfx/
:return: 外币对即期报价
:return: 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
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/fx/fx_quote.py#L80-L101
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 31.818182 |
[
7,
8,
9,
10,
11,
18,
19,
20,
21
] | 40.909091 | false | 23.076923 | 22 | 1 | 59.090909 | 4 |
def fx_pair_quote() -> pd.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
| 18,222 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/fx/fx_quote_baidu.py
|
fx_quote_baidu
|
(symbol: str = "人民币") -> pd
|
return out_df
|
百度股市通-外汇-行情榜单
https://gushitong.baidu.com/top/foreign-common-%E5%B8%B8%E7%94%A8
:param symbol: choice of {"人民币", 美元"}
:type symbol: str
:return: 外汇行情数据
:rtype: pandas.DataFrame
|
百度股市通-外汇-行情榜单
https://gushitong.baidu.com/top/foreign-common-%E5%B8%B8%E7%94%A8
:param symbol: choice of {"人民币", 美元"}
:type symbol: str
:return: 外汇行情数据
:rtype: pandas.DataFrame
| 12 | 59 |
def fx_quote_baidu(symbol: str = "人民币") -> pd.DataFrame:
"""
百度股市通-外汇-行情榜单
https://gushitong.baidu.com/top/foreign-common-%E5%B8%B8%E7%94%A8
:param symbol: choice of {"人民币", 美元"}
:type symbol: str
:return: 外汇行情数据
:rtype: pandas.DataFrame
"""
symbol_map = {
"人民币": "rmb",
"美元": "dollar",
}
url = "https://finance.pae.baidu.com/api/getforeignrank"
num = 0
params = {
'pn': num,
'rn': '20',
'type': symbol_map[symbol],
'finClientType': 'pc'
}
out_df = pd.DataFrame()
while True:
try:
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(
data_json["Result"]
)
temp_list = []
for item in temp_df["list"]:
temp_list.append(list(pd.DataFrame(item).T.iloc[1, :].values))
value_df = pd.DataFrame(temp_list, columns=pd.DataFrame(item).T.iloc[0, :].values)
big_df = pd.concat([temp_df, value_df], axis=1)
del big_df['market']
del big_df['list']
big_df.columns = [
'代码', '名称', '最新价', '涨跌额', '涨跌幅'
]
big_df['最新价'] = pd.to_numeric(big_df['最新价'])
big_df['涨跌额'] = pd.to_numeric(big_df['涨跌额'])
big_df['涨跌幅'] = pd.to_numeric(big_df['涨跌幅'].str.strip("%")) / 100
out_df = pd.concat([out_df, big_df], ignore_index=True)
num = num + 20
params.update({"pn": num})
except:
break
return out_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/fx/fx_quote_baidu.py#L12-L59
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 18.75 |
[
9,
13,
14,
15,
21,
22,
23,
24,
25,
26,
29,
30,
31,
32,
33,
34,
35,
36,
39,
40,
41,
42,
43,
44,
45,
46,
47
] | 56.25 | false | 14.705882 | 48 | 4 | 43.75 | 6 |
def fx_quote_baidu(symbol: str = "人民币") -> pd.DataFrame:
symbol_map = {
"人民币": "rmb",
"美元": "dollar",
}
url = "https://finance.pae.baidu.com/api/getforeignrank"
num = 0
params = {
'pn': num,
'rn': '20',
'type': symbol_map[symbol],
'finClientType': 'pc'
}
out_df = pd.DataFrame()
while True:
try:
r = requests.get(url, params=params)
data_json = r.json()
temp_df = pd.DataFrame(
data_json["Result"]
)
temp_list = []
for item in temp_df["list"]:
temp_list.append(list(pd.DataFrame(item).T.iloc[1, :].values))
value_df = pd.DataFrame(temp_list, columns=pd.DataFrame(item).T.iloc[0, :].values)
big_df = pd.concat([temp_df, value_df], axis=1)
del big_df['market']
del big_df['list']
big_df.columns = [
'代码', '名称', '最新价', '涨跌额', '涨跌幅'
]
big_df['最新价'] = pd.to_numeric(big_df['最新价'])
big_df['涨跌额'] = pd.to_numeric(big_df['涨跌额'])
big_df['涨跌幅'] = pd.to_numeric(big_df['涨跌幅'].str.strip("%")) / 100
out_df = pd.concat([out_df, big_df], ignore_index=True)
num = num + 20
params.update({"pn": num})
except:
break
return out_df
| 18,223 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures_derivative/sina_futures_index.py
|
zh_subscribe_exchange_symbol
|
(symbol: str = "dce")
|
订阅指定交易所品种的代码
https://finance.sina.com.cn/futuremarket/index.shtml
:param symbol: choice of {"dce", "czce", "shfe", "cffex"}
:type symbol: str
:return: 订阅指定交易所品种的代码
:rtype: pandas.DataFrame
|
订阅指定交易所品种的代码
https://finance.sina.com.cn/futuremarket/index.shtml
:param symbol: choice of {"dce", "czce", "shfe", "cffex"}
:type symbol: str
:return: 订阅指定交易所品种的代码
:rtype: pandas.DataFrame
| 19 | 44 |
def zh_subscribe_exchange_symbol(symbol: str = "dce") -> pd.DataFrame:
"""
订阅指定交易所品种的代码
https://finance.sina.com.cn/futuremarket/index.shtml
:param symbol: choice of {"dce", "czce", "shfe", "cffex"}
:type symbol: str
:return: 订阅指定交易所品种的代码
:rtype: pandas.DataFrame
"""
r = requests.get(zh_subscribe_exchange_symbol_url)
r.encoding = "gb2312"
data_json = demjson.decode(
r.text[r.text.find("{") : r.text.find("};") + 1]
)
if symbol == "czce":
data_json["czce"].remove("郑州商品交易所")
return pd.DataFrame(data_json["czce"])
if symbol == "dce":
data_json["dce"].remove("大连商品交易所")
return pd.DataFrame(data_json["dce"])
if symbol == "shfe":
data_json["shfe"].remove("上海期货交易所")
return pd.DataFrame(data_json["shfe"])
if symbol == "cffex":
data_json["cffex"].remove("中国金融期货交易所")
return pd.DataFrame(data_json["cffex"])
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures_derivative/sina_futures_index.py#L19-L44
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 34.615385 |
[
9,
10,
11,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
25
] | 57.692308 | false | 14.285714 | 26 | 5 | 42.307692 | 6 |
def zh_subscribe_exchange_symbol(symbol: str = "dce") -> pd.DataFrame:
r = requests.get(zh_subscribe_exchange_symbol_url)
r.encoding = "gb2312"
data_json = demjson.decode(
r.text[r.text.find("{") : r.text.find("};") + 1]
)
if symbol == "czce":
data_json["czce"].remove("郑州商品交易所")
return pd.DataFrame(data_json["czce"])
if symbol == "dce":
data_json["dce"].remove("大连商品交易所")
return pd.DataFrame(data_json["dce"])
if symbol == "shfe":
data_json["shfe"].remove("上海期货交易所")
return pd.DataFrame(data_json["shfe"])
if symbol == "cffex":
data_json["cffex"].remove("中国金融期货交易所")
return pd.DataFrame(data_json["cffex"])
| 18,224 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures_derivative/sina_futures_index.py
|
match_main_contract
|
(symbol: str = "shfe")
|
return temp_df
|
指定交易所的所有可以提供数据的合约
https://finance.sina.com.cn/futuremarket/index.shtml
:param symbol: choice of {"dce", "czce", "shfe", "cffex"}
:type symbol: str
:return: 指定交易所的所有可以提供数据的合约
:rtype: pandas.DataFrame
|
指定交易所的所有可以提供数据的合约
https://finance.sina.com.cn/futuremarket/index.shtml
:param symbol: choice of {"dce", "czce", "shfe", "cffex"}
:type symbol: str
:return: 指定交易所的所有可以提供数据的合约
:rtype: pandas.DataFrame
| 47 | 81 |
def match_main_contract(symbol: str = "shfe") -> pd.DataFrame:
"""
指定交易所的所有可以提供数据的合约
https://finance.sina.com.cn/futuremarket/index.shtml
:param symbol: choice of {"dce", "czce", "shfe", "cffex"}
:type symbol: str
:return: 指定交易所的所有可以提供数据的合约
:rtype: pandas.DataFrame
"""
subscribe_list = []
exchange_symbol_list = (
zh_subscribe_exchange_symbol(symbol).iloc[:, 1].tolist()
)
for item in exchange_symbol_list:
zh_match_main_contract_payload.update({"node": item})
res = requests.get(
zh_match_main_contract_url, params=zh_match_main_contract_payload
)
data_json = demjson.decode(res.text)
data_df = pd.DataFrame(data_json)
try:
main_contract = data_df[
data_df["name"].str.contains("连续")
& data_df["symbol"]
.str.extract(r"([\w])(\d)")
.iloc[:, 1]
.str.contains("0")
].iloc[0, :3]
subscribe_list.append(main_contract)
except:
# print(item, "无主力连续合约")
continue
# print("主力连续合约获取成功")
temp_df = pd.DataFrame(subscribe_list)
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures_derivative/sina_futures_index.py#L47-L81
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8
] | 25.714286 |
[
9,
10,
13,
14,
15,
18,
19,
20,
21,
28,
29,
31,
33,
34
] | 40 | false | 14.285714 | 35 | 3 | 60 | 6 |
def match_main_contract(symbol: str = "shfe") -> pd.DataFrame:
subscribe_list = []
exchange_symbol_list = (
zh_subscribe_exchange_symbol(symbol).iloc[:, 1].tolist()
)
for item in exchange_symbol_list:
zh_match_main_contract_payload.update({"node": item})
res = requests.get(
zh_match_main_contract_url, params=zh_match_main_contract_payload
)
data_json = demjson.decode(res.text)
data_df = pd.DataFrame(data_json)
try:
main_contract = data_df[
data_df["name"].str.contains("连续")
& data_df["symbol"]
.str.extract(r"([\w])(\d)")
.iloc[:, 1]
.str.contains("0")
].iloc[0, :3]
subscribe_list.append(main_contract)
except:
# print(item, "无主力连续合约")
continue
# print("主力连续合约获取成功")
temp_df = pd.DataFrame(subscribe_list)
return temp_df
| 18,225 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures_derivative/sina_futures_index.py
|
futures_display_main_sina
|
()
|
return temp_df
|
新浪主力连续合约品种一览表
https://finance.sina.com.cn/futuremarket/index.shtml
:return: 新浪主力连续合约品种一览表
:rtype: pandas.DataFrame
|
新浪主力连续合约品种一览表
https://finance.sina.com.cn/futuremarket/index.shtml
:return: 新浪主力连续合约品种一览表
:rtype: pandas.DataFrame
| 84 | 95 |
def futures_display_main_sina() -> pd.DataFrame:
"""
新浪主力连续合约品种一览表
https://finance.sina.com.cn/futuremarket/index.shtml
:return: 新浪主力连续合约品种一览表
:rtype: pandas.DataFrame
"""
temp_df = pd.DataFrame()
for item in ["dce", "czce", "shfe", "cffex"]:
temp_df = pd.concat([temp_df, match_main_contract(symbol=item)])
temp_df.reset_index(inplace=True, drop=True)
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures_derivative/sina_futures_index.py#L84-L95
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 58.333333 |
[
7,
8,
9,
10,
11
] | 41.666667 | false | 14.285714 | 12 | 2 | 58.333333 | 4 |
def futures_display_main_sina() -> pd.DataFrame:
temp_df = pd.DataFrame()
for item in ["dce", "czce", "shfe", "cffex"]:
temp_df = pd.concat([temp_df, match_main_contract(symbol=item)])
temp_df.reset_index(inplace=True, drop=True)
return temp_df
| 18,226 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures_derivative/sina_futures_index.py
|
futures_main_sina
|
(
symbol: str = "V0",
start_date: str = "19900101",
end_date: str = "22220101",
)
|
return temp_df
|
新浪财经-期货-主力连续日数据
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: 通过 ak.futures_display_main_sina() 函数获取 symbol
:type symbol: str
:param start_date: 开始时间
:type start_date: str
:param end_date: 结束时间
:type end_date: str
:return: 主力连续日数据
:rtype: pandas.DataFrame
|
新浪财经-期货-主力连续日数据
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: 通过 ak.futures_display_main_sina() 函数获取 symbol
:type symbol: str
:param start_date: 开始时间
:type start_date: str
:param end_date: 结束时间
:type end_date: str
:return: 主力连续日数据
:rtype: pandas.DataFrame
| 98 | 136 |
def futures_main_sina(
symbol: str = "V0",
start_date: str = "19900101",
end_date: str = "22220101",
) -> pd.DataFrame:
"""
新浪财经-期货-主力连续日数据
http://vip.stock.finance.sina.com.cn/quotes_service/view/qihuohangqing.html#titlePos_1
:param symbol: 通过 ak.futures_display_main_sina() 函数获取 symbol
:type symbol: str
:param start_date: 开始时间
:type start_date: str
:param end_date: 结束时间
:type end_date: str
:return: 主力连续日数据
:rtype: pandas.DataFrame
"""
trade_date = "20210817"
trade_date = trade_date[:4] + "_" + trade_date[4:6] + "_" + trade_date[6:]
url = f"https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_{symbol}{trade_date}=/InnerFuturesNewService.getDailyKLine?symbol={symbol}&_={trade_date}"
r = requests.get(url)
data_text = r.text
data_json = data_text[data_text.find("([") + 1 : data_text.rfind("])") + 1]
temp_df = pd.read_json(data_json)
temp_df.columns = ["日期", "开盘价", "最高价", "最低价", "收盘价", "成交量", "持仓量", "动态结算价"]
temp_df["日期"] = pd.to_datetime(temp_df["日期"]).dt.date
temp_df.set_index(["日期"], inplace=True)
temp_df.index = pd.to_datetime(temp_df.index)
temp_df = temp_df[start_date:end_date]
temp_df.reset_index(inplace=True)
temp_df["日期"] = pd.to_datetime(temp_df["日期"]).dt.date
temp_df["开盘价"] = pd.to_numeric(temp_df["开盘价"])
temp_df["最高价"] = pd.to_numeric(temp_df["最高价"])
temp_df["最低价"] = pd.to_numeric(temp_df["最低价"])
temp_df["收盘价"] = pd.to_numeric(temp_df["收盘价"])
temp_df["成交量"] = pd.to_numeric(temp_df["成交量"])
temp_df["持仓量"] = pd.to_numeric(temp_df["持仓量"])
temp_df["动态结算价"] = pd.to_numeric(temp_df["动态结算价"])
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures_derivative/sina_futures_index.py#L98-L136
| 25 |
[
0
] | 2.564103 |
[
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
36,
37,
38
] | 56.410256 | false | 14.285714 | 39 | 1 | 43.589744 | 10 |
def futures_main_sina(
symbol: str = "V0",
start_date: str = "19900101",
end_date: str = "22220101",
) -> pd.DataFrame:
trade_date = "20210817"
trade_date = trade_date[:4] + "_" + trade_date[4:6] + "_" + trade_date[6:]
url = f"https://stock2.finance.sina.com.cn/futures/api/jsonp.php/var%20_{symbol}{trade_date}=/InnerFuturesNewService.getDailyKLine?symbol={symbol}&_={trade_date}"
r = requests.get(url)
data_text = r.text
data_json = data_text[data_text.find("([") + 1 : data_text.rfind("])") + 1]
temp_df = pd.read_json(data_json)
temp_df.columns = ["日期", "开盘价", "最高价", "最低价", "收盘价", "成交量", "持仓量", "动态结算价"]
temp_df["日期"] = pd.to_datetime(temp_df["日期"]).dt.date
temp_df.set_index(["日期"], inplace=True)
temp_df.index = pd.to_datetime(temp_df.index)
temp_df = temp_df[start_date:end_date]
temp_df.reset_index(inplace=True)
temp_df["日期"] = pd.to_datetime(temp_df["日期"]).dt.date
temp_df["开盘价"] = pd.to_numeric(temp_df["开盘价"])
temp_df["最高价"] = pd.to_numeric(temp_df["最高价"])
temp_df["最低价"] = pd.to_numeric(temp_df["最低价"])
temp_df["收盘价"] = pd.to_numeric(temp_df["收盘价"])
temp_df["成交量"] = pd.to_numeric(temp_df["成交量"])
temp_df["持仓量"] = pd.to_numeric(temp_df["持仓量"])
temp_df["动态结算价"] = pd.to_numeric(temp_df["动态结算价"])
return temp_df
| 18,227 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures_derivative/futures_egg.py
|
futures_egg_price_yearly
|
()
|
return temp_df
|
各年度产区鸡蛋价格走势
https://www.jidan7.com/trend/
:return: 各年度产区鸡蛋价格走势
:rtype: pandas.DataFrame
|
各年度产区鸡蛋价格走势
https://www.jidan7.com/trend/
:return: 各年度产区鸡蛋价格走势
:rtype: pandas.DataFrame
| 15 | 61 |
def futures_egg_price_yearly() -> pd.DataFrame:
"""
各年度产区鸡蛋价格走势
https://www.jidan7.com/trend/
:return: 各年度产区鸡蛋价格走势
:rtype: pandas.DataFrame
"""
url = "https://www.jidan7.com/trend/"
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
js_text = soup.find_all("script")[8].string
js_text_processed = js_text.replace("\r\n", "")
js_text_processed = re.findall(r"(\[.*?])", js_text_processed)
year_list = eval(js_text_processed[1])
date_list = eval(js_text_processed[2])
value_2015_list = eval(js_text_processed[4])
value_2016_list = eval(js_text_processed[6])
value_2017_list = eval(js_text_processed[8])
value_2018_list = eval(js_text_processed[10])
value_2019_list = eval(js_text_processed[12])
value_2020_list = eval(js_text_processed[14])
value_2021_list = eval(js_text_processed[16])
value_2022_list = eval(js_text_processed[18])
temp_df = pd.DataFrame(
[
date_list,
value_2015_list,
value_2016_list,
value_2017_list,
value_2018_list,
value_2019_list,
value_2020_list,
value_2021_list,
value_2022_list,
]
).T
temp_df.columns = ["日期"] + year_list
temp_df = temp_df[:-1]
temp_df['2015年'] = pd.to_numeric(temp_df['2015年'])
temp_df['2016年'] = pd.to_numeric(temp_df['2016年'])
temp_df['2017年'] = pd.to_numeric(temp_df['2017年'])
temp_df['2018年'] = pd.to_numeric(temp_df['2018年'])
temp_df['2019年'] = pd.to_numeric(temp_df['2019年'])
temp_df['2020年'] = pd.to_numeric(temp_df['2020年'])
temp_df['2021年'] = pd.to_numeric(temp_df['2021年'])
temp_df['2022年'] = pd.to_numeric(temp_df['2022年'])
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures_derivative/futures_egg.py#L15-L61
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 14.893617 |
[
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
36,
37,
38,
39,
40,
41,
42,
43,
44,
45,
46
] | 59.574468 | false | 11.111111 | 47 | 1 | 40.425532 | 4 |
def futures_egg_price_yearly() -> pd.DataFrame:
url = "https://www.jidan7.com/trend/"
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
js_text = soup.find_all("script")[8].string
js_text_processed = js_text.replace("\r\n", "")
js_text_processed = re.findall(r"(\[.*?])", js_text_processed)
year_list = eval(js_text_processed[1])
date_list = eval(js_text_processed[2])
value_2015_list = eval(js_text_processed[4])
value_2016_list = eval(js_text_processed[6])
value_2017_list = eval(js_text_processed[8])
value_2018_list = eval(js_text_processed[10])
value_2019_list = eval(js_text_processed[12])
value_2020_list = eval(js_text_processed[14])
value_2021_list = eval(js_text_processed[16])
value_2022_list = eval(js_text_processed[18])
temp_df = pd.DataFrame(
[
date_list,
value_2015_list,
value_2016_list,
value_2017_list,
value_2018_list,
value_2019_list,
value_2020_list,
value_2021_list,
value_2022_list,
]
).T
temp_df.columns = ["日期"] + year_list
temp_df = temp_df[:-1]
temp_df['2015年'] = pd.to_numeric(temp_df['2015年'])
temp_df['2016年'] = pd.to_numeric(temp_df['2016年'])
temp_df['2017年'] = pd.to_numeric(temp_df['2017年'])
temp_df['2018年'] = pd.to_numeric(temp_df['2018年'])
temp_df['2019年'] = pd.to_numeric(temp_df['2019年'])
temp_df['2020年'] = pd.to_numeric(temp_df['2020年'])
temp_df['2021年'] = pd.to_numeric(temp_df['2021年'])
temp_df['2022年'] = pd.to_numeric(temp_df['2022年'])
return temp_df
| 18,228 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures_derivative/futures_egg.py
|
futures_egg_price
|
()
|
return temp_df
|
2015-2021年鸡蛋价格走势
https://www.jidan7.com/trend/
:return: 2015-2021年鸡蛋价格走势
:rtype: pandas.DataFrame
|
2015-2021年鸡蛋价格走势
https://www.jidan7.com/trend/
:return: 2015-2021年鸡蛋价格走势
:rtype: pandas.DataFrame
| 64 | 92 |
def futures_egg_price() -> pd.DataFrame:
"""
2015-2021年鸡蛋价格走势
https://www.jidan7.com/trend/
:return: 2015-2021年鸡蛋价格走势
:rtype: pandas.DataFrame
"""
url = "https://www.jidan7.com/trend/"
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
js_text = soup.find_all("script")[9].string
js_text_processed = js_text.replace("\r\n", "")
re.findall(r"data: (.*)", js_text_processed)
js_text_processed = re.findall(r"(\[.*?])", js_text_processed)
date_list = eval(js_text_processed[2])
value_2015_list = eval(re.findall(r"data: (\[.*?])", js_text_processed[3])[0])
temp_df = pd.DataFrame(
[
date_list,
value_2015_list,
]
).T
temp_df.dropna(how="any", inplace=True)
temp_df.columns = [
"date",
"price",
]
temp_df['price'] = pd.to_numeric(temp_df['price'])
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures_derivative/futures_egg.py#L64-L92
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 24.137931 |
[
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
22,
23,
27,
28
] | 48.275862 | false | 11.111111 | 29 | 1 | 51.724138 | 4 |
def futures_egg_price() -> pd.DataFrame:
url = "https://www.jidan7.com/trend/"
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
js_text = soup.find_all("script")[9].string
js_text_processed = js_text.replace("\r\n", "")
re.findall(r"data: (.*)", js_text_processed)
js_text_processed = re.findall(r"(\[.*?])", js_text_processed)
date_list = eval(js_text_processed[2])
value_2015_list = eval(re.findall(r"data: (\[.*?])", js_text_processed[3])[0])
temp_df = pd.DataFrame(
[
date_list,
value_2015_list,
]
).T
temp_df.dropna(how="any", inplace=True)
temp_df.columns = [
"date",
"price",
]
temp_df['price'] = pd.to_numeric(temp_df['price'])
return temp_df
| 18,229 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures_derivative/futures_egg.py
|
futures_egg_price_area
|
()
|
return temp_df
|
各主产区鸡蛋均价
https://www.jidan7.com/trend/
:return: 各主产区鸡蛋均价
:rtype: pandas.DataFrame
|
各主产区鸡蛋均价
https://www.jidan7.com/trend/
:return: 各主产区鸡蛋均价
:rtype: pandas.DataFrame
| 95 | 135 |
def futures_egg_price_area() -> pd.DataFrame:
"""
各主产区鸡蛋均价
https://www.jidan7.com/trend/
:return: 各主产区鸡蛋均价
:rtype: pandas.DataFrame
"""
url = "https://www.jidan7.com/trend/"
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
js_text = soup.find_all("script")[10].string
js_text_processed = js_text.replace("\r\n", "")
js_text_processed = re.findall(r"data: (\[.*?])", js_text_processed)
area_list = eval(js_text_processed[0])
date_list = eval(js_text_processed[1])
value_sd_list = eval(js_text_processed[2])
value_hn_list = eval(js_text_processed[3])
value_hb_list = eval(js_text_processed[4])
value_ln_list = eval(js_text_processed[5])
value_js_list = eval(js_text_processed[6])
value_hub_list = eval(js_text_processed[7])
temp_df = pd.DataFrame(
[
date_list,
value_sd_list,
value_hn_list,
value_hb_list,
value_ln_list,
value_js_list,
value_hub_list,
]
).T
temp_df.dropna(how="any", inplace=True)
temp_df.columns = ["日期"] + area_list
temp_df['山东均价'] = pd.to_numeric(temp_df['山东均价'])
temp_df['河南均价'] = pd.to_numeric(temp_df['河南均价'])
temp_df['河北均价'] = pd.to_numeric(temp_df['河北均价'])
temp_df['辽宁均价'] = pd.to_numeric(temp_df['辽宁均价'])
temp_df['江苏均价'] = pd.to_numeric(temp_df['江苏均价'])
temp_df['湖北均价'] = pd.to_numeric(temp_df['湖北均价'])
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures_derivative/futures_egg.py#L95-L135
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 17.073171 |
[
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
32,
33,
34,
35,
36,
37,
38,
39,
40
] | 58.536585 | false | 11.111111 | 41 | 1 | 41.463415 | 4 |
def futures_egg_price_area() -> pd.DataFrame:
url = "https://www.jidan7.com/trend/"
r = requests.get(url)
soup = BeautifulSoup(r.text, "lxml")
js_text = soup.find_all("script")[10].string
js_text_processed = js_text.replace("\r\n", "")
js_text_processed = re.findall(r"data: (\[.*?])", js_text_processed)
area_list = eval(js_text_processed[0])
date_list = eval(js_text_processed[1])
value_sd_list = eval(js_text_processed[2])
value_hn_list = eval(js_text_processed[3])
value_hb_list = eval(js_text_processed[4])
value_ln_list = eval(js_text_processed[5])
value_js_list = eval(js_text_processed[6])
value_hub_list = eval(js_text_processed[7])
temp_df = pd.DataFrame(
[
date_list,
value_sd_list,
value_hn_list,
value_hb_list,
value_ln_list,
value_js_list,
value_hub_list,
]
).T
temp_df.dropna(how="any", inplace=True)
temp_df.columns = ["日期"] + area_list
temp_df['山东均价'] = pd.to_numeric(temp_df['山东均价'])
temp_df['河南均价'] = pd.to_numeric(temp_df['河南均价'])
temp_df['河北均价'] = pd.to_numeric(temp_df['河北均价'])
temp_df['辽宁均价'] = pd.to_numeric(temp_df['辽宁均价'])
temp_df['江苏均价'] = pd.to_numeric(temp_df['江苏均价'])
temp_df['湖北均价'] = pd.to_numeric(temp_df['湖北均价'])
return temp_df
| 18,230 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures_derivative/sys_spot_futures.py
|
get_sys_spot_futures_dict
|
()
|
return name_url_dict
|
生意社-商品与期货-现期图: 品种和网址字典
http://www.100ppi.com/sf/792.html
:return: dict
{'铜': 'http://www.100ppi.com/sf/792.html', '铅': 'http://www.100ppi.com/sf/825.html', '锌': 'http://www.100ppi.com/sf/826.html', '铝': 'http://www.100ppi.com/sf/827.html', '螺纹钢': 'http://www.100ppi.com/sf/927.html', '线材': 'http://www.100ppi.com/sf/740.html', '燃料油': 'http://www.100ppi.com/sf/387.html', '焦炭': 'http://www.100ppi.com/sf/617.html', '天然橡胶': 'http://www.100ppi.com/sf/586.html', '聚氯乙烯': 'http://www.100ppi.com/sf/107.html', '聚乙烯': 'http://www.100ppi.com/sf/435.html', '甲醇': 'http://www.100ppi.com/sf/817.html', '菜籽油': 'http://www.100ppi.com/sf/810.html', '棕榈油': 'http://www.100ppi.com/sf/1084.html', '硬麦': 'http://www.100ppi.com/sf/349.html', '豆一': 'http://www.100ppi.com/sf/1080.html', '豆粕': 'http://www.100ppi.com/sf/312.html', '豆油': 'http://www.100ppi.com/sf/403.html', '玉米': 'http://www.100ppi.com/sf/274.html', '白糖': 'http://www.100ppi.com/sf/564.html', '棉花': 'http://www.100ppi.com/sf/344.html', 'PTA': 'http://www.100ppi.com/sf/356.html', '黄金': 'http://www.100ppi.com/sf/551.html', '白银': 'http://www.100ppi.com/sf/544.html', '玻璃': 'http://www.100ppi.com/sf/959.html', '焦煤': 'http://www.100ppi.com/sf/1121.html', '菜籽粕': 'http://www.100ppi.com/sf/1014.html', '油菜籽': 'http://www.100ppi.com/sf/1087.html', '动力煤': 'http://www.100ppi.com/sf/369.html', '石油沥青': 'http://www.100ppi.com/sf/1022.html', '铁矿石': 'http://www.100ppi.com/sf/961.html', '鸡蛋': 'http://www.100ppi.com/sf/1049.html', '锰硅': 'http://www.100ppi.com/sf/1155.html', '硅铁': 'http://www.100ppi.com/sf/1154.html', '热轧卷板': 'http://www.100ppi.com/sf/195.html', '细木工板': 'http://www.100ppi.com/sf/1158.html', '聚丙烯': 'http://www.100ppi.com/sf/718.html', '锡': 'http://www.100ppi.com/sf/1181.html', '镍': 'http://www.100ppi.com/sf/1182.html', '玉米淀粉': 'http://www.100ppi.com/sf/1209.html'}
|
生意社-商品与期货-现期图: 品种和网址字典
http://www.100ppi.com/sf/792.html
:return: dict
{'铜': 'http://www.100ppi.com/sf/792.html', '铅': 'http://www.100ppi.com/sf/825.html', '锌': 'http://www.100ppi.com/sf/826.html', '铝': 'http://www.100ppi.com/sf/827.html', '螺纹钢': 'http://www.100ppi.com/sf/927.html', '线材': 'http://www.100ppi.com/sf/740.html', '燃料油': 'http://www.100ppi.com/sf/387.html', '焦炭': 'http://www.100ppi.com/sf/617.html', '天然橡胶': 'http://www.100ppi.com/sf/586.html', '聚氯乙烯': 'http://www.100ppi.com/sf/107.html', '聚乙烯': 'http://www.100ppi.com/sf/435.html', '甲醇': 'http://www.100ppi.com/sf/817.html', '菜籽油': 'http://www.100ppi.com/sf/810.html', '棕榈油': 'http://www.100ppi.com/sf/1084.html', '硬麦': 'http://www.100ppi.com/sf/349.html', '豆一': 'http://www.100ppi.com/sf/1080.html', '豆粕': 'http://www.100ppi.com/sf/312.html', '豆油': 'http://www.100ppi.com/sf/403.html', '玉米': 'http://www.100ppi.com/sf/274.html', '白糖': 'http://www.100ppi.com/sf/564.html', '棉花': 'http://www.100ppi.com/sf/344.html', 'PTA': 'http://www.100ppi.com/sf/356.html', '黄金': 'http://www.100ppi.com/sf/551.html', '白银': 'http://www.100ppi.com/sf/544.html', '玻璃': 'http://www.100ppi.com/sf/959.html', '焦煤': 'http://www.100ppi.com/sf/1121.html', '菜籽粕': 'http://www.100ppi.com/sf/1014.html', '油菜籽': 'http://www.100ppi.com/sf/1087.html', '动力煤': 'http://www.100ppi.com/sf/369.html', '石油沥青': 'http://www.100ppi.com/sf/1022.html', '铁矿石': 'http://www.100ppi.com/sf/961.html', '鸡蛋': 'http://www.100ppi.com/sf/1049.html', '锰硅': 'http://www.100ppi.com/sf/1155.html', '硅铁': 'http://www.100ppi.com/sf/1154.html', '热轧卷板': 'http://www.100ppi.com/sf/195.html', '细木工板': 'http://www.100ppi.com/sf/1158.html', '聚丙烯': 'http://www.100ppi.com/sf/718.html', '锡': 'http://www.100ppi.com/sf/1181.html', '镍': 'http://www.100ppi.com/sf/1182.html', '玉米淀粉': 'http://www.100ppi.com/sf/1209.html'}
| 14 | 26 |
def get_sys_spot_futures_dict() -> dict:
"""
生意社-商品与期货-现期图: 品种和网址字典
http://www.100ppi.com/sf/792.html
:return: dict
{'铜': 'http://www.100ppi.com/sf/792.html', '铅': 'http://www.100ppi.com/sf/825.html', '锌': 'http://www.100ppi.com/sf/826.html', '铝': 'http://www.100ppi.com/sf/827.html', '螺纹钢': 'http://www.100ppi.com/sf/927.html', '线材': 'http://www.100ppi.com/sf/740.html', '燃料油': 'http://www.100ppi.com/sf/387.html', '焦炭': 'http://www.100ppi.com/sf/617.html', '天然橡胶': 'http://www.100ppi.com/sf/586.html', '聚氯乙烯': 'http://www.100ppi.com/sf/107.html', '聚乙烯': 'http://www.100ppi.com/sf/435.html', '甲醇': 'http://www.100ppi.com/sf/817.html', '菜籽油': 'http://www.100ppi.com/sf/810.html', '棕榈油': 'http://www.100ppi.com/sf/1084.html', '硬麦': 'http://www.100ppi.com/sf/349.html', '豆一': 'http://www.100ppi.com/sf/1080.html', '豆粕': 'http://www.100ppi.com/sf/312.html', '豆油': 'http://www.100ppi.com/sf/403.html', '玉米': 'http://www.100ppi.com/sf/274.html', '白糖': 'http://www.100ppi.com/sf/564.html', '棉花': 'http://www.100ppi.com/sf/344.html', 'PTA': 'http://www.100ppi.com/sf/356.html', '黄金': 'http://www.100ppi.com/sf/551.html', '白银': 'http://www.100ppi.com/sf/544.html', '玻璃': 'http://www.100ppi.com/sf/959.html', '焦煤': 'http://www.100ppi.com/sf/1121.html', '菜籽粕': 'http://www.100ppi.com/sf/1014.html', '油菜籽': 'http://www.100ppi.com/sf/1087.html', '动力煤': 'http://www.100ppi.com/sf/369.html', '石油沥青': 'http://www.100ppi.com/sf/1022.html', '铁矿石': 'http://www.100ppi.com/sf/961.html', '鸡蛋': 'http://www.100ppi.com/sf/1049.html', '锰硅': 'http://www.100ppi.com/sf/1155.html', '硅铁': 'http://www.100ppi.com/sf/1154.html', '热轧卷板': 'http://www.100ppi.com/sf/195.html', '细木工板': 'http://www.100ppi.com/sf/1158.html', '聚丙烯': 'http://www.100ppi.com/sf/718.html', '锡': 'http://www.100ppi.com/sf/1181.html', '镍': 'http://www.100ppi.com/sf/1182.html', '玉米淀粉': 'http://www.100ppi.com/sf/1209.html'}
"""
url = "http://www.100ppi.com/sf/792.html"
res = requests.get(url)
soup = BeautifulSoup(res.text, "lxml")
temp_item = soup.find("div", attrs={"class": "q8"}).find_all("li")
name_url_dict = dict(zip([item.find("a").get_text().strip() for item in temp_item], [item.find("a")["href"] for item in temp_item]))
return name_url_dict
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures_derivative/sys_spot_futures.py#L14-L26
| 25 |
[
0,
1,
2,
3,
4,
5,
6
] | 53.846154 |
[
7,
8,
9,
10,
11,
12
] | 46.153846 | false | 26.923077 | 13 | 3 | 53.846154 | 4 |
def get_sys_spot_futures_dict() -> dict:
url = "http://www.100ppi.com/sf/792.html"
res = requests.get(url)
soup = BeautifulSoup(res.text, "lxml")
temp_item = soup.find("div", attrs={"class": "q8"}).find_all("li")
name_url_dict = dict(zip([item.find("a").get_text().strip() for item in temp_item], [item.find("a")["href"] for item in temp_item]))
return name_url_dict
| 18,231 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures_derivative/sys_spot_futures.py
|
get_sys_spot_futures
|
(symbol: str = "铜") -
|
return table_df_one, table_df_two, table_df_three
|
生意社-商品与期货-现期图: 图和表格
:param symbol: str 品种
:return: pd.DataFrame or pic
|
生意社-商品与期货-现期图: 图和表格
:param symbol: str 品种
:return: pd.DataFrame or pic
| 29 | 41 |
def get_sys_spot_futures(symbol: str = "铜") -> pd.DataFrame:
"""
生意社-商品与期货-现期图: 图和表格
:param symbol: str 品种
:return: pd.DataFrame or pic
"""
name_url_dict = get_sys_spot_futures_dict()
url = name_url_dict[symbol]
res = requests.get(url)
table_df_one = pd.read_html(res.text, header=0, index_col=0)[1].T
table_df_two = pd.read_html(res.text, header=0, index_col=0)[2].T
table_df_three = pd.read_html(res.text, header=0, index_col=0)[3].T
return table_df_one, table_df_two, table_df_three
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures_derivative/sys_spot_futures.py#L29-L41
| 25 |
[
0,
1,
2,
3,
4,
5
] | 46.153846 |
[
6,
7,
8,
9,
10,
11,
12
] | 53.846154 | false | 26.923077 | 13 | 1 | 46.153846 | 3 |
def get_sys_spot_futures(symbol: str = "铜") -> pd.DataFrame:
name_url_dict = get_sys_spot_futures_dict()
url = name_url_dict[symbol]
res = requests.get(url)
table_df_one = pd.read_html(res.text, header=0, index_col=0)[1].T
table_df_two = pd.read_html(res.text, header=0, index_col=0)[2].T
table_df_three = pd.read_html(res.text, header=0, index_col=0)[3].T
return table_df_one, table_df_two, table_df_three
| 18,232 |
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures_derivative/futures_index_volatility_nh.py
|
futures_nh_volatility_index
|
(symbol: str = "NHCI", period: str = '20')
|
南华期货-南华指数单品种-波动率-所有历史数据
http://www.nanhua.net/nhzc/varietytrend.html
:param symbol: 通过 ak.futures_index_symbol_table_nh() 获取
:type symbol: str
:param period: 波动周期 choice of {'5', '20', '60', '120'}
:type period: str
:return: 波动率-所有历史数据
:rtype: pandas.DataFrame
|
南华期货-南华指数单品种-波动率-所有历史数据
http://www.nanhua.net/nhzc/varietytrend.html
:param symbol: 通过 ak.futures_index_symbol_table_nh() 获取
:type symbol: str
:param period: 波动周期 choice of {'5', '20', '60', '120'}
:type period: str
:return: 波动率-所有历史数据
:rtype: pandas.DataFrame
| 18 | 38 |
def futures_nh_volatility_index(symbol: str = "NHCI", period: str = '20') -> pd.DataFrame:
"""
南华期货-南华指数单品种-波动率-所有历史数据
http://www.nanhua.net/nhzc/varietytrend.html
:param symbol: 通过 ak.futures_index_symbol_table_nh() 获取
:type symbol: str
:param period: 波动周期 choice of {'5', '20', '60', '120'}
:type period: str
:return: 波动率-所有历史数据
:rtype: pandas.DataFrame
"""
symbol_df = futures_index_symbol_table_nh()
if symbol in symbol_df["code"].tolist():
t = time.time()
url = f"http://www.nanhua.net/ianalysis/volatility/{period}/{symbol}.json?t={int(round(t * 1000))}"
r = requests.get(url)
data_json = r.json()
temp_df = pd.DataFrame(data_json)
temp_df.columns = ["date", "value"]
temp_df['date'] = pd.to_datetime(temp_df["date"], unit='ms').dt.date
return temp_df
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures_derivative/futures_index_volatility_nh.py#L18-L38
| 25 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
] | 52.380952 |
[
11,
12,
13,
14,
15,
16,
17,
18,
19,
20
] | 47.619048 | false | 36.842105 | 21 | 2 | 52.380952 | 8 |
def futures_nh_volatility_index(symbol: str = "NHCI", period: str = '20') -> pd.DataFrame:
symbol_df = futures_index_symbol_table_nh()
if symbol in symbol_df["code"].tolist():
t = time.time()
url = f"http://www.nanhua.net/ianalysis/volatility/{period}/{symbol}.json?t={int(round(t * 1000))}"
r = requests.get(url)
data_json = r.json()
temp_df = pd.DataFrame(data_json)
temp_df.columns = ["date", "value"]
temp_df['date'] = pd.to_datetime(temp_df["date"], unit='ms').dt.date
return temp_df
| 18,233 |
|
akfamily/akshare
|
087025d8d6f799b30ca114013e82c1ad22dc9294
|
akshare/futures_derivative/futures_sina_cot.py
|
futures_sina_hold_pos
|
(
symbol: str = "成交量", contract: str = "IC2106", date: str = "2021-06-03"
)
|
新浪财经-商品期货-成交持仓
http://vip.stock.finance.sina.com.cn/q/view/vCffex_Positions_cjcc.php?symbol=IC2106&date=2021-06-03
:param symbol: choice of {"成交量", "多单持仓", "空单持仓"}
:type symbol: str
:param contract: 期货合约
:type contract: str
:param date: 查询日期
:type date: str
:return: 成交持仓
:rtype: pandas.DataFrame
|
新浪财经-商品期货-成交持仓
http://vip.stock.finance.sina.com.cn/q/view/vCffex_Positions_cjcc.php?symbol=IC2106&date=2021-06-03
:param symbol: choice of {"成交量", "多单持仓", "空单持仓"}
:type symbol: str
:param contract: 期货合约
:type contract: str
:param date: 查询日期
:type date: str
:return: 成交持仓
:rtype: pandas.DataFrame
| 12 | 35 |
def futures_sina_hold_pos(
symbol: str = "成交量", contract: str = "IC2106", date: str = "2021-06-03"
) -> pd.DataFrame:
"""
新浪财经-商品期货-成交持仓
http://vip.stock.finance.sina.com.cn/q/view/vCffex_Positions_cjcc.php?symbol=IC2106&date=2021-06-03
:param symbol: choice of {"成交量", "多单持仓", "空单持仓"}
:type symbol: str
:param contract: 期货合约
:type contract: str
:param date: 查询日期
:type date: str
:return: 成交持仓
:rtype: pandas.DataFrame
"""
url = "http://vip.stock.finance.sina.com.cn/q/view/vCffex_Positions_cjcc.php"
params = {"symbol": contract, "date": date}
r = requests.get(url, params=params)
if symbol == "成交量":
return pd.read_html(r.text)[2]
elif symbol == "多单持仓":
return pd.read_html(r.text)[3]
elif symbol == "空单持仓":
return pd.read_html(r.text)[4]
|
https://github.com/akfamily/akshare/blob/087025d8d6f799b30ca114013e82c1ad22dc9294/project25/akshare/futures_derivative/futures_sina_cot.py#L12-L35
| 25 |
[
0
] | 4.166667 |
[
15,
16,
17,
18,
19,
20,
21,
22,
23
] | 37.5 | false | 31.25 | 24 | 4 | 62.5 | 10 |
def futures_sina_hold_pos(
symbol: str = "成交量", contract: str = "IC2106", date: str = "2021-06-03"
) -> pd.DataFrame:
url = "http://vip.stock.finance.sina.com.cn/q/view/vCffex_Positions_cjcc.php"
params = {"symbol": contract, "date": date}
r = requests.get(url, params=params)
if symbol == "成交量":
return pd.read_html(r.text)[2]
elif symbol == "多单持仓":
return pd.read_html(r.text)[3]
elif symbol == "空单持仓":
return pd.read_html(r.text)[4]
| 18,234 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.