Class: CalcProfit::TransactionGroup

Inherits:
Object
  • Object
show all
Defined in:
lib/calc_profit/transaction_group.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(table = nil) ⇒ TransactionGroup

Returns a new instance of TransactionGroup.



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/calc_profit/transaction_group.rb', line 6

def initialize(table = nil)
  @purchases = []
  @sales = []
  @trans_by_ref = {}
  @matches = []
  @profit = 0
  @purchase_shares = 0
  @sale_shares = 0
  if table
    add_table_transactions(table)
  end
end

Instance Attribute Details

#matchesObject (readonly)

Returns the value of attribute matches.



3
4
5
# File 'lib/calc_profit/transaction_group.rb', line 3

def matches
  @matches
end

#profitObject (readonly)

Returns the value of attribute profit.



3
4
5
# File 'lib/calc_profit/transaction_group.rb', line 3

def profit
  @profit
end

#purchase_sharesObject (readonly)

Returns the value of attribute purchase_shares.



4
5
6
# File 'lib/calc_profit/transaction_group.rb', line 4

def purchase_shares
  @purchase_shares
end

#sale_sharesObject (readonly)

Returns the value of attribute sale_shares.



4
5
6
# File 'lib/calc_profit/transaction_group.rb', line 4

def sale_shares
  @sale_shares
end

Instance Method Details

#<<(t) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/calc_profit/transaction_group.rb', line 25

def <<(t)
  # Add a new transaction
  if t.purchase?
    @purchases << t
    @trans_by_ref[t.ref.to_s] = t
  elsif t.sale?
    @sales << t
    @trans_by_ref[t.ref.to_s] = t
  else
    raise ArgumentError,
      "Can only add purchase or sale transactions to TransactionGroup."
  end
end

#add_table_transactions(table) ⇒ Object



19
20
21
22
23
# File 'lib/calc_profit/transaction_group.rb', line 19

def add_table_transactions(table)
  table.rows.each do |row|
    self << Transaction.new(row)
  end
end

#matchObject



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/calc_profit/transaction_group.rb', line 39

def match
  pp = @purchases.dup2
  ss = @sales.dup2
  until pp.empty? or ss.empty? do
    # For each sale remaining, find the remaining purchase
    # with 6 months having the lowest price and match
    # to the extent of the lower number of shares
    break if ss.empty?
    best_sale = ss.max { |a, b| a.price <=> b.price }
    eligible_purchases = pp.partition { |p|
      p.date.within_6mos_of?(best_sale.date) && p.price < best_sale.price
    }
    eligible_purchases = eligible_purchases[0]
    if eligible_purchases.empty?
      ss.delete(best_sale)
      next
    end
    best_prch = eligible_purchases.min { |a, b| a.price <=> b.price }
    # Take number of shares as the smaller of the sale or buy
    if best_sale.shares >= best_prch.shares
      s = Transaction.new(code: 'S', date: best_sale.date, price: best_sale.price,
                          shares: best_prch.shares, ref: best_sale.ref,
                          info: best_sale.info)
      p = Transaction.new(code: 'P', date: best_prch.date, price: best_prch.price,
                          shares: best_prch.shares, ref: best_prch.ref,
                          info: best_prch.info)
      best_sale.shares -= best_prch.shares
      pp.delete(best_prch)
    else
      s = Transaction.new(code: 'S', date: best_sale.date, price: best_sale.price,
                          shares: best_sale.shares, ref: best_sale.ref,
                          info: best_sale.info)
      p = Transaction.new(code: 'P', date: best_prch.date, price: best_prch.price,
                          shares: best_sale.shares, ref: best_prch.ref,
                          info: best_prch.info)
      best_prch.shares -= best_sale.shares
      ss.delete(best_sale)
    end
    m = Match.new(p, s)
    unless m.profit < 0.01
      @matches << m
      @profit += m.profit
      @purchase_shares += p.shares
      @sale_shares += s.shares
    end
  end
  @matches.empty? ? nil : match_table
end

#match_tableObject



88
89
90
91
92
93
94
# File 'lib/calc_profit/transaction_group.rb', line 88

def match_table
  table = Table.new
  @matches.each do |m|
    table << m.table_row
  end
  table
end

#tp_solveObject

This method attempts to find an optimal, profit-maximizing set of matches by formulating a transportation problem and passing it to lp_solve. Requires lp_solve, which on ubuntu can be installed with

$ apt-get install lp_solve



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'lib/calc_profit/transaction_group.rb', line 110

def tp_solve
  lpf = File.new('profit.lp', 'w')

  # Write the objective function
  lpf.print("max: ")
  penalty = -1000.0
  have_eqn = false
  @purchases.each do |p|
    @sales.each do |s|
      if p.date.within_6mos_of?(s.date) and s.price > p.price
        profit = s.price - p.price
        lpf.print("#{profit} X_#{p.ref}@@#{s.ref} + ")
        have_eqn = true
      else
        lpf.print("#{penalty} X_#{p.ref}@@#{s.ref} + ")
        have_eqn = true
      end
    end
  end
  lpf.print("0;\n\n") if have_eqn

  # Write the purchase contraints
  @purchases.each do |p|
    lpf.print("P_#{p.ref}: ")
    @sales.each do |s|
      lpf.print("X_#{p.ref}@@#{s.ref} + ")
    end
    lpf.print("0 <= #{p.shares};\n")
  end

  # Write the sales contraints
  @sales.each do |s|
    lpf.print("S_#{s.ref}: ")
    @purchases.each do |p|
      lpf.print("X_#{p.ref}@@#{s.ref} + ")
    end
    lpf.print("0 <= #{s.shares};\n")
  end
  lpf.close

  # Now, pass the file into lp_solve and parse the solution
  calculated_profit = 0.0
  IO.popen("lp_solve profit.lp") do |sol|
    #File.open("profit.sol") do |sol|
    sol.each do |line|
      next if line =~ /^\s*$/
      if line =~ /^Value of objective function:\s+([-+e.\d]+)/
        calculated_profit = $1.to_f
      elsif line =~ /^X_(\S*)@@(\S*)\s+(\d+)$/
        next if $3.to_f == 0.0
        p = @trans_by_ref[$1].dup
        s = @trans_by_ref[$2].dup
        p.shares = s.shares = $3.to_f
        if s.price - p.price < 0.01
          STDERR.print "Sale #{s.ref} @ #{s.price} and Purchase #{p.ref} @ #{p.price} has no profit.\n"
        else
          m = Match.new(p, s)
          @matches << m
          @profit += m.profit
          @purchase_shares += p.shares
          @sale_shares += s.shares
        end
      end
    end
  end
  unless calculated_profit == @profit
    STDERR.print "Warning: profit calculated by lp_solve was #{calculated_profit}; by matches was #{@profit}\n"
  end
  !@matches.empty?
end

#transaction_tableObject



96
97
98
99
100
101
102
103
# File 'lib/calc_profit/transaction_group.rb', line 96

def transaction_table
  trans = @purchases + @sales
  table = Table.new
  trans.each do |tr|
    table << tr.table_row
  end
  table
end