简体   繁体   中英

How to save candlestick chart in matplotlib finance

I made some python script to create candlestick chart using mpl_finance. I have successfully made the candlestick chart but for the sake of my life I can't find a way to save the chart to png. here's my code:

!pip install yfinance
!pip install mplfinance
!pip install bokeh
!pip install mpl-finance
# https://towardsdatascience.com/trading-toolbox-03-ohlc-charts-95b48bb9d748
from mplfinance.original_flavor import candlestick_ohlc
import mplfinance as fplt

import yfinance as yf
import datetime as dt
import pandas as pd
from pandas_datareader import data as pdr 
from datetime import timedelta
import matplotlib.dates as mdates 
from bokeh.plotting import figure,show,output_file
import matplotlib.pyplot as plt
import mpl_finance as mpf #

yf.pdr_override()
start = dt.datetime.now() - timedelta(60)
now = dt.datetime.now()

stock = "BAC"

df = pdr.get_data_yahoo(stock ,start , now)

# Convert yahoo finance data to readable to mplfinance
df.index = pd.to_datetime(df.index)
dvalues = df[['Open','High', 'Low','Close']].values.tolist()

pdates = mdates.date2num(df.index)
ohlc = [ [pdates[i]] + dvalues[i] for i in range(len(pdates)) ]

plt.style.use('fivethirtyeight')
fig, ax = plt.subplots(figsize = (16,12))


mpf.candlestick_ohlc(ax, ohlc, width=0.4, colorup='green', colordown='red') # i want to save this chart. 
plt.savefig('amzn.png') # i have tried this but not avail

This can be done more simply using only the new mplfinance:

import mplfinance as mpf
import pandas as pd
import datetime as dt
import pandas_datareader as pdr 

now = dt.datetime.now()
start = now - dt.timedelta(60)

stock = "AMZN"
filename = stock.lower()+'.png'

df = pdr.get_data_yahoo(stock ,start , now)
mpf.plot(df,type='candle',style='yahoo',savefig=filename)

The result: 在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM