Thursday, May 25, 2023

Making some modifications on my article "How I will trade using MACD as indicator"

 This is in reference to my previous post(How I will trade using MACD as indicator). Based on the video, to use the MACD, it should be also checked against the 200 Exponential Moving Average indicator. For details, pls watch the said video on the article which I made as reference. I believe in his formula becasue it is based on actual historical data and also I had made the same observation as he did. 

So in this article, I modified the program accordingly to include the 200-EMA in the plot and I also use matplotlib to make it more presentable. Here is the output:



Other changes made to the program:
  1. Generate Buy/Sell Signals
  2. Red Triangle - Indicates a Buy Signal
  3. Blue Inverted Triangle - Indicates a Sell Signal
  4. Criteria for a Buy Signal :  close price is above the 200ema and the macd and signal crosses below the zero line and the histogram is positive
  5. Criteria for a Sell Signal :  close price is below the 200ema and the macd and signal crosses above the zero line and the histogram is negative
  6. Prints Buy/Signal and the Date at the command prompt

And here is the code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
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
import yfinance as yf
import matplotlib.pyplot as plt
import numpy as np

# Retrieve historical data of AAPL from Yahoo Finance
data = yf.download('AAPL', period='1y')

# Calculate 200-day EMA
data['EMA_200'] = data['Close'].ewm(span=200, adjust=False).mean()

# Calculate MACD
data['ema_12'] = data['Close'].ewm(span=12, adjust=False).mean()
data['ema_26'] = data['Close'].ewm(span=26, adjust=False).mean()
data['MACD'] = data['ema_12'] - data['ema_26']
data['Signal'] = data['MACD'].ewm(span=9, adjust=False).mean()
data['Histogram'] = data['MACD'] - data['Signal']

# Define colors based on histogram values and trends
colors = np.where((data['Histogram'] > 0) & (data['Histogram'].diff() > 0), 'green',   # Increasing and positive
                  np.where((data['Histogram'] > 0) & (data['Histogram'].diff() <= 0), 'lightgreen',  # Decreasing and positive
                           np.where((data['Histogram'] < 0) & (data['Histogram'].diff() < 0), 'red',  # Decreasing and negative
                                    'lightcoral')))  # Increasing and negative

# Find the indices where conditions are met for the blue dot
blue_dot_indices = np.where(
    (data['Close'] < data['EMA_200']) &
    (data['MACD'] > 0) &
    (data['Signal'] > 0) &
    (data['Histogram'] < 0)
)[0]

# Find the indices where conditions are met for the red dot
red_dot_indices = np.where(
    (data['Close'] > data['EMA_200']) &
    (data['MACD'] < 0) &
    (data['Signal'] < 0) &
    (data['Histogram'] > 0)
)[0]

# Plot the closing price, EMA 200, MACD line, Signal line, and Histogram
plt.figure(figsize=(12, 8))
plt.subplot(2, 1, 1)
plt.plot(data.index, data['Close'], label='Close')
plt.plot(data.index, data['EMA_200'], label='EMA 200')
plt.scatter(data.index[blue_dot_indices], data['Close'].iloc[blue_dot_indices], marker='v', c='blue', s=50, label='Sell Signal')
plt.scatter(data.index[red_dot_indices], data['Close'].iloc[red_dot_indices], marker='^', c='red', s=50, label='Buy Signal')
plt.title('AAPL Stock Price')
plt.xlabel('Date')
plt.ylabel('Price')
plt.legend()

plt.subplot(2, 1, 2)
plt.plot(data.index, data['MACD'], label='MACD')
plt.plot(data.index, data['Signal'], label='Signal')
plt.bar(data.index, data['Histogram'], label='Histogram', color=colors, alpha=0.8, width=0.8)
plt.title('MACD')
plt.xlabel('Date')
plt.ylabel('MACD')
plt.legend()

# Adjust line thickness and magnify the histogram
ax = plt.gca()
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['bottom'].set_linewidth(2.0)
ax.spines['left'].set_linewidth(2.0)
ax.bar(data.index, data['Histogram'], color=colors, alpha=0.8, width=0.8)
ax.margins(0, 0.2)

# Print "Buy" and "Sell" labels
for idx in blue_dot_indices:
    print('Sell', data.index[idx].date())
for idx in red_dot_indices:
    print('Buy', data.index[idx].date())

plt.tight_layout()
plt.show()


Saturday, May 20, 2023

Introduction to Trading with Alpaca API in Python

In this article, we'll explore how to use the Alpaca trade API in Python to place a market order, retrieve the order ID, and access account information.

Prerequisites

