创建具有多个轴(不是双轴)的烛台图表

时间:2018-06-02 18:40:53

标签: python pandas matplotlib candlestick-chart multiple-axes

我创建了一个烛台图表,显示了与移动平均线的偏差百分比,百分比为左侧Y轴参数。我想在右侧Y轴上绘制与那些百分比(由我的代码中存在的公式导出)相对应的收盘价。但是,我不是在寻找双轴。我怎么能这样做呢?

目前,我可以制作2个子图,上图中的烛台和下图的相应收盘价。这是我的代码:

import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
pd.core.common.is_list_like = pd.api.types.is_list_like
import pandas_datareader.data as web
import numpy as np
from mpl_finance import candlestick_ohlc
import matplotlib.dates as mdates
from matplotlib.dates import DateFormatter, MonthLocator, YearLocator,  DayLocator
style.use( 'ggplot' )

start_year = int( input( 'Start year: ' ) )
start_month = int( input( 'Start month: ' ) ) #for months before     October, only type in the corresponding digit without the 0
start_day = int( input( 'Start day: ' ) )

print()

end_year = int( input( 'End year: ' ) )
end_month =int( input( 'End month: ' ) ) #for months before October,     only type in the corresponding digit without the 0
end_day = int( input( 'End day: ' ) )

start = dt.datetime( start_year, start_month, start_day )
end = dt.datetime( end_year, end_month, end_day )

print()

ticker = input( 'Ticker: ' ) #should be in Uppercase
ticker = ticker.upper()

df = web.DataReader( ticker, 'morningstar', start, end )

print()

file_name = input( 'What\'s the csv file name that is stored on your device? ( ticker.csv ): ' ) #input should be in Lowercase .csv format
file_name = file_name.lower()

df.to_csv( file_name )

df = pd.read_csv( file_name, parse_dates=True, index_col=0 )


alldays = DayLocator()              # minor ticks on the days
weekFormatter = DateFormatter('%b %d %Y')  # e.g., Jan 12 2018
dayFormatter = DateFormatter('%d')      # e.g., 12

plt.subplot( 2, 1, 1 )
ax = plt.gca()
#fig.subplots_adjust(bottom=0.2)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
# ax.xaxis.set_minor_formatter(dayrmatter)

print()

reply = input( 'How many days\' exponential moving average do you want?: ' )
n = int( reply )

df[ 'EMA' ] = df[ 'Close' ].ewm( span = n, adjust=False ).mean()

df[ 'H' ] = ( df[ 'High' ] - df[ 'EMA' ] ) / df[ 'EMA' ]
df[ 'L' ] = ( df[ 'Low' ] - df[ 'EMA' ] ) / df[ 'EMA' ]
df[ 'C' ] = ( df[ 'Close' ] - df[ 'EMA' ] ) / df[ 'EMA' ]
df[ 'OP' ] = ( df[ 'Open' ] - df[ 'EMA' ] ) / df[ 'EMA' ]

                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           #

df.dropna( inplace=True )

df_corr = pd.DataFrame()

#nbr_days = len( df[ 'Date' ] )

max_h = df[ 'H' ].max()
max_input = int( max_h  * 2.4 * 100 )


min_l = df[ 'L' ].min()
min_input = int( min_l * 2.4 * 100 )

#print( int( min_input ), int( max_input ) )



l = []

for i in range( min_input, max_input ):

value = i / 200

l.append( value )

df_corr['corr'] = l

df_corr.dropna( inplace=True )


df_merged = pd.concat([df.reset_index(), df_corr ], axis=1).set_index("Symbol")

df_merged.to_csv( 'combine2.csv', index=False )

df_ohlc = df_merged

latest_ema = df_ohlc[ 'EMA' ].tail( 1 )
print( latest_ema )

df_ohlc[ 'Price' ] = ( df_ohlc[ 'corr' ] * latest_ema ) + latest_ema  #you need to take the latest EMA

print( df_ohlc )

# plot_day_summary(ax, quotes, ticksize=3)


date_list = df_ohlc[ 'Date' ].map( mdates.datestr2num )


candlestick_ohlc(ax, zip(df_ohlc[ 'Date' ].map( mdates.datestr2num ),
                     df['OP'], df['H' ],
                     df['L'], df['C']),
             width=0.6, colorup= 'g' )

ax.xaxis_date()

##ax2 = ax.twinx()
##s2 = df_ohlc[ 'Price' ]
##ax2.plot( date_list, s2 )

##plt.figure( 2 )
##plt.subplot()
##plt.plot( df_ohlc[ 'corr' ], df_ohlc[ 'Price' ] )

#ax2.plot( df_ohlc[ 'corr' ], df_ohlc[ 'Price' ] )


plt.subplot( 2, 1, 2 )
plt.plot( df_ohlc[ 'corr' ], df_ohlc[ 'Price' ], '.-' )

ax.autoscale_view()
plt.setp(plt.gca().get_xticklabels(), rotation=45,    horizontalalignment='right')


plt.show()

这是输出:

     Date   Close      High     ...            OP   corr       Price
Symbol                                   ...                                 
SPY    2017-05-30  241.50  241.7900     ...    -0.000663 -0.075 248.783803
SPY    2017-05-31  241.44  241.8800     ...    0.001416 -0.070  250.128581

此外,这是图表的样子:

enter image description here

理想情况下,我想要这样的东西,右边的y轴上的价格对应于左边的百分比,而不是日期。 (在Excel上完成): enter image description here

即使无法绘制多个轴,有没有办法链接这两个图?例如,如果我将6%视为上图中的关键点并想要检查下图中的相应价格,是否有比在下图上手动检查相应价格更快的方法?

0 个答案:

没有答案