如何在python中绘制烛台 [英] how to plot candlesticks in python
问题描述
我正在尝试用烛台创建一个简单的情节。为此,我从Yahoo获得数据并使用功能Candlestick2_ohlc对其进行绘制。目标是使用导出图像为jpg文件。
I´m trying to create a simple plot with candlesticks. For that I get the data from Yahoo and plot it using the function candlestick2_ohlc. The goal is to export the image in a jpg file using.
这是我正在使用的代码:
This is the code what I´m using:
from pandas_datareader import data
import matplotlib.pyplot as plt
from mpl_finance import candlestick2_ohlc
import matplotlib.dates as mdates
import fix_yahoo_finance as yf
import datetime
start = datetime.date(2018, 1, 1)
end = datetime.date.today()
aapl = yf.download("AAPL",start,end)
aapl.reset_index(inplace=True)
aapl['Date'] = aapl.index.map(mdates.date2num)
fig, ax = plt.subplots()
plt.xlabel("Date")
plt.ylabel("Price")
candlestick2_ohlc(ax, aapl.Open, aapl.High, aapl.Low, aapl.Close, width=1, colorup='g')
plt.savefig('my_figure.png')
plt.show()
我的第一个问题是:还有另一种简单的方法吗?您能给我一个处理财务数据的例子吗?我通常在R中使用Quantmod。
My first question is: there is another simple way to do it? Could you please give me an example to work with finance data? I usually work with quantmod in R.
第二个问题是:在我的示例中,X轴中没有日期。如何在X轴上显示带有日期的图?我应该将Date转换为AX格式,但是我不知道这样做的简单方法。
The second question is: In my example, there is no Date in the X axi. What can I do to show the plot with Dates in the X axi? I should transform the Date into a AX format but I don't know a simple way to do it.
谢谢
推荐答案
首先,您需要使用以下命令安装 plotly
软件包:
First you need to install the plotly
package using:
pip install plotly
然后,您可以绘制蜡烛图就像下面的代码一样简单:
Then, you can plot the candle plots as easy as the following code:
import plotly.graph_objects as go
import pandas as pd
from datetime import datetime
df = pd.read_csv('your_file_address')
fig = go.Figure(data=[go.Candlestick(x=df['name_of_time_column'],
open=df['name_of_open_column'],
high=df['name_of_high_column'],
low=df['name_of_low_column'],
close=df['name_of_close_column'])])
fig.show()
这篇关于如何在python中绘制烛台的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!