To get started, you'll need the following:

  • Python installed on your system
  • An Alpaca account
  • Alpaca Python SDK (alpaca-trade-api) installed

Setting up Alpaca API Credentials

Before we begin, let's set up the API credentials required to access the Alpaca trade API. Follow these steps:

  1. Sign up for an account on the Alpaca website at https://alpaca.markets/.
  2. Once you've created an account and logged in, go to the Alpaca API page at https://alpaca.markets/docs/api-documentation/.
  3. Click on the "Get your API key" button to access the API management section.
  4. Create a new API key and note down both the key ID and secret key.
Python Program
Now, let's dive into the Python program that interacts with the Alpaca trade API. Copy the following code into a Python file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import alpaca_trade_api as tradeapi

API_KEY = 'your_api_key'
SECRET_KEY = 'your_secret_key'
BASE_URL = 'https://paper-api.alpaca.markets'  # Use 'https://api.alpaca.markets' for live trading

api = tradeapi.REST(API_KEY, SECRET_KEY, base_url=BASE_URL)

symbol = 'AAPL'  # Replace with the desired stock symbol

order = api.submit_order(
    symbol=symbol,
    qty=10,
    side='buy',
    type='market',
    time_in_force='gtc'
)

order_id = order.id
print(f"Order ID: {order_id}")

account = api.get_account()
print(f"Account ID: {account.id}")
print(f"Buying Power: {account.buying_power}")
print(f"Equity: {account.equity}")

Make sure to replace 'your_api_key' and 'your_secret_key' with your actual API key credentials.

Explanation
Let's go through the code step by step:
  1. We import the necessary module alpaca_trade_api to interact with the Alpaca trade API.
  2. We set the API_KEY and SECRET_KEY variables with the key ID and secret key obtained from the Alpaca API management section. Additionally, we define the BASE_URL variable as 'https://paper-api.alpaca.markets', which is the URL for paper trading. For live trading, you can use 'https://api.alpaca.markets' as the base URL.
  3. We create an api object using the tradeapi.REST() method, passing in the API key, secret key, and base URL.
  4. We define the symbol variable with the desired stock symbol. You can replace 'AAPL' with any valid stock symbol.
  5. We use the submit_order() method to place a market order to buy 10 shares of the specified stock. The side parameter is set to 'buy', type is set to 'market', and time_in_force is set to 'gtc' (Good 'Til Canceled). The method returns an Order object, which we assign to the order.
After running the program, I got this result from my Alpaca account:


This only suggests that I was able to place a trade using the Alpaca trade api.

Correlation between Stock Price and News Reports


 There is a well-known relationship between stock prices and news reports, although it can be complex and influenced by various factors. News reports can impact stock prices by providing new information that affects investors' perception of a company's value or its future prospects. Here are a few ways in which news reports can correlate with stock prices:

  1. Earnings Announcements: When a company releases its financial results, positive or negative surprises in earnings can significantly impact stock prices. Positive earnings reports often lead to an increase in stock prices, while negative reports can cause a decline.
  2. Merger and Acquisition News: News of mergers, acquisitions, or partnerships can affect stock prices. If a company announces plans to merge with another company or acquire a competitor, it can create positive sentiment and drive up stock prices.
  3. Product Launches and Innovations: News about new products or innovative developments can influence stock prices. Positive news, such as a successful product launch or a breakthrough innovation, can generate optimism and increase stock prices.
  4. Regulatory Changes and Legal Issues: News reports related to regulatory changes, lawsuits, or other legal issues can have a significant impact on stock prices. Negative news, such as a regulatory crackdown or a lawsuit against a company, can lead to a decline in stock prices.
  5. Macroeconomic News: Broader economic news, such as changes in interest rates, inflation, or GDP growth, can affect stock prices. Economic indicators and government policies can shape market sentiment, impacting the overall direction of stock prices.

It's important to note that the relationship between news reports and stock prices is not always straightforward. The interpretation of news can vary among investors, leading to different reactions and market fluctuations. Additionally, stock prices are influenced by a range of other factors, including market sentiment, investor behavior, and overall market conditions. Therefore, while news reports can have an impact on stock prices, it's essential to consider a wide range of factors when analyzing the correlation between the two.

How does it relates to my trading strategy? I think I still need to confirm this by creating a sentiment analysis program and visualize the results against the stock movement of a given day. I am planning to get data from twitter and Finviz. I will use the following youtube video as my guide to create the Sentiment Analysis program. And once confirmed and established, the outcome can make a 5% impact on my trading decisions.

 

Managing Trading Risks by Knowing Calendar Events That Affect Market Volatility

  Introduction to Trading Risks In Forex and other financial markets, risk management is one of the most critical aspects of successful trad...