Skip to content
Course Notes: Financial Trading in Python
  • AI Chat
  • Code
  • Report
  • Spinner

    Course Notes

    Use this workspace to take notes, store code snippets, or build your own interactive cheatsheet! For courses that use data, the datasets will be available in the datasets folder.

    # Import any packages you want to use here
    import talib
    import bt

    Take Notes

    Add notes here about the concepts you've learned and code cells with code you want to keep.

    Add your notes here

    # Calculate 12-day EMA
    stock_data['EMA_12'] = talib.EMA(stock_data['Close'], 12)
    # Calculate 26-day EMA
    stock_data['EMA_26'] = talib.EMA(stock_data['Close'], 26)
    
    # Plot the EMAs with price
    plt.plot(stock_data['EMA_12'], label='EMA_12')
    plt.plot(stock_data['EMA_26'], label='EMA_26')
    plt.plot(stock_data['Close'], label='Close')
    
    # Customize and show the plot
    plt.legend()
    plt.title('EMAs')
    plt.show()
    
    # Calculate the SMA
    stock_data['SMA'] = talib.SMA(stock_data['Close'], 50)
    # Calculate the EMA
    stock_data['EMA'] = talib.EMA(stock_data['Close'], 50)
    
    # Plot the SMA, EMA with price
    plt.plot(stock_data['SMA'], label='SMA')
    plt.plot(stock_data['EMA'], label='EMA')
    plt.plot(stock_data['Close'], label='Close')
    
    # Customize and show the plot
    plt.legend()
    plt.title('SMA vs EMA')
    plt.show()
    # Calculate RSI with the default time period
    stock_data['RSI_14'] = talib.RSI(stock_data['Close'])
    
    # Calculate RSI with a time period of 21
    stock_data['RSI_21'] = talib.RSI(stock_data['Close'], timeperiod=21)
    
    # Print the last five rows
    print(stock_data.tail())
    # Calculate RSI
    stock_data['RSI'] = talib.RSI(stock_data['Close'])
    
    # Create subplots
    fig, (ax1, ax2) = plt.subplots(2)
    # Plot RSI with the price
    ax1.set_ylabel('Price')
    ax1.plot(stock_data['Close'])
    ax2.set_ylabel('RSI')
    ax2.plot(stock_data['RSI'], color='orangered')
    
    ax1.set_title('Price and RSI')
    plt.show()
    # Define the Bollinger Bands with 1-sd
    upper_1sd, mid_1sd, lower_1sd = talib.BBANDS(bitcoin_data['Close'], 
                                         nbdevup=2,
                                         nbdevdn=2,
                                         timeperiod=20)
    # Plot the upper and lower Bollinger Bands 
    plt.plot(bitcoin_data['Close'], color='green', label='Price')
    plt.plot(upper_1sd, color='tomato', label="Upper 1sd")
    plt.plot(lower_1sd, color='tomato', label='Lower 1sd')
    
    # Customize and show the plot
    plt.legend(loc='upper left')
    plt.title('Bollinger Bands (1sd)')
    plt.show()
    # Define the Bollinger Bands with 2-sd
    upper_2sd, mid_2sd, lower_2sd = talib.BBANDS(bitcoin_data['Close'],
                                         nbdevup=2,
                                         nbdevdn=2,
                                         timeperiod=20)
    # Plot the upper and lower Bollinger Bands 
    plt.plot(bitcoin_data['Close'], color='green', label='Price')
    plt.plot(upper_2sd, color='orange', label='Upper 2sd')
    plt.plot(lower_2sd, color='orange', label='Lower 2sd')
    
    # Customize and show the plot
    plt.legend(loc='upper left')
    plt.title('Bollinger Bands (2sd)')
    plt.show()
    import bt 
    import talib
    # Calculate the SMA
    sma = price_data.rolling(20).mean()
    
    # Define the strategy
    bt_strategy = bt.Strategy('AboveSMA', 
                              [bt.algos.SelectWhere(price_data > sma),
                               bt.algos.WeighEqually(),
                               bt.algos.Rebalance()])
    
    # Create the backtest and run it
    bt_backtest = bt.Backtest(bt_strategy, price_data)
    bt_result = bt.run(bt_backtest)
    # Plot the backtest result
    bt_result.plot(title='Backtest result')
    plt.show()
    import bt
    import talib
    # Calculate the EMA
    ema['Close'] = talib.EMA(price_data['Close'], timeperiod=20)
    
    # Define the strategy
    bt_strategy = bt.Strategy('AboveEMA',
                              [bt.algos.SelectWhere(price_data > ema),
                               bt.algos.WeighEqually(),
                               bt.algos.Rebalance()])
    
    # Create the backtest and run it
    bt_backtest = bt.Backtest(bt_strategy, price_data)
    bt_result = bt.run(bt_backtest)
    # Plot the backtest result
    bt_result.plot(title='Backtest result')
    plt.show()
    #TREND FOLLOWING STRATEGY (MA CROSSOVER)
    # Construct the signal
    signal[EMA_short > EMA_long] = 1
    signal[EMA_short < EMA_long] = -1
    
    # Merge the data 
    combined_df = bt.merge(signal,price_data, EMA_short,EMA_long)
    combined_df.columns = ['signal', 'Price', 'EMA_short', 'EMA_long']
    # Plot the signal, price and MAs
    combined_df.plot(secondary_y=['signal'])
    plt.show()
    
    # Define the strategy
    bt_strategy = bt.Strategy('EMA_crossover', 
                              [bt.algos.WeighTarget(signal),
                               bt.algos.Rebalance()])
    
    # Create the backtest and run it
    bt_backtest = bt.Backtest(bt_strategy, price_data)
    bt_result = bt.run(bt_backtest)
    
    # Plot the backtest result
    bt_result.plot(title='Backtest result')
    plt.show()
    #MEAN REVERSION STRATEGY
    import talib
    # Calculate the RSI
    stock_rsi = talib.RSI(price_data['Close']).to_frame()
    # Create the same DataFrame structure as RSI
    signal = stock_rsi.copy()
    signal[stock_rsi.isnull()] = 0
    # Construct the signal
    signal[stock_rsi < 30] = 1
    signal[stock_rsi > 70] = -1
    signal[(stock_rsi <= 70) & (stock_rsi >= 30)] = 0
    # Merge data into one DataFrame
    combined_df = bt.merge(signal, stock_data)
    combined_df.columns = ['Signal', 'Price']
    # Plot the signal with price
    combined_df.plot(secondary_y = ['Signal'])
    
    
    # Define the strategy
    bt_strategy = bt.Strategy('RSI_MeanReversion', 
                              [bt.algos.WeighTarget(signal),
                               bt.algos.Rebalance()])
    
    # Create the backtest and run it
    bt_backtest = bt.Backtest(bt_strategy, price_data)
    bt_result = bt.run(bt_backtest)
    # Plot the backtest result
    bt_result.plot(title='Backtest result')
    plt.show()
    # ASSESING A STRATEGY
    def signal_strategy(price_data, period, name):
        # Calculate SMA
        sma = price_data.rolling(period).mean()
        # Define the signal-based Strategy
        bt_strategy = bt.Strategy(name, 
                                  [bt.algos.SelectWhere(price_data > sma),
                                   bt.algos.WeighEqually(),
                                   bt.algos.Rebalance()])
        # Return the backtest
        return bt.Backtest(bt_strategy, price_data)
    
    # Create signal strategy backtest
    sma10 = signal_strategy(price_data, 10, name='SMA10')
    sma30 = signal_strategy(price_data, 30, name='SMA30')
    sma50 = signal_strategy(price_data, 50, name='SMA50')
    
    # Run all backtests and plot the resutls
    bt_results = bt.run(sma10,sma30,sma50)
    bt_results.plot(title='Strategy optimization')
    plt.show()
    
    def buy_and_hold(price_data, name):
        # Define the benchmark strategy
        bt_strategy = bt.Strategy(name, 
                                  [bt.algos.RunOnce(),
                                   bt.algos.SelectAll(),
                                   bt.algos.WeighEqually(),
                                   bt.algos.Rebalance()])
        # Return the backtest
        return bt.Backtest(bt_strategy, price_data)
    
    # Create benchmark strategy backtest
    benchmark = buy_and_hold(price_data, name='benchmark')
    
    # Run all backtests and plot the resutls
    bt_results = bt.run(sma10, sma30, sma50, benchmark)
    bt_results.plot(title='Strategy benchmarking')
    plt.show()