ai4finance-foundation / finrl-tutorials Goto Github PK
View Code? Open in Web Editor NEWTutorials. Please star.
Home Page: https://ai4finance.org
License: MIT License
Tutorials. Please star.
Home Page: https://ai4finance.org
License: MIT License
df_actions:
600000.SH,600009.SH,600016.SH,600028.SH,600030.SH,600031.SH,600036.SH,600050.SH,600104.SH,600196.SH,600276.SH,600309.SH,600519.SH,600547.SH,600570.SH
-1000,1000,-1000,1000,1000,-1000,1000,1000,1000,-1000,1000,1000,1000,1000,-1000
0,0,0,0,0,0,0,300,0,0,0,500,1000,1000,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
......
Like this, only traded in the firs two days, other days are 0.
How should I adjust the parameters to solve this problem?
Thanks.
MergeError: Passing 'suffixes' which cause duplicate columns {'account_value_x'} is not allowed.
please change to this code:
result = pd.merge(df_result_a2c, df_result_ddpg, left_index=True, right_index=True)
result = pd.merge(result, df_result_td3, left_index=True, right_index=True)
result = pd.merge(result, df_result_ppo, left_index=True, right_index=True, suffixes=('_1', '_2'))
result = pd.merge(result, df_result_sac, left_index=True, right_index=True)
result = pd.merge(result, MVO_result, left_index=True, right_index=True, suffixes=('_3', '_4'))
result = pd.merge(result, df_dji, left_index=True, right_index=True, suffixes=('_5', '_6'))
result.columns = ['a2c', 'ddpg', 'td3', 'ppo', 'sac', 'mean var', 'dji']
'''
conda activate base
(base) drulye@drulye-MS-7885:~/vscode/MCpypto$ conda activate base
/usr/bin/env /home/drulye/anaconda3/bin/python /home/drulye/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher 36507 -- /home/drulye/vscode/MCpypto/main.py
(base) drulye@drulye-MS-7885:~/vscode/MCpypto$ /usr/bin/env /home/drulye/anaconda3/bin/python /home/drulye/.vscode/extensions/ms-python.python-2022.20.1/pythonFiles/lib/python/debugpy/adapter/../../debugpy/launcher 36507 -- /home/drulye/vscode/MCpypto/main.py
/home/drulye/anaconda3/lib/python3.9/site-packages/scipy/__init__.py:146: UserWarning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.23.5
warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}"
QObject::moveToThread: Current thread (0x8cbc810) is not the object's thread (0x904ade0).
Cannot move to target thread (0x8cbc810)
qt.qpa.plugin: Could not load the Qt platform plugin "xcb" in "/home/drulye/anaconda3/lib/python3.9/site-packages/cv2/qt/plugins" even though it was found.
This application failed to start because no Qt platform plugin could be initialized. Reinstalling the application may fix this problem.
Available platform plugins are: xcb, eglfs, minimal, minimalegl, offscreen, vnc, webgl.
(base) drulye@drulye-MS-7885:~/vscode/MCpypto$
'''
'''
conda activate base
(base) drulye@drulye-MS-7885:~/vscode/MCpypto$ conda activate base
/home/drulye/anaconda3/bin/python /home/drulye/vscode/MCpypto/main.py
(base) drulye@drulye-MS-7885:~/vscode/MCpypto$ /home/drulye/anaconda3/bin/python /home/drulye/vscode/MCpypto/main.py
/home/drulye/anaconda3/lib/python3.9/site-packages/scipy/__init__.py:146: UserWarning: A NumPy version >=1.16.5 and <1.23.0 is required for this version of SciPy (detected version 1.23.5
warnings.warn(f"A NumPy version >={np_minversion} and <{np_maxversion}"
binance successfully connected
Using cached file ./cache/BTCUSDT_ETHUSDT_ADAUSDT_BNBUSDT_XRPUSDT_SOLUSDT_DOTUSDT_DOGEUSDT_AVAXUSDT_UNIUSDT_binance_2021-09-01_2021-09-02_5m.pickle
tech_indicator_list: ['macd', 'rsi', 'cci', 'dx']
indicator: macd
indicator: rsi
indicator: cci
indicator: dx
Succesfully add technical indicators
Successfully transformed into array
| Arguments Remove cwd: ./test_ppo
Traceback (most recent call last):
File "/home/drulye/vscode/MCpypto/main.py", line 329, in <module>
train(start_date=TRAIN_START_DATE,
File "/home/drulye/vscode/MCpypto/main.py", line 89, in train
trained_model = agent.train_model(model=model,
File "/home/drulye/vscode/FinRL-Meta/agents/elegantrl_models.py", line 79, in train_model
train_and_evaluate(model)
File "/home/drulye/vscode/ElegantRL/elegantrl/train/run.py", line 95, in train_and_evaluate
agent = init_agent(args, gpu_id, env)
File "/home/drulye/vscode/ElegantRL/elegantrl/train/run.py", line 24, in init_agent
agent = args.agent_class(args.net_dim, args.state_dim, args.action_dim, gpu_id=gpu_id, args=args)
File "/home/drulye/vscode/ElegantRL/elegantrl/agents/AgentPPO.py", line 40, in __init__
AgentBase.__init__(self, net_dim, state_dim, action_dim, gpu_id, args)
File "/home/drulye/vscode/ElegantRL/elegantrl/agents/AgentBase.py", line 57, in __init__
self.act = act_class(net_dim, state_dim, action_dim).to(self.device)
File "/home/drulye/vscode/ElegantRL/elegantrl/agents/net.py", line 397, in __init__
self.net = build_mlp_net(dims=[state_dim, *dims, action_dim])
TypeError: Value after * must be an iterable, not int
(base) drulye@drulye-MS-7885:~/vscode/MCpypto$
'''
import math
import numpy as np
import sys
sys.path.insert(0, "/home/drulye/vscode/FinRL")
sys.path.insert(0, "/home/drulye/vscode/ElegantRL")
sys.path.insert(0, "/home/drulye/vscode/FinRL-Meta")
from agents.elegantrl_models import DRLAgent as DRLAgent_erl
from agents.rllib_models import DRLAgent as DRLAgent_rllib
from agents.stablebaselines3_models import DRLAgent as DRLAgent_sb3
from meta.data_processor import DataProcessor
def train(start_date, end_date, ticker_list, data_source, time_interval,
technical_indicator_list, drl_lib, env, model_name, if_vix=True,
**kwargs):
#process data using unified data processor
DP = DataProcessor(data_source, start_date, end_date, time_interval, **kwargs)
price_array, tech_array, turbulence_array = DP.run(ticker_list,
technical_indicator_list,
if_vix, cache=True)
data_config = {'price_array': price_array,
'tech_array': tech_array,
'turbulence_array': turbulence_array}
#build environment using processed data
env_instance = env(config=data_config)
#read parameters and load agents
current_working_dir = kwargs.get('current_working_dir','./'+str(model_name))
if drl_lib == 'elegantrl':
break_step = kwargs.get('break_step', 1e6)
erl_params = kwargs.get('erl_params')
agent = DRLAgent_erl(env = env,
price_array = price_array,
tech_array=tech_array,
turbulence_array=turbulence_array)
model = agent.get_model(model_name, model_kwargs = erl_params)
trained_model = agent.train_model(model=model,
cwd=current_working_dir,
total_timesteps=break_step)
elif drl_lib == 'rllib':
total_episodes = kwargs.get('total_episodes', 100)
rllib_params = kwargs.get('rllib_params')
agent_rllib = DRLAgent_rllib(env = env,
price_array=price_array,
tech_array=tech_array,
turbulence_array=turbulence_array)
model,model_config = agent_rllib.get_model(model_name)
model_config['lr'] = rllib_params['lr']
model_config['train_batch_size'] = rllib_params['train_batch_size']
model_config['gamma'] = rllib_params['gamma']
trained_model = agent_rllib.train_model(model=model,
model_name=model_name,
model_config=model_config,
total_episodes=total_episodes)
trained_model.save(current_working_dir)
elif drl_lib == 'stable_baselines3':
total_timesteps = kwargs.get('total_timesteps', 1e6)
agent_params = kwargs.get('agent_params')
agent = DRLAgent_sb3(env = env_instance)
model = agent.get_model(model_name, model_kwargs = agent_params)
trained_model = agent.train_model(model=model,
tb_log_name=model_name,
total_timesteps=total_timesteps)
print('Training finished!')
trained_model.save(current_working_dir)
print('Trained model saved in ' + str(current_working_dir))
else:
raise ValueError('DRL library input is NOT supported. Please check.')
def test(start_date, end_date, ticker_list, data_source, time_interval,
technical_indicator_list, drl_lib, env, model_name, if_vix=True,
**kwargs):
#process data using unified data processor
DP = DataProcessor(data_source, start_date, end_date, time_interval, **kwargs)
price_array, tech_array, turbulence_array = DP.run(ticker_list,
technical_indicator_list,
if_vix, cache=True)
np.save('./price_array.npy', price_array)
data_config = {'price_array':price_array,
'tech_array':tech_array,
'turbulence_array':turbulence_array}
#build environment using processed data
env_instance = env(config=data_config)
env_config = {
"price_array": price_array,
"tech_array": tech_array,
"turbulence_array": turbulence_array,
"if_train": False,
}
env_instance = env(config=env_config)
# load elegantrl needs state dim, action dim and net dim
net_dimension = kwargs.get("net_dimension", 2 ** 7)
current_working_dir = kwargs.get("current_working_dir", "./" + str(model_name))
print("price_array: ", len(price_array))
if drl_lib == "elegantrl":
episode_total_assets = DRLAgent_erl.DRL_prediction(
model_name=model_name,
cwd=current_working_dir,
net_dimension=net_dimension,
environment=env_instance,
)
return episode_total_assets
elif drl_lib == "rllib":
# load agent
episode_total_assets = DRLAgent_rllib.DRL_prediction(
model_name=model_name,
env=env,
price_array=price_array,
tech_array=tech_array,
turbulence_array=turbulence_array,
agent_path=current_working_dir,
)
return episode_total_assets
elif drl_lib == "stable_baselines3":
episode_total_assets = DRLAgent_sb3.DRL_prediction_load_from_file(
model_name=model_name, environment=env_instance, cwd=current_working_dir
)
return episode_total_assets
else:
raise ValueError("DRL library input is NOT supported. Please check.")
class CryptoEnv: # custom env
def __init__(self, config, lookback=1, initial_capital=1e6,
buy_cost_pct=1e-3, sell_cost_pct=1e-3, gamma=0.99):
self.lookback = lookback
self.initial_total_asset = initial_capital
self.initial_cash = initial_capital
self.buy_cost_pct = buy_cost_pct
self.sell_cost_pct = sell_cost_pct
self.max_stock = 1
self.gamma = gamma
self.price_array = config['price_array']
self.tech_array = config['tech_array']
self._generate_action_normalizer()
self.crypto_num = self.price_array.shape[1]
self.max_step = self.price_array.shape[0] - lookback - 1
# reset
self.time = lookback-1
self.cash = self.initial_cash
self.current_price = self.price_array[self.time]
self.current_tech = self.tech_array[self.time]
self.stocks = np.zeros(self.crypto_num, dtype=np.float32)
self.total_asset = self.cash + (self.stocks * self.price_array[self.time]).sum()
self.episode_return = 0.0
self.gamma_return = 0.0
'''env information'''
self.env_name = 'MulticryptoEnv'
self.state_dim = 1 + (self.price_array.shape[1] + self.tech_array.shape[1])*lookback
self.action_dim = self.price_array.shape[1]
self.if_discrete = False
self.target_return = 10
def reset(self) -> np.ndarray:
self.time = self.lookback-1
self.current_price = self.price_array[self.time]
self.current_tech = self.tech_array[self.time]
self.cash = self.initial_cash # reset()
self.stocks = np.zeros(self.crypto_num, dtype=np.float32)
self.total_asset = self.cash + (self.stocks * self.price_array[self.time]).sum()
state = self.get_state()
return state
def step(self, actions) -> (np.ndarray, float, bool, None):
self.time += 1
price = self.price_array[self.time]
for i in range(self.action_dim):
norm_vector_i = self.action_norm_vector[i]
actions[i] = actions[i] * norm_vector_i
for index in np.where(actions < 0)[0]: # sell_index:
if price[index] > 0: # Sell only if current asset is > 0
sell_num_shares = min(self.stocks[index], -actions[index])
self.stocks[index] -= sell_num_shares
self.cash += price[index] * sell_num_shares * (1 - self.sell_cost_pct)
for index in np.where(actions > 0)[0]: # buy_index:
if price[index] > 0: # Buy only if the price is > 0 (no missing data in this particular date)
buy_num_shares = min(self.cash // price[index], actions[index])
self.stocks[index] += buy_num_shares
self.cash -= price[index] * buy_num_shares * (1 + self.buy_cost_pct)
"""update time"""
done = self.time == self.max_step
state = self.get_state()
next_total_asset = self.cash + (self.stocks * self.price_array[self.time]).sum()
reward = (next_total_asset - self.total_asset) * 2 ** -16
self.total_asset = next_total_asset
self.gamma_return = self.gamma_return * self.gamma + reward
self.cumu_return = self.total_asset / self.initial_cash
if done:
reward = self.gamma_return
self.episode_return = self.total_asset / self.initial_cash
return state, reward, done, None
def get_state(self):
state = np.hstack((self.cash * 2 ** -18, self.stocks * 2 ** -3))
for i in range(self.lookback):
tech_i = self.tech_array[self.time-i]
normalized_tech_i = tech_i * 2 ** -15
state = np.hstack((state, normalized_tech_i)).astype(np.float32)
return state
def close(self):
pass
def _generate_action_normalizer(self):
action_norm_vector = []
price_0 = self.price_array[0]
for price in price_0:
x = math.floor(math.log(price, 10)) #the order of magnitude
action_norm_vector.append(1/((10)**x))
action_norm_vector = np.asarray(action_norm_vector) * 10000
self.action_norm_vector = np.asarray(action_norm_vector)
env = CryptoEnv
TICKER_LIST = ['BTCUSDT','ETHUSDT','ADAUSDT','BNBUSDT','XRPUSDT',
'SOLUSDT','DOTUSDT', 'DOGEUSDT','AVAXUSDT','UNIUSDT']
TRAIN_START_DATE = '2021-09-01'
TRAIN_END_DATE = '2021-09-02'
TEST_START_DATE = '2021-09-21'
TEST_END_DATE = '2021-09-30'
INDICATORS = ['macd', 'rsi', 'cci', 'dx'] #self-defined technical indicator list is NOT supported yet
ERL_PARAMS = {"learning_rate": 2**-15,"batch_size": 2**11,
"gamma": 0.99, "seed":312,"net_dimension": 2**9,
"target_step": 5000, "eval_gap": 30, "eval_times": 1}
train(start_date=TRAIN_START_DATE,
end_date=TRAIN_END_DATE,
ticker_list=TICKER_LIST,
data_source='binance',
time_interval='5m',
technical_indicator_list=INDICATORS,
drl_lib='elegantrl',
env=env,
model_name='ppo',
current_working_dir='./test_ppo',
erl_params=ERL_PARAMS,
break_step=5e4,
if_vix=False
)
account_value_erl = test(start_date = TEST_START_DATE,
end_date = TEST_END_DATE,
ticker_list = TICKER_LIST,
data_source = 'binance',
time_interval= '5m',
technical_indicator_list= INDICATORS,
drl_lib='elegantrl',
env=env,
model_name='ppo',
current_working_dir='./test_ppo',
net_dimension = 2**9,
if_vix=False
)
/usr/local/lib/python3.10/site-packages/exchange_calendars/calendar_helpers.py in parse_date(date, param_name, calendar, raise_oob)
377 ts = parse_timestamp(date, param_name, raise_oob=False, side="left", utc=False)
378
--> 379 if ts.tz is not None:
380 raise ValueError(
381 f"Parameter {param_name}
received with timezone defined as '{ts.tz.key}'"
AttributeError: 'UTC' object has no attribute 'key'
Hi,
the README file says that for TensorFlow 2 we should use branch tf2. however, there seems only to be a master branch in the repo. Any ideas on how should I apply TensorFlow 2 on this?
Hello,
There is a pre-trained agent (agent_a2c.zip) that is included in Stock_NeurIPS2018.
I also reran the notebooks 1 and 2 to train agent_a2c. However the backtest result of the new agent is much worse than the result of the pre-trained agent, even worse than the baseline DJI. Any ideas?
Thanks!
Tagging @ZiyiXia as I see the sample agent was uploaded by you. Was this generated by following the steps in the notebooks or is there anything special about it? It seems to perform much better than the one I re-generated.
RuntimeError Traceback (most recent call last)
in <cell line: 1>()
----> 1 account_value_erl=test(start_date = '2022-08-25',
2 end_date = '2022-08-31',
3 ticker_list = ticker_list,
4 data_source = 'alpaca',
5 time_interval= '1Min',
1 frames
in DRL_prediction(model_name, cwd, net_dimension, environment)
102 with _torch.no_grad():
103 for i in range(environment.max_step):
--> 104 s_tensor = _torch.as_tensor((state,), device=device)
105 a_tensor = act(s_tensor) # action_tanh = act.forward()
106 action = (
RuntimeError: Could not infer dtype of dict
where do I find the data file (train_data.csv, trade_data.csv )for those notebooks
may someone explain the purpose of the codes from line 63 to 73?
the missing dates in the 'processed' are added to 'processed_full' and then deleted; finally it seems that the only difference between 'processed' and 'processed_full' is the position of column 'tic', what else? if it is, why not just reorganize the columns of 'processed'? 😂
Hey guys, how are you doing today?
I didn't do any changes to the file. When I run A2C, it trains normally, but I when I run the other agents training, it immediately finishes, without any logs to debug. Can someone help me figure out what is happening?
the file FinRL_HyperparameterTuning_Optuna.ipynb gives me the following error
TypeError Traceback (most recent call last)
Cell In[17], line 16
3 env_kwargs = {
4 "hmax": 100,
5 "initial_amount": 1000000,
(...)
13
14 }
15 #Instantiate the training gym compatible environment
---> 16 e_train_gym = StockTradingEnv(df = train, **env_kwargs)
TypeError: __init__() missing 1 required positional argument: 'num_stock_shares'
when defining env_kwargs, how can I fix this?
just adding some random number for num_stock_shares throws the error TypeError: can only concatenate list (not "int") to list
When FinRL is installing / cloning from github as mentioned in https://finrl.readthedocs.io/en/latest/start/installation.html#.
It is giving an error "ERROR: Package 'finrl' requires a different Python: 3.9.13 not in '<3.9,>=3.7'"
Please help me to install FINRL lib
I tested demo NeurIPS2018 with stablebaseline3, I used SAC agent, and I trained with GPU. While I increase batch size from 128 to 512, I found no changing for GPU memories and utilization rate.
The version I used as below:
stable-baselines3==1.5.0
torch==1.10.0
Training time has no change with chaning batch size, what would be the problem?
I followed the instruction to install a few packages and changed a couple .py files before I launched the train/test command to run the zxstock example. Running the training seemed to be ok but I ran into a problem when matplot could not find the test.png to load. I tried a couple folders to save it but nothing is saved. Help, please!
Here is the line I changed in zxstock_testenv.py line 116:
plt.savefig('C:\Downloads\test.png'.format(iteration))
Here is the error:
C:\Dev\Anaconda3\lib\site-packages\gym\logger.py:30: UserWarning: �[33mWARN: Could not seed environment <StockTestEnv>�[0m
warnings.warn(colorize('%s: %s'%('WARN', msg % args), 'yellow'))
Traceback (most recent call last):
File "C:\Dev\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
"main", mod_spec)
File "C:\Dev\Anaconda3\lib\runpy.py", line 85, in run_code
exec(code, run_globals)
File "C:\Users\smu\baselines\baselines\run.py", line 266, in
main()
File "C:\Users\smu\baselines\baselines\run.py", line 254, in main
obs, , done, _ = env.step(actions)
File "C:\Users\smu\baselines\baselines\common\vec_env\vec_env.py", line 108, in step
return self.step_wait()
File "C:\Users\smu\baselines\baselines\common\vec_env\dummy_vec_env.py", line 51, in step_wait
obs, self.buf_rews[e], self.buf_dones[e], self.buf_infos[e] = self.envs[e].step(action)
File "C:\Users\smu\baselines\baselines\bench\monitor.py", line 56, in step
ob, rew, done, info = self.env.step(action)
File "C:\Dev\Anaconda3\lib\site-packages\gym\envs\zxstock\zxstock_testenv.py", line 116, in step
plt.savefig('C:\Downloads\test.png'.format(iteration))
File "C:\Dev\Anaconda3\lib\site-packages\matplotlib\pyplot.py", line 689, in savefig
res = fig.savefig(*args, **kwargs)
File "C:\Dev\Anaconda3\lib\site-packages\matplotlib\figure.py", line 2094, in savefig
self.canvas.print_figure(fname, **kwargs)
File "C:\Dev\Anaconda3\lib\site-packages\matplotlib\backends\backend_qt5agg.py", line 88, in print_figure
super().print_figure(*args, **kwargs)
File "C:\Dev\Anaconda3\lib\site-packages\matplotlib\backend_bases.py", line 2075, in print_figure
**kwargs)
File "C:\Dev\Anaconda3\lib\site-packages\matplotlib\backends\backend_agg.py", line 521, in print_png
cbook.open_file_cm(filename_or_obj, "wb") as fh:
File "C:\Dev\Anaconda3\lib\contextlib.py", line 112, in enter
return next(self.gen)
File "C:\Dev\Anaconda3\lib\site-packages\matplotlib\cbook_init.py", line 407, in open_file_cm
fh, opened = to_filehandle(path_or_file, mode, True, encoding)
File "C:\Dev\Anaconda3\lib\site-packages\matplotlib\cbook_init.py", line 392, in to_filehandle
fh = open(fname, flag, encoding=encoding)
OSError: [Errno 22] Invalid argument: 'C:\Downloads\test.png'
File: Stock_NeurlPS2018_Train.ipynb
File ~/anaconda3/lib/python3.8/site-packages/finrl/meta/env_stock_trading/env_stocktrading.py:404, in StockTradingEnv._initiate_state(self)
398 if self.initial:
399 # For Initial State
400 if len(self.df.tic.unique()) > 1:
401 # for multiple stock
402 state = (
403 [self.initial_amount]
--> 404 + self.data.close.values.tolist()
405 + self.num_stock_shares
406 + sum(
407 (
408 self.data[tech].values.tolist()
409 for tech in self.tech_indicator_list
410 ),
411 [],
412 )
413 ) # append initial stocks_share to initial state, instead of all zero
414 else:
415 # for single stock
416 state = (
417 [self.initial_amount]
418 + [self.data.close]
419 + [0] * self.stock_dim
420 + sum(([self.data[tech]] for tech in self.tech_indicator_list), [])
421 )
AttributeError: 'numpy.float64' object has no attribute 'values'
----> 1 data_risk_indicator = processed_full[(processed_full.date<TRAIN_END_DATE) & (processed_full.date>=TRAIN_START_DATE)]
2 insample_risk_indicator = data_risk_indicator.drop_duplicates(subset=['date'])
NameError: name 'processed_full' is not defined
----> 1 trained_a2c = A2C.load("agent_a2c") if if_using_a2c else None
2 trained_ddpg = DDPG.load("agent_ddpg") if if_using_ddpg else None
FileNotFoundError: [Errno 2] No such file or directory: 'agent_a2c.zip'
I countered above error when I followed the tutorial (https://finrl.readthedocs.io/en/latest/start/first_glance.html). But every Colab notebook example reads files created from the previous example and sometimes non-existing files too. I am afraid that I cannot continue the tutorial.
Can I let the current Colab notebook read files created from the previous Colab notebok example?
While executing the notebook Stock_NeurIPS2018_2_Train.ipynb the following line is causing an exception
model_a2c = agent.get_model("a2c")
/usr/local/lib/python3.10/dist-packages/stable_baselines3/common/base_class.py in init(self, policy, env, learning_rate, policy_kwargs, tensorboard_log, verbose, device, support_multi_env, monitor_wrapper, seed, use_sde, sde_sample_freq, supported_action_spaces)
170
171 if supported_action_spaces is not None:
--> 172 assert isinstance(self.action_space, supported_action_spaces), (
173 f"The algorithm only supports {supported_action_spaces} as action spaces "
174 f"but {self.action_space} was provided"
AssertionError: The algorithm only supports (<class 'gym.spaces.box.Box'>, <class 'gym.spaces.discrete.Discrete'>, <class 'gym.spaces.multi_discrete.MultiDiscrete'>, <class 'gym.spaces.multi_binary.MultiBinary'>) as action spaces but Box(-1.0, 1.0, (29,), float32) was provided
Could some one help what this issue?
Yesterday I was running the FinRL_Ensemble_StockTrading_ICAIF_2020.ipynb notebook, but the PC got disconnected from power and shut down. The A2C, DDPG, and PPO models were generated, but the ipynb file doesn't allow me to continue. Is there any way to utilize the generated models to resume the process?
this command fail:
!pip install git+https://github.com/AI4Finance-Foundation/FinRL.git
results:
Running command git clone --filter=blob:none --quiet https://github.com/AI4Finance-Foundation/FinRL.git 'C:\Users\o00494123\AppData\Local\Temp\pip-req-build-9ezxx0oj'
Running command git clone --filter=blob:none --quiet https://github.com/AI4Finance-Foundation/ElegantRL.git 'C:\Users\o00494123\AppData\Local\Temp\pip-install-2rq3ux93\elegantrl_88282259f5a841b29297adcf2c823715'
Running command git clone --filter=blob:none --quiet https://github.com/quantopian/pyfolio.git 'C:\Users\o00494123\AppData\Local\Temp\pip-install-2rq3ux93\pyfolio_18a0c4c5afa942afb66e752c4b4c5c89'
ERROR: Could not find a version that satisfies the requirement ray[default,tune]==1.3.0 (from finrl) (from versions: none)
ERROR: No matching distribution found for ray[default,tune]==1.3.0
We have copied all tutorials of FinRL and FinRL-Meta to this repo.
In the future, some tutorials of FinRL and FinRL-Meta may be deleted, just leave several ones for testing purpose. Hope to receive feedback from users.
Two errors were thrown while running the first installation code paragraph in Colap.
[1] the first error:
Building wheels for collected packages: elegantrl, box2d-py
Building wheel for elegantrl (setup.py) ... done
Created wheel for elegantrl: filename=elegantrl-0.3.6-py3-none-any.whl size=195057 sha256=3ae3abaacb514d4ddfcd61705ed71e0563a61e993b566db6aaedfc234d0d8ad4
Stored in directory: /tmp/pip-ephem-wheel-cache-ic4gkgzy/wheels/d6/fb/88/7d5e5490b35f78191267fee312ce81baac55c6b9d89151e72a
error: subprocess-exited-with-error
× python setup.py bdist_wheel did not run successfully.
│ exit code: 1
╰─> See above for output.
note: This error originates from a subprocess, and is likely not a problem with pip.
Building wheel for box2d-py (setup.py) ... error
ERROR: Failed building wheel for box2d-py
Running setup.py clean for box2d-py
Successfully built elegantrl
Failed to build box2d-py
[2] the second error:
Installing collected packages: pyglet, py-spy, ply, opencensus-context, nvidia-ml-py, msgpack, gputil, distlib, colorful, websockets, websocket-client, virtualenv, thriftpy2, tensorboardX, soupsieve, setuptools, pymysql, pyluach, psutil, prometheus-client, lz4, jedi, importlib-metadata, html5lib, gym, frozendict, deprecation, charset-normalizer, blessed, requests, pycares, gpustat, cryptography, beautifulsoup4, aiohttp, yfinance, stockstats, stable-baselines3, ray, jqdatasdk, exchange_calendars, alpaca_trade_api, aiohttp-cors, aiodns, opencensus, empyrical, ccxt, pyfolio, finrl Attempting uninstall: msgpack
...
Attempting uninstall: aiohttp
Found existing installation: aiohttp 3.8.4
Uninstalling aiohttp-3.8.4:
Successfully uninstalled aiohttp-3.8.4
ERROR: pip's dependency resolver does not currently take into account all the packages that are installed.
This behaviour is the source of the following dependency conflicts. cvxpy 1.2.3 requires setuptools<=64.0.2, but you have setuptools 67.4.0 which is incompatible.
...
It continues until printing the last line:
Successfully installed inflection-0.5.1 quandl-3.7.0
The following error in the next next code paragraph is raised. I dont't know whether the errors during insrallation cause it.
ImportError Traceback (most recent call last) " style="color: var(--colab-anchor-color);">[<ipython-input-3-c2f4f1f1ce9a>](https://localhost:8080/#) in <module>
----> 1 from agents.elegantrl_models import DRLAgent as DRLAgent_erl
2 from agents.rllib_models import DRLAgent as DRLAgent_rllib
3 from agents.stablebaselines3_models import DRLAgent as DRLAgent_sb3
4 from meta.data_processor import DataProcessor 5 [/FinRL-Meta/agents/elegantrl_models.py](https://localhost:8080/#) in <module>
5 from elegantrl.agents import AgentSAC
6 from elegantrl.agents import AgentTD3
----> 7 from elegantrl.train.config import Arguments
8 from elegantrl.train.run import init_agent
9 from elegantrl.train.run import train_and_evaluate
ImportError: cannot import name
'Arguments' from 'elegantrl.train.config' (/usr/local/lib/python3.8/dist-packages/elegantrl/train/config.py)
Opened : /notebooks/FinRL/examples/FinRL_PaperTrading_Demo.ipynb on google collab and tried locally.
Both times: Part 2: Train the agent fails with Tuple error:
Alpaca successfully connected
Data cleaning started
align start and end dates
produce full timestamp index
Start processing tickers
ticker list complete
Start concat and rename
Data clean finished!
Started adding Indicators
Running Loop
Restore Timestamps
Finished adding Indicators
Data cleaning started
align start and end dates
produce full timestamp index
Start processing tickers
ticker list complete
Start concat and rename
Data clean finished!
TypeError Traceback (most recent call last)
Cell In[64], line 1
----> 1 train(start_date = '2022-08-25',
2 end_date = '2022-08-31',
3 ticker_list = ticker_list,
4 data_source = 'alpaca',
5 time_interval= '1Min',
6 technical_indicator_list= INDICATORS,
7 drl_lib='elegantrl',
8 env=env,
9 model_name='ppo',
10 if_vix=True,
11 API_KEY = API_KEY,
12 API_SECRET = API_SECRET,
13 API_BASE_URL = API_BASE_URL,
14 erl_params=ERL_PARAMS,
15 cwd='./papertrading_erl', #current_working_dir
16 break_step=1e5)
Cell In[49], line 60, in train(start_date, end_date, ticker_list, data_source, time_interval, technical_indicator_list, drl_lib, env, model_name, if_vix, **kwargs)
53 agent = DRLAgent_erl(
54 env=env,
55 price_array=price_array,
56 tech_array=tech_array,
57 turbulence_array=turbulence_array,
58 )
59 model = agent.get_model(model_name, model_kwargs=erl_params)
---> 60 trained_model = agent.train_model(
61 model=model, cwd=cwd, total_timesteps=break_step
62 )
Cell In[48], line 77, in DRLAgent.train_model(self, model, cwd, total_timesteps)
75 model.cwd = cwd
76 model.break_step = total_timesteps
---> 77 train_agent(model)
Cell In[47], line 310, in train_agent(args)
308 env = build_env(args.env_class, args.env_args)
309 agent = args.agent_class(args.net_dims, args.state_dim, args.action_dim, gpu_id=args.gpu_id, args=args)
--> 310 agent.states = env.reset()[np.newaxis, :]
312 evaluator = Evaluator(eval_env=build_env(args.env_class, args.env_args),
313 eval_per_step=args.eval_per_step,
314 eval_times=args.eval_times,
315 cwd=args.cwd)
316 torch.set_grad_enabled(False)
TypeError: tuple indices must be integers or slices, not tuple
please help as I cannot get paper trading demo to run
I noticed that your main repo has an MIT license but this repo seems to be missing one. Is this code also available under the MIT license? It would be lovely if the license were copied over to this repo too.
I get the error below. Did anybody encounter it before and fixed it?
from pypfopt.efficient_frontier import EfficientFrontier
AttributeError Traceback (most recent call last)
Cell In[17], line 1
----> 1 from pypfopt.efficient_frontier import EfficientFrontier
3 ef_mean = EfficientFrontier(meanReturns, covReturns, weight_bounds=(0, 0.5))
4 raw_weights_mean = ef_mean.max_sharpe()
File I:\anaconda3\envs\FinExp\lib\site-packages\pypfopt_init_.py:1
----> 1 from .black_litterman import (
2 BlackLittermanModel,
3 market_implied_prior_returns,
4 market_implied_risk_aversion,
5 )
6 from .cla import CLA
7 from .discrete_allocation import DiscreteAllocation, get_latest_prices
File I:\anaconda3\envs\FinExp\lib\site-packages\pypfopt\black_litterman.py:15
12 import numpy as np
13 import pandas as pd
---> 15 from . import base_optimizer
18 def market_implied_prior_returns(
19 market_caps, risk_aversion, cov_matrix, risk_free_rate=0.02
20 ):
21 r"""
22 Compute the prior estimate of returns implied by the market weights.
23 In other words, given each asset's contribution to the risk of the market
(...)
41 :rtype: pd.Series
42 """
File I:\anaconda3\envs\FinExp\lib\site-packages\pypfopt\base_optimizer.py:16
13 from collections.abc import Iterable
14 from typing import List
---> 16 import cvxpy as cp
17 import numpy as np
18 import pandas as pd
File I:\anaconda3\envs\FinExp\lib\site-packages\cvxpy_init_.py:18
1 """
2 Copyright, the CVXPY authors
3
(...)
14 limitations under the License.
15 """
16 from cvxpy.version import (
17 version as version,) # cvxpy/version.py is auto-generated
---> 18 import cvxpy.interface.scipy_wrapper
19 from cvxpy.atoms import *
20 from cvxpy.constraints import (Constraint, PSD, SOC, NonPos, NonNeg, Zero,
21 PowCone3D, PowConeND, ExpCone,
22 OpRelEntrConeQuad, RelEntrConeQuad, FiniteSet,)
File I:\anaconda3\envs\FinExp\lib\site-packages\cvxpy\interface\scipy_wrapper.py:37
33 return new_method
36 for method_name in BIN_OPS:
---> 37 method = getattr(spmatrix, method_name)
38 new_method = wrap_bin_op(method)
39 setattr(spmatrix, method_name, new_method)
AttributeError: type object 'spmatrix' has no attribute 'div'
FinRL-Tutorials/3-Practical/FinRL_PaperTrading_Demo.ipynb
In Part 2: Train the agent
Train
(https://colab.research.google.com/github/AI4Finance-Foundation/FinRL-Tutorials/blob/master/3-Practical/FinRL_PaperTrading_Demo.ipynb#scrollTo=BxcNI2fdNjip&line=1&uniqifier=1)
I run this:
train(start_date = '2022-08-25',
end_date = '2022-08-31',
ticker_list = ticker_list,
data_source = 'alpaca',
time_interval= '1Min',
technical_indicator_list= INDICATORS,
drl_lib='elegantrl',
env=env,
model_name='ppo',
if_vix=True,
API_KEY = API_KEY,
API_SECRET = API_SECRET,
API_BASE_URL = API_BASE_URL,
erl_params=ERL_PARAMS,
cwd='./papertrading_erl', #current_working_dir
break_step=1e5)
And got error.
AttributeError Traceback (most recent call last)
in <cell line: 1>()
----> 1 train(start_date = '2022-08-25',
2 end_date = '2022-08-31',
3 ticker_list = ticker_list,
4 data_source = 'alpaca',
5 time_interval= '1Min',
2 frames
/usr/local/lib/python3.9/site-packages/finrl/meta/data_processors/processor_alpaca.py in download_data(self, ticker_list, start_date, end_date, time_interval)
50 # filter opening time of the New York Stock Exchange (NYSE) (from 9:30 am to 4:00 pm) if time_interval < 1D
51 day_delta = 86400000000000 # pd.Timedelta('1D').delta == 86400000000000
---> 52 if pd.Timedelta(time_interval).delta < day_delta:
53 NYSE_open_hour = "14:30" # in UTC
54 NYSE_close_hour = "20:59" # in UTC
AttributeError: 'Timedelta' object has no attribute 'delta'
In demo NeurIPS2018, close/low/high value are used as states, it seems future leakage exist?
FinRL_StockTrading_NeurIPS_2018 doesn't exist for example.
Also a step by step setup demo would be great.
这里通过tushare获取A股数据时没有复权,后续的处理里也没有看到复权的操作。是否应该在tushare获取数据时加入复权的参数?
Originally posted by @SilverBulletLZ in #45
TypeError Traceback (most recent call last)
in <cell line: 1>()
----> 1 train(start_date = '2022-08-25',
2 end_date = '2022-08-31',
3 ticker_list = ticker_list,
4 data_source = 'alpaca',
5 time_interval= '1Min',
2 frames
in train_agent(args)
308 env = build_env(args.env_class, args.env_args)
309 agent = args.agent_class(args.net_dims, args.state_dim, args.action_dim, gpu_id=args.gpu_id, args=args)
--> 310 agent.states = env.reset()[np.newaxis, :]
311
312 evaluator = Evaluator(eval_env=build_env(args.env_class, args.env_args),
TypeError: tuple indices must be integers or slices, not tuple
I looked at the stock env code and it seems like the states involves different prices and holdings, how are they scaled? won't it stop the network from training?
Ex: [10000, 56, 32, 0, 2]
Hello
I add deep network to code and code have error. can you help me?
thanks.
part of code:
class Net(BaseFeaturesExtractor):
def __init__(self, observation_space: gym.spaces.Box, stock_dim: int = 28):
super(Net, self).__init__(observation_space, stock_dim)
self.conv1 = nn.Conv2d(1, 32, kernel_size=3)
self.conv2 = nn.Conv2d(32, 64, kernel_size=3)
self.fc3 = nn.Linear(672,stock_dim)
`
def forward(self, x):
x = F.relu(self.conv1(x))
x = F.relu(self.conv2(x))
x = nn.Flatten()(x)
# x = x.view(x.size(0), -1)
x = F.relu(self.fc3(x))
return x
policy_kwargs ={
'features_extractor_class':Net,
}
model = PPO("MlpPolicy", env= env_train, policy_kwargs=policy_kwargs)
model.learn(total_timesteps=100000)
Error:
ValueError Traceback (most recent call last)
in
----> 1 model.learn(total_timesteps=100000)
3 frames
/usr/local/lib/python3.8/dist-packages/stable_baselines3/common/buffers.py in add(self, obs, action, reward, episode_start, value, log_prob)
435
436 # Same reshape, for actions
--> 437 action = action.reshape((self.n_envs, self.action_dim))
438
439 self.observations[self.pos] = np.array(obs).copy()
ValueError: cannot reshape array of size 1792 into shape (1,28)
First of all, thanks for the source code of reinforcement learning on stock trading, it was really helpful!
From your env setup, i found that commission was not considered, and looked like you also have unlimited total positions, which might cause huge number of trades in the whole episode, which might eat up all your profits.
Hi, there is quite a lot broken in the current version of FinRL_MultiCrypto_Trading.ipynb
See: AI4Finance-Foundation/FinRL-Meta#291
Also see: #21
I am able to go around many of the problems by running old versions of the repos/dependencies but in the end i failed.
As mentioned in one of the urls. Since Jan 2023 ElegantRL is no longer compatible.
/FinRL-Meta/agents/elegantrl_models.py is also no longer compatible due to line 58 (and more) changing Arguments(agent=agent, env=env) to Arguments(agent_class=agent, env=env)
ray.rllib also seems to have had some breaking changes. Also tried version 2.0.0 since its from around date the tutorial was moved into this repo but still didn't work.
Please fix the tutorials. I realy would like to get started looking into FinRL.
Hello
I am beginner. My project is portfolio optimization using multi agent RL. Do SB3 and FinRL support implementations for this?
I have been changing the amount of data downloaded from the AlpacaAPI and I am wondering if anyone can help with how I can plot this, in the same way as the Ensemble Strategy.
Hi,
I did everything step by step as it is described in readme file, but pytest failed with 26 errors.
Please, take a look at pytest.txt
Python version is 3.6.9 on Ubuntu 18.04 bionic
How can I resolve this issue?
Thanks in advance!
turbulence_threshold and risk_indicator_col are used during backtest, however, not used in training, will it causing unmatching problem?
Unfortunatly running the China_A_share_market_tushare.py tutorial either as python or jupyter does currently not work. DataProcessor from finrl-meta 0.3.6 (latest?) has no such function and neither does the dataprocessor in finrl 0.3.5.
Is it possible to run without MujoCo?
I followed the instructions from this tutorial/notebook and expected the method to work as shown.
df_summary = ensemble_agent.run_ensemble_strategy(A2C_model_kwargs, PPO_model_kwargs, DDPG_model_kwargs, timesteps_dict)
And the code above was working before, but now it keeps throwing back the error below.
TypeError Traceback (most recent call last)
in <cell line: 1>()
----> 1 df_summary = ensemble_agent.run_ensemble_strategy(A2C_model_kwargs,
2 PPO_model_kwargs,
3 DDPG_model_kwargs,
4 timesteps_dict)
TypeError: DRLEnsembleAgent.run_ensemble_strategy() missing 2 required positional arguments: 'TD3_model_kwargs' and 'timesteps_dict'
In traditional RL, every step consists of (S, A -> S', R), but in the context of FinRL, an action taken, i.e., buy or sell at whatever quantity, does NOT transfer one state to another, i.e., that an agent takes an action does not result in a price change from today to tomorrow.
If so, how should we calculate or estimate the price at every step?
Btw, is ElegantRL functioning perfectly just like SB3?
Please help confirm or correct me!
Thanx.
Hi,
I tried running the tutorial in Google colab (the first tutorial notebook), and everything at the beginning ran without errors until this line
df = YahooDownloader(start_date = TRAIN_START_DATE,
end_date = TRADE_END_DATE,
ticker_list = config_tickers.DOW_30_TICKER).fetch_data()
I'm getting the following error:
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- AXP: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- AMGN: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- AAPL: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- BA: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- CAT: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- CSCO: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- CVX: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- GS: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- HD: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- HON: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- IBM: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- INTC: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- JNJ: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- KO: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- JPM: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- MCD: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- MMM: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- MRK: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- MSFT: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- NKE: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- PG: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- TRV: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- UNH: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- CRM: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- VZ: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- V: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- WBA: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- WMT: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- DIS: No data found for this date range, symbol may be delisted
[*********************100%***********************] 1 of 1 completed
1 Failed download:
- DOW: No data found for this date range, symbol may be delisted
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
[<ipython-input-50-b49b1e107d2c>](https://localhost:8080/#) in <cell line: 1>()
----> 1 df = YahooDownloader(start_date = TRAIN_START_DATE,
2 end_date = TRADE_END_DATE,
3 ticker_list = config_tickers.DOW_30_TICKER).fetch_data()
[/usr/local/lib/python3.9/site-packages/finrl/meta/preprocessor/yahoodownloader.py](https://localhost:8080/#) in fetch_data(self, proxy)
58 num_failures += 1
59 if num_failures == len(self.ticker_list):
---> 60 raise ValueError("no data is fetched.")
61 # reset the index, we want to use numbers as index instead of dates
62 data_df = data_df.reset_index()
ValueError: no data is fetched.
Is yahooDownloader
broken?
Error while executing FinRL_Ensemble_StockTrading_ICAIF_2020.ipynb.
While running the below block of code:
df_summary = ensemble_agent.run_ensemble_strategy(A2C_model_kwargs,
PPO_model_kwargs,
DDPG_model_kwargs,
timesteps_dict)
ValueError Traceback (most recent call last)
in <cell line: 1>()
----> 1 df_summary = ensemble_agent.run_ensemble_strategy(A2C_model_kwargs,
2 PPO_model_kwargs,
3 DDPG_model_kwargs,
4 timesteps_dict)
/usr/local/lib/python3.10/site-packages/finrl/agents/stablebaselines3/models.py in run_ensemble_strategy(self, A2C_model_kwargs, PPO_model_kwargs, DDPG_model_kwargs, timesteps_dict)
666 )
667 # print("Used Model: ", model_ensemble)
--> 668 last_state_ensemble = self.DRL_prediction(
669 model=model_ensemble,
670 name="ensemble",
/usr/local/lib/python3.10/site-packages/finrl/agents/stablebaselines3/models.py in DRL_prediction(self, model, name, last_state, iter_num, turbulence_threshold, initial)
319 last_state = trade_env.render()
320
--> 321 df_last_state = pd.DataFrame({"last_state": last_state})
322 df_last_state.to_csv(f"results/last_state_{name}_{i}.csv", index=False)
323 return last_state
/usr/local/lib/python3.10/site-packages/pandas/core/frame.py in init(self, data, index, columns, dtype, copy)
707 elif isinstance(data, dict):
708 # GH#38939 de facto copy defaults to False only in non-dict cases
--> 709 mgr = dict_to_mgr(data, index, columns, dtype=dtype, copy=copy, typ=manager)
710 elif isinstance(data, ma.MaskedArray):
711 from numpy.ma import mrecords
/usr/local/lib/python3.10/site-packages/pandas/core/internals/construction.py in dict_to_mgr(data, index, columns, dtype, typ, copy)
479 arrays = [x.copy() if hasattr(x, "dtype") else x for x in arrays]
480
--> 481 return arrays_to_mgr(arrays, columns, index, dtype=dtype, typ=typ, consolidate=copy)
482
483
/usr/local/lib/python3.10/site-packages/pandas/core/internals/construction.py in arrays_to_mgr(arrays, columns, index, dtype, verify_integrity, typ, consolidate)
113 # figure out the index, if necessary
114 if index is None:
--> 115 index = _extract_index(arrays)
116 else:
117 index = ensure_index(index)
/usr/local/lib/python3.10/site-packages/pandas/core/internals/construction.py in _extract_index(data)
643
644 if not indexes and not raw_lengths:
--> 645 raise ValueError("If using all scalar values, you must pass an index")
646
647 if have_series:
ValueError: If using all scalar values, you must pass an index
when run to
trained_ddpg = agent.train_model(
model=model_ddpg, tb_log_name="ddpg", total_timesteps=10000
)
it complains:
trained_ddpg = agent.train_model( tensorflow.python.framework.errors_impl.FailedPreconditionError: tensorboard_log/ddpg\ddpg_1 is not a directory.
How to fix it?
ps.
and another fix is in env_stocktrading_China_A_shares.py
def _get_date(self):
if len(self.df.tic.unique()) > 1:
'''
wrong code , date -->time
'''
date = self.data.date.unique()[0]
'''should be'''
date = self.data.time.unique()[0]
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.