Tutorial: Building a Custom Trading Strategy¶
Learn how to combine FinanceLib's indicators to build your own trading strategy.
Strategy: RSI + MACD + Bollinger Bands¶
from financelib import Stock
from financelib.trading.algo_trade import rsi, macd, bollinger_bands
def analyze_with_strategy(symbol: str, period: str = "6mo") -> dict:
"""Multi-indicator strategy combining RSI, MACD, and Bollinger Bands."""
stock = Stock(symbol)
df = stock.get_historical_data(period=period)
if df is None or len(df) < 50:
return {"error": "Insufficient data"}
close = df["Close"]
price = float(close.iloc[-1])
# Calculate indicators
rsi_values = rsi(close, period=14)
macd_line, signal_line = macd(close)
bb_upper, bb_middle, bb_lower = bollinger_bands(close)
current_rsi = float(rsi_values.iloc[-1])
current_macd = float(macd_line.iloc[-1])
current_signal = float(signal_line.iloc[-1])
# Score each indicator
score = 0
reasons = []
# RSI
if current_rsi < 30:
score += 2
reasons.append(f"RSI oversold ({current_rsi:.1f})")
elif current_rsi < 40:
score += 1
reasons.append(f"RSI approaching oversold ({current_rsi:.1f})")
elif current_rsi > 70:
score -= 2
reasons.append(f"RSI overbought ({current_rsi:.1f})")
# MACD
if current_macd > current_signal:
score += 1
reasons.append("MACD bullish crossover")
else:
score -= 1
reasons.append("MACD bearish")
# Bollinger Bands
if price < float(bb_lower.iloc[-1]):
score += 2
reasons.append("Price below lower BB")
elif price > float(bb_upper.iloc[-1]):
score -= 2
reasons.append("Price above upper BB")
# Generate signal
if score >= 3:
signal = "STRONG BUY"
elif score >= 1:
signal = "BUY"
elif score <= -3:
signal = "STRONG SELL"
elif score <= -1:
signal = "SELL"
else:
signal = "HOLD"
return {
"symbol": symbol,
"price": price,
"signal": signal,
"score": score,
"rsi": current_rsi,
"macd": current_macd,
"reasons": reasons,
}
# Run on BIST stocks
for symbol in ["THYAO.IS", "GARAN.IS", "ASELS.IS"]:
result = analyze_with_strategy(symbol)
print(f"{result['symbol']}: {result['signal']} (score: {result['score']})")
for reason in result['reasons']:
print(f" - {reason}")
Using the BIST Bot¶
from financelib.trading import _get_bist_bot
BISTTradeBotv1 = _get_bist_bot()
bot = BISTTradeBotv1(paper_trading=True, initial_balance=100000)
# Scan and auto-trade
signals = bot.scan_common_stocks()
for signal in signals:
if signal["signal"] in ("BUY", "SELL"):
bot.execute_paper_trade(
signal["symbol"],
signal["signal"],
signal["current_price"],
)
# Check portfolio
summary = bot.get_portfolio_summary()
print(f"Total Value: {summary['total_value']:.2f} TRY")
print(f"P&L: {summary['total_pnl']:+.2f} TRY ({summary['total_pnl_pct']:+.2f}%)")