or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

abstract-streaming.mdcycle-indicators.mdindex.mdmath-operations.mdmomentum-indicators.mdoverlap-studies.mdpattern-recognition.mdprice-transform.mdstatistical-functions.mdvolatility-indicators.mdvolume-indicators.md

abstract-streaming.mddocs/

0

# Abstract and Streaming APIs

1

2

Alternative interfaces providing flexible DataFrame support and real-time processing capabilities. These APIs complement the standard Function API by offering different approaches to technical analysis computation.

3

4

## Abstract API

5

6

The Abstract API provides a flexible interface that supports pandas DataFrames, polars DataFrames, and named input dictionaries. It's particularly useful for working with OHLCV data in a more structured format.

7

8

### Core Classes and Functions

9

10

```python { .api }

11

class Function:

12

"""

13

Abstract function wrapper for flexible indicator calculation

14

15

Supports both direct instantiation and dictionary-based inputs.

16

"""

17

def __init__(self, function_name, *args, **kwargs):

18

"""

19

Initialize abstract function

20

21

Parameters:

22

- function_name: str, name of the TA-Lib function (case-insensitive)

23

- args, kwargs: additional arguments passed to the function

24

"""

25

26

def Function(function_name, *args, **kwargs):

27

"""

28

Factory function to create abstract function instances

29

30

Parameters:

31

- function_name: str, name of TA-Lib function

32

- args, kwargs: function parameters

33

34

Returns:

35

Function: Abstract function instance

36

"""

37

```

38

39

### Direct Function Access

40

41

```python { .api }

42

# All TA-Lib functions are available as abstract functions

43

import talib.abstract as abstract

44

45

SMA = abstract.SMA

46

RSI = abstract.RSI

47

MACD = abstract.MACD

48

BBANDS = abstract.BBANDS

49

```

50

51

### Input Data Formats

52

53

The Abstract API accepts multiple input formats:

54

55

```python { .api }

56

# Dictionary with named arrays

57

inputs = {

58

'open': np.array([...]),

59

'high': np.array([...]),

60

'low': np.array([...]),

61

'close': np.array([...]),

62

'volume': np.array([...])

63

}

64

65

# pandas DataFrame with OHLCV columns

66

df = pd.DataFrame({

67

'open': [...],

68

'high': [...],

69

'low': [...],

70

'close': [...],

71

'volume': [...]

72

})

73

74

# polars DataFrame

75

import polars as pl

76

df = pl.DataFrame({

77

'open': [...],

78

'high': [...],

79

'low': [...],

80

'close': [...],

81

'volume': [...]

82

})

83

```

84

85

### Utility Functions

86

87

```python { .api }

88

def _get_defaults_and_docs(func_name):

89

"""

90

Get function parameter defaults and documentation

91

92

Parameters:

93

- func_name: str, function name

94

95

Returns:

96

dict: Function metadata including parameters and defaults

97

"""

98

```

99

100

## Streaming API

101

102

The Streaming API provides real-time processing capabilities, returning only the latest calculated value instead of full arrays. This is ideal for live trading systems and real-time analysis.

103

104

### Key Characteristics

105

106

- **Single Value Output**: Returns only the most recent indicator value

107

- **Memory Efficient**: No need to store full arrays for historical values

108

- **Real-time Friendly**: Optimized for streaming data processing

109

- **Identical Signatures**: Same parameters as regular functions

110

111

### Function Naming

112

113

All streaming functions follow the pattern `stream_FUNCTIONNAME`:

114

115

```python { .api }

116

# Regular function returns array

117

sma_array = talib.SMA(close_prices, timeperiod=20)

118

119

# Streaming function returns single float

120

latest_sma = talib.stream.SMA(close_prices, timeperiod=20)

121

# or

122

latest_sma = talib.stream_SMA(close_prices, timeperiod=20)

123

```

124

125

### Available Streaming Functions

126

127

All 175+ TA-Lib functions have streaming equivalents:

128

129

```python { .api }

130

# Overlap Studies

131

def stream_SMA(real, timeperiod=30): ...

132

def stream_EMA(real, timeperiod=30): ...

133

def stream_BBANDS(real, timeperiod=5, nbdevup=2, nbdevdn=2, matype=MA_Type.SMA): ...

134

135

# Momentum Indicators

136

def stream_RSI(real, timeperiod=14): ...

137

def stream_MACD(real, fastperiod=12, slowperiod=26, signalperiod=9): ...

138

def stream_STOCH(high, low, close, fastk_period=5, slowk_period=3,

139

slowk_matype=MA_Type.SMA, slowd_period=3, slowd_matype=MA_Type.SMA): ...

140

141

# Volume Indicators

142

def stream_AD(high, low, close, volume): ...

143

def stream_OBV(close, volume): ...

144

145

# All other categories follow the same pattern...

146

```

147

148

## Usage Examples

149

150

### Abstract API Examples

151

152

