#pythonUseMysql2.ipynbで使用
# MySQLdbのインポート
import MySQLdb
import os
import re
import sys
import datetime
import glob#ファイル一覧
import shutil#move
#株探の先物オプション記事について、特定文字列について空白をカンマに置換処理するためのメソッド
#def latterHalf(text):数字を後ろから探す
#def outMojiMKIII(text):空白をカンマに置換処理
#def csvToMysql(difile,dtablename,doptionDate,dmonth):
#def checkFile(filename):fileが存在するかチェック。パスは固定
#def fileMove(file,path):file移動
#def selectMysql(tablename):select
#メソッドを別ファイルにした。
#文字列の後ろ側の数字を後ろから探し、抜けていた場合0を埋める
def latterHalf(text):
textout=text
pattern=re.compile('[0-9]+')#findで正規表現ができない
i=0
checkArray=[]#タプルを入れる配列
while i>=0:#数字を探す
m=pattern.search(textout, i)
if m:
#print(m.start())
#print(m.end())
#これをタプル配列に入れて、N,N-1で差が大きいときに0を入れる
#print(m.span())
checkArray.append(m.span())
i = m.end()#m.start() + 1#m.end()
else:
break
n=len(checkArray)
if n>=2:#nは最低2こ必要 最後と最後の1こ前の
#print("[n-1][0]",checkArray[n-1][0])#0番目の1個目 [0](0,1)
#print("[n-2][1]",checkArray[n-2][1])#0番目の2個目
#個数はNだけど配列の指定はそれより1小さいのでN-1となる
if (checkArray[n-1][0]-checkArray[n-2][1])>=6:
print("put抜けている")
#checkArray[n-1][1]の後ろに挿入する
texttmp=textout[:checkArray[n-2][1]+2]+ '0' + textout[checkArray[n-2][1]+2:]
textout=texttmp
output=textout
return output
#end def
def outMojiMKIII(text):
#空白を削除する前に、空白の個数を数える
#株探の仕様が変わったらここを変える。2020/12/16
kuro=re.compile('[ ]+')#半角と全角の空白置換 半角全角が[半角全角]として入っている
if text.count(' ',0,15)>=13:
#空白13個はプット
opt='put'
textout=text.strip()#先頭、末尾の空白、改行を削除する
else:
#コールの場合、2種類あるのでそれをチェックする
textout=text.strip()#先頭、末尾の空白を削除する
check=kuro.sub(',',textout)#半角全角の空白を置換
count=check.split(",")
#print ('len count:',len(count))
if len(count)>=5:#配列が5個以上なら、call,putが含まれる
opt='callandput'
else:
opt='onlycall'
pattern=re.compile('[0-9]+')#findで正規表現ができない
if opt=='onlycall' or opt=='callandput':
#次に、「call,putあり」OR「Callのみ」かをチェックする。
#optSub='callandput' 'onlycall'
#callのみを先に処理して、put側を調べる
matchobj=re.search('[0-9]+',textout)#最初の数字を探す
if matchobj:
#print('マッチした文字列:'+matchobj.group())
#print('マッチした文字列グループ:',matchobj.groups())
#print( '開始位置'+str(matchobj.start()) )#先頭位置は0番として数える 3番目(4文字目)に見つかった
#print( '終了位置'+str(matchobj.end()) )#終了位置は次の番目を含んでいるので実際は1を引いた数が終了位置
#print(matchobj.span())#'マッチした文字列の (開始位置, 終了位置) のタプル'+
#2番めの数字を探す
secondMatch=pattern.search(textout,matchobj.end())#compileを使用してpatternで再度位置を指定して探す
if secondMatch:
#print( '開始位置2:'+str(secondMatch.start()) )#先頭から数えて10番目に次の数字が見つかった
#1番目と2番めの文字数が5以上空いていたら数字が抜けている事がわかる。
#ここに0を埋める処理を入れる
if secondMatch.start()-matchobj.end() >=5:
print('値が抜けてる')
# hash = "355879ACB6"
# hash = hash[:4] + '-' + hash[4:]
#文字列の挿入。#1番目の文字の3文字目くらいに0を追加する。
texttmp=textout[:matchobj.end()+2]+ '0' + textout[matchobj.end()+2:]
textout=texttmp
#put側のチェック。再度optでチェックする
if opt=='onlycall':
#置換して終わる
output=kuro.sub(',',textout)+',,,'
elif opt=='callandput':
#print('callandputの処理')
tmp=latterHalf(textout)#後半PUTの処理をして文字を返す
#置換して終わる
output=kuro.sub(',',tmp)
elif opt=='put':
#putのみの場合
#3つのカンマを付ける
tmp=latterHalf(textout)#後半PUTの処理をして文字を返す
output=',,,'+kuro.sub(',',tmp)#>>,,,26250,285,-10,189
#end if
return output
### end def
def csvToMysql(difile,dtablename,doptionDate,dmonth):
#ここからSTART
#Mysqlに接続メソッドを入れる
# データベースへの接続とカーソルの生成
connection = MySQLdb.connect(
host='localhost',
user='maseda',
passwd='Test1030',#知られても問題ないパスワード
db='Stock')
cursor = connection.cursor()
#csvファイル名
ifile=difile
#table
tablename=dtablename#"Test_Table_StockOption"#テスト用テーブルを使用する
#カラム名
rowname="(Volume1,Change1,Price1,ExercisePrice,Price2,Change2,Volume2,Month,OptionDate,CreateDate,YOBI)"
#VALUES (%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s)>>%dは%sにしないとエラーになった。
#カラム変数
month=dmonth#1#月限
optionDate=doptionDate#"2020/12/22"#データ取得の日付、たいていCSVに記載の日付になる。
dt_now=datetime.datetime.now()
createDate=dt_now.strftime('%Y-%m-%d %H:%M:%S')#今日の日付時刻を入れて、取り込み実行の日付で良い。後で削除操作するときの目安くらいだから厳密ではない
yobi=""#コメントがあればいれる。
count=0
#テーブルにデータを挿入する部分から書いていく
#CSVを1行ごとに読み取り、列ごとにカラムに入れていく
try:#ファイルが存在しないときのエラー処理try
with open(ifile,'tr') as fin:
for iline in fin:
try:
#Mysqlに直接インサートするバージョンを作業する
# ここに実行したいコードを入力します
#cursor.execute("INSERT INTO Test_Table_StockOption (カラム,) VALUES(値,,,)")
#cursor.execute("INSERT INTO " + tablename + " " + rowname + " VALUES (%s,%s)", ("test1","test2"))
#count=count+1
tmp=iline.strip().split(",")#stripしてからsplit()だと理解している。 iline.split(",")のままだと改行が入ってくるのでstripで前後の空白と改行を削除する
#CSVのデータが空の場合は、値0を入れる
if tmp[0]=='':
tmp[0]=0
if tmp[1]=='':
tmp[1]=0
if tmp[2]=='':
tmp[2]=0
if tmp[3]=='':
tmp[3]=0
if tmp[4]=='':
tmp[4]=0
if tmp[5]=='':
tmp[5]=0
if tmp[6]=='':
tmp[6]=0
#テストテーブルにインサートする前に、確認する前に、Splitを確認する。
#print(count,tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],tmp[5],tmp[6])
#%dにするとエラーになるのでINT型は%sにしておくとエラーにならない。なのでINTなのに%sとして記述してある。
cursor.execute("INSERT INTO " + tablename + " " + rowname + " VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)",\
(tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],tmp[5],tmp[6],month,optionDate,createDate,yobi))
#こっちだと、%dに値がないよとエラーになる。正しい記述のはずがパイソンではエラーになるようだ。
#cursor.execute("INSERT INTO " + tablename + " " + rowname + " VALUES (%d,%d,%d,%d,%d,%d,%d,%d,%s,%s,%s)",\
# (tmp[0],tmp[1],tmp[2],tmp[3],tmp[4],tmp[5],tmp[6],month,optionDate,createDate,yobi))
except MySQLdb.Error as e:
print('MySQLdb.Error: ', e)
connection.rollback()#失敗したらもとに戻す。これだと途中で成功してもコミットされるので、1回でもエラーのときはBREAKのほうがいいかも。
print("強制終了MYSQL")
connection.close()
return
#ofile.close()
connection.commit()
except FileNotFoundError as e: # FileNotFoundErrorは例外クラス名
print("ファイルが見つかりません。パス、ファイル名を確認してください", e)
ofile.close()
sys.exit()#ファイルがなければ終了
except Exception as e: # Exceptionは、それ以外の例外が発生した場合
print(e)
# 接続を閉じる
connection.close()
print("Mysql書き込み終了")
#defここまで
#check file
def checkFile(filename):
#他にもimport os os.listdir(path) というのもある
files=glob.glob('./option_python_execute/*.txt')
for file in files:
#print(file)
if filename in file:#ファイル名を含んでいればTRUE
print('すでに取り込み済みのファイルです。')
sys.exit()#return
#end def
def fileMove(file,path):
shutil.move(file, path)#('./new.txt', './sample')
print('file move',file)
#end def
def selectMysql(tablename):
# データベースへの接続とカーソルの生成
connection = MySQLdb.connect(
host='localhost',
user='maseda',
passwd='Test1030',#知られても問題ないパスワード
db='Stock')
cursor = connection.cursor()
try:
# ここに実行したいコードを入力します
cursor.execute("SELECT SUM(Volume1) as callVolume1, ExercisePrice, SUM(Volume2) as putVolume2 FROM "+ tablename +\
" WHERE Month=1 GROUP BY ExercisePrice ORDER BY ExercisePrice Desc")
#カラム名を取得
#cursor.execute("show columns from Table_StockOption")
# fetchall()で全件取り出し
rows = cursor.fetchall()
searchArray=[]#タプルで登録
for row in rows:
print(row[0],row[1],row[2])
searchArray.append(row)
# print(row[Volume1]) ERROR
#print(searchArray[0])#IDの情報:('ID', 'int', 'NO', 'PRI', None, 'auto_increment')
#for srow in searchArray:
# print(srow)#
except MySQLdb.Error as e:
print('MySQLdb.Error: ', e)
#表示
connection.commit()
connection.close()
#end def