python-data/east/main.py
2025-05-10 16:45:01 +08:00

110 lines
3.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import requests
import json
import pandas as pd
import matplotlib.pyplot as plt
# 设置 Matplotlib 使用的中文字体
plt.rcParams['font.sans-serif'] = ['SimHei'] # 选择合适的中文字体
plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题
def get_fund_flow_data():
"""获取资金流向数据"""
url = "https://push2.eastmoney.com/api/qt/clist/get?cb=jQuery112309006219872217847_1740232310161&fid=f62&po=1&pz=50&pn=1&np=1&fltt=2&invt=2&ut=8dec03ba335b81bf4ebdf7b29ec27d15&fs=m%3A90+t%3A2&fields=f12%2Cf14%2Cf2%2Cf3%2Cf62%2Cf184%2Cf66%2Cf69%2Cf72%2Cf75%2Cf78%2Cf81%2Cf84%2Cf87%2Cf204%2Cf205%2Cf124%2Cf1%2Cf13"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
}
try:
response = requests.get(url, headers=headers)
# 去除 JSONP 格式中的回调函数部分
response_text = response.text[response.text.find('(') + 1: response.text.rfind(')')]
data = json.loads(response_text)
if 'data' not in data or 'diff' not in data['data']:
raise Exception("未能获取到数据")
items = data['data']['diff']
parsed_data = []
for item in items:
# 获取增仓数据
increase_position = item['f72']
# 假设你想加入的另一个数据项,比如资金流入(这里只做示范)
fund_inflow = item['f62'] # 可以根据实际需要更改为其他数据字段
parsed_data.append({
'板块': item['f14'], # 板块名称
'增仓': increase_position, # 增仓值
'资金流入': fund_inflow # 假设另一个对比数据
})
# 将数据转为DataFrame
df = pd.DataFrame(parsed_data)
# 按增仓排序
df_sorted = df.sort_values(by='增仓', ascending=False)
return df_sorted
except Exception as e:
print(f"获取数据时发生错误: {str(e)}")
return None
def plot_combined_chart(data):
"""绘制增仓排名的柱状图与折线图结合"""
# 获取前10个板块及其增仓数据
sectors = data['板块'].tolist()[:10]
increase_positions = data['增仓'].tolist()[:10]
fund_inflows = data['资金流入'].tolist()[:10] # 资金流入作为对比数据
# 创建一个图形
fig, ax1 = plt.subplots(figsize=(12, 7))
# 绘制增仓值的柱状图
ax1.bar(sectors, increase_positions, color='b', alpha=0.6, label='增仓值', width=0.4)
# 设置柱状图的Y轴标签
ax1.set_xlabel('板块', fontsize=14)
ax1.set_ylabel('增仓值', fontsize=14, color='b')
ax1.tick_params(axis='y', labelcolor='b')
# 创建第二个Y轴来绘制折线图
ax2 = ax1.twinx()
ax2.plot(sectors, increase_positions, color='r', marker='o', label='增仓趋势', linewidth=2)
# 添加资金流入的折线
ax2.plot(sectors, fund_inflows, color='g', marker='^', label='资金流入', linewidth=2)
# 设置折线图的Y轴标签
ax2.set_ylabel('趋势值', fontsize=14, color='r')
ax2.tick_params(axis='y', labelcolor='r')
# 设置标题
plt.title('增仓与资金流入对比 - 柱状图与折线图结合', fontsize=16)
# 显示图形
plt.xticks(rotation=45) # 使X轴标签旋转防止重叠
fig.tight_layout() # 自动调整布局,防止标签被遮挡
# 添加图例
ax1.legend(loc='upper left')
ax2.legend(loc='upper right')
plt.show()
def main():
# 获取数据并计算
print("正在获取资金流向数据...")
data = get_fund_flow_data()
if data is not None:
print("正在生成增仓与资金流入对比的柱状图与折线图结合...")
plot_combined_chart(data)
else:
print("获取数据失败,请检查网络连接或接口可用性。")
if __name__ == "__main__":
main()