### Install finplot via pip Source: https://github.com/highfestiva/finplot/blob/master/README.md Use this command to install the library in your Python environment. ```bash $ pip install finplot ``` -------------------------------- ### Advanced Financial Charting with Bittrex Data Source: https://github.com/highfestiva/finplot/wiki/Examples This example demonstrates pulling cryptocurrency data from Bittrex, formatting it, and plotting various financial indicators like candlesticks, volume, moving averages, and custom markers. ```python import finplot as fplt import numpy as np import pandas as pd import requests # pull some data symbol = 'USDT-BTC' url = 'https://bittrex.com/Api/v2.0/pub/market/GetTicks?marketName=%s&tickInterval=fiveMin' % symbol data = requests.get(url).json() # format it in pandas df = pd.DataFrame(data['result']) df = df.rename(columns={'T':'time', 'O':'open', 'C':'close', 'H':'high', 'L':'low', 'V':'volume'}) df = df.astype({'time':'datetime64[ns]'}) # create two axes ax,ax2 = fplt.create_plot(symbol, rows=2) # plot candle sticks candles = df[['time','open','close','high','low']] fplt.candlestick_ochl(candles, ax=ax) # overlay volume on the top plot volumes = df[['time','open','close','volume']] fplt.volume_ocv(volumes, ax=ax.overlay()) # put an MA on the close price fplt.plot(df['time'], df['close'].rolling(25).mean(), ax=ax, legend='ma-25') # place some dumb markers on low wicks lo_wicks = df[['open','close']].T.min() - df['low'] df.loc[(lo_wicks>lo_wicks.quantile(0.99)), 'marker'] = df['low'] fplt.plot(df['time'], df['marker'], ax=ax, color='#4a5', style='^', legend='dumb mark') # draw some random crap on our second plot fplt.plot(df['time'], np.random.normal(size=len(df)), ax=ax2, color='#927', legend='stuff') fplt.set_y_range(-1.4, +3.7, ax=ax2) # hard-code y-axis range limitation # restore view (X-position and zoom) if we ever run this example again fplt.autoviewrestore() # we're done fplt.show() ``` -------------------------------- ### Create Volume Bar Charts Source: https://context7.com/highfestiva/finplot/llms.txt Creates volume bar charts colored by price movement. Requires columns: time, open, close, volume. This example demonstrates plotting candlesticks and volume bars on a two-panel chart. ```python import finplot as fplt import pandas as pd import numpy as np # Sample data with OHLCV df = pd.DataFrame({ 'time': pd.date_range('2023-01-01', periods=50, freq='D'), 'open': np.random.uniform(100, 110, 50), 'close': np.random.uniform(100, 110, 50), 'high': np.random.uniform(110, 120, 50), 'low': np.random.uniform(90, 100, 50), 'volume': np.random.uniform(1e6, 5e6, 50) }) # Create two-panel chart ax, ax_vol = fplt.create_plot('Price with Volume', rows=2) # Plot candlesticks fplt.candlestick_ochl(df[['time', 'open', 'close', 'high', 'low']], ax=ax) # Plot volume bars (colored by price direction) fplt.volume_ocv(df[['time', 'open', 'close', 'volume']], ax=ax_vol, candle_width=0.8) fplt.show() ``` -------------------------------- ### Configure Dark Mode and Custom Themes in Finplot Source: https://context7.com/highfestiva/finplot/llms.txt This example shows how to customize the appearance of finplot charts by setting global color variables before creating any plots. It demonstrates implementing a dark mode theme with specific colors for foreground, background, candles, and volume bars. Requires finplot, pandas, and numpy imports. ```python import finplot as fplt import pandas as pd import numpy as np # Set dark mode colors BEFORE creating plot fplt.foreground = '#ddd' fplt.background = '#1a1a2e' fplt.odd_plot_background = '#16213e' fplt.candle_bull_color = '#26a69a' fplt.candle_bear_color = '#ef5350' fplt.candle_bull_body_color = '#26a69a' fplt.volume_bull_color = '#26a69a88' fplt.volume_bear_color = '#ef535088' fplt.cross_hair_color = '#ffffff88' fplt.draw_line_color = '#ffffff' # Sample data df = pd.DataFrame({ 'time': pd.date_range('2023-01-01', periods=100, freq='D'), 'open': 100 + np.cumsum(np.random.randn(100) * 0.5), 'close': 100 + np.cumsum(np.random.randn(100) * 0.5), 'high': 105 + np.cumsum(np.random.randn(100) * 0.5), 'low': 95 + np.cumsum(np.random.randn(100) * 0.5), 'volume': np.random.uniform(1e6, 5e6, 100) }) # Create plot (dark theme applied) ax, ax_vol = fplt.create_plot('Dark Mode Chart', rows=2) fplt.candlestick_ochl(df[['time', 'open', 'close', 'high', 'low']], ax=ax) fplt.volume_ocv(df[['time', 'open', 'close', 'volume']], ax=ax_vol) fplt.show() ``` -------------------------------- ### Draw Line Charts and Scatter Markers Source: https://context7.com/highfestiva/finplot/llms.txt Draws line charts with configurable style, color, width, and optional legend. Supports scatter markers using style symbols like 'o', '^', 'v'. This example plots price, moving averages, and buy signals. ```python import finplot as fplt import pandas as pd import numpy as np # Create sample price data dates = pd.date_range('2023-01-01', periods=200, freq='D') prices = pd.Series(100 + np.cumsum(np.random.randn(200) * 0.5)) # Calculate moving averages sma_20 = prices.rolling(20).mean() sma_50 = prices.rolling(50).mean() # Create plot fplt.create_plot('Moving Averages Example') # Plot price and moving averages with different styles fplt.plot(dates, prices, color='#000', width=1, legend='Price') fplt.plot(dates, sma_20, color='#2196F3', width=2, legend='SMA 20', style='-') fplt.plot(dates, sma_50, color='#FF5722', width=2, legend='SMA 50', style='--') # Plot buy signals as scatter markers buy_signals = prices[prices < sma_20 - 2] fplt.plot(dates[buy_signals.index], buy_signals, color='#4CAF50', style='^', legend='Buy Signal') fplt.show() ``` -------------------------------- ### Create Renko Charts with Finplot Source: https://context7.com/highfestiva/finplot/llms.txt This example demonstrates how to generate Renko charts using finplot. Renko charts filter out market noise by focusing only on price movements that exceed a specified threshold. You can define the brick size using either the number of price levels (`bins`) or a fixed price movement (`step`). Requires finplot, pandas, and numpy. ```python import finplot as fplt import pandas as pd import numpy as np # Sample price data dates = pd.date_range('2023-01-01', periods=500, freq='h') prices = pd.Series(100 + np.cumsum(np.random.randn(500) * 0.3)) # Create Renko chart # bins: number of price buckets, or step: fixed price movement per brick fplt.create_plot('Renko Chart') fplt.renko(dates, prices, bins=50) # 50 price levels # Alternative: fplt.renko(dates, prices, step=0.5) # Each brick = $0.50 move fplt.show() ``` -------------------------------- ### Enable View Persistence in Finplot Charts Source: https://context7.com/highfestiva/finplot/llms.txt This example demonstrates how to enable view persistence for finplot charts using `autoviewrestore()`. This function saves the current zoom and pan position of the chart and restores it the next time the application runs, providing a seamless user experience. Requires finplot, pandas, and numpy. ```python import finplot as fplt import pandas as pd import numpy as np # Sample data df = pd.DataFrame({ 'time': pd.date_range('2020-01-01', periods=1000, freq='D'), 'open': 100 + np.cumsum(np.random.randn(1000) * 0.5), 'close': 100 + np.cumsum(np.random.randn(1000) * 0.5), 'high': 105 + np.cumsum(np.random.randn(1000) * 0.5), 'low': 95 + np.cumsum(np.random.randn(1000) * 0.5) }) # Enable view persistence - saves zoom position to ~/.finplot/ fplt.autoviewrestore() # Create and display chart fplt.create_plot('Persistent View Chart') fplt.candlestick_ochl(df[['time', 'open', 'close', 'high', 'low']]) fplt.show() # Zoom position saved on close, restored on next run ``` -------------------------------- ### Implement Real-time Updates Source: https://context7.com/highfestiva/finplot/llms.txt Uses the live helper and timer_callback to stream and visualize market data updates. ```python import finplot as fplt import pandas as pd import numpy as np # Initial data df = pd.DataFrame({ 'time': pd.date_range('2023-01-01', periods=100, freq='min'), 'open': 100 + np.cumsum(np.random.randn(100) * 0.1), 'close': 100 + np.cumsum(np.random.randn(100) * 0.1), 'high': 102 + np.cumsum(np.random.randn(100) * 0.1), 'low': 98 + np.cumsum(np.random.randn(100) * 0.1) }) # Create plot with live helper ax = fplt.create_plot('Real-time Chart') live_candles = fplt.live() live_candles.candlestick_ochl(df[['time', 'open', 'close', 'high', 'low']], ax=ax) def update_data(): global df # Simulate new data new_row = { 'time': df.time.iloc[-1] + pd.Timedelta(minutes=1), 'open': df.close.iloc[-1], 'close': df.close.iloc[-1] + np.random.randn() * 0.2, 'high': df.close.iloc[-1] + abs(np.random.randn() * 0.3), 'low': df.close.iloc[-1] - abs(np.random.randn() * 0.3) } df = pd.concat([df, pd.DataFrame([new_row])], ignore_index=True) # Update the plot live_candles.candlestick_ochl(df[['time', 'open', 'close', 'high', 'low']]) # Update every second fplt.timer_callback(update_data, 1.0) fplt.show() ``` -------------------------------- ### Add Labels and Text Annotations Source: https://context7.com/highfestiva/finplot/llms.txt Shows how to place dynamic labels at specific coordinates using labels() and static text annotations using add_text(). ```python import finplot as fplt import pandas as pd import numpy as np # Sample data with significant events dates = pd.date_range('2023-01-01', periods=50, freq='D') prices = pd.Series(100 + np.cumsum(np.random.randn(50) * 1.5)) # Identify local maxima for labels peaks = prices[(prices.shift(1) < prices) & (prices.shift(-1) < prices)] # Create label data (time, y-position, label text) label_df = pd.DataFrame({ 'time': dates[peaks.index], 'price': peaks.values + 1, # Offset above the peak 'label': ['High' for _ in peaks] }) # Create plot fplt.create_plot('Chart with Labels') # Plot price fplt.plot(dates, prices, legend='Price') # Add dynamic labels at peaks fplt.labels(label_df['time'], label_df['price'], label_df['label'], color='#ff0000', anchor=(0.5, 1)) # Add static text annotation fplt.add_text((dates[25], prices.max()), 'Important Level', color='#0000ff', anchor=(0, 0)) fplt.show() ``` -------------------------------- ### Verify Cached Data Source: https://github.com/highfestiva/finplot/wiki/Tutorial-1 Run the download script and inspect the resulting CSV file content. ```bash $ python download.py [*********************100%***********************] 1 of 1 completed $ head cache.csv Date,Open,High,Low,Close,Adj Close,Volume 2014-04-30,26.635000228881836,26.729999542236328,26.489999771118164,26.729999542236328,25.87717056274414,24800 2014-05-01,26.683500289916992,26.683500289916992,26.59000015258789,26.594999313354492,25.746477127075195,13800 2014-05-02,26.125,26.229999542236328,26.059999465942383,26.1200008392334,25.28663444519043,38600 2014-05-05,25.78499984741211,26.29400062561035,25.56999969482422,26.264999389648438,25.4270076751709,429000 2014-05-06,25.8799991607666,26.03499984741211,25.760000228881836,25.975000381469727,25.14626121520996,100200 2014-05-07,25.915000915527344,26.065000534057617,25.75749969482422,25.822500228881836,24.998626708984375,75800 2014-05-08,26.104999542236328,26.2450008392334,25.969999313354492,26.0,25.170461654663086,93000 2014-05-09,25.940000534057617,25.94499969482422,25.264999389648438,25.450000762939453,24.638011932373047,101200 2014-05-12,25.94499969482422,25.9950008392334,25.399999618530273,25.454999923706055,24.642850875854492,42800 ``` -------------------------------- ### Restore zoom state at startup Source: https://github.com/highfestiva/finplot/wiki/Snippets Enable automatic saving and restoring of the zoom position when opening and closing the plot window. ```python # By default finplot shows all or a subset of your time series at startup. To store/restore zoom position: fplt.autoviewrestore() fplt.show() # will load zoom when showing, and save zoom when closing ``` -------------------------------- ### Download and Cache Financial Data Source: https://github.com/highfestiva/finplot/wiki/Tutorial-1 Use yfinance to fetch stock data and save it to a local CSV file. ```python import yfinance as yf df = yf.download('VWAGY', '2014-05-01') # Wolksvagen df.to_csv('cache.csv') ``` -------------------------------- ### Configure Finplot Global Settings Source: https://github.com/highfestiva/finplot/wiki/Settings Adjust library behavior such as decimal precision, axis padding, and zoom constraints. ```python significant_decimals = 8 # how many digits to show significant_eps = 1e-8 # default Y-step max_zoom_points = 20 # number of visible candles when maximum zoomed in axis_height_factor = {0: 2} # top axis is twice as tall as the others clamp_grid = True # clamp crosshair by default, press g to toggle right_margin_candles = 5 # whitespace at the right-hand side side_margin = 0.5 # show half a period on each side of the center of a candle lod_candles = 3000 # when to start sampling candles lod_labels = 700 # when to start sampling candles cache_candle_factor = 3 # factor extra candles rendered to buffer y_pad = 0.03 # 3% padding at top and bottom of autozoom plots y_label_width = 65 # Y-axis width long_time = 2*365*24*60*60*1e9 # when X-axis skips over to showing years display_timezone = None # default to local winx,winy,winw,winh = 400,300,800,400 # (non-maximized) window positions ``` -------------------------------- ### Plot Daily Candlesticks with yfinance Source: https://github.com/highfestiva/finplot/wiki/Examples This snippet shows how to download daily stock data using yfinance and plot it as candlestick charts using finplot. ```python import finplot as fplt import yfinance df = yfinance.download('AAPL') fplt.candlestick_ochl(df[['Open', 'Close', 'High', 'Low']]) fplt.show() ``` -------------------------------- ### Plot Initialization and Control Source: https://github.com/highfestiva/finplot/wiki/API Functions for creating, displaying, and managing the lifecycle of a financial plot. ```APIDOC ## create_plot ### Description Initializes a new finance plot. ### Parameters - **title** (str) - Optional - Plot title - **rows** (int) - Optional - Number of rows - **init_zoom_periods** (float) - Optional - Initial zoom periods - **maximize** (bool) - Optional - Whether to maximize the window - **yscale** (str) - Optional - Y-axis scale type ## show ### Description Displays the plot. ### Parameters - **qt_exec** (bool) - Optional - Whether to execute the Qt event loop ## close ### Description Closes the current plot. ``` -------------------------------- ### Create Finplot Plot with Multiple Rows Source: https://context7.com/highfestiva/finplot/llms.txt Initializes the plotting window with configurable rows for multiple chart panels. Each row creates a separate axis sharing the same X-axis for synchronized zooming and panning. Requires yfinance for data download. ```python import finplot as fplt import pandas as pd import yfinance # Download sample data df = yfinance.download('AAPL', start='2023-01-01', end='2023-12-31') # Create a plot with 3 rows (price, volume, indicator) ax, ax_volume, ax_rsi = fplt.create_plot('AAPL Stock Analysis', rows=3) # Plot candlesticks on the main axis fplt.candlestick_ochl(df[['Open', 'Close', 'High', 'Low']], ax=ax) # Display the plot fplt.show() ``` -------------------------------- ### Play sound notification Source: https://github.com/highfestiva/finplot/wiki/Snippets Trigger a sound file playback using the built-in finplot sound utility. ```python fplt.play_sound('bot-happy.wav') # Ooh! Watch me - I just made a profit! ``` -------------------------------- ### Display Volume Profile Source: https://context7.com/highfestiva/finplot/llms.txt Displays horizontal volume distribution bars using horiz_time_volume to identify price levels with high trading activity. ```python import finplot as fplt import pandas as pd import numpy as np from collections import defaultdict # Sample OHLCV data df = pd.DataFrame({ 'time': pd.date_range('2023-01-01', periods=500, freq='h'), 'open': 100 + np.cumsum(np.random.randn(500) * 0.1), 'close': 100 + np.cumsum(np.random.randn(500) * 0.1), 'high': 102 + np.cumsum(np.random.randn(500) * 0.1), 'low': 98 + np.cumsum(np.random.randn(500) * 0.1), 'volume': np.random.uniform(1e4, 5e4, 500) }) df['hlc3'] = (df.high + df.low + df.close) / 3 # Calculate volume profile per day def calc_volume_profile(df, period='D', bins=20): data = [] _, all_bins = pd.cut(df.hlc3, bins, right=False, retbins=True) for _, g in df.groupby(pd.Grouper(key='time', freq=period)): if len(g) == 0: continue t = g.time.iloc[0] volbins = pd.cut(g.hlc3, all_bins, right=False) price2vol = defaultdict(float) for iv, vol in zip(volbins, g.volume): price2vol[iv.left] += vol data.append([t, sorted(price2vol.items())]) return data volume_profile = calc_volume_profile(df, period='D', bins=15) # Create plot fplt.create_plot('Price with Volume Profile') fplt.plot(df.time, df.close, legend='Price') fplt.horiz_time_volume(volume_profile, draw_va=0.7, draw_poc=1.0) fplt.show() ``` -------------------------------- ### Load and Print CSV Data with Pandas Source: https://github.com/highfestiva/finplot/wiki/Tutorial-1 Loads data from a CSV file into a pandas DataFrame and prints it. Ensure the CSV file is in the same directory or provide the full path. ```python import pandas as pd import finplot as fplt df = pd.read_csv('cache.csv') print(df) ``` -------------------------------- ### Render OHLC Candlestick Charts Source: https://context7.com/highfestiva/finplot/llms.txt Renders OHLC candlestick charts with customizable body and shadow drawing, and candle width. Data must be provided with columns in the order: time, open, close, high, low. ```python import finplot as fplt import pandas as pd # Prepare data with required column order: time, open, close, high, low data = { 'time': pd.date_range('2023-01-01', periods=100, freq='D'), 'open': [100 + i * 0.1 for i in range(100)], 'close': [101 + i * 0.12 for i in range(100)], 'high': [102 + i * 0.15 for i in range(100)], 'low': [99 + i * 0.08 for i in range(100)] } df = pd.DataFrame(data) # Create plot and draw candlesticks fplt.create_plot('Candlestick Example') fplt.candlestick_ochl(df[['time', 'open', 'close', 'high', 'low']], draw_body=True, draw_shadow=True, candle_width=0.6) fplt.show() ``` -------------------------------- ### Create OHLCV Chart with Volume Overlay Source: https://context7.com/highfestiva/finplot/llms.txt Generates a single-panel plot displaying candlestick data and an overlaid volume chart. ```python df = pd.DataFrame({ 'time': pd.date_range('2023-01-01', periods=100, freq='D'), 'open': 100 + np.cumsum(np.random.randn(100) * 0.5), 'close': 100 + np.cumsum(np.random.randn(100) * 0.5), 'high': 105 + np.cumsum(np.random.randn(100) * 0.5), 'low': 95 + np.cumsum(np.random.randn(100) * 0.5), 'volume': np.random.uniform(1e6, 5e6, 100) }) # Create single-panel plot ax = fplt.create_plot('Price with Volume Overlay') # Plot candlesticks on main axis fplt.candlestick_ochl(df[['time', 'open', 'close', 'high', 'low']], ax=ax) # Overlay volume on the same axis (scale=0.3 means volume takes 30% of vertical space) fplt.volume_ocv(df[['time', 'open', 'close', 'volume']], ax=ax.overlay(scale=0.3)) fplt.show() ``` -------------------------------- ### Plotting Primitives Source: https://github.com/highfestiva/finplot/wiki/API Functions for rendering various financial chart types and data visualizations. ```APIDOC ## candlestick_ochl ### Description Draws a candlestick chart. ### Parameters - **datasrc** (object) - Required - Data source - **draw_body** (bool) - Optional - Draw candle body - **draw_shadow** (bool) - Optional - Draw candle shadow - **candle_width** (float) - Optional - Width of the candle - **ax** (object) - Optional - Axis object - **colorfunc** (function) - Optional - Color filter function ## plot ### Description Draws a standard line plot. ### Parameters - **x** (array) - Required - X-axis data - **y** (array) - Optional - Y-axis data - **color** (str) - Optional - Line color - **width** (int) - Optional - Line width - **ax** (object) - Optional - Axis object ``` -------------------------------- ### Create Overlay Y-Axis Source: https://context7.com/highfestiva/finplot/llms.txt The ax.overlay() method creates a secondary Y-axis on the same chart panel, useful for overlaying volume on price or comparing different scales. ```python import finplot as fplt import pandas as pd import numpy as np ``` -------------------------------- ### Capture Chart Screenshots with Finplot Source: https://context7.com/highfestiva/finplot/llms.txt This snippet illustrates how to capture a screenshot of a finplot chart and save it to a file. It uses the `screenshot()` function, which writes the chart image to a file-like object. A timer callback is used to ensure the screenshot is taken after the chart has fully rendered. Requires finplot, pandas, and numpy. ```python import finplot as fplt import pandas as pd import numpy as np # Sample data dates = pd.date_range('2023-01-01', periods=100, freq='D') prices = pd.Series(100 + np.cumsum(np.random.randn(100) * 0.8)) fplt.create_plot('Chart for Screenshot') fplt.plot(dates, prices, legend='Price') def save_screenshot(): with open('chart_output.png', 'wb') as f: success = fplt.screenshot(f, fmt='png') print(f"Screenshot saved: {success}") # Use timer to save after rendering fplt.timer_callback(save_screenshot, 0.5, single_shot=True) fplt.show() ``` -------------------------------- ### Configure axis visibility and grid Source: https://github.com/highfestiva/finplot/wiki/Snippets Toggle visibility for crosshairs, axes, and grid lines on a specific axis object. ```python ax.set_visible(crosshair=False, xaxis=False, yaxis=True, xgrid=True, ygrid=True) ``` -------------------------------- ### Interactive Click Markers on Finplot Chart Source: https://context7.com/highfestiva/finplot/llms.txt This snippet demonstrates how to add interactive click markers to a finplot chart. It registers a callback function that is triggered on mouse clicks, allowing users to mark specific points on the chart with custom text and styles. Requires sample data and a plot to be created first. ```python import finplot as fplt import pandas as pd import numpy as np # Sample data dates = pd.date_range('2023-01-01', periods=100, freq='D') prices = pd.Series(100 + np.cumsum(np.random.randn(100) * 0.8)) # Create plot ax = fplt.create_plot('Click to Mark Points') fplt.plot(dates, prices, legend='Price') markers = [] def on_click(time, price): print(f"Clicked at time={time}, price={price:.2f}") # Add a marker at clicked position marker = fplt.add_text((time, price), 'X', color='#ff0000', anchor=(0.5, 0.5)) markers.append(marker) # Register click handler fplt.set_mouse_callback(on_click, ax=ax, when='click') # For double-click: when='dclick' # For right-click: when='rclick' # For hover: when='hover' fplt.show() ``` -------------------------------- ### Create Heatmap Visualization Source: https://context7.com/highfestiva/finplot/llms.txt Uses the heatmap function to visualize 2D matrix data such as order book depth or volume distribution. ```python import finplot as fplt import pandas as pd import numpy as np # Create sample heatmap data (time x price levels) times = pd.date_range('2023-01-01', periods=50, freq='h') price_levels = [100 + i * 0.5 for i in range(20)] # Random intensity values (e.g., order book depth) data = np.random.rand(50, 20) * 100 df = pd.DataFrame(data, index=times, columns=price_levels) # Create plot fplt.create_plot('Order Book Heatmap') # Plot heatmap fplt.heatmap(df, rect_size=0.9, filter_limit=0.1, whiteout=0.3) fplt.show() ``` -------------------------------- ### Create Interactive Lines and Shapes Source: https://context7.com/highfestiva/finplot/llms.txt Utilizes add_line, add_rect, and add_text with the interactive=True parameter to enable draggable annotations. ```python import finplot as fplt import pandas as pd import numpy as np # Sample data dates = pd.date_range('2023-01-01', periods=100, freq='D') prices = pd.Series(100 + np.cumsum(np.random.randn(100) * 0.8)) # Create plot fplt.create_plot('Interactive Annotations') fplt.plot(dates, prices, legend='Price') # Add a trend line (interactive - can be dragged) line = fplt.add_line( (dates[10], prices.iloc[10]), (dates[80], prices.iloc[80]), color='#9900ff', width=2, interactive=True ) # Add a rectangle region (interactive) rect = fplt.add_rect( (dates[30], prices.iloc[30:50].min()), (dates[50], prices.iloc[30:50].max()), color='#88cc8888', interactive=True ) # Add static text annotation text = fplt.add_text( (dates[60], prices.iloc[60]), 'Support Level', color='#bb7700' ) # To remove primitives later: fplt.remove_primitive(line) fplt.show() ``` -------------------------------- ### Configure background colors in finplot Source: https://github.com/highfestiva/finplot/wiki/Snippets Set custom background colors for even and odd rows before initializing the plot. ```python # finplot uses no background (i.e. white) on even rows and a slightly different color on odd rows. # Set your own before creating the plot. fplt.background = '#ff0' # yellow fplt.odd_plot_background = '#f0f' # purple fplt.plot(df.Close) fplt.show() ``` -------------------------------- ### Fill Area Between Plot Lines Source: https://context7.com/highfestiva/finplot/llms.txt Demonstrates using fill_between to shade the area between two lines, commonly used for visualizing Bollinger Bands. ```python import finplot as fplt import pandas as pd import numpy as np # Sample price data dates = pd.date_range('2023-01-01', periods=100, freq='D') prices = pd.Series(100 + np.cumsum(np.random.randn(100) * 0.5)) # Calculate Bollinger Bands sma = prices.rolling(20).mean() std = prices.rolling(20).std() upper_band = sma + 2 * std lower_band = sma - 2 * std # Create plot fplt.create_plot('Bollinger Bands') # Plot price fplt.plot(dates, prices, color='#000', legend='Price') # Plot bands p_upper = fplt.plot(dates, upper_band, color='#808080', legend='BB Upper') p_lower = fplt.plot(dates, lower_band, color='#808080') # Fill between bands fplt.fill_between(p_upper, p_lower, color='#bbbbbb') fplt.show() ``` -------------------------------- ### Customize Crosshair Info Source: https://context7.com/highfestiva/finplot/llms.txt Uses add_crosshair_info to inject custom data into the crosshair tooltip. ```python import finplot as fplt import pandas as pd import numpy as np # Sample data df = pd.DataFrame({ 'time': pd.date_range('2023-01-01', periods=100, freq='D'), 'open': 100 + np.cumsum(np.random.randn(100) * 0.5), 'close': 100 + np.cumsum(np.random.randn(100) * 0.5), 'high': 105 + np.cumsum(np.random.randn(100) * 0.5), 'low': 95 + np.cumsum(np.random.randn(100) * 0.5), 'volume': np.random.uniform(1e6, 5e6, 100) }) # Create plot ax = fplt.create_plot('Custom Crosshair') fplt.candlestick_ochl(df[['time', 'open', 'close', 'high', 'low']], ax=ax) # Custom crosshair info function def crosshair_info(x, y, xtext, ytext): idx = int(x + 0.5) if 0 <= idx < len(df): row = df.iloc[idx] ohlc = f"O:{row.open:.2f} H:{row.high:.2f} L:{row.low:.2f} C:{row.close:.2f}" return xtext, f"{ytext}\n{ohlc}" return xtext, ytext fplt.add_crosshair_info(crosshair_info, ax=ax) fplt.show() ``` -------------------------------- ### Set display time zone Source: https://github.com/highfestiva/finplot/wiki/Snippets Configure the display time zone for crosshairs and X-axis labels using dateutil or standard library timezone objects. ```python # Pandas normally reads datetimes in UTC time zone. # finplot by default use the local time zone of your computer (for crosshair and X-axis) from dateutil.tz import gettz fplt.display_timezone = gettz('Asia/Jakarta') # ... or in UTC = "display same as timezone-unaware data" import datetime finplot.display_timezone = datetime.timezone.utc ``` -------------------------------- ### finplot Public API Functions Source: https://github.com/highfestiva/finplot/wiki/API A collection of stable functions for creating, customizing, and managing financial plots. ```python def create_plot(title='Finance Plot', rows=1, init_zoom_periods=1e10, maximize=True, yscale='linear') def create_plot_widget(master, rows=1, init_zoom_periods=1e10, yscale='linear') def close() def price_colorfilter(item, datasrc, df) def volume_colorfilter(item, datasrc, df) def strength_colorfilter(item, datasrc, df) def volume_colorfilter_section(sections=[]) def horizvol_colorfilter(sections=[]) def candlestick_ochl(datasrc, draw_body=True, draw_shadow=True, candle_width=0.6, ax=None, colorfunc=price_colorfilter) def renko(x, y=None, bins=None, step=None, ax=None, colorfunc=price_colorfilter) def volume_ocv(datasrc, candle_width=0.8, ax=None, colorfunc=volume_colorfilter) def horiz_time_volume(datasrc, ax=None, **kwargs) def heatmap(datasrc, ax=None, **kwargs) def bar(x, y=None, width=0.8, ax=None, colorfunc=strength_colorfilter, **kwargs) def hist(x, bins, ax=None, **kwargs) def plot(x, y=None, color=None, width=1, ax=None, style=None, legend=None, zoomscale=True, **kwargs) def labels(x, y=None, labels=None, color=None, ax=None, anchor=(0.5,1)) def add_legend(text, ax=None) def fill_between(plot0, plot1, color=None) def set_x_pos(xmin, xmax, ax=None) def set_y_range(ymin, ymax, ax=None) def set_y_scale(yscale='linear', ax=None) def add_band(y0, y1, color=band_color, ax=None) def add_rect(p0, p1, color=band_color, interactive=False, ax=None) def add_line(p0, p1, color=draw_line_color, width=1, style=None, interactive=False, ax=None) def add_text(pos, s, color=draw_line_color, anchor=(0,0), ax=None) def remove_primitive(primitive) def set_time_inspector(inspector, ax=None, when='click') def add_crosshair_info(infofunc, ax=None) def timer_callback(update_func, seconds, single_shot=False) def autoviewrestore(enable=True) def refresh() def show(qt_exec=True) def play_sound(filename) def screenshot(file, fmt='png') ``` -------------------------------- ### Plot Candlestick Chart with Finplot Source: https://github.com/highfestiva/finplot/wiki/Tutorial-1 Generates and displays a candlestick chart using the 'Open', 'Close', 'High', and 'Low' columns from a pandas DataFrame. Ensure the DataFrame has a datetime index. ```python fplt.candlestick_ochl(df[['Open', 'Close', 'High', 'Low']]) fplt.show() ``` -------------------------------- ### Add secondary Y-axis to viewbox Source: https://github.com/highfestiva/finplot/wiki/Snippets Overlay a secondary Y-axis on an existing viewbox, specifying scale and axis type. ```python fplt.candlestick_ochl(df2[['Open','Close','High','Low']], ax=ax.overlay(scale=1.0, yaxis='linear')) ``` -------------------------------- ### Convert Date Column to Datetime Index Source: https://github.com/highfestiva/finplot/wiki/Tutorial-1 Converts the 'Date' column to datetime objects and then sets it as the DataFrame's index. This is crucial for time-series plotting. ```python df['Date'] = pd.to_datetime(df['Date']) df = df.set_index('Date') print(df) ``` -------------------------------- ### Manage Internal Finplot State Source: https://github.com/highfestiva/finplot/wiki/Settings Access variables that control the internal execution state, such as active windows, timers, and data tracking. ```python app = None # PyQt app windows = [] # holds all active windows timers = [] # holds all active timers sounds = {} # holds all active sounds epoch_period = 1e30 # default time between candles to something large last_ax = None # always assume we want to plot in the last axis, unless explicitly specified overlay_axs = [] # for keeping track of candlesticks in overlays viewrestore = False # controlled via autoviewrestore() master_data = {} # lookup if embedding in your own PyQt window ``` -------------------------------- ### Draw Horizontal Bands for Indicators Source: https://context7.com/highfestiva/finplot/llms.txt Uses add_horizontal_band to highlight specific price ranges, such as overbought or oversold zones in an RSI indicator. ```python import finplot as fplt import pandas as pd import numpy as np # Calculate RSI def calculate_rsi(prices, period=14): delta = prices.diff() gain = (delta.where(delta > 0, 0)).rolling(window=period).mean() loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean() rs = gain / loss return 100 - (100 / (1 + rs)) # Sample data dates = pd.date_range('2023-01-01', periods=100, freq='D') prices = pd.Series(100 + np.cumsum(np.random.randn(100) * 2)) rsi = calculate_rsi(prices) # Create RSI plot ax = fplt.create_plot('RSI with Bands') fplt.plot(dates, rsi, legend='RSI') # Add overbought/oversold bands fplt.add_horizontal_band(70, 100, color='#ffcccc', ax=ax) # Overbought zone fplt.add_horizontal_band(0, 30, color='#ccffcc', ax=ax) # Oversold zone # Set Y range for RSI fplt.set_y_range(0, 100, ax=ax) fplt.show() ``` -------------------------------- ### Display Specific Column Data Source: https://github.com/highfestiva/finplot/wiki/Tutorial-1 Prints the contents of the 'Date' column from a pandas DataFrame. This helps in inspecting the data type and format before conversion. ```python print(df['Date']) ``` -------------------------------- ### Decouple zoom and pan between axes Source: https://github.com/highfestiva/finplot/wiki/Snippets Disable the default synchronization of zoom and pan operations across different axes. ```python # finplot assumes all your axes are in the same time span. To decouple the zoom/pan link, use: ax2.decouple() ``` -------------------------------- ### Define Finplot Color Schemes Source: https://github.com/highfestiva/finplot/wiki/Settings Customize the visual appearance of charts, including legend colors, candle bodies, and volume indicators. ```python legend_border_color = '#777' legend_fill_color = '#6668' legend_text_color = '#ddd6' soft_colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'] hard_colors = ['#000000', '#772211', '#000066', '#555555', '#0022cc', '#ffcc00'] colmap_clash = ColorMap([0.0, 0.2, 0.6, 1.0], [[127, 127, 255, 51], [0, 0, 127, 51], [255, 51, 102, 51], [255, 178, 76, 51]]) foreground = '#000' background = '#fff' odd_plot_background = '#fff' candle_bull_color = '#26a69a' candle_bear_color = '#ef5350' candle_bull_body_color = background volume_bull_color = '#92d2cc' volume_bear_color = '#f7a9a7' volume_bull_body_color = volume_bull_color volume_neutral_color = '#bbb' poc_color = '#006' band_color = '#d2dfe6' cross_hair_color = '#0007' draw_line_color = '#000' draw_done_color = '#555' ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.