Python의 독립적인 가상 실행 환경(Environment)을 위한 Anaconda env 설정 방법

반응형

아나콘다 패키지로 설치한 후, conda 명령어를 이용해서 env를 생성/삭제 및 관리한다.

 

1. anaconda 64bit 설치

  https://www.anaconda.com/products/individual#download-section

 

Individual Edition | Anaconda

🐍 Open Source Anaconda Individual Edition is the world’s most popular Python distribution platform with over 20 million users worldwide. You can trust in our long-term commitment to supporting the Anaconda open-source ecosystem, the platform of choice

www.anaconda.com

 

python 3.7버젼 64bbit를 선택한다.

repo.anaconda.com/archive/Anaconda3-2020.02-Windows-x86_64.exe

주의: python 홈페이지에 가서 python을 다운받지 말자. Anaconda 설치를 하면 python이 자동으로 설치가 된다.

      이제 anaconda 홈페이지로 가서 다운을 받자. 64 bit 최신버전을 다운로드하도록 하자.

      https://youngjoongkwon.com/2018/01/26/windows-%ED%99%98%EA%B2%BD%EC%97%90%EC%84%9C-anaconda-tensorflow-%EC%84%A4%EC%B9%98%EB%AC%B8%EC%A0%9C-%ED%95%B4%EA%B2%B0%ED%95%98%EA%B8%B0-no-module-named-tensorflow-%EC%97%90%EB%9F%AC/

 

Windows 환경에서 Anaconda + Tensorflow 설치문제 해결하기 (No module named ‘tensorflow’ 에러 해결법)

python을 따로 설치한 다음 anaconda를 설치하고, tensorflow를 설치했다가 No module named ‘tensorflow’ 에러가 떴다. 물론 tensorflow는 실행할 수 없었다. 검색을 해보니 나와 비슷한 문제를 겪고있는 사람��

youngjoongkwon.com

 

2. Anaconda Prompt 실행

python version이 3.7.6임을 확인한다.

  tenserflow가 3.8버젼을 지원하지 않습니다. 3.7버젼도 3.7.6 안전한 검증된 버젼으로 설치를 권장합니다.

  (추가)

  anaconda 64bit 설치후, 제일 먼저 해주세요..
  >python -m pip install --upgrade pip

3. Python 3.8(최신) 버전의 ‘py38_32’라는 이름으로 32bit용 env를 생성합니다. 

   (키움과 같은 주식 API는 아직 32bit만 지원하므로, 32bit 가상환경을 별도로 만들어야 합니다.)

>set CONDA_FORCE_32BIT=1
>conda create -n py37_32 python=3.7 anaconda
>activate py37_32
>conda env list

4. 추가적으로 64bit용 가상환경도 별도설치하여 향후 64bit환경 개발시 사용하도록 한다.

>conda deactivate

>set CONDA_FORCE_64BIT=1
>conda create -n py38_64 python=3.8 anaconda
>activate py38_64

>pip install tensorflow  

   * Python을 anaconda에서 설치한 버젼과 달리, 별도로 설치할 경우,

     tensorflow가 설치되지 않습니다. 주의해 주세요~

5. Anaconda에서 생성한 env환경을 확인합니다. 

 

6. 가상환경 제거하기

>conda remove -n py37_32 --all

>conda remove -n py38_64 --all

 

7. 최신버젼의 tensorflow를 설치한다.

>pip install tensorflow
or 
>py -m pip install tensorflow
or
>python -m pip install --user --upgrade pip
반응형

댓글()

ValueError: invalid literal for int() with base 10

AI주식자동매매|2020. 5. 18. 10:06
반응형

파이썬 형변환에서 발생하는 오류입니다.

 

우리는 보통 형 변환시에는 하기 함수를 사용합니다.

문자형으로 바꿀 때는 str()

정수형으로 바꿀 때는 int()

실수형으로 바꿀 때는 float() 


문자열을 정수로 변환

>>> a = '10'

>>> int(a)

10

 

문자열을 실수로 변환

>>> b = '4.3'

>>> float(b)

4.3

 

정수를 문자열로 변환

>>> c = 7

>>> str(c)

'7'

 

실수를 문자열로 변환

>>> d = 2.71

>>> str(d)

'2.71'

 

문제 상황

 

하지만, 여기서 문제 상황은 조금 다릅니다.

>>> d = '51,800'

>>> int(d)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '51,800'

 

파이썬에서 다음 라인에서 에러가 걸렸습니다.

self.currentPrice = int(thirdColumnInRow.text()) 

 

thirdColumnInRow.text() 의 value가 '51,800'이기 때문에 바로 int()함수를 사용할 수 없기 때문입니다.

콤마(',')를 제거한 후 int()함수를 사용해야 합니다.

 

해결 방법

 

currentPrice = thirdColumnInRow.text().strip().replace(',', '')
self.currentPrice = int(currentPrice) 

 

이렇게 로직을 수정하니 깔끔하게 해결되었습니다.

반응형

댓글()

AttributeError: 'Kiwoom' object has no attribute 'OnEventConnect'

카테고리 없음|2020. 4. 13. 23:30
반응형

자동매매 프로그램 로직에서 키움접속이 안되어 API Setup을 수정 모드로 재설치했더니..

이런 에러가 발생합니다.

 

AttributeError: 'Kiwoom' object has no attribute 'OnEventConnect'

 

이럴때는 프로그램 추가삭제에서 APISetup.exe를 완전히 삭제하후,

APISetup 을 다시 실행해 주면 끝~~~

반응형

댓글()

UnicodeDecodeError: 'utf-8' codec can't decode byte

AI빅데이터|2020. 3. 15. 10:18
반응형

다음과 같이 subprocess에서 받아온 값에 한글이 포함될 경우,

Abaconda prompt에서 py를 실행할 경우, 제목과 같은 오류가 발생한다.

 

<코드>

RLTrader = subprocess.Popen([envPath, exeFilePath], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=subprocess_flags)
(stdout, stderr) = RLTrader.communicate(input=transData)
print("aftershock" + str(stdout))
RLTrader_results = stdout
RLTrader_results02 = RLTrader_results.decode()

 

<실행결과>

aftershockb'\xb0\xfc\xb8\xc1&&&0\r\n'
Traceback (most recent call last):
  File "pytrader4.py", line 517, in 
    SH.Start_of_RLTrader()
  File "pytrader4.py", line 294, in Start_of_RLTrader
    self.Requirement_of_current()
  File "pytrader4.py", line 425, in Requirement_of_current
    RLTrader_results02 = RLTrader_results.decode()
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position 0: invalid start byte

 

 

RLTrader = subprocess.Popen([envPath, exeFilePath], shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, creationflags=subprocess_flags)
(stdout, stderr) = RLTrader.communicate(input=transData)
print("aftershock" + str(stdout))
RLTrader_results = stdout 
RLTrader_results02 = RLTrader_results.decode(encoding='CP949')

 

이렇게 수정해 주니, 에러가 없어졌네요..

반응형

댓글()

ValueError: cannot convert float NaN to integer

AI빅데이터|2020. 3. 14. 15:43
반응형

Python pandas의 dropna() method를 사용해서

 

 - 결측값이 들어있는 행 전체 제거

   (delete row with missing values)

 - 결측값이 들어있는 열 전체를 제거

   (delete column with missing values)

 - 특정 행 또는 열 만을 대상으로 결측값이 들어있으면 제거

   (delete specific row or column with missing values)



출처: https://rfriend.tistory.com/263 [R, Python 분석과 프로그래밍의 친구 (by R Friend)]

 

Sample codes>

con = sqlite3.connect(self.databasePath)
sqlCode = "SELECT * From '%s'" % self.stock_code
chart_data = pd.read_sql(sqlCode, con, index_col=None)
chart_data = chart_data.reset_index(drop=True)
#print('chart_data after reset_indexing: ')
close = chart_data['close']
moving_mean = close.rolling(120).mean() # 120() 이동평균을 구한다.
moving_mean = moving_mean.dropna(axis=0)
moving_std = close.rolling(120).std() # 120() 이동표준편차를 구한다.
moving_std = moving_std.dropna(axis=0)

