几年前买了一点基金,一直亏损,现在股市大好,终于扭亏为盈,心里有点小得意,有空没空就想查现在赚了多少钱,查多了手酸了就想自动化,用python搞定了!
程序原理:计算收益非常简单,无非就是当前资产-投资金额,要点就在于怎么获取当前实时价格
这里我用的是度娘,直接输入基金名称或股票代号就可以查到实时价格。通知urllib库打开网页,获取页面内容,找到<span class="op-stockdynamic-cur-num c-gap-right-small">28.70</span>,中间的这串数值即为实时值。
# -*- coding: utf-8 -*-
from selenium import webdriver
import urllib, re, string
class invest(object):
def __init__(self, product, buy_price, quantity):
self.product = product
self.buy_price = buy_price #购买价格
self.quantity = quantity #购买数量
self.now_price = self.getNowPrice()
def getNowPrice(self):
url = "http://www.baidu.com/s?wd=" + self.product
webContent = urllib.urlopen(url).read()
markTxt = r'<span class="op-stockdynamic-cur-num c-gap-right-small">' #这串后面的数值即为目标值
index1 = webContent.find(markTxt) + len(markTxt)
index2 = webContent.find(r'</span>', index1)
if index1 > 1 and index2 > 1:
return string.atof(webContent[index1:index2])
else:
print "No match"
return False
def getProfit(self,):
"计算收益"
return self.quantity * (self.now_price - self.buy_price)
def getProfitRate(self,):
"计算收益率"
return self.quantity * (self.now_price - self.buy_price) / (self.buy_price * self.quantity)
def getNowValue(self,):
"计算当前价值"
return self.quantity * self.now_price
def getBuyValue(self):
"计算投资客"
return self.buy_price * self.quantity
jsTopic = invest("嘉实主题", 1.2652, 100)
js300 = invest("嘉实300", 0.7154, 100)
stock300118 = invest("300118", 10.43, 100)
print "|名称\t\t|投资金额\t|购买价格\t|购买数量\t|当前价格\t|收益\t|收益率"
print "|%10s\t|%d\t\t|%4.4f\t\t|%d\t\t|%2.4f\t\t|%d\t|%.2f%%" % (jsTopic.product, jsTopic.getBuyValue(), jsTopic.buy_price, jsTopic.quantity, jsTopic.now_price, jsTopic.getProfit(), jsTopic.getProfitRate()*100)
print "|%10s\t|%d\t\t|%4.4f\t\t|%d\t\t|%2.4f\t\t|%d\t|%.2f%%" % (js300.product, js300.getBuyValue(), js300.buy_price, js300.quantity, js300.now_price, js300.getProfit(), js300.getProfitRate()*100)
print "|%10s\t|%d\t\t|%4.4f\t|%d\t\t|%2.4f\t\t|%d\t|%.2f%%" % (stock300118.product, stock300118.getBuyValue(), stock300118.buy_price, stock300118.quantity, stock300118.now_price, stock300118.getProfit(), stock300118.getProfitRate()*100)