wuna 发表于 2022-9-1 14:27:00

python问题

这个for循环有问题,请问怎么改?

Twilight6 发表于 2022-9-1 14:27:01

wuna 发表于 2022-9-1 16:53
应该没有中途赋值,还有没有可能出现错误的原因呀


在 is_profit 之前 print 下 results 看看是不是有正常的结果

Twilight6 发表于 2022-9-1 16:05:33



检查下 results 是否中途重新赋值了

给出的代码没有涉及到报错的部分代码

wuna 发表于 2022-9-1 16:53:04

Twilight6 发表于 2022-9-1 16:05
检查下 results 是否中途重新赋值了

给出的代码没有涉及到报错的部分代码

应该没有中途赋值,还有没有可能出现错误的原因呀

wuna 发表于 2022-9-1 17:03:49

Twilight6 发表于 2022-9-1 16:59
在 is_profit 之前 print 下 results 看看是不是有正常的结果

有结果,这就是results"C:\Users\22536\Desktop\5555.png"

wuna 发表于 2022-9-1 17:10:36

Twilight6 发表于 2022-9-1 16:59
在 is_profit 之前 print 下 results 看看是不是有正常的结果

有结果,结果图想发给你看,但是图片一直转圈。
结果就是第一行列表里面一个数,第二行列表里面的数就是第一行的数再加一个新的数字,以此类推

wuna 发表于 2022-9-1 17:16:22

Twilight6 发表于 2022-9-1 16:59
在 is_profit 之前 print 下 results 看看是不是有正常的结果

结果只有12行,我感觉应该不太对

wuna 发表于 2022-9-1 17:20:44

"C:\Users\22536\Desktop\2.png"
"C:\Users\22536\Desktop\3.png"
"C:\Users\22536\Desktop\4.png"
"C:\Users\22536\Desktop\5.png"
这是这个主函数的代码。麻烦帮忙看看,咋解决问题

Twilight6 发表于 2022-9-1 17:53:46

wuna 发表于 2022-9-1 17:20
"C:%users\22536\Desktop\3.png"
"C:%users\22536\Desktop\4.png"
"C:%users\22536\Desktop\5.png"




图片你上传后才能看得到,图片地址是指在服务器地址,不是本地资源地址

wuna 发表于 2022-9-1 18:43:52

Twilight6 发表于 2022-9-1 17:53
图片你上传后才能看得到,图片地址是指在服务器地址,不是本地资源地址

那请问图片上传到哪里,你才能在评论中看到?

Twilight6 发表于 2022-9-1 18:48:48

wuna 发表于 2022-9-1 18:43
那请问图片上传到哪里,你才能在评论中看到?



回复可以直接上传

wuna 发表于 2022-9-1 19:48:08

Twilight6 发表于 2022-9-1 18:48
回复可以直接上传

前5张图片是报错的那个文件的代码,最后一个是打印的results结果。我把错误部分的完整代码给你看看,麻烦你帮我看下,怎么改。谢谢!

wyh551202 发表于 2022-9-2 14:57:20

能把源码粘出来吗,想debug看看{:10_254:}

wuna 发表于 2022-9-2 15:16:01

import os
import pickle
import pandas as pd
import random
from stable_baselines.common.policies import MlpPolicy
from stable_baselines.common.vec_env import DummyVecEnv
from stable_baselines import PPO2
from rlenv.StockTradingEnv0 import StockTradingEnv
from tasks import multi_stock_trade
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

font = fm.FontProperties(fname='font/wqy-microhei.ttc')
# plt.rc('font', family='Source Han Sans CN')
plt.rcParams['axes.unicode_minus'] = False
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
def stock_trade(stock_file):
    day_profits = []
    df = pd.read_csv(stock_file)
    df = df.sort_values('date')

    # The algorithms require a vectorized environment to run
    env = DummyVecEnv()

    model = PPO2(MlpPolicy, env, verbose=0, tensorboard_log='./log', gamma=0.95, n_steps=20, learning_rate=2.5e-2)
    model.learn(total_timesteps=int(1e5))
    df_test = pd.read_csv(stock_file.replace('train', 'test'))

    env = DummyVecEnv()
    obs = env.reset()
    for i in range(len(df_test) - 1):
      action, _states = model.predict(obs)
      obs, rewards, done, info = env.step(action)
      profit = env.render()
      day_profits.append(profit)
      if done:
            break
    return day_profits


def find_file(path, name):
    # print(path, name)
    for root, dirs, files in os.walk(path):
      for fname in files:
            if name in fname:
                return os.path.join(root, fname)


def test_a_stock_trade(stock_code):
    stock_file = find_file('./stockdata/train', str(stock_code))

    daily_profits = stock_trade(stock_file)
    fig, ax = plt.subplots()
    ax.plot(daily_profits, '-o', label=stock_code, marker='o', ms=10, alpha=0.7, mfc='orange')
    ax.grid()
    plt.xlabel('step')
    plt.ylabel('profit')
    ax.legend(prop=font)
    # plt.show()
    plt.savefig(f'./img/{stock_code}.png')
def analysis_profits(results):
    is_profit = for p in results]
    #is_profit=[]
    #for p in results:
       # p.append( is_profit)
    len(is_profit)
    import matplotlib.pyplot as plt
    import matplotlib.font_manager as fm
    font = fm.FontProperties(fname='./font/wqy-microhei.ttc')
    labels = 'Profit', 'Loss', '0'
    sizes =
    for p in is_profit:
      if p > 0:
            sizes += 1
      if p < 0:
            sizes += 1
      else:
            sizes += 1
    explode = (0.1, 0.05, 0.05)
    fig1, ax1 = plt.subplots()
    ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
            shadow=True, startangle=90)
    ax1.axis('equal')
    plt.legend(prop=font)
    plt.show()
    plt.savefig('./img/profits.png')
    import matplotlib.pyplot as plt
    import matplotlib.font_manager as fm
    font = fm.FontProperties(fname='./font/wqy-microhei.ttc')
    n_bins = 150
    fig, axs = plt.subplots()
    axs.hist(is_profit, bins=n_bins, density=True)
    plt.savefig('./img/profits_hist.png')


