如何使用雅虎查询显示多个符号的历史图表?

qv7cva1a  于 2022-10-23  发布在  其他
关注(0)|答案(2)|浏览(138)

https://yahooquery.dpguthrie.com/guide/ticker/historical/中显示图表的命令是什么


小时
我试过这个密码

import pandas as pd
import matplotlib.pyplot as plt
from yahooquery import Ticker

tickers = Ticker('aapl nflx', asynchronous=True)
df = tickers.history()
df["adjclose"].plot()
plt.xticks(rotation=90)
plt.show()

但它只是在图表中显示一个系列,如下所示:


小时
如何将aapl和nflx创建为一个图表上的两个系列?

fjaof16o

fjaof16o1#

symboldate是 Dataframe 的索引。通过绘制整个 Dataframe ,可以按顺序绘制两个系列。
这里有一种绘制每个股票行情的方法:

import pandas as pd
import matplotlib.pyplot as plt
from yahooquery import Ticker

tickers = Ticker('aapl nflx', asynchronous=True)
df = tickers.history()
df.query('symbol == "aapl"')["adjclose"].plot()
df.query('symbol == "nflx"')["adjclose"].plot()
plt.xticks(rotation=90)
plt.show()

这使用query提取每个符号。

mqxuamgl

mqxuamgl2#

首先,使用df.pivotdf转换为更容易理解的形状,以便绘制方法:

import pandas as pd
from yahooquery import Ticker

tickers = Ticker('aapl nflx', asynchronous=True)
df = tickers.history()

df_pivot = df.reset_index().pivot(index='date',
                                  columns='symbol', values='adjclose')

symbol            aapl        nflx
date                              
2022-01-03  181.259918  597.369995
2022-01-04  178.959457  591.150024
2022-01-05  174.199142  567.520020
2022-01-06  171.291199  553.289978
2022-01-07  171.460495  541.059998

接下来,看看sns.lineplot

import matplotlib.pyplot as plt
import matplotlib.dates as md
import matplotlib.ticker as mtick

import seaborn as sns
sns.set_theme()

fig, ax = plt.subplots(figsize=(10,6))

ax = sns.lineplot(data=df_pivot, palette=['r','b'], dashes=False)

# adjust axes for readability

ax.xaxis.set_major_locator(md.WeekdayLocator(byweekday = 1))
ax.set_xlim(df_pivot.index.min(), df_pivot.index.max())
ax.yaxis.set_major_locator(mtick.MultipleLocator(50))

plt.xticks(rotation=90)
plt.tight_layout()
plt.show()

结果:


小时
顺便说一句,如果你想比较这两种股票,绘制百分比可能更有意义。例如。:

df_pivot_perc = df_pivot.div(df_pivot.iloc[0,:]).mul(100)
fig, ax = plt.subplots(figsize=(10,6))

ax = sns.lineplot(data=df_pivot_perc, palette=['r','b'], dashes=False)
ax.xaxis.set_major_locator(md.WeekdayLocator(byweekday = 1))
ax.set_xlim(df_pivot.index.min(), df_pivot.index.max())

fmt = '%.0f%%'
yticks = mtick.FormatStrFormatter(fmt)
ax.yaxis.set_major_formatter(yticks)
ax.yaxis.set_major_locator(mtick.MultipleLocator(10))

plt.xticks(rotation=90)
plt.tight_layout()
plt.show()

结果:


小时

相关问题