python应用--学以致用之计算实时收益

      几年前买了一点基金,一直亏损,现在股市大好,终于扭亏为盈,心里有点小得意,有空没空就想查现在赚了多少钱,查多了手酸了就想自动化,用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)
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值