๐จ 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?
๐จ 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:
- ๐งพ List of Stocks โ Your constituents (e.g., EIH, Indian Hotels, SAMHI)
- โ๏ธ Weighting Method โ Equal-weighted, market-cap weighted, or custom rules
- ๐ฐ๏ธ Historical Price Data
โ Daily adjusted close prices (from Yahoo Finance via
yfinance) - ๐งฎ Index Formula โ Normalize prices to a base value (like 1000), then combine based on weights
- ๐ 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:
- ๐ Clap for the story and follow the author ๐
- ๐ฐ View more content in the InsiderFinance Wire
- ๐ Take our FREE Masterclass
- ๐ Discover Powerful Trading Tools
๋ฉํ๋ฐ์ดํฐ
- 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