import pandas as pd import matplotlib.pyplot as plt import mplcursors import pyodbc…
- User
import pandas as pd import matplotlib.pyplot as plt import mplcursors import pyodbc import matplotlib.ticker as ticker
Setup connection to the database
conn_str = r"DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\LIQI\Documents\microcapstrategy.accdb" try: conn = pyodbc.connect(conn_str)
# 执行查询 query = "SELECT TradingDay, SecuCode, TurnoverRateRM, YearVolatilityByDay, Prc2bk FROM Portfolio" df = pd.read_sql(query, conn) # 关闭连接finally: conn.close()
# 将相关列转换为float类型 df['TurnoverRateRM'] = df['TurnoverRateRM'].astype(float) df['YearVolatilityByDay'] = df['YearVolatilityByDay'].astype(float) df['Prc2bk'] = df['Prc2bk'].astype(float) # 统计不同tradingdate对应的每个stock ticker的因子值 statistics = df.groupby('TradingDay').agg({'TurnoverRateRM': ['mean', 'median', lambda x: x.quantile(0.1), lambda x: x.quantile(0.25), \ lambda x: x.quantile(0.75), lambda x: x.quantile(0.9)],'YearVolatilityByDay': ['mean', 'median', lambda x: x.quantile(0.1),\ lambda x: x.quantile(0.25), lambda x: x.quantile(0.75), lambda x: x.quantile(0.9)],'Prc2bk': ['mean', 'median',\ lambda x: x.quantile(0.1), lambda x: x.quantile(0.25), lambda x: x.quantile(0.75),lambda x: x.quantile(0.9)]}) # 绘制时间序列折线图 dates = statistics.index.tolist() plt.figure(figsize=(12, 12)) # 绘制因子A的时间序列折线图 ax1 =plt.subplot(3, 1, 1) ax1.plot(dates, statistics[('TurnoverRateRM', 'mean')].values, label='Mean') ax1.plot(dates, statistics[('TurnoverRateRM', 'median')].values, label='Median') ax1.plot(dates, statistics[('TurnoverRateRM', '<lambda_0>')].values, label='10% Quantile') ax1.plot(dates, statistics[('TurnoverRateRM', '<lambda_1>')].values, label='25% Quantile') ax1.plot(dates, statistics[('TurnoverRateRM', '<lambda_2>')].values, label='75% Quantile') ax1.plot(dates, statistics[('TurnoverRateRM', '<lambda_3>')].values, label='90% Quantile') ax1.set_ylabel('近月换手率') ax1.legend() ax1.xaxis.set_tick_params(rotation=45) ax1.xaxis.set_major_locator(ticker.MultipleLocator(3)) # 设置刻度间隔为3 # 绘制因子B的时间序列折线图 ax2=plt.subplot(3, 1, 2) ax2.plot(dates, statistics[('YearVolatilityByDay', 'mean')].values, label='Mean') ax2.plot(dates, statistics[('YearVolatilityByDay', 'median')].values, label='Median') ax2.plot(dates, statistics[('YearVolatilityByDay', '<lambda_0>')].values, label='10% Quantile') ax2.plot(dates, statistics[('YearVolatilityByDay', '<lambda_1>')].values, label='25% Quantile') ax2.plot(dates, statistics[('YearVolatilityByDay', '<lambda_2>')].values, label='75% Quantile') ax2.plot(dates, statistics[('YearVolatilityByDay', '<lambda_3>')].values, label='90% Quantile') ax2.set_ylabel('年化波动率') ax2.legend() ax2.xaxis.set_tick_params(rotation=45) ax2.xaxis.set_major_locator(ticker.MultipleLocator(3)) # 设置刻度间隔为3 # 绘制因子C的时间序列折线图 ax3=plt.subplot(3, 1, 3) ax3.plot(dates, statistics[('Prc2bk', 'mean')].values, label='Mean') ax3.plot(dates, statistics[('Prc2bk', 'median')].values, label='Median') ax3.plot(dates, statistics[('Prc2bk', '<lambda_0>')].values, label='10% Quantile') ax3.plot(dates, statistics[('Prc2bk', '<lambda_1>')].values, label='25% Quantile') ax3.plot(dates, statistics[('Prc2bk', '<lambda_2>')].values, label='75% Quantile') ax3.plot(dates, statistics[('Prc2bk', '<lambda_3>')].values, label='90% Quantile') ax3.set_ylabel('改良市净率') ax3.legend() ax3.xaxis.set_tick_params(rotation=45) ax3.xaxis.set_major_locator(ticker.MultipleLocator(3)) # 设置刻度间隔为3 plt.xlabel('建仓日') plt.tight_layout() # 使用mplcursors库实现鼠标悬停显示数据 mplcursors.cursor([ax1, ax2, ax3]) plt.show() 不知道为啥 我没办法通过把鼠标放在图标上获得对应的数据 请帮我检查下哪里有问题 - Assistant
根据代码的结构,我看到你在最后使用了mplcursors.cursor来实现鼠标悬停显示数据的功能。但是该功能需要matplotlib 3.3.0或更高版本才能正常工作。
如果你运行的matplotlib版本较低,可以尝试升级matplotlib到最新版本。你可以使用以下命令来升级matplotlib:
pip install --upgrade matplotlib如果升级matplotlib后仍然无法正常工作,请检查其他的依赖库是否满足要求,并确保使用的版本是兼容的。
如果你的matplotlib版本已经是3.3.0或更高版本,而鼠标悬停仍然无效,可能是操作系统或IDE的问题。试着将代码移动到一个新的Python脚本中,并在命令行中运行它,看看是否能够正常工作。
希望这些建议能够帮助你解决问题。如果还有其他疑问,请随时向我提问。
- User
如果我换用plotly库呢
- Assistant
- User
NameError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_7672/2326613152.py in 36 subplot.add_trace(go.Scatter(x=x_values, y=y_values, mode='lines', name=name)) 37 ---> 38 fig = make_subplots(rows=3, cols=1, subplot_titles=('近月换手率', '年化波动率', '改良市净率')) 39 40
NameError: name 'make_subplots' is not defined
- Assistant
上述错误是由于没有正确导入
make_subplots函数导致的。请确保在代码中添加以下导入语句:from plotly.subplots import make_subplots这将解决
NameError: name 'make_subplots' is not defined错误,并允许你正确使用make_subplots函数。如果还有其他问题,请随时提问。
- User
AttributeError Traceback (most recent call last) ~\AppData\Local\Temp/ipykernel_7672/1182989789.py in 41 42 # 绘制因子A的时间序列折线图 ---> 43 plot_time_series_subplot(fig, 1, statistics.index, statistics[('TurnoverRateRM', 'mean')].values, 'Mean') 44 plot_time_series_subplot(fig, 1, statistics.index, statistics[('TurnoverRateRM', 'median')].values,'Median') 45 plot_time_series_subplot(fig, 1, statistics.index, statistics[('TurnoverRateRM', '<lambda_0>')].values, '10% Quantile')
~\AppData\Local\Temp/ipykernel_7672/1182989789.py in plot_time_series_subplot(fig, subplot, x_values, y_values, name) 35 36 def plot_time_series_subplot(fig, subplot, x_values, y_values, name): ---> 37 subplot.add_trace(go.Scatter(x=x_values, y=y_values, mode='lines', name=name)) 38 39 fig = make_subplots(rows=3, cols=1, subplot_titles=('近月换手率', '年化波动率', '改良市净率'))
AttributeError: 'int' object has no attribute 'add_trace'
- Assistant
由于我们使用了Plotly Express模块的
add_trace函数实现添加图表,但是在你的代码中,subplot参数是一个整数,而不是一个Plotly subplot对象。为了解决这个问题,你可以使用
make_subplots函数创建一个subplot对象,并将其作为参数传递给plot_time_series_subplot函数。请尝试以下代码:
def plot_time_series_subplot(fig, subplot, x_values, y_values, name): fig.add_trace(go.Scatter(x=x_values, y=y_values, mode='lines', name=name), row=subplot, col=1) fig = make_subplots(rows=3, cols=1, subplot_titles=('近月换手率', '年化波动率', '改良市净率')) # 绘制因子A的时间序列折线图 plot_time_series_subplot(fig, 1, statistics.index, statistics[('TurnoverRateRM', 'mean')].values, 'Mean') plot_time_series_subplot(fig, 1, statistics.index, statistics[('TurnoverRateRM', 'median')].values, 'Median') plot_time_series_subplot(fig, 1, statistics.index, statistics[('TurnoverRateRM', '<lambda_0>')].values, '10% Quantile') plot_time_series_subplot(fig, 1, statistics.index, statistics[('TurnoverRateRM', '<lambda_1>')].values, '25% Quantile') plot_time_series_subplot(fig, 1, statistics.index, statistics[('TurnoverRateRM', '<lambda_2>')].values, '75% Quantile') plot_time_series_subplot(fig, 1, statistics.index, statistics[('TurnoverRateRM', '<lambda_3>')].values, '90% Quantile') # 绘制因子B的时间序列折线图 plot_time_series_subplot(fig, 2, statistics.index, statistics[('YearVolatilityByDay', 'mean')].values, 'Mean') plot_time_series_subplot(fig, 2, statistics.index, statistics[('YearVolatilityByDay', 'median')].values, 'Median') plot_time_series_subplot(fig, 2, statistics.index, statistics[('YearVolatilityByDay', '<lambda_0>')].values, '10% Quantile') plot_time_series_subplot(fig, 2, statistics.index, statistics[('YearVolatilityByDay', '<lambda_1>')].values, '25% Quantile') plot_time_series_subplot(fig, 2, statistics.index, statistics[('YearVolatilityByDay', '<lambda_2>')].values, '75% Quantile') plot_time_series_subplot(fig, 2, statistics.index, statistics[('YearVolatilityByDay', '<lambda_3>')].values, '90% Quantile') # 绘制因子C的时间序列折线图 plot_time_series_subplot(fig, 3, statistics.index, statistics[('Prc2bk', 'mean')].values, 'Mean') plot_time_series_subplot(fig, 3, statistics.index