Browse Source

New analyzer: EquityAnalyzer

EquityAnalyzer calculates bar-based equity
master
Denis Tereshkin 7 years ago
parent
commit
1b22f9b6f2
  1. 58
      src/naiback/analyzers/equityanalyzer.py
  2. 4
      src/naiback/strategy/strategy.py

58
src/naiback/analyzers/equityanalyzer.py

@ -0,0 +1,58 @@ @@ -0,0 +1,58 @@
from .analyzer import Analyzer
import numpy as np
class EquityAnalyzer(Analyzer):
def __init__(self, strategy):
self.strategy = strategy
def get_result(self):
positions = self.strategy.broker.retired_positions() # TODO also add open positions
bars = self.strategy.all_bars
equity = self.calc_equity(positions, bars[0])
return equity
def calc_equity(self, positions, bars):
timestamp = bars.timestamp
close = bars.close
cumulative_pnl = 0
equity = []
prev_p = 0
print(len(close), len(timestamp))
for (p,ts) in zip(close, timestamp):
active_positions = self.positions_for_timestamp(positions, ts)
for pos in active_positions:
if pos.entry_time() == ts:
if pos.is_long():
cumulative_pnl += (p - pos.entry_price())
else:
cumulative_pnl -= (p - pos.entry_price())
elif pos.exit_time() == ts:
if pos.is_long():
cumulative_pnl += (pos.exit_price() - prev_p)
else:
cumulative_pnl -= (pos.exit_price() - prev_p)
else:
if pos.is_long():
cumulative_pnl += (p - prev_p)
else:
cumulative_pnl -= (p - prev_p)
equity.append(cumulative_pnl)
prev_p = p
return equity
def positions_for_timestamp(self, positions, timestamp):
result = []
for p in positions:
if p.entry_time() <= timestamp and p.exit_time() >= timestamp:
result.append(p)
return result

4
src/naiback/strategy/strategy.py

@ -4,6 +4,7 @@ from naiback.broker.broker import Broker @@ -4,6 +4,7 @@ from naiback.broker.broker import Broker
from naiback.data.bars import Bars
from naiback.analyzers.statsanalyzer import StatsAnalyzer
from naiback.analyzers.tradeslistanalyzer import TradesListAnalyzer
from naiback.analyzers.equityanalyzer import EquityAnalyzer
from naiback.exceptions import NaibackException
import math
@ -19,7 +20,8 @@ class Strategy: @@ -19,7 +20,8 @@ class Strategy:
self.bars = None
self.trade_size = 1
self.analyzers = { 'stats' : StatsAnalyzer(self),
'tradeslist' : TradesListAnalyzer(self) }
'tradeslist' : TradesListAnalyzer(self),
'equity' : EquityAnalyzer(self) }
def get_analyzer(self, analyzer_id):
return self.analyzers[analyzer_id]

Loading…
Cancel
Save