how to plot candlesticks in python

北城以北 提交于 2019-12-24 00:39:33

问题


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()

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.

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.

Thanks


回答1:


Use Plotly and you can plot a candlestick chart with one line of code.

df[['Open', 'High', 'Low', 'Close']]['2018-01-01':'20XX-XX-XX'].iplot(kind="candle")

Before using plotly, you need install plotly and cufflinks with pip at your command line:

pip install plotly

pip install cufflinks

Also you need to import followings on the top of your Jupiter Notebook:

from plotly import __version__

import cufflinks as cf

from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot

init_notebook_mode (connected=True)

cf.go_offline()



回答2:


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()


来源:https://stackoverflow.com/questions/53697655/how-to-plot-candlesticks-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!