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 을 다시 실행해 주면 끝~~~

반응형

댓글()

MS OLE DB Driver Download

MS SQL Server|2020. 3. 22. 09:38
반응형

다음 Link에서 다운 받으시면 됩니다.

https://docs.microsoft.com/en-us/sql/connect/oledb/download-oledb-driver-for-sql-server?view=sql-server-ver15

 

반응형

'MS SQL Server' 카테고리의 다른 글

MS SQL Version확인 방법  (0) 2020.03.22

댓글()

MS SQL Version확인 방법

MS SQL Server|2020. 3. 22. 09:24
반응형

SELECT SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition');

 

SELECT @@VERSION ;

 

반응형

'MS SQL Server' 카테고리의 다른 글

MS OLE DB Driver Download  (0) 2020.03.22

댓글()

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 입력하여 로그인

반응형

댓글()