โ† Back to list

๐Ÿจ Building Your Own Stock Market Index: Why, How, and a Real Example with Hotel Stocks

๐ŸŒŸ Introduction: Why Follow the Herd When You Can Lead It?

Manish Peshwani in InsiderFinance Wire ยท 2025-07-06 11:08 ยท 58 claps ยท 4.1 min read paywalled
#stock-market #python #finance #investing #custom-index
Open on Medium โ†—
Wiki topics: INV ยท Investing & Markets ECO ยท Economy ยท General โœˆ๏ธ ยท Travel

๐Ÿจ Building Your Own Stock Market Index: Why, How, and a Real Example with Hotel Stocks

๐ŸŒŸ Introduction: Why Follow the Herd When You Can Lead It?

We all follow stock indices โ€” NIFTY 50, SENSEX, NIFTY Next 50. But hereโ€™s the catch: these indices were built for broad benchmarking, not for personalised strategies or sector-specific insights.

What if youโ€™re bullish on the hospitality sector post-pandemic? What if you want to track only high-dividend PSU stocks, or your own ESG portfolio?

This is where Custom Indexing comes in.

In this article, weโ€™ll explore:

  • โœ… Why custom indices matter
  • โœ… How to build one from scratch
  • โœ… A Python-powered hotel stock index example
  • โœ… How you can use it in real-world investing

๐Ÿ’ก 1. Why Do We Need Custom Indices?

๐Ÿฆ Traditional Indices Are One-Size-Fits-All

Conventional indices reflect broad market movements. But investors often want sharper lenses:

  • ๐Ÿ“Š Track a specific sector (e.g., renewable energy, AI, hotels)
  • ๐Ÿ“ˆ Backtest custom strategies (e.g., GARP, momentum, dividend yield)
  • ๐Ÿง  Learn sector-specific behaviour (cyclicality, mean reversion, drawdowns)
  • ๐Ÿ“ Create better benchmarks for a personal portfolio or fund

๐Ÿง  Use-Cases for Custom Indexes:

  • Thematic Investing (hotels, green energy, EV)
  • ESG filters
  • Smart beta strategies
  • Backtesting sector rotation strategies
  • Valuation benchmarking (compare your picks against a peer basket)

๐Ÿ› ๏ธ 2. How to Create a Custom Index?

Creating an index is like baking a cake โ€” you need:

  1. ๐Ÿงพ List of Stocks โ†’ Your constituents (e.g., EIH, Indian Hotels, SAMHI)
  2. โš–๏ธ Weighting Method โ†’ Equal-weighted, market-cap weighted, or custom rules
  3. ๐Ÿ•ฐ๏ธ Historical Price Data โ†’ Daily adjusted close prices (from Yahoo Finance via yfinance)
  4. ๐Ÿงฎ Index Formula โ†’ Normalize prices to a base value (like 1000), then combine based on weights
  5. ๐Ÿ“Š Visualisation & Analysis โ†’ Compare against other indices, calculate CAGR, returns, etc.

๐Ÿจ 3. Real Example: Hotel Industry Custom Index

Letโ€™s say we want to track the Indian hotel industry performance. Weโ€™ll include:

  • EIH (EIHOTEL.NS)
  • Indian Hotels (INDHOTEL.NS)
  • SAMHI Hotels (SAMHI.NS)

Weโ€™ll use a market-cap weighted approach for realism.

๐Ÿ’ป 4. Python Code: Create the Hotel Index from Scratch

Hereโ€™s a full working Python script. Youโ€™ll need:

pip install yfinance pandas matplotlib seaborn
import yfinance as yf
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

# Step 1: Define hotel stocks and tickers
tickers = {
    "EIH": "EIHOTEL.NS",
    "Indian Hotels": "INDHOTEL.NS",
    "SAMHI Hotels": "SAMHI.NS"
}

# Step 2: Download historical price data
start_date = "2022-01-01"
end_date = pd.Timestamp.today().strftime('%Y-%m-%d')

price_data = yf.download(list(tickers.values()), start=start_date, end=end_date, auto_adjust=True)["Close"]
price_data.columns = tickers.keys()
price_data.dropna(inplace=True)

