numbering elements in a pandas dataframe












0















I am trying to build a small stock trading reporting in pandas. It's getting a little complicated because of subsequent buys and sells.
Assuming I have my buys and sells in a dataframe:



         import pandas as pd
data = pd.read_csv("ticker1.csv", delimiter=";")
data['cumsum']=data['quantity'].cumsum(axis=0)

data
Date qty price cumsum
0 2018-01-20 80 20.70 80
1 2018-02-14 90 20.82 170
2 2018-02-19 -100 20.62 70
3 2018-02-27 -70 20.55 0
4 2018-03-13 30 19.80 30
5 2018-03-14 10 19.55 40
6 2018-03-30 -20 20.92 20
7 2018-04-01 -10 20.95 10
8 2018-04-10 -10 21.03 0
9 2018-05-04 25 19.77 25
10 2018-05-31 -10 20.22 15


So there can be "completed" cycles of buying and selling whenever cumsum =0 (no short-selling). In this example, there would be an open position of 15 at the end.
In order to analyze the trades, I'd like to group them like this:



            Date              qty price      cumsum   group 
0 2018-01-20 80 20.70 80 1
1 2018-02-14 90 20.82 170 1
2 2018-02-19 -100 20.62 70 1
3 2018-02-27 -70 20.55 0 1
4 2018-03-13 30 19.80 30 2
5 2018-03-14 10 19.55 40 2
6 2018-03-30 -20 20.92 20 2
7 2018-04-01 -10 20.95 10 2
8 2018-04-10 -10 21.03 0 2
9 2018-05-04 25 19.77 25 3
10 2018-05-31 -10 20.22 15 3


