Chapter 8: Investment Strategies and Risk Management
Claude
32min
Chapter 8: Investment Strategies and Risk Management
8.1 Cryptocurrency Investment Basics
8.1.1 Pre-Investment Preparation
Cryptocurrency investment is characterized by high risk and high returns. Investors need to be well-prepared:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import yfinance as yf
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')
class CryptoInvestmentAnalyzer:
def __init__(self):
self.portfolio = {}
self.investment_history = []
def add_investment(self, symbol, amount, price, date=None):
"""Add investment record"""
if date is None:
date = datetime.now()
investment = {
'symbol': symbol,
'amount': amount,
'price': price,
'value': amount * price,
'date': date
}
self.investment_history.append(investment)
if symbol in self.portfolio:
self.portfolio[symbol]['amount'] += amount
self.portfolio[symbol]['total_invested'] += investment['value']
else:
self.portfolio[symbol] = {
'amount': amount,
'total_invested': investment['value']
}
print(f"Added investment: {amount} {symbol} @ ${price}")
def calculate_portfolio_value(self, current_prices):
"""Calculate current portfolio value"""
total_value = 0
portfolio_summary = {}
for symbol, holdings in self.portfolio.items():
if symbol in current_prices:
current_value = holdings['amount'] * current_prices[symbol]
profit_loss = current_value - holdings['total_invested']
profit_loss_pct = (profit_loss / holdings['total_invested']) * 100
portfolio_summary[symbol] = {
'amount': holdings['amount'],
'avg_cost': holdings['total_invested'] / holdings['amount'],
'current_price': current_prices[symbol],
'current_value': current_value,
'total_invested': holdings['total_invested'],
'profit_loss': profit_loss,
'profit_loss_pct': profit_loss_pct
}
total_value += current_value
return portfolio_summary, total_value
# Create investment analyzer
analyzer = CryptoInvestmentAnalyzer()
# Simulate investment records
analyzer.add_investment('BTC', 0.5, 45000)
analyzer.add_investment('ETH', 2.0, 3000)
analyzer.add_investment('BTC', 0.3, 50000)
# Current prices (simulated)
current_prices = {
'BTC': 48000,
'ETH': 3200
}
portfolio, total_value = analyzer.calculate_portfolio_value(current_prices)
print("\nPortfolio Analysis:")
print(f"Total Investment Value: ${total_value:,.2f}")
print("\nDetailed Holdings:")
for symbol, data in portfolio.items():
print(f"{symbol}:")
print(f" Quantity Held: {data['amount']}")
print(f" Average Cost: ${data['avg_cost']:,.2f}")
print(f" Current Price: ${data['current_price']:,.2f}")
print(f" Current Value: ${data['current_value']:,.2f}")
print(f" Profit/Loss: ${data['profit_loss']:,.2f} ({data['profit_loss_pct']:.2f}%)")
8.1.2 Market Analysis Tools
class TechnicalAnalysis:
def __init__(self):
self.indicators = {}
def calculate_sma(self, prices, window):
"""Simple Moving Average"""
return prices.rolling(window=window).mean()
def calculate_ema(self, prices, window):
"""Exponential Moving Average"""
return prices.ewm(span=window).mean()
def calculate_rsi(self, prices, window=14):
"""Relative Strength Index"""
delta = prices.diff()
gain = (delta.where(delta > 0, 0)).rolling(window=window).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=window).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return rsi
def calculate_bollinger_bands(self, prices, window=20, num_std=2):
"""Bollinger Bands"""
sma = self.calculate_sma(prices, window)
std = prices.rolling(window=window).std()
upper_band = sma + (std * num_std)
lower_band = sma - (std * num_std)
return upper_band, sma, lower_band
def generate_signals(self, prices):
"""Generate trading signals"""
# Calculate technical indicators
sma_20 = self.calculate_sma(prices, 20)
sma_50 = self.calculate_sma(prices, 50)
rsi = self.calculate_rsi(prices)
upper_band, middle_band, lower_band = self.calculate_bollinger_bands(prices)
signals = pd.DataFrame(index=prices.index)
signals['price'] = prices
signals['sma_20'] = sma_20
signals['sma_50'] = sma_50
signals['rsi'] = rsi
signals['upper_band'] = upper_band
signals['lower_band'] = lower_band
# Generate buy/sell signals
signals['signal'] = 0
# Buy signal: short-term MA crosses above long-term MA and RSI < 30
buy_condition = (signals['sma_20'] > signals['sma_50']) & (signals['rsi'] < 30)
signals.loc[buy_condition, 'signal'] = 1
# Sell signal: short-term MA crosses below long-term MA and RSI > 70
sell_condition = (signals['sma_20'] < signals['sma_50']) & (signals['rsi'] > 70)
signals.loc[sell_condition, 'signal'] = -1
return signals
# Generate sample price data
np.random.seed(42)
dates = pd.date_range(start='2023-01-01', end='2024-01-01', freq='D')
initial_price = 40000
returns = np.random.normal(0.001, 0.03, len(dates))
prices = [initial_price]
for r in returns[1:]:
prices.append(prices[-1] * (1 + r))
price_series = pd.Series(prices, index=dates)
# Technical analysis
ta = TechnicalAnalysis()
signals = ta.generate_signals(price_series)
print("Technical Analysis Signals (Last 5 Days):")
print(signals.tail()[['price', 'sma_20', 'sma_50', 'rsi', 'signal']])
8.2 Investment Strategies Explained
8.2.1 HODL Strategy
class HODLStrategy:
def __init__(self, initial_investment=10000):
self.initial_investment = initial_investment
self.holdings = {}
self.strategy_name = "HODL Strategy"
def execute_strategy(self, symbol, price_data):
"""Execute HODL strategy"""
# Buy and hold from day one
initial_price = price_data.iloc[0]
amount = self.initial_investment / initial_price
self.holdings[symbol] = {
'amount': amount,
'buy_price': initial_price,
'buy_date': price_data.index[0]
}
# Calculate daily portfolio value
portfolio_values = []
for date, price in price_data.items():
current_value = amount * price
portfolio_values.append(current_value)
return pd.Series(portfolio_values, index=price_data.index)
def calculate_performance(self, final_value):
"""Calculate strategy performance"""
total_return = (final_value - self.initial_investment) / self.initial_investment
return {
'strategy': self.strategy_name,
'initial_investment': self.initial_investment,
'final_value': final_value,
'total_return': total_return,
'total_return_pct': total_return * 100
}
# Execute HODL strategy
hodl = HODLStrategy(10000)
hodl_values = hodl.execute_strategy('BTC', price_series)
hodl_performance = hodl.calculate_performance(hodl_values.iloc[-1])
print("HODL Strategy Performance:")
print(f"Initial Investment: ${hodl_performance['initial_investment']:,.2f}")
print(f"Final Value: ${hodl_performance['final_value']:,.2f}")
print(f"Total Return: {hodl_performance['total_return_pct']:.2f}%")
8.2.2 Dollar-Cost Averaging (DCA)
class DCAStrategy:
def __init__(self, monthly_investment=1000):
self.monthly_investment = monthly_investment
self.strategy_name = "Dollar Cost Averaging"
self.investments = []
def execute_strategy(self, symbol, price_data):
"""Execute DCA strategy"""
portfolio_values = []
total_amount = 0
current_value = 0
# Monthly investments
monthly_dates = price_data.resample('M').first().index
for date in price_data.index:
if date in monthly_dates:
# Execute investment
price = price_data[date]
amount = self.monthly_investment / price
total_amount += amount
investment = {
'date': date,
'price': price,
'amount': amount,
'investment': self.monthly_investment
}
self.investments.append(investment)
current_price = price_data[date]
current_value = total_amount * current_price
portfolio_values.append(current_value)
return pd.Series(portfolio_values, index=price_data.index)
def calculate_performance(self, final_value):
"""Calculate strategy performance"""
total_invested = len(self.investments) * self.monthly_investment
total_return = (final_value - total_invested) / total_invested
return {
'strategy': self.strategy_name,
'total_invested': total_invested,
'final_value': final_value,
'total_return': total_return,
'total_return_pct': total_return * 100,
'num_investments': len(self.investments)
}
# Execute DCA strategy
dca = DCAStrategy(1000)
dca_values = dca.execute_strategy('BTC', price_series)
dca_performance = dca.calculate_performance(dca_values.iloc[-1])
print("\nDCA Strategy Performance:")
print(f"Total Investments: {dca_performance['num_investments']}")
print(f"Total Invested: ${dca_performance['total_invested']:,.2f}")
print(f"Final Value: ${dca_performance['final_value']:,.2f}")
print(f"Total Return: {dca_performance['total_return_pct']:.2f}%")
8.2.3 Trend Following Strategy
class TrendFollowingStrategy:
def __init__(self, initial_capital=10000, short_window=20, long_window=50):
self.initial_capital = initial_capital
self.short_window = short_window
self.long_window = long_window
self.strategy_name = "Trend Following"
self.trades = []
def execute_strategy(self, symbol, price_data):
"""Execute trend following strategy"""
# Calculate moving averages
short_ma = price_data.rolling(window=self.short_window).mean()
long_ma = price_data.rolling(window=self.long_window).mean()
portfolio_values = []
cash = self.initial_capital
position = 0 # Position quantity
for i, (date, price) in enumerate(price_data.items()):
if i < self.long_window:
portfolio_values.append(self.initial_capital)
continue
current_short_ma = short_ma.iloc[i]
current_long_ma = long_ma.iloc[i]
prev_short_ma = short_ma.iloc[i-1]
prev_long_ma = long_ma.iloc[i-1]
# Buy signal: short-term MA crosses above long-term MA
if (current_short_ma > current_long_ma and
prev_short_ma <= prev_long_ma and
position == 0 and cash > 0):
position = cash / price
cash = 0
self.trades.append({
'date': date,
'action': 'BUY',
'price': price,
'amount': position
})
# Sell signal: short-term MA crosses below long-term MA
elif (current_short_ma < current_long_ma and
prev_short_ma >= prev_long_ma and
position > 0):
cash = position * price
self.trades.append({
'date': date,
'action': 'SELL',
'price': price,
'amount': position
})
position = 0
# Calculate current portfolio value
current_value = cash + (position * price)
portfolio_values.append(current_value)
return pd.Series(portfolio_values, index=price_data.index)
def calculate_performance(self, portfolio_values):
"""Calculate strategy performance"""
final_value = portfolio_values.iloc[-1]
total_return = (final_value - self.initial_capital) / self.initial_capital
return {
'strategy': self.strategy_name,
'initial_capital': self.initial_capital,
'final_value': final_value,
'total_return': total_return,
'total_return_pct': total_return * 100,
'num_trades': len(self.trades)
}
# Execute trend following strategy
trend = TrendFollowingStrategy(10000)
trend_values = trend.execute_strategy('BTC', price_series)
trend_performance = trend.calculate_performance(trend_values)
print("\nTrend Following Strategy Performance:")
print(f"Initial Capital: ${trend_performance['initial_capital']:,.2f}")
print(f"Final Value: ${trend_performance['final_value']:,.2f}")
print(f"Total Return: {trend_performance['total_return_pct']:.2f}%")
print(f"Number of Trades: {trend_performance['num_trades']}")
8.3 Risk Management
8.3.1 Risk Metrics
class RiskAnalyzer:
def __init__(self):
self.risk_metrics = {}
def calculate_volatility(self, returns):
"""Calculate volatility"""
return returns.std() * np.sqrt(252) # Annualized volatility
def calculate_var(self, returns, confidence_level=0.05):
"""Calculate Value at Risk (VaR)"""
return np.percentile(returns, confidence_level * 100)
def calculate_cvar(self, returns, confidence_level=0.05):
"""Calculate Conditional Value at Risk (CVaR)"""
var = self.calculate_var(returns, confidence_level)
return returns[returns <= var].mean()
def calculate_max_drawdown(self, portfolio_values):
"""Calculate maximum drawdown"""
peak = portfolio_values.expanding().max()
drawdown = (portfolio_values - peak) / peak
return drawdown.min()
def calculate_sharpe_ratio(self, returns, risk_free_rate=0.02):
"""Calculate Sharpe ratio"""
excess_returns = returns.mean() * 252 - risk_free_rate
volatility = self.calculate_volatility(returns)
return excess_returns / volatility
def comprehensive_risk_analysis(self, portfolio_values):
"""Comprehensive risk analysis"""
returns = portfolio_values.pct_change().dropna()
metrics = {
'volatility': self.calculate_volatility(returns),
'var_5%': self.calculate_var(returns, 0.05),
'cvar_5%': self.calculate_cvar(returns, 0.05),
'max_drawdown': self.calculate_max_drawdown(portfolio_values),
'sharpe_ratio': self.calculate_sharpe_ratio(returns)
}
return metrics
# Risk analysis
risk_analyzer = RiskAnalyzer()
# Analyze risk for each strategy
strategies = {
'HODL': hodl_values,
'DCA': dca_values,
'Trend Following': trend_values
}
print("\nStrategy Risk Analysis:")
print("-" * 60)
print(f"{'Strategy':<15} {'Volatility':<10} {'Max Drawdown':<10} {'Sharpe Ratio':<10}")
print("-" * 60)
for name, values in strategies.items():
if len(values) > 1:
risk_metrics = risk_analyzer.comprehensive_risk_analysis(values)
print(f"{name:<15} {risk_metrics['volatility']:<10.2%} "
f"{risk_metrics['max_drawdown']:<10.2%} "
f"{risk_metrics['sharpe_ratio']:<10.2f}")
8.3.2 Position Sizing
class PositionSizing:
def __init__(self, total_capital):
self.total_capital = total_capital
def kelly_criterion(self, win_probability, avg_win, avg_loss):
"""Kelly Criterion for optimal position size"""
if avg_loss <= 0:
return 0
b = avg_win / avg_loss # Odds ratio
p = win_probability # Win rate
kelly_fraction = (b * p - (1 - p)) / b
return max(0, min(kelly_fraction, 0.25)) # Cap at 25%
def fixed_percentage(self, percentage=0.02):
"""Fixed percentage risk"""
return self.total_capital * percentage
def volatility_based_sizing(self, volatility, target_risk=0.02):
"""Volatility-based position size"""
if volatility <= 0:
return 0
position_size = (target_risk * self.total_capital) / volatility
return position_size
# Position sizing example
position_sizer = PositionSizing(100000)
# Assumed trading statistics
win_prob = 0.6
avg_win = 0.05
avg_loss = 0.03
kelly_size = position_sizer.kelly_criterion(win_prob, avg_win, avg_loss)
fixed_size = position_sizer.fixed_percentage(0.02)
print(f"\nPosition Management Recommendations:")
print(f"Kelly Criterion suggested position: {kelly_size:.2%}")
print(f"Fixed 2% risk position: ${fixed_size:,.2f}")
8.3.3 Portfolio Optimization
import scipy.optimize as optimize
class PortfolioOptimizer:
def __init__(self, expected_returns, cov_matrix):
self.expected_returns = expected_returns
self.cov_matrix = cov_matrix
self.num_assets = len(expected_returns)
def portfolio_stats(self, weights):
"""Calculate portfolio statistics"""
portfolio_return = np.sum(weights * self.expected_returns)
portfolio_variance = np.dot(weights.T, np.dot(self.cov_matrix, weights))
portfolio_std = np.sqrt(portfolio_variance)
sharpe_ratio = portfolio_return / portfolio_std
return portfolio_return, portfolio_std, sharpe_ratio
def negative_sharpe(self, weights):
"""Negative Sharpe ratio (for minimization)"""
return -self.portfolio_stats(weights)[2]
def optimize_sharpe(self):
"""Maximize Sharpe ratio"""
constraints = {'type': 'eq', 'fun': lambda x: np.sum(x) - 1}
bounds = tuple((0, 1) for _ in range(self.num_assets))
initial_guess = np.array([1/self.num_assets] * self.num_assets)
result = optimize.minimize(
self.negative_sharpe,
initial_guess,
method='SLSQP',
bounds=bounds,
constraints=constraints
)
return result.x
def efficient_frontier(self, num_portfolios=100):
"""Generate efficient frontier"""
min_ret = self.expected_returns.min()
max_ret = self.expected_returns.max()
target_returns = np.linspace(min_ret, max_ret, num_portfolios)
efficient_portfolios = []
for target in target_returns:
constraints = [
{'type': 'eq', 'fun': lambda x: np.sum(x) - 1},
{'type': 'eq', 'fun': lambda x: np.sum(x * self.expected_returns) - target}
]
bounds = tuple((0, 1) for _ in range(self.num_assets))
initial_guess = np.array([1/self.num_assets] * self.num_assets)
result = optimize.minimize(
lambda x: np.dot(x.T, np.dot(self.cov_matrix, x)),
initial_guess,
method='SLSQP',
bounds=bounds,
constraints=constraints
)
if result.success:
ret, std, sharpe = self.portfolio_stats(result.x)
efficient_portfolios.append({
'return': ret,
'std': std,
'sharpe': sharpe,
'weights': result.x
})
return efficient_portfolios
# Portfolio optimization example
assets = ['BTC', 'ETH', 'BNB', 'ADA']
expected_returns = np.array([0.15, 0.12, 0.10, 0.08]) # Annualized returns
cov_matrix = np.array([
[0.04, 0.02, 0.015, 0.01],
[0.02, 0.03, 0.012, 0.008],
[0.015, 0.012, 0.025, 0.006],
[0.01, 0.008, 0.006, 0.02]
]) # Covariance matrix
optimizer = PortfolioOptimizer(expected_returns, cov_matrix)
optimal_weights = optimizer.optimize_sharpe()
print(f"\nOptimal Portfolio Allocation:")
for i, asset in enumerate(assets):
print(f"{asset}: {optimal_weights[i]:.2%}")
ret, std, sharpe = optimizer.portfolio_stats(optimal_weights)
print(f"\nPortfolio Performance:")
print(f"Expected Return: {ret:.2%}")
print(f"Expected Volatility: {std:.2%}")
print(f"Sharpe Ratio: {sharpe:.2f}")
8.4 Risk Management Practices
8.4.1 Stop-Loss Strategies
class StopLossManager:
def __init__(self):
self.stop_loss_orders = {}
def set_stop_loss(self, symbol, entry_price, stop_loss_pct=0.1):
"""Set stop loss"""
stop_price = entry_price * (1 - stop_loss_pct)
self.stop_loss_orders[symbol] = {
'entry_price': entry_price,
'stop_price': stop_price,
'stop_loss_pct': stop_loss_pct
}
print(f"Stop loss set: {symbol} entry price ${entry_price:.2f}, stop price ${stop_price:.2f}")
def trailing_stop_loss(self, symbol, current_price, trailing_pct=0.05):
"""Trailing stop loss"""
if symbol not in self.stop_loss_orders:
return False
order = self.stop_loss_orders[symbol]
new_stop_price = current_price * (1 - trailing_pct)
# Only update if new stop price is higher than current stop price
if new_stop_price > order['stop_price']:
order['stop_price'] = new_stop_price
print(f"Trailing stop loss updated: {symbol} new stop price ${new_stop_price:.2f}")
return True
return False
def check_stop_loss(self, symbol, current_price):
"""Check if stop loss is triggered"""
if symbol not in self.stop_loss_orders:
return False
stop_price = self.stop_loss_orders[symbol]['stop_price']
if current_price <= stop_price:
print(f"Stop loss triggered: {symbol} current price ${current_price:.2f} <= stop price ${stop_price:.2f}")
return True
return False
# Stop loss management example
stop_manager = StopLossManager()
stop_manager.set_stop_loss('BTC', 45000, 0.1)
# Simulate price movements
prices = [46000, 47000, 44000, 43000, 48000, 40000]
for price in prices:
print(f"\nCurrent price: ${price}")
# Check trailing stop loss
stop_manager.trailing_stop_loss('BTC', price, 0.05)
# Check if stop loss is triggered
if stop_manager.check_stop_loss('BTC', price):
print("Execute stop loss sell")
break
8.4.2 Capital Management Rules
class RiskManagementRules:
def __init__(self, total_capital, max_risk_per_trade=0.02, max_portfolio_risk=0.20):
self.total_capital = total_capital
self.max_risk_per_trade = max_risk_per_trade
self.max_portfolio_risk = max_portfolio_risk
self.current_positions = {}
self.total_risk = 0
def calculate_position_size(self, entry_price, stop_loss_price):
"""Calculate position size"""
if entry_price <= stop_loss_price:
return 0
risk_per_share = entry_price - stop_loss_price
risk_amount = self.total_capital * self.max_risk_per_trade
position_size = risk_amount / risk_per_share
return position_size
def can_open_position(self, position_risk):
"""Check if new position can be opened"""
new_total_risk = self.total_risk + position_risk
return new_total_risk <= self.max_portfolio_risk
def add_position(self, symbol, entry_price, stop_loss_price, position_size):
"""Add new position"""
position_risk = (entry_price - stop_loss_price) * position_size / self.total_capital
if self.can_open_position(position_risk):
self.current_positions[symbol] = {
'entry_price': entry_price,
'stop_loss_price': stop_loss_price,
'position_size': position_size,
'risk': position_risk
}
self.total_risk += position_risk
print(f"Position opened: {symbol}, size: {position_size:.4f}, risk: {position_risk:.2%}")
return True
else:
print(f"Risk too high, cannot open position {symbol}")
return False
def close_position(self, symbol):
"""Close position"""
if symbol in self.current_positions:
position = self.current_positions[symbol]
self.total_risk -= position['risk']
del self.current_positions[symbol]
print(f"Position closed: {symbol}")
def get_risk_summary(self):
"""Get risk summary"""
return {
'total_capital': self.total_capital,
'total_risk': self.total_risk,
'risk_percentage': self.total_risk * 100,
'available_risk': (self.max_portfolio_risk - self.total_risk) * 100,
'active_positions': len(self.current_positions)
}
# Capital management example
risk_manager = RiskManagementRules(100000)
# Calculate position size
entry_price = 45000
stop_loss_price = 43000
position_size = risk_manager.calculate_position_size(entry_price, stop_loss_price)
print(f"Recommended position size: {position_size:.6f} BTC")
print(f"Investment amount: ${position_size * entry_price:.2f}")
# Open position
risk_manager.add_position('BTC', entry_price, stop_loss_price, position_size)
# Risk summary
risk_summary = risk_manager.get_risk_summary()
print(f"\nRisk Management Summary:")
print(f"Total Capital: ${risk_summary['total_capital']:,.2f}")
print(f"Current Risk: {risk_summary['risk_percentage']:.2f}%")
print(f"Available Risk: {risk_summary['available_risk']:.2f}%")
print(f"Active Positions: {risk_summary['active_positions']}")
8.5 Trading Psychology
8.5.1 Common Cognitive Biases
class TradingPsychologyAnalyzer:
def __init__(self):
self.trading_log = []
self.biases_detected = []
def log_trade(self, symbol, action, price, reason, emotion_score=5):
"""Log trade"""
trade = {
'timestamp': datetime.now(),
'symbol': symbol,
'action': action,
'price': price,
'reason': reason,
'emotion_score': emotion_score # 1-10, 1=extreme fear, 10=extreme greed
}
self.trading_log.append(trade)
def detect_revenge_trading(self, window_hours=24):
"""Detect revenge trading"""
if len(self.trading_log) < 2:
return False
recent_trades = []
current_time = datetime.now()
for trade in self.trading_log:
if (current_time - trade['timestamp']).total_seconds() / 3600 <= window_hours:
recent_trades.append(trade)
if len(recent_trades) >= 5: # More than 5 trades in 24 hours
self.biases_detected.append({
'bias': 'Revenge Trading',
'description': 'Excessive trading in short period',
'timestamp': current_time
})
return True
return False
def detect_fomo(self, emotion_threshold=8):
"""Detect FOMO (Fear of Missing Out)"""
if not self.trading_log:
return False
last_trade = self.trading_log[-1]
if (last_trade['action'] == 'BUY' and
last_trade['emotion_score'] >= emotion_threshold and
'rising' in last_trade['reason'].lower()):
self.biases_detected.append({
'bias': 'FOMO',
'description': 'Emotional buying during price increase',
'timestamp': last_trade['timestamp']
})
return True
return False
def detect_loss_aversion(self):
"""Detect loss aversion"""
buy_trades = [t for t in self.trading_log if t['action'] == 'BUY']
sell_trades = [t for t in self.trading_log if t['action'] == 'SELL']
if len(buy_trades) > len(sell_trades) * 2: # Many more buys than sells
self.biases_detected.append({
'bias': 'Loss Aversion',
'description': 'Unwilling to realize losses',
'timestamp': datetime.now()
})
return True
return False
def get_psychology_report(self):
"""Generate psychology analysis report"""
return {
'total_trades': len(self.trading_log),
'biases_detected': self.biases_detected,
'average_emotion_score': np.mean([t['emotion_score'] for t in self.trading_log]) if self.trading_log else 0,
'recommendations': self.generate_recommendations()
}
def generate_recommendations(self):
"""Generate improvement recommendations"""
recommendations = []
bias_types = [b['bias'] for b in self.biases_detected]
if 'Revenge Trading' in bias_types:
recommendations.append("Set daily maximum trading limit")
if 'FOMO' in bias_types:
recommendations.append("Develop clear buying strategy, avoid emotional decisions")
if 'Loss Aversion' in bias_types:
recommendations.append("Strictly execute stop-loss strategy")
if not recommendations:
recommendations.append("Continue maintaining rational trading")
return recommendations
# Trading psychology analysis example
psychology = TradingPsychologyAnalyzer()
# Simulate trade records
trades = [
('BTC', 'BUY', 45000, 'Technical analysis shows breakout', 6),
('ETH', 'BUY', 3000, 'News says it will rise', 9),
('BTC', 'SELL', 46000, 'Take profit', 5),
('BNB', 'BUY', 300, 'Everyone is buying', 8),
('ADA', 'BUY', 0.5, 'Price is rising', 9),
('DOT', 'BUY', 25, 'FOMO', 10)
]
for symbol, action, price, reason, emotion in trades:
psychology.log_trade(symbol, action, price, reason, emotion)
psychology.detect_fomo()
psychology.detect_revenge_trading()
psychology.detect_loss_aversion()
report = psychology.get_psychology_report()
print("Trading Psychology Analysis Report:")
print(f"Total Trades: {report['total_trades']}")
print(f"Average Emotion Score: {report['average_emotion_score']:.1f}/10")
print(f"\nDetected Cognitive Biases:")
for bias in report['biases_detected']:
print(f"- {bias['bias']}: {bias['description']}")
print(f"\nImprovement Recommendations:")
for rec in report['recommendations']:
print(f"- {rec}")
8.6 Chapter Summary
This chapter provided a detailed introduction to various aspects of cryptocurrency investment strategies and risk management:
Key Points
- Diversified Investment Strategies: HODL, DCA, trend following and other strategies each have their pros and cons
- Risk Management is Critical: Use technical indicators to quantify and control risks
- Position Management: Reasonable capital allocation is key to success
- Psychological Control: Identify and overcome cognitive biases
Practical Recommendations
- Develop clear investment plans and risk management rules
- Use technical analysis tools to assist decision-making
- Strictly execute stop-loss strategies
- Remain rational and avoid emotional trading
- Diversify investments - don’t put all eggs in one basket
Cryptocurrency investment requires professional knowledge, strict discipline, and continuous learning. Through this chapter, you should be able to build an investment strategy and risk management system that suits you.