# Step 3: Fetch market caps with fallback handling
market_caps = {}
fallback_market_caps = {
    "EIH": 4500 * 1e7,            # โ‚น4,500 Cr
    "Indian Hotels": 65000 * 1e7, # โ‚น65,000 Cr
    "SAMHI Hotels": 2500 * 1e7    # โ‚น2,500 Cr
}

for name, ticker in tickers.items():
    try:
        info = yf.Ticker(ticker).get_info()
        market_cap = info.get("marketCap", 0)
        if market_cap == 0:
            print(f"[Warning] No market cap for {name} โ€“ using fallback.")
            market_cap = fallback_market_caps[name]
    except Exception as e:
        print(f"[Error] Failed to fetch market cap for {name} โ€“ using fallback. Error: {e}")
        market_cap = fallback_market_caps[name]
    market_caps[name] = market_cap

# Step 4: Calculate market cap weights
weights = pd.Series(market_caps)
weights = weights / weights.sum()
print("\n=== Market Cap Weights ===")
print(weights.round(4))

# Step 5: Normalize prices and compute market cap weighted index
normalized_prices = price_data / price_data.iloc[0]
market_cap_index = (normalized_prices * weights).sum(axis=1) * 1000  # Base 1000

# Step 6: Prepare index and constituent data for plotting
index_df = pd.DataFrame({
    "Hotel Index (Market Cap Weighted)": market_cap_index,
    **{name: normalized_prices[name]*1000 for name in tickers.keys()}
})

# Step 7: Plot index and constituents
plt.figure(figsize=(14, 6))
sns.set(style="whitegrid")
for col in index_df.columns:
    plt.plot(index_df.index, index_df[col], label=col)
plt.title("Hotel Industry Index vs Constituents", fontsize=16)
plt.xlabel("Date")
plt.ylabel("Index Value (Base 1000)")
plt.legend()
plt.tight_layout()
plt.show()

# Step 8: Cumulative returns
returns = index_df.pct_change().dropna()
cumulative_returns = (1 + returns).cumprod() * 100

plt.figure(figsize=(14, 6))
for col in cumulative_returns.columns:
    plt.plot(cumulative_returns.index, cumulative_returns[col], label=col)
plt.title("Cumulative Returns of Hotel Index and Stocks", fontsize=16)
plt.xlabel("Date")
plt.ylabel("Cumulative Return (%)")
plt.legend()
plt.tight_layout()
plt.show()

# Step 9: Performance summary
start_val = market_cap_index.iloc[0]
end_val = market_cap_index.iloc[-1]
days = (market_cap_index.index[-1] - market_cap_index.index[0]).days

cagr = (end_val / start_val) ** (1 / (days / 365.25)) - 1
total_return = (end_val / start_val - 1)

print("\n=== Hotel Industry Custom Index Performance ===")
print(f"Start Date     : {start_date}")
print(f"End Date       : {end_date}")
print(f"Total Return   : {total_return:.2%}")
print(f"CAGR           : {cagr:.2%}")

Below is a sample output of the above script:

๐Ÿ“Š 5. How to Use a Custom Index in Practice

Here are real ways to apply your index:

๐Ÿง  Final Thoughts

The beauty of investing is in making it personal โ€” and nothing is more personal than building your own index.

Whether youโ€™re tracking hotels, hydrogen, healthtech, or havan kunds, the tools are in your hands.

This isnโ€™t just for quants or fund managers. With just a few lines of Python, you can build professional-grade tools that deepen your market understanding โ€” and maybe even outperform the benchmarks.

A Message from InsiderFinance

Thanks for being a part of our community! Before you go:


๋ฉ”ํƒ€๋ฐ์ดํ„ฐ
post_id
7d7d5f70f32c
slug
building-your-own-stock-market-index-why-how-and-a-real-example-with-hotel-stocks-7d7d5f70f32c
url
https://wire.insiderfinance.io/building-your-own-stock-market-index-why-how-and-a-real-example-with-hotel-stocks-7d7d5f70f32c
canonical_url
https://wire.insiderfinance.io/building-your-own-stock-market-index-why-how-and-a-real-example-with-hotel-stocks-7d7d5f70f32c
author_url
https://medium.com/@manishpeshwani
status
ok
fetched_at
2026-08-26 22:04:17