Example #1
0
    def buy(self, code, value, date, is_value=True):
        """

        :param code: Fcode
        :param value:
        :param date: datetime obj
        :param is_value: bool, default True. whether the quantity in value is counted in value or in share,
                only value is supported for funds. 基金无法按份额申购。
        :return:
        """
        if self.verbose:
            print(f"buy {value} of {code} on {date.strftime('%Y-%m-%d')}")
        if code in self.trades:
            df = self.trades[code].status
            cftable = self.trades[code].cftable
            cftable = cftable[cftable["date"] <= self.lastdates[code]]
            remtable = self.trades[code].remtable
            remtable = remtable[remtable["date"] <= self.lastdates[code]]
            self.lastdates[code] = date
            df2 = pd.DataFrame([[date, value]], columns=["date", self.get_code(code)])
            df = df.append(df2)
            self.trades[code] = trade(
                self.infos[code],
                df,
                cftable=cftable,
                remtable=remtable,
            )
        else:
            self.lastdates[code] = date
            if code not in self.infos:
                self.infos[code] = self.get_info(code)
            df = pd.DataFrame({"date": [date], self.get_code(code): [value]})
            self.trades[code] = trade(self.infos[code], df)
Example #2
0
 def __init__(self,
              *fundtradeobj,
              status=None,
              fetch=False,
              save=False,
              path="",
              form="csv"):
     if not fundtradeobj:
         # warning: not a very good way to automatic generate these fund obj
         # because there might be some funds use round_down for share calculation, ie, label=2 must be given
         # unless you are sure corresponding funds are added to the droplist
         fundtradeobj = []
         for code in status.columns[1:]:
             try:
                 fundtradeobj.append(
                     trade(
                         fundinfo(code,
                                  fetch=fetch,
                                  save=save,
                                  path=path,
                                  form=form),
                         status,
                     ))
             except FundTypeError:
                 fundtradeobj.append(
                     trade(
                         mfundinfo(code,
                                   fetch=fetch,
                                   save=save,
                                   path=path,
                                   form=form),
                         status,
                     ))
     self.fundtradeobj = tuple(fundtradeobj)
     self.totcftable = self._mergecftb()
Example #3
0
    def __init__(self,
                 *fundtradeobj,
                 status=None,
                 property=None,
                 fetch=False,
                 save=False,
                 path="",
                 form="csv"):
        if isinstance(status, record):
            if not property:
                property = getattr(status, "property", {})
            status = status.status
        elif not property:
            property = {}

        if not fundtradeobj:
            # warning: not a very good way to automatic generate these fund obj
            # because there might be some funds use round_down for share calculation, ie, label=2 must be given
            # unless you are sure corresponding funds are added to the droplist
            fundtradeobj = []
            for code in status.columns[1:]:
                # r1, d2, v4 p = r+d+v
                p = property.get(code, 0)
                round_label = p % 2
                dividend_label = ((p - round_label) / 2) % 2
                value_label = ((p - round_label - dividend_label) / 4) % 2
                try:
                    fundtradeobj.append(
                        trade(
                            fundinfo(
                                code,
                                round_label=round_label,
                                dividend_label=dividend_label,
                                fetch=fetch,
                                save=save,
                                path=path,
                                form=form,
                            ),
                            status,
                        ))
                except FundTypeError:
                    fundtradeobj.append(
                        trade(
                            mfundinfo(
                                code,
                                round_label=round_label,
                                value_label=value_label,
                                fetch=fetch,
                                save=save,
                                path=path,
                                form=form,
                            ),
                            status,
                        ))
        self.fundtradeobj = tuple(fundtradeobj)
        self.totcftable = self._mergecftb()
Example #4
0
    def sell(self, code, share, date, is_value=False):
        """

        :param code:
        :param share:
        :param date: datetime obj
        :param is_value: bool, default False. 货币基金可按照金额赎回
        :return:
        """

        share = abs(share)
        if self.verbose:
            print(f"sell {share} of {code} on {date.strftime('%Y-%m-%d')}")
        if code not in self.trades:
            raise TradeBehaviorError("You are selling something that you don't have")
        df = self.trades[code].status
        cftable = self.trades[code].cftable
        cftable = cftable[cftable["date"] <= self.lastdates[code]]
        remtable = self.trades[code].remtable
        remtable = remtable[remtable["date"] <= self.lastdates[code]]
        self.lastdates[code] = date
        self.lastdates[code] = date
        df2 = pd.DataFrame([[date, -share]], columns=["date", self.get_code(code)])
        df = df.append(df2)
        if is_value:
            self.set_fund(code, value_label=1)
        self.trades[code] = trade(
            self.infos[code],
            df,
            cftable=cftable,
            remtable=remtable,
        )
        if is_value:
            self.set_fund(code, value_label=0)
