import numpy as np
import matplotlib.pyplot as mp
from scipy import stats
x=np.linspace(-4,4,500)
mp.figure('Normal and t Distribution',facecolor='lightgray')
mp.title('Normal Distribution',fontsize=20)
mp.xlabel('x',fontsize=14)
mp.ylabel('y',fontsize=14)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
mp.plot(x,stats.norm.pdf(x),label='Normal')
mp.show()
mp.title('t Distribution',fontsize=20)
mp.plot(x,stats.t.pdf (x,5),label='n=5')
mp.plot(x,stats.t.pdf (x,30),label='n=30')
mp.legend()
mp.show()
分类: Python
-
python绘制正态分布图
-
python的akshare库调用股票数据的方法
import akshare as ak import pandas as pd import os print("==================腾讯某股票历史数据获取======================================") # tengxun stock data stock_zh_a_hist_tx_df = ak.stock_zh_a_hist_tx(symbol="sz000937", start_date="20230101", end_date="20250513", adjust="") print(stock_zh_a_hist_tx_df.head()) #filename = os.path.join(os.path.dirname("__file__"),"sz000937.csv") stock_zh_a_hist_tx_df.to_csv("sz000937.csv", index=False) # # # 股票最新数据 print("===================上证股票最新数据================================") stock_sh_a_spot_em_df = ak.stock_sh_a_spot_em() print(stock_sh_a_spot_em_df.head()) stock_sh_a_spot_em_df.to_csv("stock_sh_a_spot_em_df.csv", index=False) print("=====================深圳股票最新数据==============================") stock_sz_a_spot_em_df = ak.stock_sz_a_spot_em() print(stock_sz_a_spot_em_df.head()) stock_sz_a_spot_em_df.to_csv("stock_sz_a_spot_em_df.csv", index=False) print("==============某股票分钟数据=====================================") # 股票分钟数据 stock_zh_a_minute_df = ak.stock_zh_a_minute(symbol='sz000937', period='1', adjust="qfq") print(stock_zh_a_minute_df.head()) stock_zh_a_minute_df.to_csv("stock_zh_a_minute_df.csv", index=False) print("========深圳板块成交数据===========================================") stock_szse_sector_summary_df = ak.stock_szse_sector_summary(symbol="当年", date="202504") print(stock_szse_sector_summary_df.head()) stock_szse_sector_summary_df.to_csv("stock_szse_sector_summary_df.csv", index=False) # print("========================================================") # 获取概览数据 # stock_sse_summary_df = ak.stock_sse_summary() # print(stock_sse_summary_df) # print("========================================================") # #深圳股票数据统计 # stock_szse_summary_df = ak.stock_szse_summary(date="20200619") # print(stock_szse_summary_df) -
python获取某只股票的历史数据和所有股票最新数据
#获取所有A股股票最新数据并写入 Excel 文件 import akshare as ak import pandas as pd import os import schedule import time import logging # 获取某只股票历史数据并写入 Excel 文件 stock_data = ak.stock_zh_a_hist( symbol="000937", start_date="20220101", end_date="20250512", # 设置复权类型,可选前复权(qfq)、后复权(hfq)或不复权,此处注释掉表示暂不设置 # adjust="qfq" # 可选前复权、后复权或不复权 ) # 定义要写入数据的 Excel 文件路径 excel_path = "stock_data_000937.xlsx" # 将 Excel 文件路径与当前脚本所在目录拼接,确保文件保存在脚本同目录下 excel_path = os.path.join(os.path.dirname(__file__), excel_path) try: # 将获取到的股票数据写入 Excel 文件,不包含索引列 stock_data.to_excel(excel_path, index=False) # 打印成功信息,提示数据已成功写入指定文件 print(f"数据已成功写入到 {excel_path} 文件中!") except Exception as e: # 若写入过程中出现异常,打印错误信息 print(f"写入 Excel 文件时出错: {e}") #定义一个函数,用于获取并保存股票最新股价数据 def get_and_save_stock_data(): """ 从东方财富获取最新的 A 股股票数据,并将其保存到一个 Excel 文件中。 文件名包含时间戳,且文件会存储在脚本所在的同一目录下。 记录操作成功或失败的日志信息。 """ try: # 调用 akshare 库的函数获取 A 股实时行情数据 data = ak.stock_zh_a_spot_em() # 打印获取到的数据的前几行,用于调试查看数据结构 print(data.head()) # 使用 time.strftime 函数生成当前时间的字符串,格式为年月日时分秒 current_time = time.strftime("%Y%m%d%H%M%S") # Generate a file name with a timestamp file_name = f'stock_data_{current_time}.xlsx' # Create a full file path by combining the directory of the current script and the file name file_path = os.path.join(os.path.dirname(__file__), file_name) # Write the data to an Excel file, without including the index data.to_excel(file_path, index=False) # Log the successful retrieval and storage of the stock data logging.info(f"Successfully retrieved stock data and saved to {file_path} at {time.strftime('%Y-%m-%d %H:%M:%S')}") except Exception as e: # Log any errors that occur during the retrieval or storage of the stock data logging.error(f"An error occurred while retrieving or saving stock data: {e}") # Configure logging to record events at the INFO level logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') # Schedule the function to run every 10 or(0.5) minutes schedule.every(1).minutes.do(get_and_save_stock_data) # Start the scheduling loop,Ctrl+C to stop 终止运行 try: # Continuously check and run scheduled tasks while True: # Check if any scheduled tasks are due and run them schedule.run_pending() # Pause the loop for 1 second to avoid excessive CPU usage time.sleep(1) except KeyboardInterrupt: logging.info("Program terminated by user.结束") -
python获取A股数据并存入csv文件
import akshare as ak import pandas as pd import os import schedule import time import logging def get_and_save_stock_data(): """ Fetches the latest A-share stock data from Eastmoney and saves it to an Excel file. The file is named with a timestamp and stored in the same directory as the script. Logs the success or failure of the operation. """ try: # 获取股票数据 # data = ak.stock_zh_a_spot_em() data = ak.stock_zh_a_spot() print(data.head(150)) # 打印数据的基本信息 print("数据基本信息:") data.info() # 打印数据行数和列数 rows, columns = data.shape if rows < 3000: print("数据可能未获取完整,请检查网络连接或稍后重试。") else: print("数据获取完整。") # 打印数据行数 print("数据行数:", rows) # 生成带时间的文件名 current_time = time.strftime("%Y%m%d%H%M%S") # Generate a file name with a timestamp file_name = f'stock_data_{current_time}.xlsx' # Create a full file path by combining the directory of the current script and the file name file_path = os.path.join(os.path.dirname(__file__), file_name) # Write the data to an Excel file, without including the index data.to_excel(file_path, index=False) # Log the successful retrieval and storage of the stock data logging.info(f"Successfully retrieved stock data and saved to {file_path} at {time.strftime('%Y-%m-%d %H:%M:%S')}") except Exception as e: # Log any errors that occur during the retrieval or storage of the stock data logging.error(f"An error occurred while retrieving or saving stock data: {e}") # Configure logging to record events at the INFO level logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') # Schedule the function to run every 1 minute schedule.every(0.5).minutes.do(get_and_save_stock_data) # Start the scheduling loop try: import msvcrt # Import msvcrt module for Windows key detection import keyboard # Import the keyboard library logging.info("Press 'Q' or 'q' to terminate the program.") while True: schedule.run_pending() time.sleep(.5) # Check if the 'Q' key is pressed if msvcrt.kbhit() and msvcrt.getch().decode('utf-8').upper() == 'Q': logging.info("Program terminated by user.") break # Check if the 'q' key is pressed if keyboard.is_pressed('q'): logging.info("Program terminated by user.") break except KeyboardInterrupt: logging.info("Program terminated by user.结束") -
请给出下列代码的运行结果
def double_number(numbers): numbers[:] = [num*2 for num in numbers] # return my_list return numbers my_list = [1,2,3] result = double_number(my_list) print(my_list) # output [2, 4, 6] -
python绘制正态分布和t分布图形
import numpy as np import matplotlib.pyplot as mp from scipy import stats x=np.linspace(-4,4,500) mp.figure('Normal and t Distribution',facecolor='lightgray') mp.title('Normal Distribution',fontsize=20) mp.xlabel('x',fontsize=14) mp.ylabel('y',fontsize=14) mp.tick_params(labelsize=10) mp.grid(linestyle=':') mp.plot(x,stats.norm.pdf(x),label='Normal') mp.show() mp.title('t Distribution',fontsize=20) mp.plot(x,stats.t.pdf (x,5),label='n=5') mp.plot(x,stats.t.pdf (x,30),label='n=30') mp.legend() mp.show() -
使用python的akshare库读取股票实时数据并保存
这段代码的主要功能是定时获取 A 股股票数据并保存到 Excel 文件中,同时记录操作日志。具体步骤如下:
- 导入必要的库:导入
akshare、pandas、os、schedule、time和logging库,用于获取股票数据、数据处理、文件路径操作、定时任务、时间处理和日志记录。 - 定义获取并保存股票数据的函数:
get_and_save_stock_data函数从东方财富获取最新的 A 股股票数据,生成带有时间戳的文件名,将数据保存为 Excel 文件,并记录操作成功或失败的日志。 - 配置日志记录:使用
logging.basicConfig配置日志记录,设置日志级别为INFO,并指定日志格式。 - 设置定时任务:使用
schedule库设置定时任务,每 10 分钟调用一次get_and_save_stock_data函数。 - 循环检查并执行定时任务:使用
while True循环不断检查是否有定时任务到期,并执行到期的任务。每次循环暂停 1 秒,以避免过度占用 CPU 资源。
通过以上步骤,代码实现了定时获取和保存股票数据的功能,并记录了操作日志。
在这个修改后的代码中,我们使用try-except块包裹了while循环,当用户按下Ctrl+C时,会触发KeyboardInterrupt异常,程序会捕获这个异常并记录一条日志信息,然后正常退出。import akshare as ak import pandas as pd import os import schedule import time import logging def get_and_save_stock_data(): """ Fetches the latest A-share stock data from Eastmoney and saves it to an Excel file. The file is named with a timestamp and stored in the same directory as the script. Logs the success or failure of the operation. """ try: # 获取股票数据 data = ak.stock_zh_a_spot_em() print(data.head()) # 生成带时间的文件名 current_time = time.strftime("%Y%m%d%H%M%S") # Generate a file name with a timestamp file_name = f'stock_data_{current_time}.xlsx' # Create a full file path by combining the directory of the current script and the file name file_path = os.path.join(os.path.dirname(__file__), file_name) # Write the data to an Excel file, without including the index data.to_excel(file_path, index=False) # Log the successful retrieval and storage of the stock data logging.info(f"Successfully retrieved stock data and saved to {file_path} at {time.strftime('%Y-%m-%d %H:%M:%S')}") except Exception as e: # Log any errors that occur during the retrieval or storage of the stock data logging.error(f"An error occurred while retrieving or saving stock data: {e}") # Configure logging to record events at the INFO level logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') # Schedule the function to run every 10 or 0.5 minutes schedule.every(0.5).minutes.do(get_and_save_stock_data) # Start the scheduling loop,Ctrl+C to stop 终止运行 try: # Continuously check and run scheduled tasks while True: # Check if any scheduled tasks are due and run them schedule.run_pending() # Pause the loop for 1 second to avoid excessive CPU usage time.sleep(1) except KeyboardInterrupt: logging.info("Program terminated by user.结束") - 导入必要的库:导入
-
使用python把字符串转换成base64编码
import base64 def main(): # Read the input string from the user. data = input("Enter the text you want to encode: ") # Encode the string using base64 encoding. encoded_data = base64.b64encode(data.encode()) # Print the result. print("Encoded Data:", encoded_data) if __name__ == '__main__': main()Save this code in a file, for example base64_encoder.py, and run it using Python interpreter:
python python base64_encoder.py Replace the input text with your desired string to encode into base64 format.
-
How to use pushbullet send messages
To use the Pushbullet Python library, you can follow these steps:
- Install the library:python
pip install pushbullet.py - Get your API key:
- Go to the Pushbullet website.
- Log in to your account.
- Navigate to the “Account Settings” page.
- You will find your API key under the “Access Tokens” section.
- Using the library: Here’s a simple example to get you started:python
from pushbullet import Pushbullet# Replace 'YOUR_API_KEY' with your actual API keypb = Pushbullet('YOUR_API_KEY')
#pb = Pushbullet(‘o.rGjZOE7xAgj7ILoFIHfM1JXKddUsMSv4’)# Get a list of devicesdevices = pb.devices# Send a notepush = pb.push_note("Title", "Body")
For more detailed usage, you can check out the Pushbullet Python library documentation.
If you have any specific use cases or need further assistance, feel free to ask!
Pushbullet 是一个非常方便的 Python 库,可以帮助你在设备之间发送通知、链接、文件等。以下是 Pushbullet 的一些主要功能和使用方法:
功能
与你的 Pushbullet 账户关联的设备(需要下载对应的pushbullet手机APP、电脑客户端)之间传递以下内容:
- 发送通知:可以向你的设备发送通知。
- 发送链接:可以在设备之间发送链接。
- 发送文件:可以在设备之间发送文件。
- 查看设备列表:可以查看与你的 Pushbullet 账户关联的设备列表。
使用方法
首先,你需要安装 Pushbullet 库。你可以使用以下命令来安装它:
pip install pushbullet.py
接下来,你需要获取一个 API 密钥。你可以在 Pushbullet 的网站上登录你的账户,然后在设置中找到 API 密钥。
代码示例
以下是一个简单的代码示例,展示了如何使用 Pushbullet 库发送通知:
from pushbullet import Pushbullet
# 使用你的 API 密钥初始化 Pushbullet
pb = Pushbullet("YOUR_API_KEY")
#pb = Pushbullet('o.rGjZOE7xAgj7ILoFIHfM1JXKddUsMSv4')
# 发送通知
push = pb.push_note("标题", "这是通知的内容")你还可以发送链接和文件,以下是一些示例代码:
# 发送链接
push = pb.push_link("标题", "https://www.example.com")
# 发送文件
with open("example.txt", "rb") as file:
file_data = pb.upload_file(file, "example.txt")
push = pb.push_file(**file_data)以上代码python3.13.1,WIN10调试通过。
- Install the library:python