In partnership with

Where the smartest investors start their day

The Alternative Investing Report (A.I.R.) helps you get smarter on alternative assets from crypto treasury companies to Pre-IPO venture secondaries to private credit and more.

Join 100,000+ investors to get the latest insights and trends driving private markets, a weekly investment pick from a notable investor, and bonus offers to join top private market platforms and managers. And it’s totally free.

🚀 Your Investing Journey Just Got Better: Premium Subscriptions Are Here! 🚀

It’s been 4 months since we launched our premium subscription plans at GuruFinance Insights, and the results have been phenomenal! Now, we’re making it even better for you to take your investing game to the next level. Whether you’re just starting out or you’re a seasoned trader, our updated plans are designed to give you the tools, insights, and support you need to succeed.

Here’s what you’ll get as a premium member:

  • Exclusive Trading Strategies: Unlock proven methods to maximize your returns.

  • In-Depth Research Analysis: Stay ahead with insights from the latest market trends.

  • Ad-Free Experience: Focus on what matters most—your investments.

  • Monthly AMA Sessions: Get your questions answered by top industry experts.

  • Coding Tutorials: Learn how to automate your trading strategies like a pro.

  • Masterclasses & One-on-One Consultations: Elevate your skills with personalized guidance.

Our three tailored plans—Starter Investor, Pro Trader, and Elite Investor—are designed to fit your unique needs and goals. Whether you’re looking for foundational tools or advanced strategies, we’ve got you covered.

Don’t wait any longer to transform your investment strategy. The last 4 months have shown just how powerful these tools can be—now it’s your turn to experience the difference.

Have you ever wondered if there’s a way to know EXACTLY where a stock price stands within its normal trading range?

Well… there is. And it’s called Bollinger Band %B.

🤔 What Exactly IS Bollinger Band %B?

Picture this… You’re looking at a stock chart with those familiar Bollinger Bands — three lines dancing around the price. But here’s the problem: How do you quantify where the price is between those bands?

That’s where %B comes in. 🎯

Bollinger Band %B is a normalized indicator that tells the price’s position relative to the Bollinger Bands. Think of it as a measuring stick that always runs from 0 to 1 (or 0% to 100%).

  • %B = 1.0 (100%) → Price is at the upper band 📈

  • %B = 0.5 (50%) → Price is at the middle band (the moving average)

  • %B = 0.0 (0%) → Price is at the lower band 📉

Simple, right?

Kickstart your holiday campaigns

CTV should be central to any growth marketer’s Q4 strategy. And with Roku Ads Manager, launching high-performing holiday campaigns is simple and effective.

With our intuitive interface, you can set up A/B tests to dial in the most effective messages and offers, then drive direct on-screen purchases via the remote with shoppable Action Ads that integrate with your Shopify store for a seamless checkout experience.

Don’t wait to get started. Streaming on Roku picks up sharply in early October. By launching your campaign now, you can capture early shopping demand and be top of mind as the seasonal spirit kicks in.

Get a $500 ad credit when you spend your first $500 today with code: ROKUADS500. Terms apply.

🧮 The Magic Formula Behind %B

The calculation is surprisingly elegant:

%B = (Close - Lower Band) / (Upper Band - Lower Band)

Let me break this down…

The numerator (Close — Lower Band) tells you how far the price is from the lower band.

The denominator (Upper Band — Lower Band) is the total width of the bands.

Divide them, and you get a normalized value that shows the price’s relative position.

📐 Quick Example:

Let’s say:

  • Close Price: $155

  • Lower Band: $150

  • Upper Band: $160

%B = ($155 — $150) / ($160 — $150) = $5 / $10 = 0.5 or 50%

The price is right in the middle!

🤝 How %B Works WITH Bollinger Bands

Here’s where it gets interesting…

Traditional Bollinger Bands show the price action and volatility. But %B quantifies it. This means you can:

  1. Set precise entry/exit rules 📋

  2. Identify overbought/oversold conditions with numbers, not just eyeballing 👀

  3. Backtest strategies systematically

  4. Automate trading decisions based on clear thresholds

Think of Bollinger Bands as the map… and %B as your GPS coordinates. 🗺️

🎯 Creating Trading Signals with %B

Now for the exciting part… How do we actually TRADE with this?

The most popular approach uses threshold levels:

The Strategy 💰

BUY Signal (Oversold): When %B crosses above 0.2 (20%)

  • Why? The price has bounced from the lower regions and is showing momentum back up ↗️

SELL Signal (Overbought): When %B crosses below 0.8 (80%)

  • Why? The price has reached the upper regions and might be due for a pullback ↘️

This creates a mean reversion strategy… The bands expand and contract with volatility, but %B always keeps you oriented. 🧭

Ready to see this in action? Let me walk you through the complete implementation step by step…

Step 1: Setup and Data Collection

!pip install yfinance pandas numpy matplotlib vectorbt -q
import yfinance as yf
import pandas as pd
import numpy as np
import vectorbt as vbt
import warnings
warnings.filterwarnings('ignore')

