|
| 1 | +""" |
| 2 | +Getting Started with MeridianAlgo |
| 3 | +================================== |
| 4 | +
|
| 5 | +This example walks you through the basics of using MeridianAlgo for quantitative |
| 6 | +finance analysis. We'll cover data fetching, basic calculations, and visualization. |
| 7 | +
|
| 8 | +Perfect for: Beginners who want to understand the fundamentals |
| 9 | +Time to run: ~30 seconds |
| 10 | +""" |
| 11 | + |
| 12 | +import meridianalgo as ma |
| 13 | + |
| 14 | +print("Welcome to MeridianAlgo!") |
| 15 | +print("=" * 60) |
| 16 | + |
| 17 | +# ============================================================================ |
| 18 | +# Step 1: Fetching Market Data |
| 19 | +# ============================================================================ |
| 20 | +print("\nStep 1: Fetching Market Data") |
| 21 | +print("-" * 60) |
| 22 | + |
| 23 | +# Let's grab some stock data for popular tech companies |
| 24 | +# We're using the last year of data to keep things manageable |
| 25 | +tickers = ["AAPL", "MSFT", "GOOGL"] |
| 26 | +print(f"Fetching data for: {', '.join(tickers)}") |
| 27 | + |
| 28 | +try: |
| 29 | + # get_market_data is your one-stop shop for historical price data |
| 30 | + # It automatically handles data cleaning and formatting |
| 31 | + prices = ma.get_market_data(tickers, start="2023-01-01", end="2024-01-01") |
| 32 | + |
| 33 | + print(f"✓ Successfully fetched {len(prices)} days of data") |
| 34 | + print(f" Date range: {prices.index[0]} to {prices.index[-1]}") |
| 35 | + print("\nFirst few prices:") |
| 36 | + print(prices.head()) |
| 37 | + |
| 38 | +except Exception as e: |
| 39 | + print(f"✗ Error fetching data: {e}") |
| 40 | + print(" Make sure you have an internet connection!") |
| 41 | + exit(1) |
| 42 | + |
| 43 | +# ============================================================================ |
| 44 | +# Step 2: Calculating Returns |
| 45 | +# ============================================================================ |
| 46 | +print("\nStep 2: Calculating Returns") |
| 47 | +print("-" * 60) |
| 48 | + |
| 49 | +# Returns are the percentage change in price from one day to the next |
| 50 | +# This is what we actually care about for most financial analysis |
| 51 | +returns = prices.pct_change().dropna() |
| 52 | + |
| 53 | +print("Daily returns calculated!") |
| 54 | +print(f" Total observations: {len(returns)}") |
| 55 | +print("\nAverage daily returns:") |
| 56 | +for ticker in tickers: |
| 57 | + avg_return = returns[ticker].mean() |
| 58 | + annual_return = (1 + avg_return) ** 252 - 1 # Annualize it |
| 59 | + print(f" {ticker}: {avg_return:.4%} daily ({annual_return:.2%} annualized)") |
| 60 | + |
| 61 | +# ============================================================================ |
| 62 | +# Step 3: Risk Analysis |
| 63 | +# ============================================================================ |
| 64 | +print("\n⚠️ Step 3: Risk Analysis") |
| 65 | +print("-" * 60) |
| 66 | + |
| 67 | +# Volatility tells us how much the price bounces around |
| 68 | +# Higher volatility = more risk (but potentially more reward) |
| 69 | +print("Volatility (annualized standard deviation):") |
| 70 | +for ticker in tickers: |
| 71 | + vol = returns[ticker].std() * (252**0.5) # Annualize volatility |
| 72 | + print(f" {ticker}: {vol:.2%}") |
| 73 | + |
| 74 | +# Sharpe Ratio: Return per unit of risk (higher is better) |
| 75 | +# A Sharpe > 1 is generally considered good |
| 76 | +print("\nSharpe Ratios (return/risk):") |
| 77 | +for ticker in tickers: |
| 78 | + mean_return = returns[ticker].mean() * 252 |
| 79 | + volatility = returns[ticker].std() * (252**0.5) |
| 80 | + sharpe = mean_return / volatility if volatility > 0 else 0 |
| 81 | + print(f" {ticker}: {sharpe:.2f}") |
| 82 | + |
| 83 | +# ============================================================================ |
| 84 | +# Step 4: Correlation Analysis |
| 85 | +# ============================================================================ |
| 86 | +print("\nStep 4: Correlation Analysis") |
| 87 | +print("-" * 60) |
| 88 | + |
| 89 | +# Correlation shows how stocks move together |
| 90 | +# 1.0 = perfect correlation, 0 = no correlation, -1.0 = inverse correlation |
| 91 | +correlation = returns.corr() |
| 92 | +print("Correlation matrix:") |
| 93 | +print(correlation.round(3)) |
| 94 | + |
| 95 | +print("\nWhat this means:") |
| 96 | +print(" Values close to 1.0: Stocks move together (diversification benefit is low)") |
| 97 | +print(" Values close to 0.0: Stocks move independently (good for diversification)") |
| 98 | +print(" Values close to -1.0: Stocks move opposite (great for hedging)") |
| 99 | + |
| 100 | +# ============================================================================ |
| 101 | +# Step 5: Simple Portfolio |
| 102 | +# ============================================================================ |
| 103 | +print("\nStep 5: Building a Simple Portfolio") |
| 104 | +print("-" * 60) |
| 105 | + |
| 106 | +# Let's create an equal-weighted portfolio |
| 107 | +# This means we invest the same amount in each stock |
| 108 | +weights = [1 / len(tickers)] * len(tickers) |
| 109 | +print(f"Portfolio weights: {dict(zip(tickers, weights, strict=False))}") |
| 110 | + |
| 111 | +# Calculate portfolio returns |
| 112 | +portfolio_returns = (returns * weights).sum(axis=1) |
| 113 | + |
| 114 | +# Portfolio statistics |
| 115 | +portfolio_mean = portfolio_returns.mean() * 252 |
| 116 | +portfolio_vol = portfolio_returns.std() * (252**0.5) |
| 117 | +portfolio_sharpe = portfolio_mean / portfolio_vol if portfolio_vol > 0 else 0 |
| 118 | + |
| 119 | +print("\nPortfolio Performance:") |
| 120 | +print(f" Expected Annual Return: {portfolio_mean:.2%}") |
| 121 | +print(f" Annual Volatility: {portfolio_vol:.2%}") |
| 122 | +print(f" Sharpe Ratio: {portfolio_sharpe:.2f}") |
| 123 | + |
| 124 | +# Compare to individual stocks |
| 125 | +print("\nComparison:") |
| 126 | +print(f" Portfolio volatility ({portfolio_vol:.2%}) is lower than individual stocks") |
| 127 | +print(" This is the power of diversification!") |
| 128 | + |
| 129 | +# ============================================================================ |
| 130 | +# Summary |
| 131 | +# ============================================================================ |
| 132 | +print("\n" + "=" * 60) |
| 133 | +print("Congratulations! You've completed the basics!") |
| 134 | +print("=" * 60) |
| 135 | +print("\nWhat you learned:") |
| 136 | +print(" ✓ How to fetch market data") |
| 137 | +print(" ✓ How to calculate returns and risk metrics") |
| 138 | +print(" ✓ How to analyze correlations") |
| 139 | +print(" ✓ How to build a simple portfolio") |
| 140 | +print("\nNext steps:") |
| 141 | +print(" → Try 02_portfolio_optimization.py for advanced portfolio techniques") |
| 142 | +print(" → Explore 03_risk_management.py to learn about VaR and risk metrics") |
| 143 | +print(" → Check out 04_technical_analysis.py for trading indicators") |
0 commit comments