如何在 Python 中制作可滚动的烛台图?

how to make srollable candelstick plot in Python?

我有以下烛台图。我想让它滚动,以便我可以看到更多详细信息。当前情节太长,看不到细节。 我在这里找到了使线图可滚动的示例:

但是,更新烛台似乎比更新折线图复杂得多。烛台图 returns 线和补丁。你能帮忙吗?

from pandas.io.data import get_data_yahoo
import matplotlib.pyplot as plt
from matplotlib import dates as mdates
from matplotlib import ticker as mticker
from matplotlib.finance import candlestick_ohlc
import datetime as dt
symbol = "GOOG"

data = get_data_yahoo(symbol, start = '2011-9-01', end = '2015-10-23')
data.reset_index(inplace=True)
data['Date']=mdates.date2num(data['Date'].astype(dt.date))
fig = plt.figure()
ax1 = plt.subplot2grid((1,1),(0,0))
plt.title('How to make it scrollable')
plt.ylabel('Price')
ax1.xaxis.set_major_locator(mticker.MaxNLocator(6))
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

candlestick_ohlc(ax1,data.values,width=0.2)

对于你想要的,我建议使用 Plotly,它允许交互式数据可视化(包括滚动、缩放、平移等),并且有一个很好的 Python API。

这里有两种不同的方法(在这两种情况下,您都需要 pip install plotly

  1. 使用 Plotly 网站 API(需要您 create an account here 并获取您的用户名和 API 密钥。您需要连接到互联网才能生成情节。)

    from pandas.io.data import get_data_yahoo
    import matplotlib.pyplot as plt
    from matplotlib import dates as mdates
    from matplotlib import ticker as mticker
    from matplotlib.finance import candlestick_ohlc
    import datetime as dt
    # Imports for Plotly
    import plotly.plotly as py
    import plotly.tools as tls
    from plotly.tools import FigureFactory as FF
    
    # Put your credentials here
    tls.set_credentials_file(username='YourUserName', api_key='YourAPIKey')
    
    # Getting the data
    symbol = "GOOG"
    data = get_data_yahoo(symbol, start = '2011-9-01', end = '2015-10-23')
    data.reset_index(inplace=True)
    # Not needed anymore, we'll use the string-formatted dates.
    #data['Date']=mdates.date2num(data['Date'].astype(dt.date))
    
    # Creating the Plotly Figure
    fig = FF.create_candlestick(data.Open, data.High, data.Low, data.Close, dates=data.Date)
    lay = fig.layout
    
    # Formatting the ticks.
    lay.xaxis.nticks = 6
    lay.xaxis.tickformat = "%Y-%m-%d"
    
    # Removing the hover annotations Plotly adds by default, but this is optional.
    lay.hovermode = False
    
    # A nice title...
    lay.title = "See, I made it scrollable :)"
    py.iplot(fig)
    
  2. 使用 Plotly 的离线模式。我假设您将使用 Jupyter(IPython 笔记本)。您不需要连接到互联网。

    from pandas.io.data import get_data_yahoo
    import matplotlib.pyplot as plt
    from matplotlib import dates as mdates
    from matplotlib import ticker as mticker
    from matplotlib.finance import candlestick_ohlc
    import datetime as dt
    
    # Imports for Plotly
    from plotly.offline import download_plotlyjs, init_notebook_mode, iplot
    import plotly.tools as tls
    from plotly.tools import FigureFactory as FF
    
    init_notebook_mode() # Inject Plotly.js into the notebook
    
    # Getting the data
    symbol = "GOOG"
    data = get_data_yahoo(symbol, start = '2011-9-01', end = '2015-10-23')
    data.reset_index(inplace=True)
    # Not needed anymore, we'll use the string-formatted dates.
    #data['Date']=mdates.date2num(data['Date'].astype(dt.date))
    
    # Creating the Plotly Figure
    fig = FF.create_candlestick(data.Open, data.High, data.Low, data.Close, dates=data.Date)
    lay = fig.layout
    
    # Formatting the ticks.
    lay.xaxis.nticks = 6
    lay.xaxis.tickformat = "%Y-%m-%d"
    
    # Removing the hover annotations Plotly adds by default, but this is optional.
    lay.hovermode = False
    
    # A nice title...
    lay.title = "See, I made it scrollable :)"
    iplot(fig)
    

缩放前的结果...

...在特定区域放大后。

如果您有任何其他问题,请告诉我。希望答案适合您!

您可以绘制整幅图,然后使用滑块小部件修改坐标区。

我无法复制你的数据,因为我没有 pandas.io.data 库,所以我修改了 the candlestick example from here,并添加了滑块。

import matplotlib.pyplot as plt
import datetime
from matplotlib.widgets import Slider
from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc
from matplotlib.dates import DateFormatter, WeekdayLocator,\
    DayLocator, MONDAY

# (Year, month, day) tuples suffice as args for quotes_historical_yahoo
date1 = (2004, 2, 1)
date2 = (2004, 4, 12)

mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
alldays = DayLocator()              # minor ticks on the days
weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
dayFormatter = DateFormatter('%d')      # e.g., 12

quotes = quotes_historical_yahoo_ohlc('INTC', date1, date2)
if len(quotes) == 0:
    raise SystemExit

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
#ax.xaxis.set_minor_formatter(dayFormatter)

#plot_day_summary(ax, quotes, ticksize=3)
candlestick_ohlc(ax, quotes, width=0.6)

ax.xaxis_date()
ax.autoscale_view()
plt.axis([datetime.date(*date1).toordinal(), datetime.date(*date1).toordinal()+10, 18.5, 22.5])
plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')


axcolor = 'lightgoldenrodyellow'
axpos = plt.axes([0.2, 0.05, 0.65, 0.03], axisbg=axcolor)


spos = Slider(axpos, 'Position', datetime.date(*date1).toordinal(), datetime.date(*date2).toordinal())

def update(val):
    pos = spos.val
    ax.axis([pos,pos+10, 18.5, 22.5])
    fig.canvas.draw_idle()

spos.on_changed(update)

plt.show()

我硬编码了一些坐标轴大小和位置的值,请​​在适应您的代码时小心。

如果需要,也可以实现相同的想法来添加垂直滚动。