# -*- coding: utf-8 -*-
#
# Copyright 2017 Ricequant, Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os

from six import StringIO

from rqalpha.interface import AbstractMod
from rqalpha.utils.logger import system_log
from rqalpha.events import Events


class ProgressiveOutputCSVMod(AbstractMod):

    def start_up(self, env, mod_config):
        self._env = env
        self._mod_config = mod_config

        env.event_bus.add_listener(Events.TRADE, self._output_trade)
        env.event_bus.add_listener(Events.POST_BAR, self._output_feeds)

        self._csv_txt = StringIO()
        output_path = mod_config.output_path

        self.csv_file = open(os.path.join(output_path, "feeds.csv"), 'a')

    def _output_trade(self, account, trade):
        pass

    def _output_feeds(self, *args, **kwargs):
        misc_account = self._env.account
        # trading_date = self._env.trading_dt.date()
        calendar_date = self._env.calendar_dt.date()
        portfolio = misc_account.portfolio
        # daily_return = portfolio.daily_returns

        output_txt = "{} {}\n".format(calendar_date, portfolio)
        self.csv_file.write(output_txt)
        self.csv_file.flush()

    def tear_down(self, code, exception=None):
        pass

@@ -607,16 +607,27 @@
 mport os
+%0Aimport csv
 %0A%0Afrom s
@@ -692,52 +692,8 @@
 Mod%0A
-from rqalpha.utils.logger import system_log%0A
 from
@@ -1108,72 +1108,415 @@
     
-self.csv_file = open(os.path.join(output_path, %22feeds.csv%22), 'a'
+filename = os.path.join(output_path, %22portfolio.csv%22)%0A        new_file = False%0A        if not os.path.exists(filename):%0A            new_file = True%0A        self.csv_file = open(filename, 'a')%0A        fieldnames = %5B%22datetime%22, %22portfolio_value%22, %22market_value%22, %22total_returns%22%5D%0A        self.csv_writer = csv.DictWriter(self.csv_file, fieldnames)%0A        if new_file:%0A            self.csv_writer.writeheader(
 )%0A%0A 
@@ -1664,61 +1664,8 @@
 unt%0A
-        # trading_date = self._env.trading_dt.date()%0A
     
@@ -1756,24 +1756,25 @@
 rtfolio%0A
+%0A
         
 # daily_
@@ -1769,24 +1769,102 @@
     
-# daily
+self.csv_writer.writerow(%7B%0A            %22datetime%22: calendar_date,%0A            %22total
 _return
- =
+s%22:
  por
@@ -1874,21 +1874,21 @@
 lio.
-daily
+total
 _returns
 %0A%0A  
@@ -1883,17 +1883,17 @@
 _returns
-%0A
+,
 %0A       
@@ -1897,102 +1897,119 @@
     
-output_txt = %22%7B%7D %7B%7D%5Cn%22.format(calendar_date, portfolio)%0A        self.csv_file.write(output_txt
+    %22portfolio_value%22: portfolio.portfolio_value,%0A            %22market_value%22: portfolio.market_value,%0A        %7D
 )%0A  

use csv.DictWriter to append data