import pandas as pd
import openpyxl
file_name = r'02-林业.xlsx'
wb = openpyxl.load_workbook(file_name, read_only=True)
name_lst = wb.sheetnames 
stock_name = name_lst[0]  
df_stock_values = pd.read_excel(file_name, sheet_name=stock_name)
lst_date = list(df_stock_values['trade_date'])  
lst_open = list(df_stock_values['open'])  
lst_close = list(df_stock_values['close'])  
lst_high = list(df_stock_values['high'])  
lst_low = list(df_stock_values['low'])  

# 4. 根据该公司的名称及代码,查询指定日期内的数据
# 5. 调用函数,计算在该时间内的股票开盘价的均值内容:def get_stock_avg_open(stock_name, start_date, end_date):
    df_stock_values = pd.read_excel(file_name, sheet_name=stock_name)
    df_stock_values['trade_date'] = pd.to_datetime(df_stock_values['trade_date'], format='%Y%m%d')
    df_stock_values.set_index('trade_date', inplace=True)
    df_stock_values = df_stock_values.loc[start_date:end_date]
    avg_open = df_stock_values['open'].mean()
    return avg_open

start_date = '2020-01-01'
end_date = '2020-12-31'
avg_open = get_stock_avg_open(stock_name, start_date, end_date)
print(f'The average opening price of {stock_name} from {start_date} to {end_date} is {avg_open:.2f} RMB.') # 输出结果:The average opening price of 中国林业 from 2020-01-01 to 2020-12-31 is 7.71 RMB.

This code snippet demonstrates how to use Python's Pandas library to effectively analyze stock data. By reading data from an Excel file and utilizing Pandas' capabilities, you can efficiently calculate the average opening price of a stock within a specific date range. This technique is particularly valuable for financial analysis and provides insights into stock performance over time.

Python Pandas: Calculate Average Opening Price of Stock within a Date Range

原文地址: https://www.cveoy.top/t/topic/nj57 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录