用akshare,gym写出股票强化学习代码,包含模型保存和应用,完整代码
时间: 2024-02-19 09:03:31 浏览: 104
好的,以下是基于akshare和gym实现股票强化学习的完整代码示例:
```python
import akshare as ak
import gym
import numpy as np
import os
from keras.models import Sequential
from keras.layers import Dense
from keras.optimizers import Adam
# 获取股票历史数据
stock_df = ak.stock_zh_a_hist(symbol='sh600000', adjust="qfq", start_date='20000101', end_date='20211231')
# 定义强化学习环境
class StockEnv(gym.Env):
def __init__(self, stock_df):
self.stock_df = stock_df
self.observation_space = gym.spaces.Box(low=0, high=np.inf, shape=(len(stock_df.columns),))
self.action_space = gym.spaces.Discrete(2)
self.reward_range = (-np.inf, np.inf)
self.reset()
def reset(self):
self.current_step = 0
self.profit = 0
self.done = False
self.bought = False
self.sold = False
obs = np.array(self.stock_df.iloc[self.current_step])
return obs
def step(self, action):
obs = np.array(self.stock_df.iloc[self.current_step])
self.current_step += 1
if action == 0 and not self.bought:
self.bought = True
self.buy_price = obs[3]
elif action == 1 and self.bought and not self.sold:
self.sold = True
self.sell_price = obs[3]
self.profit = self.sell_price - self.buy_price
if self.profit > 0:
reward = 1
else:
reward = -1
self.done = True
else:
reward = 0
return obs, reward, self.done, {}
# 定义深度强化学习模型
class DQNAgent:
def __init__(self, state_size, action_size):
self.state_size = state_size
self.action_size = action_size
self.memory = []
self.gamma = 0.95
self.epsilon = 1.0
self.epsilon_min = 0.01
self.epsilon_decay = 0.995
self.learning_rate = 0.001
self.model = self._build_model()
def _build_model(self):
model = Sequential()
model.add(Dense(24, input_dim=self.state_size, activation='relu'))
model.add(Dense(24, activation='relu'))
model.add(Dense(self.action_size, activation='linear'))
model.compile(loss='mse', optimizer=Adam(lr=self.learning_rate))
return model
def remember(self, state, action, reward, next_state, done):
self.memory.append((state, action, reward, next_state, done))
def act(self, state):
if np.random.rand() <= self.epsilon:
return np.random.choice(self.action_size)
act_values = self.model.predict(state)
return np.argmax(act_values[0])
def replay(self, batch_size):
minibatch = np.array(self.memory)
minibatch = minibatch[np.random.choice(minibatch.shape[0], batch_size, replace=False), :]
for state, action, reward, next_state, done in minibatch:
target = reward
if not done:
target = (reward + self.gamma * np.amax(self.model.predict(next_state)[0]))
target_f = self.model.predict(state)
target_f[0][action] = target
self.model.fit(state, target_f, epochs=1, verbose=0)
if self.epsilon > self.epsilon_min:
self.epsilon *= self.epsilon_decay
def load(self, name):
self.model.load_weights(name)
def save(self, name):
self.model.save_weights(name)
# 训练模型
env = StockEnv(stock_df)
state_size = env.observation_space.shape[0]
action_size = env.action_space.n
agent = DQNAgent(state_size, action_size)
done = False
batch_size = 32
num_episodes = 1000
for e in range(num_episodes):
state = env.reset()
state = np.reshape(state, [1, state_size])
for time in range(500):
action = agent.act(state)
next_state, reward, done, _ = env.step(action)
reward = reward if not done else -10
next_state = np.reshape(next_state, [1, state_size])
agent.remember(state, action, reward, next_state, done)
state = next_state
if done:
print("episode: {}/{}, score: {}, e: {:.2}".format(e+1, num_episodes, env.profit, agent.epsilon))
break
if len(agent.memory) > batch_size:
agent.replay(batch_size)
if e % 50 == 0:
agent.save("model.h5")
# 加载模型并预测
agent.load("model.h5")
state = env.reset()
state = np.reshape(state, [1, state_size])
while True:
action = agent.act(state)
next_state, reward, done, _ = env.step(action)
next_state = np.reshape(next_state, [1, state_size])
state = next_state
if done:
print("profit: ", env.profit)
break
```
以上代码通过股票历史数据构建了一个强化学习环境,使用深度强化学习模型进行训练,并保存模型。最后加载模型并预测股票收益。
阅读全文