<SYSTEM_TASK:>
Given the following text description, write Python code to implement the functionality described below step by step
<END_TASK>
<USER_TASK:>
Description:
 Golden Cross / Death Cross S&P 500 index (^GSPC)
1. sma50&gt;sma200, buy
2. sma50&lt;sma200, sell your long position.
THIS IS MEANT FOR EDUCATIONAL PURPOSES.  The condensed version is in strategy.ipynb
Step1:  Some global data
Step2:  Include dividends? (If yes, set to True)
Step3:  Fetch symbol data from internet; use cache if available.
Step4:  Select timeseries between start and end. Back adjust prices relative to adj_close for dividends and splits.
Step5:  Add technical indicator
Step6:  Finalize the time series before implementing trading strategy
Step7:  Plot closing price along with moving averages
Step8:  Create Trade Log (tlog); Create Daily Balance (dbal)
Step10:  Algo
Step11:  Retrieve raw log and trade log DataFrames
Step12:  View trade log
Step13:  Generate strategy stats - display all available stats
Step14:  Run Benchmark
Step15:  Plot Equity Curves
Step16:  Plot Trades
Step17:  Strategy vs Benchmark
<ASSISTANT_TASK:>
Python Code:
import datetime
import matplotlib.pyplot as plt
import pandas as pd
import pinkfish as pf
# 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: Golden Cross / Death Cross S&P 500 index (^GSPC)
1. sma50&gt;sma200, buy
2. sma50&lt;sma200, sell your long position.
THIS IS MEANT FOR EDUCATIONAL PURPOSES.  The condensed version is in strategy.ipynb
End of explanation
symbol = '^GSPC'
#symbol = 'SPY'
#symbol = '^DJI'
#symbol = 'DJA'
#symbol = 'DIA'
#symbol = 'QQQ'
#symbol = 'IWM'
#symbol = 'TLT'
#symbol = 'GLD'
#symbol = 'AAPL'
#symbol = 'BBRY'
capital = 10000
start = datetime.datetime(1900, 1, 1)
#start = datetime.datetime(*pf.SP500_BEGIN)
end = datetime.datetime.now()
Explanation: Some global data
End of explanation
use_adj = True
Explanation: Include dividends? (If yes, set to True)
End of explanation
ts = pf.fetch_timeseries(symbol)
ts.head()
Explanation: Fetch symbol data from internet; use cache if available.
End of explanation
ts = pf.select_tradeperiod(ts, start, end, use_adj)
ts.head()
Explanation: Select timeseries between start and end. Back adjust prices relative to adj_close for dividends and splits.
End of explanation
sma50 = pf.SMA(ts, timeperiod=50)
ts['sma50'] = sma50
sma200 = pf.SMA(ts, timeperiod=200)
ts['sma200'] = sma200
ts.head()
Explanation: Add technical indicator: 50 day ma and 200 day ma
End of explanation
ts, start = pf.finalize_timeseries(ts, start, dropna=True, drop_columns=['open', 'high', 'low'])
ts.head()
Explanation: Finalize the time series before implementing trading strategy
End of explanation
fig = plt.figure()
axes = fig.add_subplot(111,  ylabel='Price in $')
ts['close'].plot(ax=axes, label='close', color='k')
ts['sma50'].plot(ax=axes, label='sma50', color='r')
ts['sma200'].plot(ax=axes, label='sma200', color='b')
plt.legend(loc='best')
Explanation: Plot closing price along with moving averages
End of explanation
tlog = pf.TradeLog(symbol)
dbal = pf.DailyBal()
Explanation: Create Trade Log (tlog); Create Daily Balance (dbal)
End of explanation
pf.TradeLog.cash = capital
import time
t0 = time.time()
# This is not the fatest, but allows you the Dataframe directly (769 msec).
for i in range(len(ts.index)):
    date = ts.index[i]
    high = ts['high'][i]; low = ts['low'][i]; close = ts['close'][i]
    sma50 = ts['sma50'][i]; sma200 = ts['sma200'][i]
# This is the slowest (1.481 sec).
for i, (index, row) in enumerate(ts.iterrows()):
    date = index
    high = row['high']; low = row['low']; close = row['close']
    sma50 = row['sma50']; sma200 = row['sma200']
# Using .at[] is faster (517 msec).
for i, index in enumerate(ts.index):
    date = index
    high = ts.at[index, 'high']; low = ts.at[index, 'low']; close = ts.at[index, 'close']
    sma50 = ts.at[index, 'sma50']; sma200 = ts.at[index, 'sma200']
# Converting to dict is supposed to be fastest, but it isn't (1.215 msec).
# The looping itself is fast (129 msec), but the conversion to dict takes too long.
# Also, a new column must be created for the index, which takes time.
ts['date'] = ts.index
ts_dict = ts.to_dict('records')
for i, row in enumerate(ts_dict):
    date = row['date']
    high = row['high']; low = row['low']; close = row['close']
    sma50 = row['sma50']; sma200 = row['sma200']
# Using itertuples is by far fastest for looping (219 msec)
for i, row in enumerate(ts.itertuples()):
    date = row.Index.to_pydatetime()
    high = row.high; low = row.low; close = row.close
    sma50 = row.sma50; sma200 = row.sma200
for i, row in enumerate(ts.itertuples()):
    date = row.Index.to_pydatetime()
    close = row.close
    sma50 = row.sma50; sma200 = row.sma200
    end_flag = pf.is_last_row(ts, i)
    shares = 0
    
    # Buy
    if tlog.shares == 0:
        if sma50 > sma200 and ts['sma50'][i-1] <= ts['sma200'][i-1]:
            # Enter buy in trade log
            shares = tlog.buy(date, close)  
    # Sell
    else:
        if sma50 < sma200 or end_flag:
            # Enter sell in trade log
            shares = tlog.sell(date, close)
#     if shares > 0:
#         print("{0} BUY  {1} {2} @ {3:.2f}".format(
#               date, shares, symbol, close))
#     elif shares < 0:
#         print("{0} SELL {1} {2} @ {3:.2f}".format(
#               date, -shares, symbol, close))
    # Record daily balance
    dbal.append(date, close)  
t1 = time.time()
total = t1-t0
print(total)
        
Explanation: Algo: Buy when 50 day ma crosses above 200 day ma.  Sell when 50 day ma crosses below 200 day ma.
End of explanation
rlog = tlog.get_log_raw()
tlog = tlog.get_log()
rlog.tail()
Explanation: Retrieve raw log and trade log DataFrames
End of explanation
tlog.head(50)
dbal = dbal.get_log(tlog)
dbal.tail()
close = dbal['close']
close
Explanation: View trade log
End of explanation
stats = pf.stats(ts, tlog, dbal, capital)
pf.print_full(stats)
Explanation: Generate strategy stats - display all available stats
End of explanation
benchmark = pf.Benchmark(symbol, capital, start, end, use_adj=use_adj)
benchmark.run()
Explanation: Run Benchmark
End of explanation
pf.plot_equity_curve(dbal, benchmark=benchmark.dbal)
Explanation: Plot Equity Curves: Strategy vs Benchmark
End of explanation
pf.plot_trades(dbal, benchmark=benchmark.dbal)
Explanation: Plot Trades
End of explanation
df = pf.summary(stats, benchmark.stats, metrics=pf.currency_metrics)
df
extras = ('avg_month',)
df = pf.plot_bar_graph(stats, benchmark.stats, extras=extras)
df
Explanation: Strategy vs Benchmark
End of explanation
<END_TASK>