```python

153

import talib.abstract as abstract

154

import pandas as pd

155

import numpy as np

156

157

# Using dictionary inputs

158

inputs = {

159

'open': np.random.random(100) * 100,

160

'high': np.random.random(100) * 100 + 5,

161

'low': np.random.random(100) * 100 - 5,

162

'close': np.random.random(100) * 100,

163

'volume': np.random.random(100) * 1000

164

}

165

166

# Calculate indicators using abstract API

167

sma = abstract.SMA(inputs, timeperiod=20)

168

rsi = abstract.RSI(inputs, timeperiod=14)

169

upper, middle, lower = abstract.BBANDS(inputs, timeperiod=20)

170

171

# Using pandas DataFrame

172

df = pd.DataFrame(inputs)

173

macd_line, signal_line, histogram = abstract.MACD(df)

174

175

# Advanced usage with custom price selection

176

sma_high = abstract.SMA(inputs, timeperiod=20, price='high')

177

sma_volume = abstract.SMA(inputs, timeperiod=20, price='volume')

178

179

# Multiple output handling with DataFrames

180

stoch_k, stoch_d = abstract.STOCH(df)

181

if isinstance(df, pd.DataFrame):

182

# Returns pandas Series with matching index

183

print(f"Latest %K: {stoch_k.iloc[-1]:.2f}")

184

print(f"Latest %D: {stoch_d.iloc[-1]:.2f}")

185

```

186

187

### Streaming API Examples

188

189

```python

190

import talib.stream as stream

191

import numpy as np

192

193

# Sample streaming data (in real application, this would be live data)

194

close_prices = np.array([100, 101, 102, 101, 103, 105, 104, 106])

195

196

# Calculate streaming indicators (returns only latest values)

197

latest_sma = stream.SMA(close_prices, timeperiod=5)

198

latest_rsi = stream.RSI(close_prices, timeperiod=14)

199

latest_ema = stream.EMA(close_prices, timeperiod=10)

200

201

print(f"Current SMA(5): {latest_sma:.2f}")

202

print(f"Current RSI(14): {latest_rsi:.2f}")

203

print(f"Current EMA(10): {latest_ema:.2f}")

204

205

# For indicators that return multiple values

206

macd, signal, histogram = stream.MACD(close_prices)

207

print(f"MACD: {macd:.4f}, Signal: {signal:.4f}, Histogram: {histogram:.4f}")

208

209

# Real-time trading system example

210

def process_new_price(new_price, price_history, max_history=100):

211

# Add new price and maintain history size

212

price_history.append(new_price)

213

if len(price_history) > max_history:

214

price_history.pop(0)

215

216

# Calculate streaming indicators

217

current_sma = stream.SMA(np.array(price_history), timeperiod=20)

218

current_rsi = stream.RSI(np.array(price_history), timeperiod=14)

219

220

# Trading logic

221

if current_rsi < 30 and new_price > current_sma:

222

return "BUY_SIGNAL"

223

elif current_rsi > 70 and new_price < current_sma:

224

return "SELL_SIGNAL"

225

else:

226

return "HOLD"

227

228

# Usage in streaming context

229

price_buffer = [100, 101, 102, 103, 104]

230

signal = process_new_price(105, price_buffer)

231

print(f"Trading signal: {signal}")

232

```

233

234

### Comparison of APIs

235

236

```python

237

import talib

238

import talib.abstract as abstract

239

import talib.stream as stream

240

import numpy as np

241

242

close_prices = np.random.random(50) * 100

243

244

# Function API - returns full array

245

sma_array = talib.SMA(close_prices, timeperiod=10)

246

print(f"Function API - Array length: {len(sma_array)}")

247

248

# Abstract API - flexible input handling

249

inputs = {'close': close_prices}

250

sma_abstract = abstract.SMA(inputs, timeperiod=10)

251

print(f"Abstract API - Array length: {len(sma_abstract)}")

252

253

# Streaming API - returns single value

254

sma_latest = stream.SMA(close_prices, timeperiod=10)

255

print(f"Streaming API - Single value: {sma_latest:.2f}")

256

257

# All should give the same latest value

258

print(f"Values match: {abs(sma_array[-1] - sma_latest) < 1e-10}")

259

```

260

261

## When to Use Each API

262

263

### Function API

264

- **Best for**: Backtesting, historical analysis, batch processing

265

- **Advantages**: Simple, direct, efficient for array operations

266

- **Use cases**: Strategy backtesting, indicator plotting, historical analysis

267

268

### Abstract API

269

- **Best for**: DataFrame-based workflows, flexible data handling

270

- **Advantages**: Supports multiple data formats, integration with pandas/polars

271

- **Use cases**: Data analysis pipelines, research environments, multi-asset analysis

272

273

### Streaming API

274

- **Best for**: Real-time systems, memory-constrained applications

275

- **Advantages**: Memory efficient, optimized for live data

276

- **Use cases**: Live trading systems, real-time dashboards, algorithmic trading