Python 股票数据分析:获取上市公司信息和计算平均数
import pandas as pd
import openpyxl
file_name = '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'])
# 请编写函数,功能为,分别输出上市公司的名字列表和股票代码列表
# name_sh为上市公司名称和代码的列表,其形式为: ['平潭发展000592.SZ', 'ST景谷600265.SH']
# 请编写函数,功能为,输出输入列表的平均数
def get_company_info(df):
'''
获取上市公司的名称和股票代码列表
参数:
df:Pandas DataFrame,包含股票交易信息
返回值:
name_sh:list,上市公司名称和代码的列表,其形式为: ['平潭发展000592.SZ', 'ST景谷600265.SH']
'''
name_lst = wb.sheetnames
stock_name = name_lst[0]
df_stock_values = pd.read_excel(file_name, sheet_name=stock_name)
lst_name = df_stock_values['ts_code'].unique()
name_sh = [name + '.' + code[-2:] for code, name in zip(lst_name, df_stock_values['name'])]
return name_sh
def get_average(lst):
'''
计算列表的平均数
参数:
lst:list,需要计算平均数的列表
返回值:
平均数
'''
return sum(lst)/len(lst)
# 示例
name_sh_lst = get_company_info(df_stock_values)
print(name_sh_lst)
lst = [1, 2, 3, 4, 5]
print(get_average(lst)) # 输出3.0
原文地址: https://www.cveoy.top/t/topic/nj23 著作权归作者所有。请勿转载和采集!