Example #5
0
 def __init__(self, policylist, namelist=None, date=today()):
     self.warn = []
     self.message = []
     self.policylist = policylist
     if namelist is None:
         self.namelist = [i for i in range(len(policylist))]
     else:
         self.namelist = namelist
     assert len(self.policylist) == len(self.namelist)
     for i, policy in enumerate(policylist):
         row = policy.status[policy.status["date"] == date]
         if len(row) == 1:
             warn = (
                 policy.aim.name,
                 policy.aim.code,
                 row.iloc[0].loc[policy.aim.code],
                 self.namelist[i],
             )
             self.warn.append(warn)
             if warn[2] > 0:
                 sug = "买入%s元" % warn[2]
             elif warn[2] < 0:
                 ratio = -warn[2] / 0.005 * 100
                 share = (trade(fundinfo(warn[1]),
                                policy.status).briefdailyreport().get(
                                    "currentshare", 0))
                 share = -warn[2] / 0.005 * share
                 sug = "卖出%s%%的份额,也即%s份额" % (ratio, share)
             self.message.append("根据%s计划,建议%s,%s(%s)" %
                                 (warn[3], sug, warn[0], warn[1]))
     self.content = "\n".join(map(str, self.message))
Example #6
0
 def __init__(self,
              *fundtradeobj,
              status=None,
              fetch=False,
              save=False,
              path="",
              form="csv",
              totmoney=100000,
              cashobj=None):
     super().__init__(*fundtradeobj,
                      status=status,
                      fetch=fetch,
                      save=save,
                      path=path,
                      form=form)
     if cashobj is None:
         cashobj = cashinfo()
     self.totmoney = totmoney
     nst = mulfix._vcash(totmoney, self.totcftable, cashobj)
     cashtrade = trade(cashobj, nst)
     # 		 super().__init__(*self.fundtradeobj, cashtrade)
     self.fundtradeobj = list(self.fundtradeobj)
     self.fundtradeobj.append(cashtrade)
     self.fundtradeobj = tuple(self.fundtradeobj)
     btnk = bottleneck(self.totcftable)
     if btnk > totmoney:
         raise TradeBehaviorError("the initial total cash is too low")
     self.totcftable = pd.DataFrame(data={
         "date": [nst.iloc[0].date],
         "cash": [-totmoney]
     })
Example #7
0
 def __init__(self, *fundtradeobj, status=None, fetch=False, save=False, path='', form='csv', totmoney=100000,
              cashobj=None):
     super().__init__(*fundtradeobj, status=status, fetch=fetch, save=save, path=path, form=form)
     if cashobj is None:
         cashobj = cashinfo()
     self.totmoney = totmoney
     nst = mulfix._vcash(totmoney, self.totcftable, cashobj)
     cashtrade = trade(cashobj, nst)
     #		 super().__init__(*self.fundtradeobj, cashtrade)
     self.fundtradeobj = list(self.fundtradeobj)
     self.fundtradeobj.append(cashtrade)
     self.fundtradeobj = tuple(self.fundtradeobj)
     btnk = bottleneck(self.totcftable)
     if btnk > totmoney:
         raise Exception('the initial total cash is too low')
     self.totcftable = pd.DataFrame(data={'date': [nst.iloc[0].date], 'cash': [-totmoney]})
Example #8
0
 def __init__(self,
              *fundtradeobj,
              status=None,
              istatus=None,
              property=None,
              fetch=False,
              save=False,
              path="",
              form="csv"):
     if isinstance(status, record):
         if not property:
             property = getattr(status, "property", {})
         status = status.status
     elif not property:
         property = {}
     self.is_in = False
     if fundtradeobj:
         for t in fundtradeobj:
             if isinstance(t, itrade):
                 self.is_in = True
             break
     else:
         fundtradeobj = []
         # warning: not a very good way to automatic generate these fund obj
         # because there might be some funds use round_down for share calculation, ie, label=2 must be given
         # unless you are sure corresponding funds are added to the droplist
     fundcodelist = [f.code for f in fundtradeobj]
     if status is not None:
         for code in status.columns:
             if code == "date":
                 continue
             # r1, d2, v4 p = r+d+v
             if code in fundcodelist:
                 continue
             p = property.get(code, 0)
             round_label = p % 2
             dividend_label = ((p - round_label) / 2) % 2
             value_label = ((p - round_label - dividend_label) / 4) % 2
             try:
                 fundtradeobj.append(
                     trade(
                         fundinfo(
                             code,
                             round_label=round_label,
                             dividend_label=dividend_label,
                             fetch=fetch,
                             save=save,
                             path=path,
                             form=form,
                         ),
                         status,
                     ))
             except FundTypeError:
                 fundtradeobj.append(
                     trade(
                         mfundinfo(
                             code,
                             round_label=round_label,
                             value_label=value_label,
                             fetch=fetch,
                             save=save,
                             path=path,
                             form=form,
                         ),
                         status,
                     ))
         if istatus is not None:
             self.is_in = True
             if isinstance(istatus, irecord):
                 istatus = istatus.status
             for code in istatus.code.unique():
                 if code not in fundcodelist and not code.startswith("#"):
                     fundtradeobj.append(itrade(code, istatus))
     self.fundtradeobj = tuple(fundtradeobj)
     self.totcftable = self._mergecftb()