I am trying to group the transactions until the next time cumsum =0.
Then I could loop over the groupings for further analysis (e.g. see if it was a winning or losing trade, # days between first buy and last sale etc.) and I would be able to see that in this case there is an open position at the moment (if last value for cumsum != 0).



Could someone please give me a hint how I could realize the grouping?



Thanks










share|improve this question



























    0















    I am trying to build a small stock trading reporting in pandas. It's getting a little complicated because of subsequent buys and sells.
    Assuming I have my buys and sells in a dataframe:



             import pandas as pd
    data = pd.read_csv("ticker1.csv", delimiter=";")
    data['cumsum']=data['quantity'].cumsum(axis=0)

    data
    Date qty price cumsum
    0 2018-01-20 80 20.70 80
    1 2018-02-14 90 20.82 170
    2 2018-02-19 -100 20.62 70
    3 2018-02-27 -70 20.55 0
    4 2018-03-13 30 19.80 30
    5 2018-03-14 10 19.55 40
    6 2018-03-30 -20 20.92 20
    7 2018-04-01 -10 20.95 10
    8 2018-04-10 -10 21.03 0
    9 2018-05-04 25 19.77 25
    10 2018-05-31 -10 20.22 15


    So there can be "completed" cycles of buying and selling whenever cumsum =0 (no short-selling). In this example, there would be an open position of 15 at the end.
    In order to analyze the trades, I'd like to group them like this:



                Date              qty price      cumsum   group 
    0 2018-01-20 80 20.70 80 1
    1 2018-02-14 90 20.82 170 1
    2 2018-02-19 -100 20.62 70 1
    3 2018-02-27 -70 20.55 0 1
    4 2018-03-13 30 19.80 30 2
    5 2018-03-14 10 19.55 40 2
    6 2018-03-30 -20 20.92 20 2
    7 2018-04-01 -10 20.95 10 2
    8 2018-04-10 -10 21.03 0 2
    9 2018-05-04 25 19.77 25 3
    10 2018-05-31 -10 20.22 15 3


    I am trying to group the transactions until the next time cumsum =0.
    Then I could loop over the groupings for further analysis (e.g. see if it was a winning or losing trade, # days between first buy and last sale etc.) and I would be able to see that in this case there is an open position at the moment (if last value for cumsum != 0).



    Could someone please give me a hint how I could realize the grouping?



    Thanks










    share|improve this question

























      0












      0








      0








      I am trying to build a small stock trading reporting in pandas. It's getting a little complicated because of subsequent buys and sells.
      Assuming I have my buys and sells in a dataframe:



               import pandas as pd
      data = pd.read_csv("ticker1.csv", delimiter=";")
      data['cumsum']=data['quantity'].cumsum(axis=0)

      data
      Date qty price cumsum
      0 2018-01-20 80 20.70 80
      1 2018-02-14 90 20.82 170
      2 2018-02-19 -100 20.62 70
      3 2018-02-27 -70 20.55 0
      4 2018-03-13 30 19.80 30
      5 2018-03-14 10 19.55 40
      6 2018-03-30 -20 20.92 20
      7 2018-04-01 -10 20.95 10
      8 2018-04-10 -10 21.03 0
      9 2018-05-04 25 19.77 25
      10 2018-05-31 -10 20.22 15


      So there can be "completed" cycles of buying and selling whenever cumsum =0 (no short-selling). In this example, there would be an open position of 15 at the end.
      In order to analyze the trades, I'd like to group them like this:



                  Date              qty price      cumsum   group 
      0 2018-01-20 80 20.70 80 1
      1 2018-02-14 90 20.82 170 1
      2 2018-02-19 -100 20.62 70 1
      3 2018-02-27 -70 20.55 0 1
      4 2018-03-13 30 19.80 30 2
      5 2018-03-14 10 19.55 40 2
      6 2018-03-30 -20 20.92 20 2
      7 2018-04-01 -10 20.95 10 2
      8 2018-04-10 -10 21.03 0 2
      9 2018-05-04 25 19.77 25 3
      10 2018-05-31 -10 20.22 15 3


      I am trying to group the transactions until the next time cumsum =0.
      Then I could loop over the groupings for further analysis (e.g. see if it was a winning or losing trade, # days between first buy and last sale etc.) and I would be able to see that in this case there is an open position at the moment (if last value for cumsum != 0).



      Could someone please give me a hint how I could realize the grouping?



      Thanks










      share|improve this question














      I am trying to build a small stock trading reporting in pandas. It's getting a little complicated because of subsequent buys and sells.
      Assuming I have my buys and sells in a dataframe:



               import pandas as pd
      data = pd.read_csv("ticker1.csv", delimiter=";")
      data['cumsum']=data['quantity'].cumsum(axis=0)

      data
      Date qty price cumsum
      0 2018-01-20 80 20.70 80
      1 2018-02-14 90 20.82 170
      2 2018-02-19 -100 20.62 70
      3 2018-02-27 -70 20.55 0
      4 2018-03-13 30 19.80 30
      5 2018-03-14 10 19.55 40
      6 2018-03-30 -20 20.92 20
      7 2018-04-01 -10 20.95 10
      8 2018-04-10 -10 21.03 0
      9 2018-05-04 25 19.77 25
      10 2018-05-31 -10 20.22 15


      So there can be "completed" cycles of buying and selling whenever cumsum =0 (no short-selling). In this example, there would be an open position of 15 at the end.
      In order to analyze the trades, I'd like to group them like this:



                  Date              qty price      cumsum   group 
      0 2018-01-20 80 20.70 80 1
      1 2018-02-14 90 20.82 170 1
      2 2018-02-19 -100 20.62 70 1
      3 2018-02-27 -70 20.55 0 1
      4 2018-03-13 30 19.80 30 2
      5 2018-03-14 10 19.55 40 2
      6 2018-03-30 -20 20.92 20 2
      7 2018-04-01 -10 20.95 10 2
      8 2018-04-10 -10 21.03 0 2
      9 2018-05-04 25 19.77 25 3
      10 2018-05-31 -10 20.22 15 3


      I am trying to group the transactions until the next time cumsum =0.
      Then I could loop over the groupings for further analysis (e.g. see if it was a winning or losing trade, # days between first buy and last sale etc.) and I would be able to see that in this case there is an open position at the moment (if last value for cumsum != 0).



      Could someone please give me a hint how I could realize the grouping?



      Thanks







      python pandas dataframe






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 24 '18 at 17:13









      RazzleDazzleRazzleDazzle

      237




      237
























          1 Answer
          1






          active

          oldest

          votes


















          2














          Coincidentally, one solution is to apply Series.cumsum() on the column named cumsum:



          df['group'] = (df['cumsum'].shift() == 0).astype(int).cumsum() + 1
          df

          Date qty price cumsum group
          0 2018-01-20 80 20.70 80 1
          1 2018-02-14 90 20.82 170 1
          2 2018-02-19 -100 20.62 70 1
          3 2018-02-27 -70 20.55 0 1
          4 2018-03-13 30 19.80 30 2
          5 2018-03-14 10 19.55 40 2
          6 2018-03-30 -20 20.92 20 2
          7 2018-04-01 -10 20.95 10 2
          8 2018-04-10 -10 21.03 0 2
          9 2018-05-04 25 19.77 25 3
          10 2018-05-31 -10 20.22 15 3





          share|improve this answer
























          • Thanks - that’s really an elegant way to this! I would not have thought of that myself!

            – RazzleDazzle
            Nov 24 '18 at 18:05











          • @RazzleDazzle, you're welcome! You'll learn fast as you continue writing and reading code, and this will become second nature to you :)

            – Peter Leimbigler
            Nov 24 '18 at 18:31











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53460558%2fnumbering-elements-in-a-pandas-dataframe%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          2














          Coincidentally, one solution is to apply Series.cumsum() on the column named cumsum:



          df['group'] = (df['cumsum'].shift() == 0).astype(int).cumsum() + 1
          df

          Date qty price cumsum group
          0 2018-01-20 80 20.70 80 1
          1 2018-02-14 90 20.82 170 1
          2 2018-02-19 -100 20.62 70 1
          3 2018-02-27 -70 20.55 0 1
          4 2018-03-13 30 19.80 30 2
          5 2018-03-14 10 19.55 40 2
          6 2018-03-30 -20 20.92 20 2
          7 2018-04-01 -10 20.95 10 2
          8 2018-04-10 -10 21.03 0 2
          9 2018-05-04 25 19.77 25 3
          10 2018-05-31 -10 20.22 15 3





          share|improve this answer
























          • Thanks - that’s really an elegant way to this! I would not have thought of that myself!

            – RazzleDazzle
            Nov 24 '18 at 18:05











          • @RazzleDazzle, you're welcome! You'll learn fast as you continue writing and reading code, and this will become second nature to you :)

            – Peter Leimbigler
            Nov 24 '18 at 18:31
















          2














          Coincidentally, one solution is to apply Series.cumsum() on the column named cumsum:



          df['group'] = (df['cumsum'].shift() == 0).astype(int).cumsum() + 1
          df

          Date qty price cumsum group
          0 2018-01-20 80 20.70 80 1
          1 2018-02-14 90 20.82 170 1
          2 2018-02-19 -100 20.62 70 1
          3 2018-02-27 -70 20.55 0 1
          4 2018-03-13 30 19.80 30 2
          5 2018-03-14 10 19.55 40 2
          6 2018-03-30 -20 20.92 20 2
          7 2018-04-01 -10 20.95 10 2
          8 2018-04-10 -10 21.03 0 2
          9 2018-05-04 25 19.77 25 3
          10 2018-05-31 -10 20.22 15 3





          share|improve this answer
























          • Thanks - that’s really an elegant way to this! I would not have thought of that myself!

            – RazzleDazzle
            Nov 24 '18 at 18:05











          • @RazzleDazzle, you're welcome! You'll learn fast as you continue writing and reading code, and this will become second nature to you :)

            – Peter Leimbigler
            Nov 24 '18 at 18:31














          2












          2








          2







          Coincidentally, one solution is to apply Series.cumsum() on the column named cumsum:



          df['group'] = (df['cumsum'].shift() == 0).astype(int).cumsum() + 1
          df

          Date qty price cumsum group
          0 2018-01-20 80 20.70 80 1
          1 2018-02-14 90 20.82 170 1
          2 2018-02-19 -100 20.62 70 1
          3 2018-02-27 -70 20.55 0 1
          4 2018-03-13 30 19.80 30 2
          5 2018-03-14 10 19.55 40 2
          6 2018-03-30 -20 20.92 20 2
          7 2018-04-01 -10 20.95 10 2
          8 2018-04-10 -10 21.03 0 2
          9 2018-05-04 25 19.77 25 3
          10 2018-05-31 -10 20.22 15 3





          share|improve this answer













          Coincidentally, one solution is to apply Series.cumsum() on the column named cumsum:



          df['group'] = (df['cumsum'].shift() == 0).astype(int).cumsum() + 1
          df

          Date qty price cumsum group
          0 2018-01-20 80 20.70 80 1
          1 2018-02-14 90 20.82 170 1
          2 2018-02-19 -100 20.62 70 1
          3 2018-02-27 -70 20.55 0 1
          4 2018-03-13 30 19.80 30 2
          5 2018-03-14 10 19.55 40 2
          6 2018-03-30 -20 20.92 20 2
          7 2018-04-01 -10 20.95 10 2
          8 2018-04-10 -10 21.03 0 2
          9 2018-05-04 25 19.77 25 3
          10 2018-05-31 -10 20.22 15 3






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 24 '18 at 17:17









          Peter LeimbiglerPeter Leimbigler

          4,3731415




          4,3731415













          • Thanks - that’s really an elegant way to this! I would not have thought of that myself!

            – RazzleDazzle
            Nov 24 '18 at 18:05











          • @RazzleDazzle, you're welcome! You'll learn fast as you continue writing and reading code, and this will become second nature to you :)

            – Peter Leimbigler
            Nov 24 '18 at 18:31



















          • Thanks - that’s really an elegant way to this! I would not have thought of that myself!

            – RazzleDazzle
            Nov 24 '18 at 18:05











          • @RazzleDazzle, you're welcome! You'll learn fast as you continue writing and reading code, and this will become second nature to you :)

            – Peter Leimbigler
            Nov 24 '18 at 18:31

















          Thanks - that’s really an elegant way to this! I would not have thought of that myself!

          – RazzleDazzle
          Nov 24 '18 at 18:05





          Thanks - that’s really an elegant way to this! I would not have thought of that myself!

          – RazzleDazzle
          Nov 24 '18 at 18:05













          @RazzleDazzle, you're welcome! You'll learn fast as you continue writing and reading code, and this will become second nature to you :)

          – Peter Leimbigler
          Nov 24 '18 at 18:31





          @RazzleDazzle, you're welcome! You'll learn fast as you continue writing and reading code, and this will become second nature to you :)

          – Peter Leimbigler
          Nov 24 '18 at 18:31




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53460558%2fnumbering-elements-in-a-pandas-dataframe%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Wiesbaden

          Marschland

          Dieringhausen