我有一个包含日期,开放,高,低,关闭和音量值的python数据帧df
。
我正在尝试烛台图表股票。由于某些原因,我似乎无法matplotlib.finance.candlestick2_ochl()
核心显示股票价格收盘self.df['closep']
高于股价开盘self.df['openp']
的日子。在这些积极的(绿色)日子里,matplotlib要么显示十字星,要么一无所有。
不太清楚为什么我会遇到这种行为。我怀疑它与我的程序从我的Pandas DataFrame self.df
访问库存数据的方式有关。
这是我的代码:
# Visualize my stock data
import pandas as pd
import datetime
import time
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ochl
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
class MyStock:
def __init__(self, stock):
self.stock = stock
self.pullData()
def pullData(self):
try:
print('Currently pulling', self.stock)
print(str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')))
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + self.stock + '/chartdata;type=quote;range=5d/csv'
self.df = pd.read_csv(urlToVisit, header=None, names=['date', 'closep', 'highp', 'lowp', 'openp', 'volume'],
skiprows=22, dtype=float)
print('Pulled', self.stock, '\n')
except Exception as e:
print('main loop', str(e))
print('Constucting DataFrame\n')
self.df['date'] = pd.to_datetime(self.df['date'], unit='s')
self.df = self.df.set_index('date').tz_localize('UTC').tz_convert('US/Eastern').reset_index()
self.df['date'] = self.df['date'].dt.strftime('%Y-%m-%d %H:%M:%S')
print(self.df.tail())
def CandleStick(self):
self.fig = plt.figure()
ax1 = plt.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4, axisbg='w')
candlestick2_ochl(ax1, opens=self.df['openp'], closes=self.df['closep'], highs=self.df['highp'], lows=self.df['lowp'], width=.75, colorup='k', colordown='r', alpha=0.75)
plt.ylabel('Stock Price')
ax1.grid(True)
for label in ax1.xaxis.get_ticklabels():
label.set_rotation(90)
plt.subplots_adjust(left=.10, bottom=.19, right=.93, top=.95, wspace=.20, hspace=0)
plt.suptitle(self.stock + ' Stock Price')
plt.show()
amd = MyStock('AMD')
amd.CandleStick()
和输出的屏幕截图以及DataFrame的相关部分:
您可以在此屏幕上清楚地看到正日(绿色)未正确显示。我确信我在这里遗漏了一些非常明显的东西。
感谢任何帮助。
答案 0 :(得分:1)
请参阅此代码,以生成正确颜色的烛台:
import pandas as pd
import datetime
import time
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.finance import candlestick2_ochl
import matplotlib.ticker as mticker
import matplotlib.dates as mdates
class MyStock:
def __init__(self, stock):
self.stock = stock
self.pullData()
def pullData(self):
try:
print('Currently pulling', self.stock)
print(str(datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d %H:%M:%S')))
urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + self.stock + '/chartdata;type=quote;range=2d/csv'
self.df = pd.read_csv(urlToVisit, header=None, names=['date', 'closep', 'highp', 'lowp', 'openp', 'volume'],
skiprows=22, dtype=float)
print('Pulled', self.stock, '\n')
except Exception as e:
print('main loop', str(e))
print('Constucting DataFrame\n')
self.df['date'] = pd.to_datetime(self.df['date'], unit='s')
self.df = self.df.set_index('date').tz_localize('UTC').tz_convert('US/Eastern').reset_index()
self.df['date'] = self.df['date'].dt.strftime('%Y-%m-%d %H:%M:%S')
print(self.df.tail())
def CandleStick(self):
self.fig = plt.figure()
ax1 = plt.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4, axisbg='w')
candlestick2_ochl(ax1,
self.df['openp'], self.df['highp'], self.df['lowp'], self.df['closep'],
width=.75, colorup='g', colordown='r', alpha=0.75)
plt.ylabel('Stock Price')
ax1.grid(True)
for label in ax1.xaxis.get_ticklabels():
label.set_rotation(90)
plt.subplots_adjust(left=.10, bottom=.19, right=.93, top=.95, wspace=.20, hspace=0)
plt.suptitle(self.stock + ' Stock Price')
plt.show()
amd = MyStock('AMD')
amd.CandleStick()
答案 1 :(得分:-3)
我使用Matplotlib 1.5.1,在matplotlib目录中有一个finance.py文件,第1059-1067行。原始代码是:
candlestick2_ohlc(ax, opens, highs, closes, lows, width=width,
colorup=colorup, colordown=colordown,
alpha=alpha)
def candlestick2_ohlc(ax, opens, highs, lows, closes, width=4,
colorup='k', colordown='r',
alpha=0.75,
):
应该是:
(在参数中交换'关闭'和'低谷的地方)
candlestick2_ohlc(ax, opens, highs, lows, closes, width=width,
colorup=colorup, colordown=colordown,
alpha=alpha)
def candlestick2_ohlc(ax, opens, highs, lows, closes, width=4,
colorup='k', colordown='r',
alpha=0.75,
):
编辑此文件并保存。它应该解决你的问题。
Candlestick Chart。抱歉没有这里显示的图片。你有 单击上面的URL以查看效果。
在2小时内解决了这个问题(现在是凌晨2点) 就像我2小时前猜到的那样(但不是完全相同的地方),让人感到非常伤心。
我在官方Matplotlib API文档中找到了这句话,章节:" matplotlib.finance":
保留原始参数顺序。
这与您的问题有关吗?
实际上,我遇到了和你一样的问题。fig = plt.figure()
ax1 = plt.subplot(1,1,1)
candlestick(ax1,
opens=test_data.open,
closes=test_data.close,
highs=test_data.high,
lows=test_data.low,
width=1,
colorup='k',
colordown='r',
alpha=0.75)
fig.savefig('index.png',dpi=300,bbox_inches='tight')
我得到了这个: some wrong chart ploted by me