这2天有同学在 miniqmt如何读取通达信自选股涨跌幅 通达信自选股文章留言 让写一写 同花顺自选股。
那这里写一写方法, 由于国庆节假日 miniqmt不稳定,那我就演示下获取 通达信自选股代码就好了, 至于自选股涨跌幅 你完全可以利用 miniqmt的get_full_tick 获取涨跌幅就好了,细节你可以看我写的通达信自选股涨跌幅获取的方式。
获取同花顺自选股 我自己了解到的有2种方式, 这里都写一写。
1、读取同花顺的 自选股文件 , 文件大概位于 同花顺安装目录 下 个人目录的 SelfStockInfo.json文件下。
比如我的文件路径是 D:\lwj\ths\同花顺\mx_xxxx\SelfStockInfo.json
其实打开SelfStockInfo.json, 你会发现里面是一个json, 包括 code、同花顺的市场定义、自选股添加时的价格、 自选股添加的时间。 既然知道结构了,那简单做一下json解析就好了。 这里提供一个例子,仅供参考
import json
import pandas as pd
from datetime import datetime
def read_ths_self_stock(file_path):
"""
读取同花顺自选股JSON文件并解析股票代码
:param file_path: SelfStockInfo.json文件的完整路径
:return: 包含股票代码和基本信息的DataFrame
"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
data = json.load(file)
print(f"成功读取自选股文件,共找到 {len(data)} 只股票")
# 解析每只股票的信息
stock_list = []
for stock in data:
stock_info = {
'股票代码': stock['C'],
'市场代码': stock['M'],
'价格': stock.get('P', stock.get('p', 'N/A')),
}
stock_list.append(stock_info)
return pd.DataFrame(stock_list)
except FileNotFoundError:
print(f"错误:文件 {file_path} 未找到")
return pd.DataFrame()
except json.JSONDecodeError as e:
print(f"错误:JSON文件解析失败 - {e}")
return pd.DataFrame()
except Exception as e:
print(f"错误:读取文件时发生未知错误 - {e}")
return pd.DataFrame()
def display_stock_info(df):
"""
美化显示股票信息
:param df: 股票数据框
"""
if df.empty:
print("没有可显示的数据")
return
print("\n" + "=" * 60)
print("同花顺自选股列表")
print("=" * 60)
# 按股票代码排序
df_sorted = df.sort_values('股票代码')
print(f"{'股票代码':<10} ")
print("-" * 60)
for idx, row in df_sorted.iterrows():
print(f"{row['股票代码']:<10}")
# 主程序
if __name__ == "__main__":
# 您的文件路径
file_path = r"D:\lwj\ths\同花顺\mx_431554917\SelfStockInfo.json"
# 读取自选股文件
print("正在读取自选股文件...")
stock_df = read_ths_self_stock(file_path)
if not stock_df.empty:
# 显示自选股信息
display_stock_info(stock_df)
else:
print("未能读取到自选股数据")2、第二种方式我们通过网络请求获取,这里需要用到同花顺的cookie。 至于同花顺的cookie怎么获取, 打开同花顺网页,登录下账户,network里找一找就看到了。 这里提供一个例子,仅供参考
import requests
import re
import json
import time
import pandas as pd
class TonghuashunAPI:
def __init__(self, cookie):
"""
初始化同花顺API接口
:param cookie: 同花顺登录后的Cookie字符串
"""
self.cookie = cookie
self.headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36',
'Referer': 'http://stock.10jqka.com.cn/my/zixuan.shtml',
'Cookie': cookie,
'DNT': '1'
}
def get_self_stock(self):
"""
获取同花顺自选股列表(带市场代码)
返回格式示例:selfStock({"errorCode":0,"errorMsg":"","result":[{"code":"600519","marketid":"17"}],"isT":true})
"""
try:
# 生成防缓存时间戳(精确到毫秒)
timestamp = int(time.time() * 1000)
url = f'https://t.10jqka.com.cn/newcircle/group/getSelfStockWithMarket/?callback=selfStock&_={timestamp}'
response = requests.get(url, headers=self.headers, timeout=10)
response.raise_for_status() # 检查HTTP错误
return response.text
except Exception as e:
print(f"请求失败: {e}")
return None
def parse_jsonp(self, jsonp_str, callback_name='selfStock'):
"""
解析JSONP响应为Python字典
:param jsonp_str: JSONP格式的字符串
:param callback_name: 回调函数名
"""
try:
# 方法1:使用正则提取JSON部分
pattern = re.compile(fr'{re.escape(callback_name)}\((.*)\);?', re.DOTALL)
match = pattern.search(jsonp_str)
if match:
json_str = match.group(1)
return json.loads(json_str)
else:
# 方法2:直接去除回调函数名和括号
stripped = jsonp_str.replace(f"{callback_name}(", "").replace(");", "")
return json.loads(stripped)
except Exception as e:
print(f"JSONP解析失败: {e}")
return None
def convert_to_dataframe(self, data):
"""
将解析后的数据转换为DataFrame
"""
if data and data.get('errorCode') == 0:
return pd.DataFrame(data['result'])
return pd.DataFrame()
# 使用示例
if __name__ == "__main__":
# 替换为您的实际Cookie(通过浏览器开发者工具获取)
USER_COOKIE = "xxx=xxxx"
# 创建API实例
ths = TonghuashunAPI(cookie=USER_COOKIE)
# 获取自选股数据
jsonp_response = ths.get_self_stock()
if jsonp_response:
# 解析JSONP数据
parsed_data = ths.parse_jsonp(jsonp_response)
# 转换为DataFrame
df_stocks = ths.convert_to_dataframe(parsed_data)
if not df_stocks.empty:
print("获取自选股成功!")
print(df_stocks)
def add_market_suffix(row):
code = row['code']
market = row['marketid']
if market == '17': # 沪市
return f"{code}.SH"
elif market == '33': # 深市
return f"{code}.SZ"
elif market == '87': # 北交所
return f"{code}.BJ"
return code
df_stocks['full_code'] = df_stocks.apply(add_market_suffix, axis=1)
print("\n带交易所后缀的股票代码:")
print(df_stocks[['code', 'marketid', 'full_code']])
else:
print("未获取到自选股数据")
else:
print("请求失败,请检查网络或Cookie有效性")备注:这2个例子,我在本地都跑过的, 你修改对 同花顺的路径 ,或 同花顺的cookie都能获取得到。 不要问我更基础的细节了。