### Setup for mplfinance Examples Source: https://github.com/matplotlib/mplfinance/blob/master/examples/fill_between.ipynb Imports necessary libraries and configures IPython for multiple outputs. Reads daily S&P 500 data and displays its shape and head. ```python from IPython.core.interactiveshell import InteractiveShell InteractiveShell.ast_node_interactivity = "all" ``` ```python %matplotlib inline import pandas as pd ``` ```python daily = pd.read_csv('data/SP500_NOV2019_Hist.csv',index_col=0,parse_dates=True) daily.index.name = 'Date' daily.shape daily.head(3) ``` ```python import mplfinance as mpf mpf.__version__ ``` -------------------------------- ### Import Libraries and Check Versions Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/issues/Issue26_bug_fix_volume_bar_widths.ipynb Imports the necessary mplfinance and pandas libraries and checks their installed versions. This is a standard setup step for using the libraries. ```python import mplfinance as mpf mpf.__version__ import pandas as pd pd.__version__ ``` -------------------------------- ### Install mplfinance Source: https://github.com/matplotlib/mplfinance/blob/master/README.md Install the mplfinance package using pip. This command upgrades the package if it is already installed. ```bash pip install --upgrade mplfinance ``` -------------------------------- ### Define Plotting Setup Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/check_use_cases.ipynb Defines a dictionary 'setup' with common plotting parameters for mplfinance, specifying the plot type, whether to include volume, and to return the figure object. ```python setup = dict(type='candle',volume=True,returnfig=True) ``` -------------------------------- ### Define Plotting Setup Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/issues/issue171_widths.ipynb Defines a dictionary `setup` to configure plotting parameters for mplfinance. This includes plot type, volume display, figure scaling, and moving averages. ```python setup = dict(type='candle',volume=True,figscale=0.8,mav=(10,20,30)) ``` -------------------------------- ### Display mplfinance Version and File Path Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/issues/issue236_timezone_bug.ipynb Prints the version and file path of the installed mplfinance library. This is useful for debugging and verifying the library's installation. ```python print(fplt.__version__,fplt.__file__) ``` -------------------------------- ### Example Output of Calculated Values Source: https://github.com/matplotlib/mplfinance/wiki/Access-to-mplfinance-Calculated-Values This is an example of the data structure that mplfinance populates into the dictionary passed to `return_calculated_values`. It includes moving averages (mav8, mav20, mav30), min/max values, and specific data like 'renko_bricks'. ```text { 'mav20': array([ nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 119.75656377, 118.96970631, 118.37956322, 117.78942013, 117.19927704, 116.60913394, 116.01899085, 115.62556212, 115.42884776, 115.42884776, 115.62556212, 116.01899085, 116.41241958, 116.80584831, 117.19927704, 117.59270576, 117.98613449, 118.37956322, 118.57627759, 118.57627759, 118.57627759, 118.77299195, 118.96970631, 119.36313504, 119.75656377, 120.34670686, 121.13356432, 121.92042178, 122.70727924, 123.49413669, 124.28099415, 125.06785161, 125.85470906, 126.64156652, 127.23170961, 127.82185271, 128.4119958 , 128.80542453, 129.19885326, 129.78899635, 130.57585381]), 'mav30': array([ nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, 118.1172774 , 117.72384867, 117.46156285, 117.33041995, 117.33041995, 117.33041995, 117.33041995, 117.46156285, 117.59270576, 117.72384867, 117.85499158, 118.1172774 , 118.37956322, 118.64184904, 118.77299195, 119.03527777, 119.4287065 , 119.82213523, 120.21556395, 120.60899268, 121.13356432, 121.78927887, 122.44499342, 123.23185087, 124.01870833, 124.80556579, 125.59242325, 126.24813779, 126.77270943, 127.29728107, 127.82185271]), 'mav8': array([ nan, nan, nan, nan, nan, nan, nan, 125.06785161, 123.10070796, 121.13356432, 119.16642068, 117.69106295, 116.70749112, 116.21570521, 115.7239193 , 115.23213339, 115.23213339, 115.7239193 , 116.70749112, 117.19927704, 117.19927704, 117.19927704, 117.19927704, 117.19927704, 116.70749112, 115.7239193 , 114.74034748, 114.24856157, 114.24856157, 114.24856157, 114.74034748, 115.7239193 , 117.19927704, 119.16642068, 120.64177841, 121.62535023, 122.60892205, 123.10070796, 123.10070796, 122.60892205, 122.11713614, 121.62535023, 121.62535023, 121.62535023, 121.62535023, 122.11713614, 123.10070796, 124.5760657 , 126.05142343, 127.52678116, 129.00213889, 130.96928254, 132.93642618, 134.41178391, 135.39535573, 135.88714164, 135.88714164, 135.39535573, 134.90356982, 134.41178391]), 'maxx': 59.983333333333334, 'maxy': 141.78857257142855, 'minx': -0.9833333333333333, 'miny': 110.3142742857142, 'renko_bricks': [ 131.95285435714285, 129.98571071428572, 128.01856707142858, 126.05142342857143, 124.08427978571427, 122.11713614285712, 120.14999249999997, 118.18284885714282, 116.21570521428566, 114.24856157142851, 112.28141792857136, 114.24856157142851, 116.21570521428566, 118.18284885714282, 116.21570521428566, 114.24856157142851, 116.21570521428566, 118.18284885714282, 120.14999249999997, 118.18284885714282, ] ``` -------------------------------- ### Adjust Color Brightness Example Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/macd_color_issue594.ipynb Demonstrates adjusting the brightness of black ('k') by adding an amount to its RGB components. ```python #c = [int(v*255) for v in mc.to_rgb('blue')] adj = 0.6 c = [min(1.0,v+adj) for v in mc.to_rgb('k')] c ``` -------------------------------- ### Print pandas and mplfinance Versions Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/issues/Issue77_test.ipynb Outputs the installed versions of the pandas and mplfinance libraries. This is useful for debugging compatibility issues. ```python print(pd.__version__) print(mpf.__version__) ``` -------------------------------- ### Plot Financial Data with mplfinance Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/dev_scale_padding.ipynb Import mplfinance and plot a DataFrame. This example shows a basic plot without custom scale padding. ```python import mplfinance as mpf mpf.__version__ #mpf.plot(df,volume=True,scale_padding=dict(left=0.1,right=0.05),tight_layout=True) mpf.plot(df,volume=True,tight_layout=True) ``` -------------------------------- ### Import Libraries Source: https://github.com/matplotlib/mplfinance/blob/master/examples/indicators/golden_cross.ipynb Import necessary libraries for data manipulation and plotting. Ensure pandas, mplfinance, and numpy are installed. ```python import pandas as pd import mplfinance as mpf import numpy as np ``` -------------------------------- ### Plotting with Multiple External Axes (Example 2) Source: https://github.com/matplotlib/mplfinance/blob/master/examples/external_axes.ipynb Set up a figure with three subplots, sharing the x-axis for two of them. This example demonstrates plotting multiple addplots on different external axes, including OHLC data and Bollinger Bands. ```python %%capture fig = mpf.figure(style='charles',figsize=(7,8)) ax1 = fig.add_subplot(3,1,1) ax2 = fig.add_subplot(3,1,2,sharex=ax1) ax3 = fig.add_subplot(3,1,3) ``` ```python ap = [ mpf.make_addplot(df,type='ohlc',ax=ax2,ylabel='OHLC Price'), mpf.make_addplot(df[['UpperB','LowerB']],ax=ax1) ] mpf.plot(df,ax=ax1,volume=ax3,addplot=ap,xrotation=10,type='candle') ``` ```python fig ``` -------------------------------- ### Define Plotting Setup Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/widths_so75526312.ipynb Defines a dictionary for common plotting parameters, including plot type, volume display, and moving averages. ```python setup = dict(type='candle',volume=True,mav=(7,15,22)) ``` -------------------------------- ### Create a Simple Point and Figure Chart Source: https://github.com/matplotlib/mplfinance/blob/master/examples/price-movement_plots.ipynb Use `type='pnf'` (or `type='p&f'`, `type='pointnfigure'`) to generate a Point and Figure chart. This example uses default parameters. ```python mpf.plot(daily,type='pnf') ``` -------------------------------- ### Specify Marketcolors with RGBA (0-255) Source: https://github.com/matplotlib/mplfinance/blob/master/examples/marketcolor_overrides.ipynb Similar to the previous example, this demonstrates using `mpf.make_marketcolors` with RGBA values for 'up' specified as integers between 0 and 255. The `marketcolor_overrides` parameter is used to apply these settings. ```python # =================================================================================== # Here we specify `up` as rgba using the convention that rgb are ints from 0 and 255 : mc = mpf.make_marketcolors(base_mpf_style='yahoo',up=(178,255,178,0.4),down='fuchsia', edge={'up':'blue','down':'#000000'},wick='#cc6600') mco = [None,None,mc,mc,None] mpf.plot(df,volume=True,style='yahoo',type='candle',marketcolor_overrides=mco) ``` -------------------------------- ### Basic mplfinance Plotting Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/check_use_cases.ipynb A basic example of plotting financial data with mplfinance. It sets up plotting parameters and then calls the mpf.plot function. ```python figscale = 1.0 setup = dict(type='candle',volume=True,mav=(10,40),returnfig=True) # #num = 240 # for num in range(30,241,30): # for s in styles: # # w = dict(vol_width=0.65 ,vol_linewidth=0.65, # # candle_width=.312 ,candle_linewidth=0.438, # # ohlc_ticksize=0.35 ,ohlc_linewidth=0.525) # f,a = mpf.plot(data[num],**setup,figscale=figscale, style=s, title=s) # # w = dict(vol_width=0.6 ,vol_linewidth=0.65, # # candle_width=.285 ,candle_linewidth=0.376, # # ohlc_ticksize=0.35 ,ohlc_linewidth=0.525) # #f,a = mpf.plot(data[num],**setup,figscale=figscale, style=s, title=s) ``` ```python f,a = mpf.plot(data[70],**setup,figscale=figscale) ``` -------------------------------- ### List Files in Directory Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/stackoverflow.65487952.ipynb Lists files in the current directory that start with 'a'. Useful for verifying saved plot files. ```bash ls -l a* ``` -------------------------------- ### Inspect mplfinance File Path Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/rcParams.ipynb Retrieve the file path of the installed mplfinance library. This can be helpful for debugging or understanding library location. ```python mpf.__file__ ``` -------------------------------- ### Initialize an empty list for OHLC data Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/issues/issue94.ipynb Use this to start collecting Open, High, Low, Close data points before creating a DataFrame. ```python ohlc = [] ``` -------------------------------- ### Example of Formatted mplfinance Style Output Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/external_axes_stacking.ipynb Displays the formatted output of an mplfinance style dictionary, showing how it would appear after being processed by the printing script. This includes the 'style = dict(...)' format and the command to write the style to a file. ```python style = dict( style_name = 'kenan', base_mpl_style = 'seaborn-darkgrid', marketcolors = { 'candle': {'up': 'k', 'down': 'r'}, 'edge': {'up': 'k', 'down': 'r'}, 'wick': {'up': 'k', 'down': 'r'}, 'ohlc': {'up': 'k', 'down': 'k'}, 'volume': {'up': '#1f77b4', 'down': '#1f77b4'}, 'vcedge': {'up': '#1f77b4', 'down': '#1f77b4'}, 'vcdopcod': False, 'alpha': 0.9, 'hollow': 'w'}, mavcolors = [ '#40e0d0', '#ff00ff', '#ffd700', '#1f77b4', '#ff7f0e', '#2ca02c', '#e377c2'], y_on_right = False, gridcolor = None, gridstyle = None, facecolor = '#DCE3EF', rc = [ ('axes.edgecolor', 'black'), ('axes.linewidth', 1.5), ('axes.labelsize', 'large'), ('axes.labelweight', 'semibold'), ('lines.linewidth', 2.0), ('font.weight', 'medium'), ('font.size', 12.0)], base_mpf_style = 'default') mpf.write_style_file(s,"kenan.py") ``` -------------------------------- ### Importing Old API Methods in mplfinance Source: https://github.com/matplotlib/mplfinance/blob/master/README.md To use methods from the older mpl-finance package with the new mplfinance installation, import them from the mplfinance.original_flavor module. This allows for a gradual transition to the new API. ```python from mpl_finance import ``` ```python from mplfinance.original_flavor import ``` ```python from mplfinance.original_flavor import candlestick_ohlc ``` -------------------------------- ### Get Width Configuration with return_width_config Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/widths_so75526312.ipynb Use `return_width_config` with an empty dictionary to retrieve the current width configuration values. This is useful for understanding default settings or for debugging. ```python import pprint as pp setup=dict(type='candle',volume=True,figscale=0.75) wconfig = {} mpf.plot(df.iloc[0:80],**setup,return_width_config=wconfig) pp.pprint(wconfig) wconfig={} mpf.plot(df.iloc[0:80],**setup,return_width_config=wconfig,show_nontrading=True) pp.pprint(wconfig) ``` -------------------------------- ### Multi-color fill_between for Both Panels Source: https://github.com/matplotlib/mplfinance/blob/master/examples/fill_between.ipynb Extends the multi-color fill_between concept to both the main price panel and the volume panel. This example fills between Open and Close prices in the main panel and uses conditional fills for the volume panel. ```python print(''' Here, as an additional example, we create "multi-color" fill_between for both panels: ''') fbvolume_above = dict(y1=daily['Volume'].values, y2=daily['Volume'].mean(), alpha=0.4, color='lime', interpolate=True, where=(daily['Volume'] > daily['Volume'].mean()).values) fbvolume_below = fbvolume_above.copy() fbvolume_below['color'] = 'magenta' fbvolume_below['where'] = (daily['Volume'] < daily['Volume'].mean()).values avol = [daily['Volume'].mean()]*len(daily) ap = mpf.make_addplot(avol,panel=1,fill_between=[fbvolume_above,fbvolume_below],color='k',linestyle='-.',width=0.25) fbclose_above = dict(y1=daily['Open'].values , y2=daily['Close'].values , alpha=0.4, interpolate=True, color='lime', where=(daily['Close']>daily['Open']).values ) fbclose_below = fbclose_above.copy() fbclose_below['color'] = 'magenta' fbclose_below['where'] = (daily['Close']", line 1\n stop here\n ^\nSyntaxError: invalid syntax ``` -------------------------------- ### Import Libraries Source: https://github.com/matplotlib/mplfinance/blob/master/examples/indicators/donchian_channel.ipynb Import pandas for data manipulation and mplfinance for plotting. ```python import pandas as pd import mplfinance as mpf ``` -------------------------------- ### Load and Prepare Data Source: https://github.com/matplotlib/mplfinance/blob/master/examples/indicators/donchian_channel.ipynb Read stock data from a CSV file, set the index to Date, and select the last 200 records. This prepares the DataFrame for plotting. ```python # Read in daily data for the S&P 500 from November of 2019 idf = pd.read_csv('../data/yahoofinance-INTC-19950101-20040412.csv',index_col=0,parse_dates=True).tail(200) df = idf.copy() df.index.name = 'Date' df.shape df.head(2) df.tail(2) ``` -------------------------------- ### Get Type of rcParam Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/rcParams.ipynb Determines and prints the data type of a specific rcParam, in this case, 'grid.linestyle'. Helps understand what kind of value is expected. ```python type(mpl.rcParams['grid.linestyle']) ``` -------------------------------- ### Import Matplotlib and Set Backend Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/issues/Issue77_test.ipynb Imports the matplotlib.pyplot module and sets the backend to 'inline' for displaying plots directly within a notebook. The '%matplotlib qt' line is commented out, indicating it's not currently active. ```python #%matplotlib qt %matplotlib inline import matplotlib.pyplot as plt ``` -------------------------------- ### Get Alternative Reference Image Histogram Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/test_plot_image_comparison.ipynb Calculates the histogram for an alternative reference PIL Image object. This is used in RMS calculations for comparison. ```python h1rt = img01reft.histogram() ``` -------------------------------- ### Get Bounding Box of Image Differences Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/test_plot_image_comparison.ipynb Retrieves the bounding box of the differing regions in a PIL Image object. Returns None if there are no differences. ```python diff.getbbox() ``` -------------------------------- ### Import Libraries and Initialize Plotting Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/issues/issue568_pnf_calcs.ipynb Imports necessary libraries including pandas for data manipulation, mplfinance for plotting, and numpy. It also sets up a pretty printer for displaying complex data structures. ```python %matplotlib inline import pandas as pd import mplfinance as mpf import numpy as np from matplotlib import ticker import pprint pp = pprint.PrettyPrinter(indent=2) ``` -------------------------------- ### Display Saved Image Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/macd_and_widths.ipynb Opens a saved plot image file ('tight.png') using Pillow and displays it using Matplotlib. Requires Pillow and Matplotlib to be installed. ```python from PIL import Image im = Image.open('tight.png') import matplotlib.pyplot as plt def plotimg(im): fig,ax = plt.subplots() ax.set_axis_off() ax.imshow(im) plt.show() plotimg(im) ``` -------------------------------- ### Prepare data for multiple addplot configurations Source: https://github.com/matplotlib/mplfinance/blob/master/examples/addplot.ipynb Prepare data for multiple additional plots, including signals derived from custom functions and existing DataFrame columns. Assumes `percentB_belowzero` is defined elsewhere. ```python low_signal = percentB_belowzero(df['PercentB'], df['Close']) high_signal = percentB_aboveone(df['PercentB'], df['Close']) ``` -------------------------------- ### Generate date pairs for trend lines Source: https://github.com/matplotlib/mplfinance/blob/master/examples/using_lines.ipynb Creates pairs of consecutive dates from a list of dates. These pairs define the start and end points for trend lines. ```python # now generate a sequence of date pairs: datepairs = [(d1,d2) for d1,d2 in zip(dates,dates[1:])] datepairs ``` -------------------------------- ### Plot Basic OHLC and Candlestick Charts Source: https://github.com/matplotlib/mplfinance/blob/master/examples/resample10years.ipynb Plots a basic candlestick chart with volume using the loaded daily stock data. Requires the mplfinance library to be installed. ```python import mplfinance as mpf mpf.__version__ mpf.plot(df,volume=True,type='candle') ``` -------------------------------- ### Initialize Pretty Printer Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/mpl.zorderaxes.ipynb Initializes a PrettyPrinter object from the pprint module for formatted output of complex data structures. ```python import pprint\npp = pprint.PrettyPrinter(indent=4) ``` -------------------------------- ### Adding Subplots with Different Styles Source: https://github.com/matplotlib/mplfinance/blob/master/examples/scratch_pad/dev_external_axes.ipynb Adds multiple subplots to an existing figure, each with a distinct mplfinance style. This setup is useful for comparing different chart styles side-by-side. ```python s = mpf.make_mpf_style(base_mpl_style='fast',base_mpf_style='nightclouds') ax1 = mpf.add_subplot(2,2,1,fig=fig,style='blueskies') ax2 = mpf.add_subplot(2,2,2,fig=fig,style='yahoo') ax3 = mpf.add_subplot(2,2,3,fig=fig,style=s) ax4 = mpf.add_subplot(2,2,4,fig=fig,style='starsandstripes') ```