-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12_numpy_foundation.py
More file actions
60 lines (47 loc) · 1.74 KB
/
Copy path12_numpy_foundation.py
File metadata and controls
60 lines (47 loc) · 1.74 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"""
12_numpy_foundation.py
----------------------
Concept: Numpy (Numerical Python)
Context: High-performance vector calculations for signals and backtesting.
Faster than Python lists for math operations on large datasets.
"""
import numpy as np
import time
# 1. Numpy Arrays vs Lists
# Scenario: Apply a fee of 0.1% to 1 million trade prices
print("--- 1. Speed Test: Lists vs Numpy ---")
num_trades = 1000000
prices_list = [100.0] * num_trades
prices_np = np.ones(num_trades) * 100.0
# List approach
start = time.time()
fees_list = [p * 0.001 for p in prices_list]
print(f"List Time: {time.time() - start:.4f} seconds")
# Numpy approach (Vectorized)
start = time.time()
fees_np = prices_np * 0.001
print(f"Numpy Time: {time.time() - start:.4f} seconds!")
# 2. Vectorized Signal Generation
print("\n--- 2. Vectorized Signals ---")
# Simulating 10 closing prices
closes = np.array([100, 102, 104, 103, 101, 99, 98, 100, 105, 107])
# Simulating a moving average (fixed scalar for demo)
ma_threshold = 102.0
# Generate boolean array for signals
buy_signals = closes > ma_threshold
print(f"Prices: {closes}")
print(f"Buy Signals (Prices > {ma_threshold}): {buy_signals}")
# Filter prices where signal is True
entry_prices = closes[buy_signals]
print(f"executed Trades at: {entry_prices}")
# 3. Log Returns (Best for volatility calc)
print("\n--- 3. Log Returns ---")
price_series = np.array([100, 105, 102, 110, 108])
# Log return = ln(P_t / P_t-1)
# np.diff computes P_t - P_t-1, but we need ratios.
# Best way: ln(Price) - ln(Prev_Price)
log_prices = np.log(price_series)
returns = np.diff(log_prices)
print(f"Prices: {price_series}")
print(f"Log Returns: {returns}")
print(f"Total Return: {np.sum(returns):.4f} (approx {(price_series[-1]/price_series[0]) - 1:.2f}%)")