使用matplotlib绘制烛台以获取没有周末间隔的时间序列 [英] Plotting candlestick with matplotlib for time series w/o weekend gaps

查看:196
本文介绍了使用matplotlib绘制烛台以获取没有周末间隔的时间序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在从yahoo-finance导入数据后尝试绘制烛台系列。我正在使用python 2.7

trying to plot a candlestick serie after importing datas from yahoo-finance. I'm using python 2.7

我已经绘制了一个系列,我想添加与烛台相同的系列,但是我不知道如何做到这一点:

I have already a serie plotted and I want to add the same one as candlestick but I don't see how I can do that :

import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ohlc

#Reset the index to remove Date column from index
df_ohlc = data.reset_index()
#Naming columns
df_ohlc.columns = ["Date","Open","High",'Low',"Close", "Adj Close", "Volume"]
#Normal plot
ax1 = plt.subplot()
ax1.plot(df_ohlc["Date"], df_ohlc["Close"], label = "Price", color="blue", linewidth=2.0)
#Candle plot
candlestick2_ohlc(ax1,df_ohlc['Open'],df_ohlc['High'],df_ohlc['Low'],df_ohlc['Close'],width=0.6)

如果我单独绘制烛台,看起来不错,但x轴是整数列表。

If I plot candlestick alone, it looks fine but the x axis is a list of integers.

如果我在转换 df_ohlc [ Date]之后单独绘制烛台

If I plot candlestick alone after converting df_ohlc["Date"] to float then reconverting to datetime, it plots the serie with the correct x axis but there are gaps on the weekend even if the serie isn't defined for these dates.

有没有办法在同一时间绘制两个系列时间 ?我打算添加更多的序列,例如移动平均线,OLS,布林线等等。

Is there a way to plot both series at the same time ? I'm planning to add more series like moving average, OLS, Bollinger etc...

推荐答案

您可以删除周末的缺口,并以这种方式使人类可读的日期xticklabels。请注意,此脚本是用python 3编写的,可能与python 2有所不同。

You can remove weekend gaps and make human-readable dates xticklabels in this way. Note that, this script is written in python 3 and there may be some differences from python 2.

import quandl
import numpy as np
from mpl_finance import candlestick_ohlc
import matplotlib.pyplot as plt

# getting data and modifying it to remove gaps at weekends
r = quandl.get('WIKI/AAPL', start_date='2016-01-01', end_date='2017-11-10')
date_list = np.array(r.index.to_pydatetime())
plot_array = np.zeros([len(r), 5])
plot_array[:, 0] = np.arange(plot_array.shape[0])
plot_array[:, 1:] = r.iloc[:, :4]

# plotting candlestick chart
fig, ax = plt.subplots()
num_of_bars = 100  # the number of candlesticks to be plotted
candlestick_ohlc(ax, plot_array[-num_of_bars:], colorup='g', colordown='r')
ax.margins(x=0.0, y=0.1)
ax.yaxis.tick_right()
x_tick_labels = []
ax.set_xlim(right=plot_array[-1, 0]+10)
ax.grid(True, color='k', ls='--', alpha=0.2)
# setting xticklabels actual dates instead of numbers
indices = np.linspace(plot_array[-num_of_bars, 0], plot_array[-1, 0], 8, dtype=int)
for i in indices:
    date_dt = date_list[i]
    date_str = date_dt.strftime('%b-%d')
    x_tick_labels.append(date_str)
ax.set(xticks=indices, xticklabels=x_tick_labels)

plt.show()

这篇关于使用matplotlib绘制烛台以获取没有周末间隔的时间序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