if __name__ == '__main__':
    files = os.listdir("stockdata/train")
    files_test = os.listdir("stockdata/test")
    all_files_list = list(set(files) & set(files_test))
    for i in all_files_list:
      # 使用celery做并发
      code = ".".join(i.split(".")[:2])
      multi_stock_trade.apply_async(args=(code,))
      # multi_stock_trade(code)

    import pickle
    files = os.listdir("result")
    results = []
    for f_name in files:
      f = open(f"result/{f_name}", "rb")
      data = pickle.load(f)
      results.append(data[-1])
      print(results)
    analysis_profits(results)

wuna 发表于 2022-9-2 15:16:41

wyh551202 发表于 2022-9-2 14:57
能把源码粘出来吗,想debug看看

import os
import pickle
import pandas as pd
import random
from stable_baselines.common.policies import MlpPolicy
from stable_baselines.common.vec_env import DummyVecEnv
from stable_baselines import PPO2
from rlenv.StockTradingEnv0 import StockTradingEnv
from tasks import multi_stock_trade
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

font = fm.FontProperties(fname='font/wqy-microhei.ttc')
# plt.rc('font', family='Source Han Sans CN')
plt.rcParams['axes.unicode_minus'] = False
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
def stock_trade(stock_file):
    day_profits = []
    df = pd.read_csv(stock_file)
    df = df.sort_values('date')

    # The algorithms require a vectorized environment to run
    env = DummyVecEnv()

    model = PPO2(MlpPolicy, env, verbose=0, tensorboard_log='./log', gamma=0.95, n_steps=20, learning_rate=2.5e-2)
    model.learn(total_timesteps=int(1e5))
    df_test = pd.read_csv(stock_file.replace('train', 'test'))

    env = DummyVecEnv()
    obs = env.reset()
    for i in range(len(df_test) - 1):
      action, _states = model.predict(obs)
      obs, rewards, done, info = env.step(action)
      profit = env.render()
      day_profits.append(profit)
      if done:
            break
    return day_profits


def find_file(path, name):
    # print(path, name)
    for root, dirs, files in os.walk(path):
      for fname in files:
            if name in fname:
                return os.path.join(root, fname)


def test_a_stock_trade(stock_code):
    stock_file = find_file('./stockdata/train', str(stock_code))

    daily_profits = stock_trade(stock_file)
    fig, ax = plt.subplots()
    ax.plot(daily_profits, '-o', label=stock_code, marker='o', ms=10, alpha=0.7, mfc='orange')
    ax.grid()
    plt.xlabel('step')
    plt.ylabel('profit')
    ax.legend(prop=font)
    # plt.show()
    plt.savefig(f'./img/{stock_code}.png')
def analysis_profits(results):
    is_profit = for p in results]
    #is_profit=[]
    #for p in results:
       # p.append( is_profit)
    len(is_profit)
    import matplotlib.pyplot as plt
    import matplotlib.font_manager as fm
    font = fm.FontProperties(fname='./font/wqy-microhei.ttc')
    labels = 'Profit', 'Loss', '0'
    sizes =
    for p in is_profit:
      if p > 0:
            sizes += 1
      if p < 0:
            sizes += 1
      else:
            sizes += 1
    explode = (0.1, 0.05, 0.05)
    fig1, ax1 = plt.subplots()
    ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
            shadow=True, startangle=90)
    ax1.axis('equal')
    plt.legend(prop=font)
    plt.show()
    plt.savefig('./img/profits.png')
    import matplotlib.pyplot as plt
    import matplotlib.font_manager as fm
    font = fm.FontProperties(fname='./font/wqy-microhei.ttc')
    n_bins = 150
    fig, axs = plt.subplots()
    axs.hist(is_profit, bins=n_bins, density=True)
    plt.savefig('./img/profits_hist.png')


if __name__ == '__main__':
    files = os.listdir("stockdata/train")
    files_test = os.listdir("stockdata/test")
    all_files_list = list(set(files) & set(files_test))
    for i in all_files_list:
      # 使用celery做并发
      code = ".".join(i.split(".")[:2])
      multi_stock_trade.apply_async(args=(code,))
      # multi_stock_trade(code)

    import pickle
    files = os.listdir("result")
    results = []
    for f_name in files:
      f = open(f"result/{f_name}", "rb")
      data = pickle.load(f)
      results.append(data[-1])
      print(results)
    analysis_profits(results)

wuna 发表于 2022-9-2 15:19:39

wyh551202 发表于 2022-9-2 14:57
能把源码粘出来吗,想debug看看

Traceback (most recent call last):
File "C:/Users/22536/Desktop/15.rl_learning/main.py", line 115, in <module>
    analysis_profits(results)
File "C:/Users/22536/Desktop/15.rl_learning/main.py", line 63, in analysis_profits
    is_profit = for p in results]
File "C:/Users/22536/Desktop/15.rl_learning/main.py", line 63, in <listcomp>
    is_profit = for p in results]
IndexError: invalid index to scalar variable.














Process finished with exit code 1
这是我的报错
页: [1]
查看完整版本: python问题