We’re using:

  • yfinance → Download stock data 📥

  • pandas/numpy → Data manipulation 🔢

  • vectorbt → Lightning-fast backtesting ⚡

  • matplotlib → Visualizations 📊

Step 2: Download Stock Data

def get_clean_financial_data(ticker, start_date, end_date):
    print(f"\nDownloading data for {ticker}...")
    data = yf.download(ticker, start=start_date, end=end_date, progress=False)
    
    if data.empty:
        print(f"Error: No data found for ticker '{ticker}'")
        return None
    
    # Clean the data
    data.columns = data.columns.get_level_values(0) if isinstance(data.columns, pd.MultiIndex) else data.columns
    data = data.ffill()  # Forward fill missing values
    
    if data.index.tz is not None:
        data.index = data.index.tz_localize(None)
    
    return data

This function handles all the messy details of downloading and cleaning stock data. Forward filling ensures no gaps!

Step 3: Calculate Bollinger Bands

# Calculate 20-day Simple Moving Average
df['SMA_20'] = df['Close'].rolling(window=20).mean()

# Calculate 20-day Standard Deviation
df['STD_20'] = df['Close'].rolling(window=20).std()

# Upper Band = SMA + (2 × Standard Deviation)
df['Upper_Band'] = df['SMA_20'] + (df['STD_20'] * 2)

# Lower Band = SMA - (2 × Standard Deviation)
df['Lower_Band'] = df['SMA_20'] - (df['STD_20'] * 2)

The standard Bollinger Bands use:

  • 20-day period (industry standard)

  • 2 standard deviations (captures ~95% of price action) 📊

Step 4: Calculate %B (The Star of the Show!)

df['B%'] = (df['Close'] - df['Lower_Band']) / (df['Upper_Band'] - df['Lower_Band'])

This single line creates our %B indicator… Simple yet powerful! 💪

Business news as it should be.

Join 4M+ professionals who start their day with Morning Brew—the free newsletter that makes business news quick, clear, and actually enjoyable.

Each morning, it breaks down the biggest stories in business, tech, and finance with a touch of wit to keep things smart and interesting.

🚦 Step 5: Generate Trading Signals

# Entry: When %B crosses ABOVE 0.2 (oversold bounce)
entries = (df['B%'] > 0.2) & (df['B%'].shift(1) <= 0.2)

# Exit: When %B crosses BELOW 0.8 (overbought retreat)
exits = (df['B%'] < 0.8) & (df['B%'].shift(1) >= 0.8)

The .shift(1) compares today's value with yesterday's... This detects the crossover moment!

🔥 Step 6: Backtest with VectorBT

pf = vbt.Portfolio.from_signals(
    close=df['Close'],
    entries=entries,
    exits=exits,
    size=np.inf,        # Use all available capital
    fees=0.002,         # 0.2% trading fees
    slippage=0.001,     # 0.1% slippage
    freq='D',           # Daily frequency
    init_cash=10000     # Start with $10,000
)

VectorBT handles all the complex portfolio math:

  • Position sizing 💰

  • Fee calculations 🧾

  • Performance metrics 📊

  • Trade logging 📝

📝 Step 7: Format Trade Logs

The code includes a comprehensive format_trade_logs() function that transforms raw backtest data into readable trade logs showing:

  • Entry/Exit dates and prices 📅

  • Position sizes 📦

  • Fees paid 💳

  • Net profit/loss 💵

  • Portfolio value after each trade 📈

Transaction Log:
   Entry Date  Entry Price   Exit Date  Exit Price  Quantity  Entry Fees ($)  Exit Fees ($)  Total Fees ($)  Net PnL ($)  Return (%)  Portfolio Value ($)
0  2025-01-06       425.94  2025-01-27      431.75     23.43           19.96          20.23           40.19        55.88        0.96             10096.07
1  2025-01-31       413.20  2025-05-16      453.07     24.38           20.15          22.10           42.25       887.64        9.23             11025.96
2  2025-08-27       507.25  2025-09-16      508.53     21.69           22.01          22.06           44.07       -60.28       -0.15             11009.75

Step 8: Visualize Everything

The visualization shows:

  1. Top panel: Price with Bollinger Bands and entry/exit markers

  2. Bottom panel: The %B indicator with threshold levels 📏

🎮 Try It Yourself!

Want to run this code and test it with your own stocks?

👉 Access the full interactive notebook here: Bollinger Band %B Strategy on Google Colab

Just click the link, hit “Run All,” and watch the magic happen!

You can easily modify:

  • The ticker symbol (currently “MSFT”) 🏢

  • The time period (currently 1 year) 📆

  • The %B thresholds (0.2 and 0.8) 🎚️

  • The Bollinger Band parameters (20-day, 2 std dev) ⚙️

💭 Final Thoughts…

The stock market is complex… But tools like Bollinger Band %B help us make sense of the chaos. By normalizing price position, we gain clarity. By setting thresholds, we gain discipline. By backtesting, we gain confidence.

So go ahead… Download that Colab notebook. Run it. Tweak it. Break it. Learn from it.

Happy trading! 💰

Keep Reading

No posts found