fa-quant 1.2.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fa_quant-1.2.1.dist-info/METADATA +236 -0
- fa_quant-1.2.1.dist-info/RECORD +106 -0
- fa_quant-1.2.1.dist-info/WHEEL +4 -0
- fa_quant-1.2.1.dist-info/entry_points.txt +2 -0
- fa_quant-1.2.1.dist-info/licenses/LICENSE +21 -0
- financial_agent/__init__.py +1 -0
- financial_agent/agents/__init__.py +0 -0
- financial_agent/agents/claude/__init__.py +0 -0
- financial_agent/agents/gpt/__init__.py +0 -0
- financial_agent/agents/grok/__init__.py +0 -0
- financial_agent/dl/__init__.py +0 -0
- financial_agent/dl/models/__init__.py +0 -0
- financial_agent/dl/models/baseline_model.py +23 -0
- financial_agent/dl/preprocessing/__init__.py +0 -0
- financial_agent/dl/preprocessing/data_windowing.py +135 -0
- financial_agent/harness/__init__.py +73 -0
- financial_agent/harness/__main__.py +430 -0
- financial_agent/harness/_system/factor_scoring.py +175 -0
- financial_agent/harness/_system/settlement_ledger.py +1222 -0
- financial_agent/harness/audit.py +393 -0
- financial_agent/harness/equity_policy.toml +179 -0
- financial_agent/harness/fingerprint.py +55 -0
- financial_agent/harness/gates.py +522 -0
- financial_agent/harness/handlers.py +77 -0
- financial_agent/harness/helpers.py +47 -0
- financial_agent/harness/kernels.py +696 -0
- financial_agent/harness/ledger.py +325 -0
- financial_agent/harness/lifecycle.py +127 -0
- financial_agent/harness/manifest.py +113 -0
- financial_agent/harness/market_calendar.py +50 -0
- financial_agent/harness/mcp.py +505 -0
- financial_agent/harness/policy.py +248 -0
- financial_agent/harness/runner.py +275 -0
- financial_agent/harness/schema.py +451 -0
- financial_agent/harness/scoring.py +363 -0
- financial_agent/harness/skills.py +458 -0
- financial_agent/quant/__init__.py +1 -0
- financial_agent/quant/__main__.py +506 -0
- financial_agent/quant/backtest/__init__.py +16 -0
- financial_agent/quant/backtest/config.py +74 -0
- financial_agent/quant/backtest/costs.py +62 -0
- financial_agent/quant/backtest/engine.py +248 -0
- financial_agent/quant/backtest/metrics.py +102 -0
- financial_agent/quant/backtest/result.py +51 -0
- financial_agent/quant/data/__init__.py +21 -0
- financial_agent/quant/data/bars.py +103 -0
- financial_agent/quant/data/cache.py +168 -0
- financial_agent/quant/data/providers.py +138 -0
- financial_agent/quant/data/quality.py +104 -0
- financial_agent/quant/data/synthetic.py +67 -0
- financial_agent/quant/execution/__init__.py +24 -0
- financial_agent/quant/execution/alpaca.py +293 -0
- financial_agent/quant/execution/broker.py +98 -0
- financial_agent/quant/execution/ibkr.py +634 -0
- financial_agent/quant/execution/journal.py +139 -0
- financial_agent/quant/execution/paper.py +254 -0
- financial_agent/quant/execution/reconcile.py +35 -0
- financial_agent/quant/mcp.py +210 -0
- financial_agent/quant/portfolio.py +56 -0
- financial_agent/quant/quant_policy.toml +40 -0
- financial_agent/quant/risk/__init__.py +21 -0
- financial_agent/quant/risk/killswitch.py +61 -0
- financial_agent/quant/risk/limits.py +109 -0
- financial_agent/quant/risk/orders.py +91 -0
- financial_agent/quant/risk/pretrade.py +157 -0
- financial_agent/quant/risk/state.py +86 -0
- financial_agent/quant/runner/__init__.py +20 -0
- financial_agent/quant/runner/config.py +254 -0
- financial_agent/quant/runner/promotion.py +277 -0
- financial_agent/quant/runner/report.py +231 -0
- financial_agent/quant/runner/session.py +705 -0
- financial_agent/quant/strategies/__init__.py +19 -0
- financial_agent/quant/strategies/base.py +44 -0
- financial_agent/quant/strategies/benchmarks.py +54 -0
- financial_agent/quant/strategies/momentum.py +80 -0
- financial_agent/quant/strategies/registry.py +65 -0
- financial_agent/quant/strategies/research.py +226 -0
- financial_agent/quant/strategies/trend.py +91 -0
- financial_agent/quant/validation/__init__.py +41 -0
- financial_agent/quant/validation/bootstrap.py +39 -0
- financial_agent/quant/validation/certificate.py +189 -0
- financial_agent/quant/validation/gate.py +304 -0
- financial_agent/quant/validation/overfitting.py +148 -0
- financial_agent/quant/validation/stress.py +33 -0
- financial_agent/quant/validation/walkforward.py +157 -0
- financial_agent/rl/__init__.py +13 -0
- financial_agent/rl/agent.py +112 -0
- financial_agent/rl/environment.py +177 -0
- financial_agent/rl/trainer.py +142 -0
- financial_agent/trading/__init__.py +0 -0
- financial_agent/trading/autotrain/__init__.py +0 -0
- financial_agent/trading/autotrain/training.py +92 -0
- financial_agent/trading/backtest.py +118 -0
- financial_agent/trading/config/__init__.py +0 -0
- financial_agent/trading/config/config.py +1587 -0
- financial_agent/trading/marketdata/__init__.py +0 -0
- financial_agent/trading/marketdata/yahoodownloader.py +99 -0
- financial_agent/trading/model/__init__.py +0 -0
- financial_agent/trading/model/models.py +466 -0
- financial_agent/trading/preprocessing/__init__.py +0 -0
- financial_agent/trading/preprocessing/data.py +32 -0
- financial_agent/trading/preprocessing/preprocessors.py +162 -0
- financial_agent/trading/utils/__init__.py +0 -0
- financial_agent/trading/utils/gpu_config.py +213 -0
- financial_agent/trading/utils/main.py +52 -0
- financial_agent/trading/utils/setup_gpu_for_notebooks.py +130 -0
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
import pandas as pd
|
|
3
|
+
from stockstats import StockDataFrame as Sdf
|
|
4
|
+
from ..config import config
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class FeatureEngineer:
|
|
8
|
+
"""Provides methods for preprocessing the stock price data
|
|
9
|
+
|
|
10
|
+
Attributes
|
|
11
|
+
----------
|
|
12
|
+
use_technical_indicator : boolean
|
|
13
|
+
we technical indicator or not
|
|
14
|
+
tech_indicator_list : list
|
|
15
|
+
a list of technical indicator names (modified from config.py)
|
|
16
|
+
use_turbulence : boolean
|
|
17
|
+
use turbulence index or not
|
|
18
|
+
user_defined_feature:boolean
|
|
19
|
+
user user defined features or not
|
|
20
|
+
|
|
21
|
+
Methods
|
|
22
|
+
-------
|
|
23
|
+
preprocess_data()
|
|
24
|
+
main method to do the feature engineering
|
|
25
|
+
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
def __init__(
|
|
29
|
+
self,
|
|
30
|
+
use_technical_indicator=True,
|
|
31
|
+
tech_indicator_list=config.TECHNICAL_INDICATORS_LIST,
|
|
32
|
+
use_turbulence=False,
|
|
33
|
+
user_defined_feature=False,
|
|
34
|
+
):
|
|
35
|
+
self.use_technical_indicator = use_technical_indicator
|
|
36
|
+
self.tech_indicator_list = tech_indicator_list
|
|
37
|
+
self.use_turbulence = use_turbulence
|
|
38
|
+
self.user_defined_feature = user_defined_feature
|
|
39
|
+
|
|
40
|
+
def preprocess_data(self, df):
|
|
41
|
+
"""main method to do the feature engineering
|
|
42
|
+
@:param config: source dataframe
|
|
43
|
+
@:return: a DataMatrices object
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
if self.use_technical_indicator == True:
|
|
47
|
+
# add technical indicators using stockstats
|
|
48
|
+
df = self.add_technical_indicator(df)
|
|
49
|
+
print("Successfully added technical indicators")
|
|
50
|
+
|
|
51
|
+
# add turbulence index for multiple stock
|
|
52
|
+
if self.use_turbulence == True:
|
|
53
|
+
df = self.add_turbulence(df)
|
|
54
|
+
print("Successfully added turbulence index")
|
|
55
|
+
|
|
56
|
+
# add user defined feature
|
|
57
|
+
if self.user_defined_feature == True:
|
|
58
|
+
df = self.add_user_defined_feature(df)
|
|
59
|
+
print("Successfully added user defined features")
|
|
60
|
+
|
|
61
|
+
# fill the missing values at the beginning and the end
|
|
62
|
+
df = df.fillna(method="bfill").fillna(method="ffill")
|
|
63
|
+
return df
|
|
64
|
+
|
|
65
|
+
def add_technical_indicator(self, data):
|
|
66
|
+
"""
|
|
67
|
+
calculate technical indicators
|
|
68
|
+
use stockstats package to add technical inidactors
|
|
69
|
+
:param data: (df) pandas dataframe
|
|
70
|
+
:return: (df) pandas dataframe
|
|
71
|
+
"""
|
|
72
|
+
df = data.copy()
|
|
73
|
+
df = df.sort_values(by=['tic','date'])
|
|
74
|
+
stock = Sdf.retype(df.copy())
|
|
75
|
+
unique_ticker = stock.tic.unique()
|
|
76
|
+
|
|
77
|
+
for indicator in self.tech_indicator_list:
|
|
78
|
+
indicator_df = pd.DataFrame()
|
|
79
|
+
for i in range(len(unique_ticker)):
|
|
80
|
+
try:
|
|
81
|
+
temp_indicator = stock[stock.tic == unique_ticker[i]][indicator]
|
|
82
|
+
temp_indicator = pd.DataFrame(temp_indicator)
|
|
83
|
+
temp_indicator['tic'] = unique_ticker[i]
|
|
84
|
+
temp_indicator['date'] = df[df.tic == unique_ticker[i]]['date'].to_list()
|
|
85
|
+
indicator_df = pd.concat([indicator_df, temp_indicator])
|
|
86
|
+
except Exception as e:
|
|
87
|
+
print(e)
|
|
88
|
+
indicator_df.reset_index(drop=True, inplace=True)
|
|
89
|
+
df = df.merge(indicator_df[['tic','date',indicator]],on=['tic','date'],how='left')
|
|
90
|
+
df = df.sort_values(by=['date','tic'])
|
|
91
|
+
return df
|
|
92
|
+
|
|
93
|
+
def add_user_defined_feature(self, data):
|
|
94
|
+
"""
|
|
95
|
+
add user defined features
|
|
96
|
+
:param data: (df) pandas dataframe
|
|
97
|
+
:return: (df) pandas dataframe
|
|
98
|
+
"""
|
|
99
|
+
df = data.copy()
|
|
100
|
+
df["daily_return"] = df.close.pct_change(1)
|
|
101
|
+
# df['return_lag_1']=df.close.pct_change(2)
|
|
102
|
+
# df['return_lag_2']=df.close.pct_change(3)
|
|
103
|
+
# df['return_lag_3']=df.close.pct_change(4)
|
|
104
|
+
# df['return_lag_4']=df.close.pct_change(5)
|
|
105
|
+
return df
|
|
106
|
+
|
|
107
|
+
def add_turbulence(self, data):
|
|
108
|
+
"""
|
|
109
|
+
add turbulence index from a precalcualted dataframe
|
|
110
|
+
:param data: (df) pandas dataframe
|
|
111
|
+
:return: (df) pandas dataframe
|
|
112
|
+
"""
|
|
113
|
+
df = data.copy()
|
|
114
|
+
turbulence_index = self.calculate_turbulence(df)
|
|
115
|
+
df = df.merge(turbulence_index, on="date")
|
|
116
|
+
df = df.sort_values(["date", "tic"]).reset_index(drop=True)
|
|
117
|
+
return df
|
|
118
|
+
|
|
119
|
+
def calculate_turbulence(self, data):
|
|
120
|
+
"""calculate turbulence index based on dow 30"""
|
|
121
|
+
# can add other market assets
|
|
122
|
+
df = data.copy()
|
|
123
|
+
df_price_pivot = df.pivot(index="date", columns="tic", values="close")
|
|
124
|
+
# use returns to calculate turbulence
|
|
125
|
+
df_price_pivot = df_price_pivot.pct_change()
|
|
126
|
+
|
|
127
|
+
unique_date = df.date.unique()
|
|
128
|
+
# start after a year
|
|
129
|
+
start = 252
|
|
130
|
+
turbulence_index = [0] * start
|
|
131
|
+
# turbulence_index = [0]
|
|
132
|
+
count = 0
|
|
133
|
+
for i in range(start, len(unique_date)):
|
|
134
|
+
current_price = df_price_pivot[df_price_pivot.index == unique_date[i]]
|
|
135
|
+
# use one year rolling window to calcualte covariance
|
|
136
|
+
hist_price = df_price_pivot[
|
|
137
|
+
(df_price_pivot.index < unique_date[i])
|
|
138
|
+
& (df_price_pivot.index >= unique_date[i - 252])
|
|
139
|
+
]
|
|
140
|
+
# Drop tickers which has number missing values more than the "oldest" ticker
|
|
141
|
+
filtered_hist_price = hist_price.iloc[hist_price.isna().sum().min():].dropna(axis=1)
|
|
142
|
+
|
|
143
|
+
cov_temp = filtered_hist_price.cov()
|
|
144
|
+
current_temp = current_price[[x for x in filtered_hist_price]] - np.mean(filtered_hist_price, axis=0)
|
|
145
|
+
temp = current_temp.values.dot(np.linalg.pinv(cov_temp)).dot(
|
|
146
|
+
current_temp.values.T
|
|
147
|
+
)
|
|
148
|
+
if temp > 0:
|
|
149
|
+
count += 1
|
|
150
|
+
if count > 2:
|
|
151
|
+
turbulence_temp = temp[0][0]
|
|
152
|
+
else:
|
|
153
|
+
# avoid large outlier because of the calculation just begins
|
|
154
|
+
turbulence_temp = 0
|
|
155
|
+
else:
|
|
156
|
+
turbulence_temp = 0
|
|
157
|
+
turbulence_index.append(turbulence_temp)
|
|
158
|
+
|
|
159
|
+
turbulence_index = pd.DataFrame(
|
|
160
|
+
{"date": df_price_pivot.index, "turbulence": turbulence_index}
|
|
161
|
+
)
|
|
162
|
+
return turbulence_index
|
|
File without changes
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""
|
|
2
|
+
GPU Configuration Module for Financial Agent
|
|
3
|
+
============================================
|
|
4
|
+
|
|
5
|
+
This module provides centralized GPU configuration for all TensorFlow operations
|
|
6
|
+
in the financial agent project. It handles device detection, memory management,
|
|
7
|
+
and provides utility functions for GPU-accelerated training.
|
|
8
|
+
|
|
9
|
+
Usage:
|
|
10
|
+
from gpu_config import setup_gpu, get_device_string, pick_device, DEVICE
|
|
11
|
+
|
|
12
|
+
# Setup GPU at the beginning of your script
|
|
13
|
+
setup_gpu()
|
|
14
|
+
|
|
15
|
+
# Or pick a device manually
|
|
16
|
+
device = pick_device(prefer_gpu=True) # Returns '/device:GPU:0' or '/CPU:0'
|
|
17
|
+
|
|
18
|
+
# Use DEVICE for all TensorFlow operations
|
|
19
|
+
with tf.device(DEVICE):
|
|
20
|
+
model = build_model()
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
import os
|
|
24
|
+
import tensorflow as tf
|
|
25
|
+
|
|
26
|
+
# Global device variable
|
|
27
|
+
DEVICE = None
|
|
28
|
+
|
|
29
|
+
def pick_device(prefer_gpu=True) -> str:
|
|
30
|
+
"""
|
|
31
|
+
Pick the optimal device for TensorFlow operations.
|
|
32
|
+
|
|
33
|
+
Args:
|
|
34
|
+
prefer_gpu (bool): Whether to prefer GPU over CPU if available
|
|
35
|
+
|
|
36
|
+
Returns:
|
|
37
|
+
str: Device name (e.g., '/device:GPU:0' or '/CPU:0')
|
|
38
|
+
"""
|
|
39
|
+
if prefer_gpu:
|
|
40
|
+
gpus = tf.config.list_logical_devices('GPU')
|
|
41
|
+
if gpus:
|
|
42
|
+
return gpus[0].name # e.g., '/device:GPU:0'
|
|
43
|
+
return '/CPU:0'
|
|
44
|
+
|
|
45
|
+
def setup_gpu():
|
|
46
|
+
"""
|
|
47
|
+
Configure GPU settings for optimal performance across all notebooks and scripts.
|
|
48
|
+
|
|
49
|
+
This function:
|
|
50
|
+
1. Disables XLA compilation to avoid platform detection issues
|
|
51
|
+
2. Sets up memory growth for GPU devices
|
|
52
|
+
3. Configures TensorFlow for better compatibility
|
|
53
|
+
4. Sets the global DEVICE variable
|
|
54
|
+
|
|
55
|
+
Returns:
|
|
56
|
+
str: The device string to use for TensorFlow operations
|
|
57
|
+
"""
|
|
58
|
+
global DEVICE
|
|
59
|
+
|
|
60
|
+
# Disable XLA compilation to avoid platform detection issues
|
|
61
|
+
os.environ['TF_XLA_FLAGS'] = '--tf_xla_enable_xla_devices=false'
|
|
62
|
+
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'
|
|
63
|
+
|
|
64
|
+
# Configure TensorFlow for better compatibility
|
|
65
|
+
tf.config.run_functions_eagerly(False)
|
|
66
|
+
tf.config.optimizer.set_jit(False) # Disable XLA JIT compilation
|
|
67
|
+
|
|
68
|
+
# Set memory growth for GPU if available
|
|
69
|
+
gpus = tf.config.experimental.list_physical_devices('GPU')
|
|
70
|
+
if gpus:
|
|
71
|
+
try:
|
|
72
|
+
for gpu in gpus:
|
|
73
|
+
tf.config.experimental.set_memory_growth(gpu, True)
|
|
74
|
+
print(f"ā GPU available: {len(gpus)} device(s)")
|
|
75
|
+
print("ā Memory growth enabled for all GPU devices")
|
|
76
|
+
except RuntimeError as e:
|
|
77
|
+
print(f"GPU memory growth setting failed: {e}")
|
|
78
|
+
else:
|
|
79
|
+
print("ā No GPU detected, using CPU")
|
|
80
|
+
|
|
81
|
+
# Pick the optimal device using actual TensorFlow device names
|
|
82
|
+
DEVICE = pick_device(prefer_gpu=True)
|
|
83
|
+
print(f"ā TensorFlow configured for device: {DEVICE}")
|
|
84
|
+
return DEVICE
|
|
85
|
+
|
|
86
|
+
def get_device_string():
|
|
87
|
+
"""
|
|
88
|
+
Get the current device string for TensorFlow operations.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
str: Device string (e.g., '/device:GPU:0' or '/CPU:0')
|
|
92
|
+
"""
|
|
93
|
+
if DEVICE is None:
|
|
94
|
+
return setup_gpu()
|
|
95
|
+
return DEVICE
|
|
96
|
+
|
|
97
|
+
def get_device_info():
|
|
98
|
+
"""
|
|
99
|
+
Get detailed information about available devices.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
dict: Device information including GPU details
|
|
103
|
+
"""
|
|
104
|
+
info = {
|
|
105
|
+
'tensorflow_version': tf.__version__,
|
|
106
|
+
'gpu_available': len(tf.config.experimental.list_physical_devices('GPU')) > 0,
|
|
107
|
+
'gpu_count': len(tf.config.experimental.list_physical_devices('GPU')),
|
|
108
|
+
'current_device': get_device_string(),
|
|
109
|
+
'gpu_devices': tf.config.experimental.list_physical_devices('GPU'),
|
|
110
|
+
'cpu_devices': tf.config.experimental.list_physical_devices('CPU')
|
|
111
|
+
}
|
|
112
|
+
return info
|
|
113
|
+
|
|
114
|
+
def print_device_info():
|
|
115
|
+
"""Print comprehensive device information."""
|
|
116
|
+
info = get_device_info()
|
|
117
|
+
print("=" * 50)
|
|
118
|
+
print("GPU CONFIGURATION INFO")
|
|
119
|
+
print("=" * 50)
|
|
120
|
+
print(f"TensorFlow Version: {info['tensorflow_version']}")
|
|
121
|
+
print(f"GPU Available: {info['gpu_available']}")
|
|
122
|
+
print(f"GPU Count: {info['gpu_count']}")
|
|
123
|
+
print(f"Current Device: {info['current_device']}")
|
|
124
|
+
|
|
125
|
+
if info['gpu_devices']:
|
|
126
|
+
print("\nGPU Devices:")
|
|
127
|
+
for i, gpu in enumerate(info['gpu_devices']):
|
|
128
|
+
print(f" {i}: {gpu}")
|
|
129
|
+
|
|
130
|
+
print(f"\nCPU Devices: {len(info['cpu_devices'])}")
|
|
131
|
+
print("=" * 50)
|
|
132
|
+
|
|
133
|
+
def configure_mixed_precision():
|
|
134
|
+
"""
|
|
135
|
+
Configure mixed precision training for better GPU performance.
|
|
136
|
+
|
|
137
|
+
Returns:
|
|
138
|
+
bool: True if mixed precision is enabled, False otherwise
|
|
139
|
+
"""
|
|
140
|
+
if 'GPU' in get_device_string():
|
|
141
|
+
try:
|
|
142
|
+
policy = tf.keras.mixed_precision.Policy('mixed_float16')
|
|
143
|
+
tf.keras.mixed_precision.set_global_policy(policy)
|
|
144
|
+
print("ā Mixed precision training enabled for GPU")
|
|
145
|
+
return True
|
|
146
|
+
except Exception as e:
|
|
147
|
+
print(f"Failed to enable mixed precision: {e}")
|
|
148
|
+
return False
|
|
149
|
+
else:
|
|
150
|
+
print("Mixed precision only available on GPU")
|
|
151
|
+
return False
|
|
152
|
+
|
|
153
|
+
def get_optimal_batch_size(base_batch_size=32):
|
|
154
|
+
"""
|
|
155
|
+
Get optimal batch size based on available device.
|
|
156
|
+
|
|
157
|
+
Args:
|
|
158
|
+
base_batch_size (int): Base batch size for CPU
|
|
159
|
+
|
|
160
|
+
Returns:
|
|
161
|
+
int: Optimized batch size for the current device
|
|
162
|
+
"""
|
|
163
|
+
if 'GPU' in get_device_string():
|
|
164
|
+
# Increase batch size for GPU
|
|
165
|
+
return base_batch_size * 4
|
|
166
|
+
else:
|
|
167
|
+
return base_batch_size
|
|
168
|
+
|
|
169
|
+
def create_device_aware_model(model_builder, *args, **kwargs):
|
|
170
|
+
"""
|
|
171
|
+
Create a model with proper device placement.
|
|
172
|
+
|
|
173
|
+
Args:
|
|
174
|
+
model_builder: Function that builds the model
|
|
175
|
+
*args: Arguments for model builder
|
|
176
|
+
**kwargs: Keyword arguments for model builder
|
|
177
|
+
|
|
178
|
+
Returns:
|
|
179
|
+
tf.keras.Model: Model created on the appropriate device
|
|
180
|
+
"""
|
|
181
|
+
with tf.device(get_device_string()):
|
|
182
|
+
model = model_builder(*args, **kwargs)
|
|
183
|
+
return model
|
|
184
|
+
|
|
185
|
+
def train_on_device(model, x_train, y_train, **kwargs):
|
|
186
|
+
"""
|
|
187
|
+
Train a model with proper device placement.
|
|
188
|
+
|
|
189
|
+
Args:
|
|
190
|
+
model: Keras model to train
|
|
191
|
+
x_train: Training features
|
|
192
|
+
y_train: Training labels
|
|
193
|
+
**kwargs: Additional arguments for model.fit()
|
|
194
|
+
|
|
195
|
+
Returns:
|
|
196
|
+
tf.keras.callbacks.History: Training history
|
|
197
|
+
"""
|
|
198
|
+
# Convert to tensors with proper device placement
|
|
199
|
+
with tf.device(get_device_string()):
|
|
200
|
+
x_train_tensor = tf.convert_to_tensor(x_train, dtype=tf.float32)
|
|
201
|
+
y_train_tensor = tf.convert_to_tensor(y_train, dtype=tf.float32)
|
|
202
|
+
|
|
203
|
+
# Train the model
|
|
204
|
+
history = model.fit(x_train_tensor, y_train_tensor, **kwargs)
|
|
205
|
+
return history
|
|
206
|
+
|
|
207
|
+
# Initialize GPU configuration when module is imported
|
|
208
|
+
if __name__ == "__main__":
|
|
209
|
+
setup_gpu()
|
|
210
|
+
print_device_info()
|
|
211
|
+
else:
|
|
212
|
+
# Auto-setup when imported
|
|
213
|
+
setup_gpu()
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import logging
|
|
3
|
+
import os
|
|
4
|
+
import time
|
|
5
|
+
from argparse import ArgumentParser
|
|
6
|
+
import datetime
|
|
7
|
+
|
|
8
|
+
from ..config import config
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def build_parser():
|
|
12
|
+
parser = ArgumentParser()
|
|
13
|
+
parser.add_argument(
|
|
14
|
+
"--mode",
|
|
15
|
+
dest="mode",
|
|
16
|
+
help="start mode, train, download_data" " backtest",
|
|
17
|
+
metavar="MODE",
|
|
18
|
+
default="train",
|
|
19
|
+
)
|
|
20
|
+
return parser
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def main():
|
|
24
|
+
parser = build_parser()
|
|
25
|
+
options = parser.parse_args()
|
|
26
|
+
if not os.path.exists("./" + config.DATA_SAVE_DIR):
|
|
27
|
+
os.makedirs("./" + config.DATA_SAVE_DIR)
|
|
28
|
+
if not os.path.exists("./" + config.TRAINED_MODEL_DIR):
|
|
29
|
+
os.makedirs("./" + config.TRAINED_MODEL_DIR)
|
|
30
|
+
if not os.path.exists("./" + config.TENSORBOARD_LOG_DIR):
|
|
31
|
+
os.makedirs("./" + config.TENSORBOARD_LOG_DIR)
|
|
32
|
+
if not os.path.exists("./" + config.RESULTS_DIR):
|
|
33
|
+
os.makedirs("./" + config.RESULTS_DIR)
|
|
34
|
+
|
|
35
|
+
if options.mode == "train":
|
|
36
|
+
from ..autotrain import training
|
|
37
|
+
|
|
38
|
+
training.train_one()
|
|
39
|
+
|
|
40
|
+
elif options.mode == "download_data":
|
|
41
|
+
from ..marketdata.yahoodownloader import YahooDownloader
|
|
42
|
+
|
|
43
|
+
df = YahooDownloader(start_date=config.START_DATE,
|
|
44
|
+
end_date=config.END_DATE,
|
|
45
|
+
ticker_list=config.DOW_30_TICKER).fetch_data()
|
|
46
|
+
now = datetime.datetime.now().strftime("%Y%m%d-%Hh%M")
|
|
47
|
+
df.to_csv("./" + config.DATA_SAVE_DIR + "/" + now + ".csv")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
if __name__ == "__main__":
|
|
52
|
+
main()
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
"""
|
|
2
|
+
GPU Setup Script for Jupyter Notebooks
|
|
3
|
+
======================================
|
|
4
|
+
|
|
5
|
+
This script sets up GPU configuration for all Jupyter notebooks in the core_trading directory.
|
|
6
|
+
Run this script at the beginning of any notebook to ensure proper GPU configuration.
|
|
7
|
+
|
|
8
|
+
Usage in Jupyter Notebook:
|
|
9
|
+
%run setup_gpu_for_notebooks.py
|
|
10
|
+
|
|
11
|
+
Or import and use:
|
|
12
|
+
from setup_gpu_for_notebooks import setup_gpu_for_notebook
|
|
13
|
+
setup_gpu_for_notebook()
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
import os
|
|
17
|
+
import sys
|
|
18
|
+
import warnings
|
|
19
|
+
|
|
20
|
+
# Add the current directory to Python path
|
|
21
|
+
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
22
|
+
if current_dir not in sys.path:
|
|
23
|
+
sys.path.append(current_dir)
|
|
24
|
+
|
|
25
|
+
# Import GPU configuration
|
|
26
|
+
from gpu_config import setup_gpu, print_device_info, DEVICE, get_device_string
|
|
27
|
+
|
|
28
|
+
def setup_gpu_for_notebook():
|
|
29
|
+
"""
|
|
30
|
+
Setup GPU configuration for Jupyter notebooks.
|
|
31
|
+
This function should be called at the beginning of any notebook.
|
|
32
|
+
"""
|
|
33
|
+
print("=" * 60)
|
|
34
|
+
print("š SETTING UP GPU FOR FINANCIAL AGENT NOTEBOOKS")
|
|
35
|
+
print("=" * 60)
|
|
36
|
+
|
|
37
|
+
# Setup GPU configuration
|
|
38
|
+
device = setup_gpu()
|
|
39
|
+
|
|
40
|
+
# Print device information
|
|
41
|
+
print_device_info()
|
|
42
|
+
|
|
43
|
+
# Import TensorFlow and other ML libraries
|
|
44
|
+
try:
|
|
45
|
+
import tensorflow as tf
|
|
46
|
+
print(f"ā
TensorFlow {tf.__version__} loaded successfully")
|
|
47
|
+
|
|
48
|
+
# Test GPU availability
|
|
49
|
+
if device == '/GPU:0':
|
|
50
|
+
print("ā
GPU acceleration is ENABLED")
|
|
51
|
+
print("ā
All TensorFlow operations will use GPU")
|
|
52
|
+
else:
|
|
53
|
+
print("ā ļø GPU not available, using CPU")
|
|
54
|
+
|
|
55
|
+
except ImportError as e:
|
|
56
|
+
print(f"ā Error importing TensorFlow: {e}")
|
|
57
|
+
return False
|
|
58
|
+
|
|
59
|
+
# Import other required libraries
|
|
60
|
+
try:
|
|
61
|
+
import numpy as np
|
|
62
|
+
import pandas as pd
|
|
63
|
+
print(f"ā
NumPy {np.__version__} loaded successfully")
|
|
64
|
+
print(f"ā
Pandas {pd.__version__} loaded successfully")
|
|
65
|
+
except ImportError as e:
|
|
66
|
+
print(f"ā Error importing required libraries: {e}")
|
|
67
|
+
return False
|
|
68
|
+
|
|
69
|
+
print("=" * 60)
|
|
70
|
+
print("ā
GPU SETUP COMPLETE - READY FOR TRAINING!")
|
|
71
|
+
print("=" * 60)
|
|
72
|
+
|
|
73
|
+
return True
|
|
74
|
+
|
|
75
|
+
def get_notebook_device():
|
|
76
|
+
"""
|
|
77
|
+
Get the current device for use in notebook cells.
|
|
78
|
+
|
|
79
|
+
Returns:
|
|
80
|
+
str: Device string ('/GPU:0' or '/CPU:0')
|
|
81
|
+
"""
|
|
82
|
+
return get_device_string()
|
|
83
|
+
|
|
84
|
+
def print_training_info():
|
|
85
|
+
"""
|
|
86
|
+
Print information about GPU-accelerated training.
|
|
87
|
+
"""
|
|
88
|
+
print("\n" + "=" * 60)
|
|
89
|
+
print("š GPU-ACCELERATED TRAINING INFORMATION")
|
|
90
|
+
print("=" * 60)
|
|
91
|
+
|
|
92
|
+
device = get_device_string()
|
|
93
|
+
|
|
94
|
+
if device == '/GPU:0':
|
|
95
|
+
print("š GPU ACCELERATION ENABLED")
|
|
96
|
+
print(" ⢠All TensorFlow operations will use GPU")
|
|
97
|
+
print(" ⢠Training will be significantly faster")
|
|
98
|
+
print(" ⢠Memory growth is enabled for optimal performance")
|
|
99
|
+
print(" ⢠XLA compilation is disabled to prevent errors")
|
|
100
|
+
else:
|
|
101
|
+
print("š» CPU TRAINING MODE")
|
|
102
|
+
print(" ⢠All operations will use CPU")
|
|
103
|
+
print(" ⢠Training will be slower but more stable")
|
|
104
|
+
print(" ⢠No GPU memory management needed")
|
|
105
|
+
|
|
106
|
+
print("\nš USAGE IN YOUR NOTEBOOK:")
|
|
107
|
+
print(" ⢠Use DEVICE variable for all tf.device() calls")
|
|
108
|
+
print(" ⢠Models will automatically be created on the correct device")
|
|
109
|
+
print(" ⢠Training functions handle device placement automatically")
|
|
110
|
+
|
|
111
|
+
print("=" * 60)
|
|
112
|
+
|
|
113
|
+
if __name__ == "__main__":
|
|
114
|
+
# Run setup when script is executed directly
|
|
115
|
+
setup_gpu_for_notebook()
|
|
116
|
+
print_training_info()
|
|
117
|
+
else:
|
|
118
|
+
# Auto-setup when imported
|
|
119
|
+
setup_gpu_for_notebook()
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
|