import datetime

import matplotlib.pyplot as plt
import pandas as pd

import pinkfish as pf
import strategy

# Format price data.
pd.options.display.float_format = '{:0.2f}'.format

%matplotlib inline

# Set size of inline plots.
'''note: rcParams can't be in same cell as import matplotlib
   or %matplotlib inline
   
   %matplotlib notebook: will lead to interactive plots embedded within
   the notebook, you can zoom and resize the figure
   
   %matplotlib inline: only draw static images in the notebook
'''
plt.rcParams["figure.figsize"] = (10, 7)

"""
Explanation: merge-trades
The purpose of this example is to demonstrate the merge capability of the trade log.  You may want to merge your trades when you are examining the result of trading algorithms that scaling in and/or out of positions.  You can view a whole sequence of trades as one trade instead of the individual trades.  For example, you scale in 4 different buy operations, then sell all at once.  Using merge, those 4 trades will be grouped into 1 buy operation with the single sell operation.  Statistical Analysis in pinkfish will treat this as a single trade instead of 4 distinct trades.  This will be useful in evaluating the effectiveness of a scaling algorithm.
Double 7's (Short Term Trading Strategies that Work)

1. The SPY is above its 200-day moving average
2. The SPY closes at a X-day low, buy some shares.
   If it falls further, buy some more, etc...
3. If the SPY closes at a X-day high, sell your entire long position.

(Scaling in; compare regular trade log vs merged trade log)
End of explanation
"""


capital = 10000
start = datetime.datetime(2020, 1, 1)
end = datetime.datetime.now()

"""
Explanation: Some global data
End of explanation
"""


symbols = ['SPY', 'SPY_merged']

"""
Explanation: Define symbols
End of explanation
"""


options = {
    'use_adj' : False,
    'use_cache' : True,
    'stop_loss_pct' : 1.0,
    'margin' : 1,
    'period' : 7,
    'max_open_trades' : 4,
    'enable_scale_in' : True,
    'enable_scale_out' : True,
    'merge_trades' : False
}

"""
Explanation: Options
End of explanation
"""


options['merge_trades'] = False
strategies = pd.Series(dtype=object)
for symbol in symbols:
    print(symbol, end=" ")
    strategies[symbol] = strategy.Strategy(symbols[0], capital, start, end, options)
    strategies[symbol].run()
    options['merge_trades'] = True

# View all columns and row in dataframe
pd.set_option('display.max_columns', None)
pd.set_option('display.max_rows', None)

# View raw log
strategies[symbols[0]].rlog

# View unmerged trade log
strategies[symbols[0]].tlog

# View merged trade log
strategies[symbols[1]].tlog

"""
Explanation: Run Strategy
End of explanation
"""


metrics = strategies[symbol].stats.index

df = pf.optimizer_summary(strategies, metrics)
df

"""
Explanation: Summarize results - compare statistics between unmerged and merged view of trade log.
End of explanation
"""