moving_mean02 = moving_mean.iloc[-1:]
print('moving_mean02: ')
print(moving_mean02)
moving_mean02 = int(pd.DataFrame(moving_mean02).values)
moving_std02 = moving_std.iloc[-1:]
moving_std02 = int(pd.DataFrame(moving_std02).values)
moving_std02 = moving_std02 * 3

반응형

댓글()

ModuleNotFoundError: No module named 'Crypto.Math'

AI빅데이터|2020. 2. 17. 07:35
반응형

exe 파일 생성을 위한 pyinstaller 실행시 발생하는 에러였습니다.

 

다음과 같은 순서대로 하기 실행하니, 없어졌습니다.

 

pip uninstall crypto

pip uninstall pycryptodome

pip install pycryptodome

 

다음으로 다시 실행..

 

conda install pycryptodome

conda uninstall crypto

conda install pyinstaller

 

하기 링크를 참조하였습니다.

https://stackoverflow.com/questions/57713994/modulenotfounderror-no-module-named-crypto-math

반응형

댓글()

AWS EC2 인스턴스 생성 후 Console화면 열기

AI빅데이터|2020. 2. 12. 00:39
반응형

AWS EC2 인스턴스 생성

- 선택: Ubuntu 18.02 버전, 프리티어 선택

 

1) SSH 접속

    해당 인스턴스의 public IP 와 user name: 'ubuntu' 사용하여 로그인한다.

2) 서버 Update

   $ sudo apt-get update

3) 가상환경 프로그램 설치 (virtualenv)
   $ sudo pip3 install virtualenv

4) Jupyter Notecbook 실행하기 위한 가상환경 생성 (venv)
  $ virtualenv venv

5) 가상환경 활성화
  $ source venv/bin/activate

6) 가상환경에서 Jupyter Notebook 설치
  $ sudo pip3 install notebook

7) 가상환경에서 설치된 프로그램 List 확인

  $ pip3 list

8) python3 이 정상적으로 실행되는지 확인
  $ python3

9) ipython 인터프리터에서 다음과 같이 실행하여 비밀번호 생성
   $ ipython

     (Console 화면)

    (venv) ubuntu@ip-172-31-15-177:~$ ipython
    /usr/local/lib/python3.6/dist-packages/IPython/core/interactiveshell.py:935: UserWarning: Attempting  

    to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.

    warn("Attempting to work in a virtualenv. If you encounter problems, please "
    Python 3.6.9 (default, Nov 7 2019, 10:44:02)
    Type 'copyright', 'credits' or 'license' for more information
    IPython 7.12.0 -- An enhanced Interactive Python. Type '?' for help.

    In [1]: from notebook.auth import passwd

    In [2]: passwd()
    Enter password:
    Verify password:
    Out[2]: 'sha1:015d71bac4da:deae4732e311fb67c3ab20ceb9d12244553e2440'

 

10) EC2의 Port를 Open 함 (아래의 예는 8888 Port)

11) Jupyter Notebook에 root 권한 부여 후 Background 에서 항상 실행되도록 함
   $ jupyter notebook --ip=0.0.0.0 --port=8888 --allow-root

   [Ctrl] + Z 입력하여 실행 종료

   $ bg
   $ disown -h

 

12) Public IP로 접속 후, 기 설정한 Password 입력하여 로그인

반응형

댓글()

pytorch jupyter notebook 실행시 OSError: [Errno 99] Cannot assign requested address

카테고리 없음|2020. 2. 12. 00:09
반응형

 

다음 순서대로.. update하고, jupyter설치한 다음

다음처럼 쭉 하나씩 처리하시면 됩니다.

어떤 분은 "$jupyter notebook --allow-root" 이럻게 하면 저런 에러 납니다.

 

$sudo apt update
$sudo apt install python3-pip
$sudo pip3 install -vU setuptools
$sudo pip3 install jupyter
$jupyter notebook --ip=0.0.0.0 --port=8888 --allow-root

 

참고 사이트: https://nevido.tistory.com/331

반응형

댓글()