以前から作ろうと思っていた投資シュミレーション用のツール作成に着手した。色々と作成しないといけない物があると思うが、手始めに資金管理を行うモジュールを作成してみた。
#-*- coding:utf-8 -*- class MoneyManage(): #初期資金を設定 def __init__(self,money): self.money=money self.stock={} #銘柄購入 #購入日,銘柄,購入金額,購入数を設定 def buy(self,day,code,price,number): if self.money >= price * number: self.money -= price * number self.stock.setdefault((day,code),(price,number)) print "buy:%s" % code else: print "no moeny" #銘柄売却 #購入日,銘柄,購入金額,購入数を設定 def sell(self,day,code,price,number): if self.stock.get((day,code)): del self.stock[(day,code)] self.money += price * number print "sell:%s" % code else: print "no stock code" #現在の保有銘柄を表示 def stockHold(self): return self.stock #資金、保有銘柄を表示 def show(self): print "*" * 20 print "stockCode:%s" % str(",".join(map(str,self.stock.keys())) if len(self.stock) > 1 else self.stock.keys()[0]) print "money:%s" % str(self.money) print "stockPrice:%s" % str(sum([price * number for (day,code),(price,number) in self.stock.items()])) print "totalPrice:%s" % str(self.money + sum([price * number for (day,code),(price,number) in self.stock.items()])) print "*" * 20 #動作確認用 def main(): stock = MoneyManage(1000000) stock.buy(20150712,1234,100,500) stock.buy(20150722,2222,300,200) stock.show() stock.sell(20150712,1234,120,500) stock.show() print stock.stockHold() if __name__ == '__main__': main()
内容としては、銘柄を購入したり、売買した際の資金と銘柄を管理するモジュールとなっている。実際に動かした際は表示はこんな感じ
buy:1234 #銘柄1234を購入 buy:2222 #銘柄2222を購入 ******************** #現在の資金状況 stockCode:(20150722, 2222),(20150712, 1234) money:890000 stockPrice:110000 totalPrice:1000000 ******************** sell:1234 #銘柄1234を売却 ******************** #現在の資金状況 stockCode:(20150722, 2222) money:950000 stockPrice:60000 totalPrice:1010000 ********************
次は売買用のモジュールを作成する様にしたい。