{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# 股票管理" ] }, { "cell_type": "markdown", "metadata": { "toc-hr-collapsed": true, "toc-nb-collapsed": true }, "source": [ "## 股票信息导入" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import baostock as bs\n", "import pandas as pd\n", "\n", "#### 登陆系统 ####\n", "lg = bs.login()\n", "# 显示登陆返回信息\n", "print('login respond error_code:'+lg.error_code)\n", "print('login respond error_msg:'+lg.error_msg)\n", "\n", "#### 获取证券信息 ####\n", "rs = bs.query_all_stock(day=\"2020-10-20\")\n", "print('query_all_stock respond error_code:'+rs.error_code)\n", "print('query_all_stock respond error_msg:'+rs.error_msg)\n", "\n", "#### 打印结果集 ####\n", "data_list = []\n", "while (rs.error_code == '0') & rs.next():\n", " # 获取一条记录,将记录合并在一起\n", " data_list.append(rs.get_row_data())\n", "#results = pd.DataFrame(data_list, columns=rs.fields)\n", "\n", "#### 结果集输出到csv文件 #### \n", "#result.to_csv(\"all_stock.csv\", encoding=\"utf-8\", index=False)\n", "for result in data_list:\n", " print(result)\n", "\n", "#### 登出系统 ####\n", "bs.logout()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import baostock as bs\n", "import pandas as pd\n", "import pymysql\n", "\n", "# 登陆系统\n", "lg = bs.login()\n", "# 显示登陆返回信息\n", "print('login respond error_code:'+lg.error_code)\n", "print('login respond error_msg:'+lg.error_msg)\n", "\n", "# 获取证券基本资料\n", "rs = bs.query_stock_basic(code=\"\")\n", "# rs = bs.query_stock_basic(code_name=\"浦发银行\") # 支持模糊查询\n", "print('query_stock_basic respond error_code:'+rs.error_code)\n", "print('query_stock_basic respond error_msg:'+rs.error_msg)\n", "\n", "# 打印结果集\n", "data_list = []\n", "while (rs.error_code == '0') & rs.next():\n", " # 获取一条记录,将记录合并在一起\n", " data_list.append(rs.get_row_data())\n", "#result = pd.DataFrame(data_list, columns=rs.fields)\n", "# 结果集输出到csv文件\n", "#result.to_csv(\"D:/stock_basic.csv\", encoding=\"gbk\", index=False)\n", "\n", "db = pymysql.connect(\"localhost\",\"root\",\"songyi\",\"stock\" )\n", "cursor = db.cursor()\n", "\n", "sql = \"insert into stock_info (code,name,ipoDate,outDate,type,status) values(%s,%s,%s,%s,%s,%s)\"\n", "try:\n", " cursor.executemany(sql,tuple(data_list))\n", " db.commit()\n", " print(\"ok!\")\n", "except:\n", " # 如果发生错误则回滚\n", " print(\"error!\")\n", " db.rollback() \n", "db.close()\n", "# 登出系统\n", "bs.logout()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 每日持有标的信息导入" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "tags": [] }, "outputs": [], "source": [ "import csv\n", "import pymysql\n", "\n", "def read_data(filename):\n", " detail = {}\n", " with open(filename) as f:\n", " reader = csv.reader(f)\n", " #header_row =next(reader)\n", " for row in reader:\n", " detail.setdefault(row[0],[])\n", " detail[row[0]].append(row[1])\n", " return detail\n", "m_xx = []\n", "m_stock = {}\n", "db = pymysql.connect(\"localhost\",\"root\",\"songyi\",\"stock\" )\n", "cursor = db.cursor()\n", "sql = 'select code,name from stock_info where type=\"1\"'\n", "cursor.execute(sql)\n", "results = cursor.fetchall()\n", "for result in results:\n", " m_stock[result[0]] = result[1]\n", "#print(m_stock)\n", "filename = '每日标的信息.csv'\n", "detail = read_data(filename)\n", "for k,v in detail.items():\n", " m_rq = '2020-' + k[0:2] + '-' + k[2:]\n", " i = 1\n", " for m_dm in v:\n", " if m_dm[0:1] == '6':\n", " m_dm = 'sh.' + m_dm\n", " else:\n", " m_dm = 'sz.' + m_dm\n", " print('\\t'+m_dm + '\\t'+m_stock[m_dm])\n", " m_xx.append((m_rq,m_dm,i))\n", " i += 1\n", "choice = input('以上为本日数据,是否导入?(y/n)')\n", "if choice.upper() == \"Y\":\n", " sql = \"insert into daily_item (rq,code,ord) values(%s,%s,%s)\"\n", " try:\n", " cursor.executemany(sql,m_xx)\n", " db.commit()\n", " print(\"ok!\")\n", " except:\n", " # 如果发生错误则回滚\n", " print(\"error!\")\n", " db.rollback() \n", "db.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 每日调仓信息导入" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import csv\n", "import pymysql\n", "\n", "def read_data(filename):\n", " detail = {}\n", " \n", " with open(filename) as f:\n", " reader = csv.reader(f)\n", "# header_row =next(reader)\n", " for row in reader:\n", " detail1 = {}\n", " detail.setdefault(row[3],[])\n", " detail1 = {'dm':row[0],'zj':row[1],'ly':row[2],'cb':row[4]}\n", " detail[row[3]].append(detail1)\n", " return detail\n", "m_xx = []\n", "m_add = []\n", "m_sub = []\n", "db = pymysql.connect(\"localhost\",\"root\",\"songyi\",\"stock\" )\n", "cursor = db.cursor()\n", "filename = '调仓明细.csv'\n", "detail = read_data(filename)\n", "#print(detail)\n", "for rq in sorted(detail.keys()):\n", " m_rq = '2020-' + rq[0:2] + '-' + rq[2:]\n", " for xx_move in detail[rq]:\n", " m_dm = xx_move['dm']\n", " if m_dm[0:1] == '6':\n", " m_dm = 'sh.' + m_dm\n", " else:\n", " m_dm = 'sz.' + m_dm\n", " m_xx.append((m_rq,m_dm,int(xx_move['zj']),xx_move['ly']))\n", " if xx_move['zj'] == '1':\n", " m_add.append((m_dm,xx_move['ly'],float(xx_move['cb'])))\n", " else:\n", " m_sub.append((m_dm))\n", "#print(m_xx)\n", "sql = \"insert into change_item (rq,code,pos,reason) values(%s,%s,%s,%s)\"\n", "try:\n", " cursor.executemany(sql,m_xx)\n", " if len(m_add) > 0:\n", " sql_add = \"insert into stock_item (code,reason,cost) values(%s,%s,%s)\"\n", " cursor.executemany(sql_add,m_add)\n", " if len(m_sub) > 0:\n", " sql_sub = \"update stock_item set status=0 where code=%s\"\n", " cursor.executemany(sql_sub,m_sub) \n", " db.commit()\n", " print(\"导入成功!\")\n", "except:\n", " # 如果发生错误则回滚\n", " print(\"error!\")\n", " db.rollback() \n", "\n", "db.close()" ] }, { "cell_type": "markdown", "metadata": { "toc-hr-collapsed": true, "toc-nb-collapsed": true }, "source": [ "## 持仓股票信息导入" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pymysql\n", "db = pymysql.connect(\"localhost\",\"root\",\"songyi\",\"stock\" )\n", "cursor = db.cursor()\n", "sql = 'SELECT a.unit,a.CODE,b.cost FROM daily_item AS a,daily_cost as b WHERE a.rq=(select max(rq) FROM daily_item) AND a.code=b.code'\n", "cursor.execute(sql)\n", "results = cursor.fetchall()\n", "sql = \"insert into stock_item(item,code,cost) values(%s,%s,%s)\"\n", "try:\n", " cursor.executemany(sql,list(results))\n", " #db.commit()\n", " print(\"ok!\")\n", "except:\n", " # 如果发生错误则回滚\n", " print(\"error!\")\n", " db.rollback() \n", "sql = 'SELECT a.reason,a.code from change_item AS a WHERE a.pos=1'\n", "cursor.execute(sql)\n", "results = cursor.fetchall()\n", "sql = \"update stock_item set reason=%s where code=%s \"\n", "try:\n", " cursor.executemany(sql,list(results))\n", " #db.commit()\n", " print(\"ok!\")\n", "except:\n", " # 如果发生错误则回滚\n", " print(\"error!\")\n", " db.rollback() \n", "db.close()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 外汇实时数据采集" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import requests\n", "import time\n", "from bs4 import BeautifulSoup\n", "import pymongo\n", "import re\n", "\n", "#pattern = re.compile('(?<=\\\").*(?=\\\")')\n", "pattern = re.compile(r'\\\"(.*)\\\"')\n", "#myclient = pymongo.MongoClient('mongodb://localhost:27017/')\n", "#mydb = myclient[\"gaokao\"]\n", "#mycol = mydb[\"news\"]\n", "url = 'http://hq.sinajs.cn/list=USDCAD'\n", "strhtml = requests.get(url)\n", "#strhtml.encoding = 'utf8'\n", "soup = BeautifulSoup(strhtml.text,'lxml')\n", "data = strhtml.text\n", "#data1 = data.split(\"\\r\")\n", "#data = soup.select('schoolList')\n", "#for item1 in data:\n", "# print(item1.get_text())\n", "if pattern.findall(data):\n", " for data1 in pattern.findall(data):\n", " data2 = data1.split(',')\n", " print(data2)\n", " print('当前买入价:',data2[1])\n", " print('当前卖出价:',data2[2])\n", " print('昨收价:',data2[3])\n", " print('今开价:',data2[5])\n", " print('最高价:',data2[6])\n", " print('最低价:',data2[7])\n", " print(float(data2[7]))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from email.mime.text import MIMEText\n", "from email.header import Header\n", "import smtplib\n", "import requests\n", "import time\n", "import re\n", "\n", "pattern = re.compile(r'\\\"(.*)\\\"')\n", "url = 'http://hq.sinajs.cn/list=USDCAD'\n", "strhtml = requests.get(url)\n", "data = strhtml.text\n", "if pattern.findall(data):\n", " for data1 in pattern.findall(data):\n", " data2 = data1.split(',')\n", "#print(data2)\n", "with open('price.txt','r') as fl:\n", " for line in fi:\n", " p_high = line.split(',')[0]\n", " p_low = line.split(',')[1]\n", "\n", "message ='当前美元加元买入价:{},卖出价:{}'.format(data2[1],data2[2])\n", "msg = MIMEText(message,'plain','utf-8')\n", "msg['Subject'] = Header(\"外汇价格已经到达预期价位!\",'utf-8')\n", "msg['From'] = Header('512song@sina.com')\n", "msg['To'] = Header('491525765@qq.com','utf-8')\n", "\n", "from_addr = '512song@sina.com' #发件邮箱\n", "password = '409fe5d8471da663' #邮箱密码\n", "to_addr = 'songyi@yeah.net' #收件邮箱\n", "smtp_server = 'smtp.sina.com' #SMTP服务器,以新浪为例\n", "try:\n", " server = smtplib.SMTP(smtp_server,25) #第二个参数为默认端口为25,有些邮件有特殊端口\n", " print('开始登录')\n", " server.set_debuglevel(1) \n", " server.login(from_addr,password) #登录邮箱\n", " print('登录成功')\n", " print(\"邮件开始发送\")\n", " server.sendmail(from_addr,to_addr,msg.as_string()) #将msg转化成string发出\n", " server.quit()\n", " print(\"邮件发送成功\")\n", "except smtplib.SMTPException as e:\n", " print(\"邮件发送失败\",e)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from email.mime.text import MIMEText\n", "from email.header import Header\n", "import smtplib\n", "import requests\n", "import time\n", "import re\n", "\n", "pattern = re.compile(r'\\\"(.*)\\\"')\n", "url = 'http://hq.sinajs.cn/list=USDCAD'\n", "strhtml = requests.get(url)\n", "data = strhtml.text\n", "if pattern.findall(data):\n", " for data1 in pattern.findall(data):\n", " data2 = data1.split(',')\n", "print(data2)\n", "\n", "message ='当前美元加元最高价:{},最低价:{}'.formtat()\n", "msg = MIMEText(message,'plain','utf-8')\n", "\n", "msg['Subject'] = Header(\"测试smtp邮件\",'utf-8')\n", "msg['From'] = Header('512song@sina.com')\n", "msg['To'] = Header('491525765@qq.com','utf-8')\n", "\n", "from_addr = '512song@sina.com' #发件邮箱\n", "password = '409fe5d8471da663' #邮箱密码\n", "to_addr = '491525765@qq.com' #收件邮箱\n", "\n", "smtp_server = 'smtp.sina.com' #SMTP服务器,以新浪为例\n", "try:\n", " server = smtplib.SMTP(smtp_server,25) #第二个参数为默认端口为25,有些邮件有特殊端口\n", " print('开始登录')\n", " server.set_debuglevel(1) \n", " server.login(from_addr,password) #登录邮箱\n", " print('登录成功')\n", " print(\"邮件开始发送\")\n", " server.sendmail(from_addr,to_addr,msg.as_string()) #将msg转化成string发出\n", " server.quit()\n", " print(\"邮件发送成功\")\n", "except smtplib.SMTPException as e:\n", " print(\"邮件发送失败\",e)\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 财务报表获取" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import akshare as ak\n", "\n", "stock_financial_debt_ths_df = ak.stock_financial_debt_ths(symbol=\"000338\", indicator=\"按年度\")\n", "print(stock_financial_debt_ths_df)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import akshare as ak\n", "\n", "stock_financial_report_sina_df = ak.stock_financial_report_sina(stock=\"000338\", symbol=\"资产负债表\")\n", "print(stock_financial_report_sina_df)" ] }, { "cell_type": "code", "execution_count": 62, "metadata": { "execution": { "iopub.execute_input": "2024-06-19T13:06:55.726456Z", "iopub.status.busy": "2024-06-19T13:06:55.725703Z", "iopub.status.idle": "2024-06-19T13:06:56.342226Z", "shell.execute_reply": "2024-06-19T13:06:56.341651Z", "shell.execute_reply.started": "2024-06-19T13:06:55.726387Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "报告期\n", "净利润\n", "净利润同比增长率\n", "扣非净利润\n", "扣非净利润同比增长率\n", "营业总收入\n", "营业总收入同比增长率\n", "基本每股收益\n", "每股净资产\n", "每股资本公积金\n", "每股未分配利润\n", "每股经营现金流\n", "销售净利率\n", "销售毛利率\n", "净资产收益率\n", "净资产收益率-摊薄\n", "营业周期\n", "存货周转率\n", "存货周转天数\n", "应收账款周转天数\n", "流动比率\n", "速动比率\n", "保守速动比率\n", "产权比率\n", "资产负债率\n" ] } ], "source": [ "import akshare as ak\n", "\n", "stock_financial_abstract_ths_df = ak.stock_financial_abstract_ths(symbol=\"000338\", indicator=\"按报告期\")\n", "data1 = stock_financial_abstract_ths_df\n", "a1 = data1.loc[ data1.报告期 =='2023-12-31']\n", "for value in a1:\n", " print(value)" ] }, { "cell_type": "code", "execution_count": 77, "metadata": { "execution": { "iopub.execute_input": "2024-06-19T14:11:40.411486Z", "iopub.status.busy": "2024-06-19T14:11:40.410724Z", "iopub.status.idle": "2024-06-19T14:11:42.179997Z", "shell.execute_reply": "2024-06-19T14:11:42.179418Z", "shell.execute_reply.started": "2024-06-19T14:11:40.411414Z" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 报告期 报表核心指标 *所有者权益(或股东权益)合计 *资产合计 *负债合计 *归属于母公司所有者权益合计 \\\n", "0 2024-03-31 32.83亿 69.36亿 36.53亿 29.06亿 \n", "1 2023-12-31 32.53亿 69.56亿 37.03亿 28.84亿 \n", "2 2023-09-30 31.75亿 66.75亿 35.00亿 28.18亿 \n", "3 2023-06-30 31.88亿 71.97亿 40.08亿 27.95亿 \n", "4 2023-03-31 31.30亿 70.27亿 38.97亿 27.52亿 \n", ".. ... ... ... ... ... ... \n", "99 1996-12-31 1.80亿 3.06亿 1.26亿 1.65亿 \n", "100 1996-06-30 1.56亿 2.60亿 1.04亿 1.41亿 \n", "101 1995-12-31 8217.50万 1.66亿 8384.17万 6716.24万 \n", "102 1994-12-31 6585.60万 1.17亿 5120.34万 6467.31万 \n", "103 1993-12-31 2460.94万 3472.74万 1011.79万 2460.94万 \n", "\n", " 报表全部指标 流动资产 货币资金 交易性金融资产 ... 所有者权益(或股东权益) 实收资本(或股本) 资本公积 \\\n", "0 6.44亿 False ... 8.80亿 9.54亿 \n", "1 7.67亿 False ... 8.80亿 9.54亿 \n", "2 6.47亿 False ... 8.80亿 9.53亿 \n", "3 10.33亿 False ... 8.80亿 9.53亿 \n", "4 7.29亿 False ... 8.80亿 9.53亿 \n", ".. ... ... ... ... ... ... ... ... \n", "99 3507.95万 700.00万 ... 7865.00万 6117.91万 \n", "100 False False ... 6050.00万 6110.36万 \n", "101 1591.58万 False ... 5000.00万 1287.21万 \n", "102 2316.67万 False ... 5000.00万 1287.21万 \n", "103 296.69万 False ... 1919.72万 False \n", "\n", " 其他综合收益 盈余公积 未分配利润 归属于母公司所有者权益合计 少数股东权益 所有者权益(或股东权益)合计 \\\n", "0 5833.01万 1.92亿 8.07亿 29.06亿 3.77亿 32.83亿 \n", "1 5825.59万 1.92亿 7.87亿 28.84亿 3.69亿 32.53亿 \n", "2 3869.46万 1.64亿 7.65亿 28.18亿 3.58亿 31.75亿 \n", "3 3873.28万 1.64亿 7.44亿 27.95亿 3.93亿 31.88亿 \n", "4 3871.64万 1.64亿 7.02亿 27.52亿 3.78亿 31.30亿 \n", ".. ... ... ... ... ... ... \n", "99 False 807.23万 1678.16万 1.65亿 1554.03万 1.80亿 \n", "100 False 429.03万 1500.51万 1.41亿 1470.25万 1.56亿 \n", "101 False 429.03万 False 6716.24万 1501.27万 8217.50万 \n", "102 False 152.04万 False 6467.31万 118.29万 6585.60万 \n", "103 False 3000.00 540.93万 2460.94万 False 2460.94万 \n", "\n", " 负债和所有者权益(或股东权益)合计 \n", "0 69.36亿 \n", "1 69.56亿 \n", "2 66.75亿 \n", "3 71.97亿 \n", "4 70.27亿 \n", ".. ... \n", "99 3.06亿 \n", "100 2.60亿 \n", "101 1.66亿 \n", "102 1.17亿 \n", "103 3472.74万 \n", "\n", "[104 rows x 76 columns]\n" ] } ], "source": [ "import akshare as ak\n", "\n", "stock_financial_debt_ths_df = ak.stock_financial_debt_ths(symbol=\"000407\", indicator=\"按报告期\")\n", "print(stock_financial_debt_ths_df)" ] }, { "cell_type": "code", "execution_count": 63, "metadata": { "execution": { "iopub.execute_input": "2024-06-19T13:07:12.047237Z", "iopub.status.busy": "2024-06-19T13:07:12.046427Z", "iopub.status.idle": "2024-06-19T13:07:13.315936Z", "shell.execute_reply": "2024-06-19T13:07:13.315381Z", "shell.execute_reply.started": "2024-06-19T13:07:12.047146Z" }, "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " 报告期 报表核心指标 *现金及现金等价物净增加额 *经营活动产生的现金流量净额 *投资活动产生的现金流量净额 \\\n", "0 2024-03-31 -60.70亿 29.83亿 -150.61亿 \n", "1 2023-12-31 39.41亿 174.06亿 -209.01亿 \n", "2 2023-09-30 94.28亿 92.62亿 -43.20亿 \n", "3 2023-06-30 78.75亿 64.26亿 -15.06亿 \n", "4 2023-03-31 26.73亿 23.26亿 -50.84亿 \n", ".. ... ... ... ... ... \n", "89 2000-12-31 3.18亿 -7071.17万 -3.18亿 \n", "90 2000-06-30 1.73亿 -1.90亿 -2.30亿 \n", "91 1999-12-31 4665.82万 -5.24亿 -2.35亿 \n", "92 1998-12-31 -1388.42万 1.58亿 -1.44亿 \n", "93 1998-06-30 -1.28亿 2923.72万 -6786.66万 \n", "\n", " *筹资活动产生的现金流量净额 *期末现金及现金等价物余额 报表全部指标 一、经营活动产生的现金流量 销售商品、提供劳务收到的现金 ... \\\n", "0 59.59亿 449.44亿 335.98亿 ... \n", "1 73.72亿 510.13亿 1282.64亿 ... \n", "2 42.17亿 565.00亿 936.39亿 ... \n", "3 27.18亿 549.46亿 648.24亿 ... \n", "4 55.17亿 497.44亿 328.30亿 ... \n", ".. ... ... ... ... ... ... \n", "89 7.05亿 False 59.76亿 ... \n", "90 5.90亿 False 18.19亿 ... \n", "91 8.07亿 False 23.89亿 ... \n", "92 -2747.59万 False 26.06亿 ... \n", "93 -8964.03万 False 6.94亿 ... \n", "\n", " 经营性应付项目的增加 其他 间接法-经营活动产生的现金流量净额 2、不涉及现金收支的重大投资和筹资活动: \\\n", "0 False False False \n", "1 -11.97亿 False 174.06亿 \n", "2 False False False \n", "3 -47.23亿 False 64.26亿 \n", "4 False False False \n", ".. ... ... ... ... \n", "89 19.71亿 1179.35万 -7071.17万 \n", "90 2.16亿 False -1.90亿 \n", "91 -2849.51万 False -5.24亿 \n", "92 4.49亿 9.16万 1.58亿 \n", "93 1.50亿 3133.53万 2923.72万 \n", "\n", " 3、现金及现金等价物净变动情况: 现金的期末余额 减:现金的期初余额 加:现金等价物的期末余额 减:现金等价物的期初余额 \\\n", "0 False False False False \n", "1 203.40万 160.40万 510.11亿 470.70亿 \n", "2 False False False False \n", "3 119.00万 160.40万 549.45亿 470.70亿 \n", "4 False False False False \n", ".. ... ... ... ... ... \n", "89 8.73亿 5.62亿 736.77万 False \n", "90 7.41亿 5.68亿 False False \n", "91 5.68亿 5.21亿 False False \n", "92 5.21亿 5.35亿 False False \n", "93 4.07亿 5.35亿 False False \n", "\n", " 间接法-现金及现金等价物净增加额 \n", "0 False \n", "1 39.41亿 \n", "2 False \n", "3 78.75亿 \n", "4 False \n", ".. ... \n", "89 3.18亿 \n", "90 1.73亿 \n", "91 4665.82万 \n", "92 -1388.42万 \n", "93 -1.28亿 \n", "\n", "[94 rows x 75 columns]\n" ] } ], "source": [ "import akshare as ak\n", "\n", "stock_financial_cash_ths_df = ak.stock_financial_cash_ths(symbol=\"000063\", indicator=\"按报告期\")\n", "print(stock_financial_cash_ths_df)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 财务报表获取(资产负债)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import openpyxl\n", "import json\n", "import akshare as ak\n", "\n", "fi_xls = 'data/山东辖区境内上市公司名单.xlsx'\n", "dict1 = {}\n", "list1 = ['2021-12-31','2022-12-31','2023-12-31','2024-03-31']\n", "\n", "wb = openpyxl.load_workbook(fi_xls)\n", "sheet = wb.active\n", "list2 = ['*资产合计','货币资金','交易性金融资产','*负债合计']\n", "for n in range(2,sheet.max_row+1): \n", " code = str(sheet.cell(n,2).value).rjust(6,\"0\")\n", " dict1.setdefault(code,{})\n", " name = sheet.cell(n,3).value\n", " address = sheet.cell(n,4).value\n", " phone = sheet.cell(n,5).value\n", " dict1[code]['name'] = name\n", " dict1[code]['address'] = address\n", " dict1[code]['phone'] = phone\n", "for k, v in dict1.items():\n", " data = ak.stock_financial_debt_ths(symbol=k, indicator=\"按报告期\")\n", " for item in list1:\n", " data1 = data.loc[ data.报告期 ==item]\n", " if data1.shape[0] >0:\n", " dict1[k].setdefault(item,{})\n", " for item1 in list2:\n", " if item1 in data1.keys():\n", " for value in data1[item1]:\n", " dict1[k][item][item1] = value\n", " else:\n", " dict1[k][item][item1] = 'null'\n", " \n", "with open('data/山东辖区境内上市公司相关财务数据.json','w') as fl2:\n", " json.dump(dict1,fl2,ensure_ascii=False) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 财务报表获取(利润)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "filename = 'data/山东辖区境内上市公司相关财务数据.json'\n", "with open(filename,'r') as fl:\n", " dict1 = json.load(fl)\n", "list1 = ['2021-12-31','2022-12-31','2023-12-31','2024-03-31']\n", "list2 = ['营业总收入','净利润']\n", "for k, v in dict1.items():\n", " data = ak.stock_financial_abstract_ths(symbol=k, indicator=\"按报告期\")\n", " for item in list1:\n", " data1 = data.loc[ data.报告期 ==item]\n", " if data1.shape[0] >0:\n", " dict1[k].setdefault(item,{})\n", " for item1 in list2:\n", " if item1 in data1.keys():\n", " for value in data1[item1]:\n", " dict1[k][item][item1] = value\n", " else:\n", " dict1[k][item][item1] = 'null'\n", " \n", "with open('data/山东辖区境内上市公司相关财务数据1.json','w') as fl2:\n", " json.dump(dict1,fl2,ensure_ascii=False) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 财务报表获取(现金流量)" ] }, { "cell_type": "code", "execution_count": 64, "metadata": { "execution": { "iopub.execute_input": "2024-06-19T13:07:43.950488Z", "iopub.status.busy": "2024-06-19T13:07:43.949732Z", "iopub.status.idle": "2024-06-19T13:11:06.767989Z", "shell.execute_reply": "2024-06-19T13:11:06.767426Z", "shell.execute_reply.started": "2024-06-19T13:07:43.950420Z" } }, "outputs": [], "source": [ "filename = 'data/山东辖区境内上市公司相关财务数据1.json'\n", "with open(filename,'r') as fl:\n", " dict1 = json.load(fl)\n", "list1 = ['2021-12-31','2022-12-31','2023-12-31','2024-03-31']\n", "list2 = ['*经营活动产生的现金流量净额']\n", "for k, v in dict1.items():\n", " data = ak.stock_financial_cash_ths(symbol=k, indicator=\"按报告期\")\n", " for item in list1:\n", " data1 = data.loc[ data.报告期 ==item]\n", " if data1.shape[0] >0:\n", " dict1[k].setdefault(item,{})\n", " for item1 in list2:\n", " if item1 in data1.keys():\n", " for value in data1[item1]:\n", " dict1[k][item][item1] = value\n", " else:\n", " dict1[k][item][item1] = 'null'\n", " \n", "with open('data/山东辖区境内上市公司相关财务数据1.json','w') as fl2:\n", " json.dump(dict1,fl2,ensure_ascii=False) " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### 导出数据至excel" ] }, { "cell_type": "code", "execution_count": 75, "metadata": { "execution": { "iopub.execute_input": "2024-06-19T14:02:35.424509Z", "iopub.status.busy": "2024-06-19T14:02:35.423890Z", "iopub.status.idle": "2024-06-19T14:02:35.770723Z", "shell.execute_reply": "2024-06-19T14:02:35.770187Z", "shell.execute_reply.started": "2024-06-19T14:02:35.424450Z" } }, "outputs": [], "source": [ "filename = 'data/山东辖区境内上市公司相关财务数据1.json'\n", "with open(filename,'r') as fl:\n", " dict1 = json.load(fl)\n", "filename = 'data/山东辖区境内上市公司相关财务数据1.xlsx'\n", "wb = openpyxl.Workbook()\n", "sheet = wb.active\n", "list1 = ['2021-12-31','2022-12-31','2023-12-31','2024-03-31']\n", "i = 0\n", "for k, v in dict1.items():\n", " \n", " sheet.merge_cells(f'A{i*4+1}:A{i*4+4}')\n", " sheet.merge_cells(f'B{i*4+1}:B{i*4+4}')\n", " sheet.merge_cells(f'C{i*4+1}:C{i*4+4}')\n", " sheet[f'A{i*4+1}'] = i+1\n", " sheet[f'B{i*4+1}'] = k\n", " sheet[f'C{i*4+1}'] = v['name']\n", " n = 1\n", " for item in list1:\n", " \n", " if item in v.keys():\n", " sheet[f'D{i*4+n}'] = item\n", " sheet[f'E{i*4+n}'] = v[item]['*资产合计']\n", " sheet[f'F{i*4+n}'] = v[item]['货币资金']\n", " sheet[f'G{i*4+n}'] = v[item]['交易性金融资产']\n", " sheet[f'H{i*4+n}'] = v[item]['*负债合计']\n", " sheet[f'I{i*4+n}'] = v[item]['营业总收入']\n", " sheet[f'J{i*4+n}'] = v[item]['净利润']\n", " sheet[f'K{i*4+n}'] = v[item]['*经营活动产生的现金流量净额']\n", " else:\n", " sheet[f'D{i*4+n}'] = item\n", " sheet[f'E{i*4+n}'] = ''\n", " sheet[f'F{i*4+n}'] = ''\n", " sheet[f'G{i*4+n}'] = ''\n", " sheet[f'H{i*4+n}'] = ''\n", " sheet[f'I{i*4+n}'] = ''\n", " sheet[f'J{i*4+n}'] = ''\n", " sheet[f'K{i*4+n}'] = ''\n", " n+=1\n", " i+=1\n", "wb.save(filename) \n", " " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": { "toc-hr-collapsed": true, "toc-nb-collapsed": true }, "source": [ "# pygal图表" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import pygal\n", "bar_chart = pygal.Bar(height=300)\n", "bar_chart.add('Fibonacci', [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55])\n", "bar_chart.add('Padovan', [1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12])\n", "svg = bar_chart.render()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "from IPython.display import SVG\n", "SVG(svg)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.12.3" }, "toc-autonumbering": true, "toc-showcode": true, "toc-showmarkdowntxt": true }, "nbformat": 4, "nbformat_minor": 4 }