Premchan369 commited on
Commit
12fb8be
·
verified ·
1 Parent(s): 7370e85

Upload macro_features.py

Browse files
Files changed (1) hide show
  1. macro_features.py +64 -0
macro_features.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Macro Features - FRED data, yield curve, VIX, credit spreads"""
2
+ import numpy as np
3
+ import pandas as pd
4
+ from typing import List
5
+
6
+ class MacroFeatures:
7
+ """Macroeconomic and sentiment overlay features"""
8
+
9
+ @staticmethod
10
+ def fetch_fred_data(series_ids, start='2020-01-01', end='2024-01-01'):
11
+ """Fetch macro data from FRED. Series: DGS10, DGS2, T10Y2Y, VIXCLS, UNRATE, BAA10YM"""
12
+ try:
13
+ from fredapi import Fred
14
+ import os
15
+ fred = Fred(api_key=os.environ.get('FRED_API_KEY', ''))
16
+ data = {}
17
+ for sid in series_ids:
18
+ try:
19
+ data[sid] = fred.get_series(sid, observation_start=start, observation_end=end)
20
+ except Exception as e:
21
+ print(f"FRED {sid}: {e}")
22
+ return pd.DataFrame(data)
23
+ except ImportError:
24
+ return MacroFeatures._synthetic_macro(start, end)
25
+
26
+ @staticmethod
27
+ def _synthetic_macro(start='2020-01-01', end='2024-01-01'):
28
+ dates = pd.bdate_range(start=start, end=end)
29
+ n = len(dates)
30
+ np.random.seed(42)
31
+ level = np.cumsum(np.random.normal(0, 0.01, n)) + 2.0
32
+ return pd.DataFrame({
33
+ 'DGS10': level + np.random.normal(0, 0.05, n),
34
+ 'DGS2': level * 0.6 + np.random.normal(0, 0.03, n),
35
+ 'T10Y2Y': level * 0.4 + np.random.normal(0, 0.02, n),
36
+ 'VIXCLS': 18 + np.random.normal(0, 3, n).clip(10, 45),
37
+ 'BAA10YM': 2.5 + np.random.normal(0, 0.2, n),
38
+ }, index=dates)
39
+
40
+ @staticmethod
41
+ def yield_curve_features(treasury_10y, treasury_2y):
42
+ features = pd.DataFrame(index=treasury_10y.index)
43
+ features['yc_spread'] = treasury_10y - treasury_2y
44
+ features['yc_slope'] = features['yc_spread'].diff(21)
45
+ features['yc_inversion'] = (features['yc_spread'] < 0).astype(float)
46
+ features['yc_zscore'] = (features['yc_spread'] - features['yc_spread'].rolling(252).mean()) / features['yc_spread'].rolling(252).std().replace(0, 1)
47
+ return features
48
+
49
+ @staticmethod
50
+ def vix_features(vix):
51
+ features = pd.DataFrame(index=vix.index)
52
+ features['vix_level'] = vix
53
+ features['vix_change'] = vix.pct_change()
54
+ features['vix_zscore'] = (vix - vix.rolling(63).mean()) / vix.rolling(63).std().replace(0, 1)
55
+ features['vix_term'] = vix.rolling(5).mean() - vix.rolling(21).mean()
56
+ return features
57
+
58
+ @staticmethod
59
+ def credit_spread_features(spread):
60
+ features = pd.DataFrame(index=spread.index)
61
+ features['credit_spread'] = spread
62
+ features['credit_change'] = spread.diff(21)
63
+ features['credit_zscore'] = (spread - spread.rolling(252).mean()) / spread.rolling(252).std().replace(0, 1)
64
+ return features