@firstthumb/tefas-api
v1.1.2
Published
TypeScript client library for TEFAS (Turkish Electronic Fund Information System) API
Maintainers
Readme
TEFAS API Client
A simple TypeScript library to get fund data from TEFAS (Turkish Electronic Fund Information System). Works in both browsers and Node.js.
Features
- 🔍 Search for funds by name or code
- 📊 Get fund history (prices, assets, participants)
- 📈 Calculate performance metrics (Sharpe ratio, volatility, returns)
- ⚡ Fast and small - less than 16KB
- 💾 Automatic caching for improved performance
- ✅ Full TypeScript support
- 🌐 Works in browser and Node.js 18+
Install
npm install @firstthumb/tefas-apiQuick Start
Search for Funds
import { TefasClient } from '@firstthumb/tefas-api';
const client = new TefasClient();
const results = await client.searchFund('IPB');
// [{ fundCode: "IPB", fundName: "İSTANBUL PORTFÖY BİRİNCİ DEĞİŞKEN FON" }]Get Fund Data
// Get specific fund (searches all fund types)
const data = await client.getFund('2024-01-01', '2024-01-31', 'IPB');
// Returns merged data with history (price, volume) and content (stocks, bonds)
// Filter by fund type - get only pension funds
const pensionFunds = await client.getFund('2024-01-01', '2024-01-31', undefined, FundType.EMK);
// Get specific fund in specific type
const specificFund = await client.getFund('2024-01-01', '2024-01-31', 'TGE', FundType.EMK);Fuzzy Date Support
const data = await client.getFund('yesterday', 'today');
const lastMonth = await client.getFund('last month', 'today');
// Supports natural language: "today", "yesterday", "last week", "last month", etc.Performance Metrics
import { PerformanceCalculator, FundType } from '@firstthumb/tefas-api';
// Get only investment funds (YAT) using fundType parameter
const fundData = await client.getFund('2024-01-01', '2024-12-31', 'IPB', FundType.YAT);
const metrics = PerformanceCalculator.calculateMetrics(fundData.results, {
riskFreeRate: 0.10,
frequency: 'daily',
method: 'simple'
});
// Returns: cumulativeReturn, annualizedReturn, annualizedVolatility, sharpeRatioCaching for Performance
The client includes automatic caching to improve performance and reduce API calls. You can use the built-in memory cache or provide your own cache adapter (Redis, Cloudflare KV, etc.):
Default Memory Cache
// Default: caching enabled with 15-minute TTL
const client = new TefasClient();
// Custom cache configuration
const customClient = new TefasClient({
cache: {
enabled: true,
ttl: 5 * 60 * 1000, // 5 minutes
maxSize: 500 // Maximum 500 cache entries
}
});
// Cache management (all methods are async)
await client.clearCache(); // Clear all cache
await client.invalidateCache('2024-01-01', '2024-01-31'); // Remove specific entry
const stats = await client.getCacheStats(); // Get cache statistics
const removed = await client.pruneCache(); // Remove expired entriesCustom Cache Adapter
Cloudflare Workers KV
Built-in adapter for Cloudflare Workers:
import { TefasClient, CloudflareKVCacheAdapter } from '@firstthumb/tefas-api';
// In a Cloudflare Worker
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const cache = new CloudflareKVCacheAdapter({
namespace: env.TEFAS_CACHE,
ttl: 15 * 60 * 1000, // 15 minutes
prefix: 'tefas:'
});
const client = new TefasClient({ cacheAdapter: cache });
const data = await client.getFund('2024-01-01', '2024-12-31');
return Response.json(data);
}
};Custom Implementation
Implement your own adapter for Redis, localStorage, etc.:
import { CacheAdapter } from '@firstthumb/tefas-api';
class RedisCacheAdapter implements CacheAdapter<any> {
async get(key: string) {
const value = await redis.get(key);
return value ? JSON.parse(value) : undefined;
}
async set(key: string, value: any, ttl?: number) {
await redis.setEx(key, ttl ?? 900, JSON.stringify(value));
}
async delete(key: string) {
return (await redis.del(key)) > 0;
}
async clear() {
// Implement based on your needs
}
async has(key: string) {
return (await redis.exists(key)) === 1;
}
}
// Use custom cache
const client = new TefasClient({
cacheAdapter: new RedisCacheAdapter()
});Benefits:
- 90-99% faster for repeated queries
- Reduces API load
- Perfect for dashboards and real-time UIs
- Flexible: use any cache backend (Redis, KV, localStorage, etc.)
Search Options
// Filter by fund type
const results = await client.searchFund('IPB', {
fundType: FundType.YAT,
limit: 5
});Fund Types
FundType.EMK // Pension funds (Emeklilik)
FundType.YAT // Investment funds (Yatırım)
FundType.BYF // Umbrella funds
FundType.GYF // Real estate funds
FundType.GSYF // Real estate investment fundsError Handling
import { ValidationError, TefasApiError, NetworkError } from '@firstthumb/tefas-api';
try {
const results = await client.searchFund('IPB');
} catch (error) {
if (error instanceof ValidationError) {
console.log('Invalid input:', error.message);
} else if (error instanceof TefasApiError) {
console.log('API error:', error.message);
} else if (error instanceof NetworkError) {
console.log('Network error:', error.message);
}
}Requirements
- Node.js 18+
- Modern browser with
fetchsupport - TypeScript 5.0+ (optional)
Examples
Check the examples/ folder for more usage examples.
Development
npm install
npm test
npm run buildLicense
MIT License
