פייתון למימון - מדריך מסחר אלגוריתמי למתחילים

הטכנולוגיה הפכה לנכס במימון. מוסדות פיננסיים מתפתחים כעת לחברות טכנולוגיה ולא רק להישאר עסוקים בהיבטים הפיננסיים של התחום.

אלגוריתמים מתמטיים מביאים לחדשנות ומהירות. הם יכולים לעזור לנו להשיג יתרון תחרותי בשוק.

המהירות והתדירות של עסקאות פיננסיות, יחד עם נפחי הנתונים הגדולים, הפנו תשומת לב רבה לטכנולוגיה של כל המוסדות הפיננסיים הגדולים.

מסחר אלגוריתמי או כמותי הוא תהליך של עיצוב ופיתוח אסטרטגיות מסחר המבוססות על ניתוחים מתמטיים וסטטיסטיים. זהו תחום פיננסי מתוחכם להפליא.

מדריך זה משמש כמדריך למתחילים למסחר כמותי עם פייתון. אתה תמצא את הפוסט הזה מאוד מועיל אם אתה:

  1. סטודנט או מישהו שמטרתו להיות אנליסט כמותי (קוונט) בקרן או בבנק.
  2. מישהו שמתכנן לפתוח עסק מסחרי כמותי משלו.

נעבור על הנושאים הבאים בפוסט זה:

  • יסודות המניות והמסחר
  • חילוץ נתונים מ- Quandl API
  • ניתוח נתוני חקר על נתוני תמחור מניות
  • ממוצעים נעים
  • גיבוש אסטרטגיית מסחר עם Python
  • הדמיה של ביצועי האסטרטגיה

לפני שנצלול לעומק את הפרטים והדינמיקה של נתוני תמחור המניות, עלינו להבין תחילה את יסודות המימון. אם אתה מישהו שמכיר את האוצר וכיצד המסחר עובד, אתה יכול לדלג על סעיף זה ולחץ כאן כדי לעבור לפרק הבא.

מהן מניות? מהו מסחר במניות?

מניות

מניה היא ייצוג של חלק בבעלות על תאגיד, המונפק בסכום מסוים. זהו סוג של ביטחון פיננסי המבסס את תביעתך על נכסי החברה וביצועיה.

ארגון או חברה מנפיקים מניות כדי לגייס יותר כספים / הון על מנת להגדיל ולעסוק בפרויקטים נוספים. מניות אלה זמינות אז לציבור ונמכרות ונרכשות.

אסטרטגיית מסחר ומסחר במניות

תהליך הקנייה והמכירה של מניות קיימות שהונפקו בעבר נקרא מסחר במניות. יש מחיר שבו ניתן לקנות ולמכור מניה, וזה ממשיך להשתנות בהתאם לביקוש ולהיצע בשוק המניות.

בהתאם לביצועי החברה ולפעולותיה, מחירי המניות עשויים לנוע ולרדת, אך תנועת מחירי המניות אינה מוגבלת לביצועי החברה.

סוחרים משלמים כסף בתמורה לבעלות בתוך חברה, בתקווה לבצע כמה עסקאות רווחיות ולמכור את המניות במחיר גבוה יותר.

טכניקה חשובה נוספת שעוקבים אחר הסוחרים היא מכירה קצרה. זה כרוך בהשאלת מניות ומכירה מיידית בתקווה לרכוש אותן מאוחר יותר במחיר נמוך יותר, להחזירן למלווה ולהגדיל את המרווח.

לכן, רוב הסוחרים עוקבים אחר תוכנית ומודל לסחר. זו ידועה כאסטרטגיית מסחר.

סוחרים כמותיים בקרנות גידור ובבנקים להשקעה מתכננים ומפתחים אסטרטגיות ומסגרות מסחר אלה לבדיקתן. זה דורש מומחיות עמוקה בתכנות והבנה של השפות הדרושות לבניית האסטרטגיה שלך.

Python היא אחת משפות התכנות הפופולריות ביותר בהן נעשה שימוש, כמו C ++, Java, R ו- MATLAB. היא מאומצת באופן נרחב בכל התחומים, במיוחד במדעי הנתונים, בגלל התחביר הקל שלה, הקהילה הענקית ותמיכת הצד השלישי.

תזדקק להכרות עם פייתון וסטטיסטיקה על מנת להפיק את המירב ממדריך זה. הקפד לצחצח את הפייתון שלך ולבדוק את יסודות הסטטיסטיקה.

חילוץ נתונים מממשק ה- API של Quandl

על מנת לחלץ נתוני תמחור מניות, נשתמש בממשק ה- API של Quandl. אבל לפני כן, בואו נקבע את סביבת העבודה. כך:

  1. במסוף שלך, צור ספרייה חדשה לפרויקט (תן שם איך שאתה רוצה):
mkdir 
  1. וודא שהתקנת Python 3 ו- virtualenv במחשב שלך.
  2. צור פיתרון 3 וירטואלי חדש באמצעות virtualenv והפעל אותו באמצעות source /bin/activate.
  3. כעת התקן את מחברת jupyter באמצעות pip והקלד pip install jupyter-notebookבמסוף.
  4. באופן דומה, להתקין את pandas, quandl, ו numpyהחבילות.
  5. הפעל jupyter-notebookאת המסוף שלך.

כעת, המחברת שלך אמורה לפעול ב- localhost כמו צילום המסך למטה:

אתה יכול ליצור את המחברת הראשונה שלך על ידי לחיצה על Newהתפריט הנפתח בצד ימין. וודא שיצרת חשבון ב- Quandl. בצע את השלבים המוזכרים כאן כדי ליצור את מפתח ה- API שלך.

לאחר שתסיים, בוא נצלול ממש ב:

# importing required packages
import pandas as pd import quandl as q

פנדה הולכת להיות החבילה המשמשת בצורה הקפדנית ביותר במדריך זה מכיוון שנעשה הרבה מניפולציות ותכנון נתונים.

לאחר ייבוא ​​החבילות, נגיש בקשות ל- API של Quandl באמצעות חבילת Quandl:

# set the API key q.ApiConfig.api_key = "”
#send a get request to query Microsoft's end of day stock prices from 1st #Jan, 2010 to 1st Jan, 2019 msft_data = q.get("EOD/MSFT", start_date="2010-01-01", end_date="2019-01-01")
# look at the first 5 rows of the dataframe msft_data.head()

הנה לנו נתוני תמחור המניות של מיקרוסופט ב- 9 השנים האחרונות. כל מה שהיה עליכם לעשות היה להתקשר getלשיטה מחבילת Quandl ולספק את סמל המניות, MSFT, ואת פרק הזמן עבור הנתונים הדרושים לכם.

זה היה ממש פשוט, נכון? בואו נתקדם להבין ולחקור את הנתונים האלה עוד יותר.

ניתוח נתוני חקר על נתוני תמחור מניות

כאשר הנתונים בידינו, הדבר הראשון שעלינו לעשות הוא להבין מה הוא מייצג ואיזה מידע הוא עוטף.

בהדפסת המידע של DataFrame נוכל לראות את כל מה שהוא מכיל:

כפי שנראה בצילום המסך לעיל, ה- DataFrame מכיל DatetimeIndex, כלומר אנו עוסקים בנתוני סדרות זמן.

ניתן לחשוב על אינדקס כמבנה נתונים המסייע לנו לשנות או להפנות את הנתונים. נתוני סדרות זמן הם רצף תמונות של מחירים שנלקחו במרווחי זמן עוקבים ובמרווח זהה.

במסחר נתוני תמחור מניות EOD לוכדים את תנועתם של פרמטרים מסוימים לגבי מניה, כגון מחיר המניה, לאורך פרק זמן מוגדר עם נקודות נתונים שנרשמו במרווחי זמן קבועים.

טרמינולוגיה חשובה

כאשר נסתכל על עמודות אחרות, בואו ננסה להבין מה מייצג כל עמודה:

  • פתיחה / סגירה - קולטת את מחיר הפתיחה / הסגירה של המניה
  • Adj_Open / Adj_Close - מחיר פתיחה / סגירה מותאם הוא מחיר מניה בכל יום מסחר מסוים שתוקן כדי לכלול חלוקת דיבידנד, פיצול מניות ופעולות ארגוניות אחרות שהתרחשו בכל עת לפני פתיחת היום הבא.
  • נפח - הוא רושם את מספר המניות הנסחרות ביום מסחר נתון.
  • גבוה / נמוך - הוא עוקב אחר המחיר הגבוה והנמוך ביותר של המניה במהלך יום מסחר מסוים.

אלה הטורים החשובים שנתמקד בהם בנקודת זמן זו.

אנו יכולים ללמוד על הנתונים הסטטיסטיים המסכמים של הנתונים, המראים לנו את מספר השורות, ממוצע, מקסימום, סטיות תקן וכן הלאה. נסה להריץ את שורת הקוד הבאה בתא Ipython:

msft_data.describe()

מדגם מחדש ()

נעשה שימוש בשיטת resample () של פנדה כדי להקל על שליטה וגמישות בהמרת התדרים של נתוני סדרות הזמן. אנו יכולים לציין את מרווחי הזמן לדגימת הנתונים מחדש לחודשי, רבעוני או שנתי, ולבצע את הפעולה הנדרשת עליהם.

msft_data.resample('M').mean()

זו דרך מעניינת לנתח את ביצועי המניות בטווחי זמן שונים.

חישוב תשואות

תשואה כספית היא פשוט הכסף שהושג או אבד על השקעה. תשואה יכולה לבוא לידי ביטוי באופן סמלי כשינוי בסכום ההשקעה לאורך זמן. ניתן לחשב אותו כאחוז הנגזר מיחס הרווח להשקעה.

לרשותנו pct_change () למטרה זו. כך תוכל לחשב תשואות:

# Import numpy package import numpy as np
# assign `Adj Close` to `daily_close` daily_close = msft_data[['Adj_Close']]
# returns as fractional change daily_return = daily_close.pct_change()
# replacing NA values with 0 daily_return.fillna(0, inplace=True)
print(daily_return)

זה ידפיס את התשואות שהמניה הניבה על בסיס יומי. הכפלת המספר ב- 100 תתן לך את השינוי באחוזים.

הנוסחה המשמשת ב- pct_change () היא:

החזר = {(מחיר ב- t) - (מחיר ב- t-1)} / {מחיר ב- t-1}

כעת, כדי לחשב את ההחזר החודשי, כל שעליך לעשות הוא:

mdata = msft_data.resample('M').apply(lambda x: x[-1]) monthly_return = mdata.pct_change()

לאחר הדגימה מחדש של הנתונים לחודשים (לימי עסקים), נוכל להשיג את היום המסחרי האחרון בחודש באמצעות apply()הפונקציה.

apply() takes in a function and applies it to each and every row of the Pandas series. The lambda function is an anonymous function in Python which can be defined without a name, and only takes expressions in the following format:

Lambda: expression

For example, lambda x: x * 2 is a lambda function. Here, x is the argument and x * 2 is the expression that gets evaluated and returned.

Moving Averages in Trading

The concept of moving averages is going to build the base for our momentum-based trading strategy.

In finance, analysts often have to evaluate statistical metrics continually over a sliding window of time, which is called moving window calculations.

Let’s see how we can calculate the rolling mean over a window of 50 days, and slide the window by 1 day.

rolling()

This is the magical function which does the tricks for us:

# assigning adjusted closing prices to adj_pricesadj_price = msft_data['Adj_Close']
# calculate the moving average mav = adj_price.rolling(window=50).mean()
# print the resultprint(mav[-10:])

You’ll see the rolling mean over a window of 50 days (approx. 2 months). Moving averages help smooth out any fluctuations or spikes in the data, and give you a smoother curve for the performance of the company.

We can plot and see the difference:

# import the matplotlib package to see the plot import matplotlib.pyplot as plt adj_price.plot()

You can now plot the rolling mean():

mav.plot()

And you can see the difference for yourself, how the spikes in the data are consumed to give a general sentiment around the performance of the stock.

Formulating a Trading Strategy

Here comes the final and most interesting part: designing and making the trading strategy. This will be a step-by-step guide to developing a momentum-based Simple Moving Average Crossover (SMAC) strategy.

Momentum-based strategies are based on a technical indicator that capitalizes on the continuance of the market trend. We purchase securities that show an upwards trend and short-sell securities which show a downward trend.

The SMAC strategy is a well-known schematic momentum strategy. It is a long-only strategy. Momentum, here, is the total return of stock including the dividends over the last n months. This period of n months is called the lookback period.

There are 3 main types of lookback periods: short term, intermediate-term, and long term. We need to define 2 different lookback periods of a particular time series.

A buy signal is generated when the shorter lookback rolling mean (or moving average) overshoots the longer lookback moving average. A sell signal occurs when the shorter lookback moving average dips below the longer moving average.

Now, let’s see how the code for this strategy will look:

# step1: initialize the short and long lookback periods short_lb = 50long_lb = 120
# step2: initialize a new DataFrame called signal_df with a signal column signal_df = pd.DataFrame(index=msft_data.index)signal_df['signal'] = 0.0
# step3: create a short simple moving average over the short lookback period signal_df['short_mav'] = msft_data['Adj_Close'].rolling(window=short_lb, min_periods=1, center=False).mean()
# step4: create long simple moving average over the long lookback period signal_df['long_mav'] = msft_data['Adj_Close'].rolling(window=long_lb, min_periods=1, center=False).mean()
# step5: generate the signals based on the conditional statement signal_df['signal'][short_lb:] = np.where(signal_df['short_mav'][short_lb:] > signal_df['long_mav'][short_lb:], 1.0, 0.0) 
# step6: create the trading orders based on the positions column signal_df['positions'] = signal_df['signal'].diff()signal_df[signal_df['positions'] == -1.0]

Let’s see what’s happening here. We have created 2 lookback periods. The short lookback period short_lb is 50 days, and the longer lookback period for the long moving average is defined as a long_lb of 120 days.

We have created a new DataFrame which is designed to capture the signals. These signals are being generated whenever the short moving average crosses the long moving average using the np.where. It assigns 1.0 for true and 0.0 if the condition comes out to be false.

The positions columns in the DataFrame tells us if there is a buy signal or a sell signal, or to stay put. We're basically calculating the difference in the signals column from the previous row using diff.

And there we have our strategy implemented in just 6 steps using Pandas. Easy, wasn't it?

Now, let’s try to visualize this using Matplotlib. All we need to do is initialize a plot figure, add the adjusted closing prices, short, and long moving averages to the plot, and then plot the buy and sell signals using the positions column in the signal_df above:

# initialize the plot using plt fig = plt.figure()
# Add a subplot and label for y-axis plt1 = fig.add_subplot(111, ylabel="Price in $")
msft_data['Adj_Close'].plot(ax=plt1,, lw=2.)
# plot the short and long lookback moving averages signal_df[['short_mav', 'long_mav']].plot(ax=plt1, lw=2., figsize=(12,8))
# plotting the sell signals plt1.plot(signal_df.loc[signal_df.positions == -1.0].index, signal_df.short_mav[signal_df.positions == -1.0],'v', markersize=10,)
# plotting the buy signals plt1.plot(signal_df.loc[signal_df.positions == 1.0].index, signal_df.short_mav[signal_df.positions == 1.0], '^', markersize=10,) # Show the plotplt.show()

Running the above cell in the Jupyter notebook would yield a plot like the one below:

Now, you can clearly see that whenever the blue line (short moving average) goes up and beyond the orange line (long moving average), there is a pink upward marker indicating a buy signal.

A sell signal is denoted by a black downward marker where there’s a fall of the short_mav below long_mav.

Visualize the Performance of the Strategy on Quantopian

Quantopian is a Zipline-powered platform that has manifold use cases. You can write your own algorithms, access free data, backtest your strategy, contribute to the community, and collaborate with Quantopian if you need capital.

We have written an algorithm to backtest our SMA strategy, and here are the results:

Here is an explanation of the above metrics:

  • Total return: The total percentage return of the portfolio from the start to the end of the backtest.
  • Specific return: The difference between the portfolio’s total returns and common returns.
  • Common return: Returns that are attributable to common risk factors. There are 11 sector and 5 style risk factors that make up these returns. The Sector Exposure and Style Exposure charts in the Risk section provide more detail on these factors.
  • Sharpe: The 6-month rolling Sharpe ratio. It is a measure of risk-adjusted investment. It is calculated by dividing the portfolio’s excess returns over the risk-free rate by the portfolio’s standard deviation.
  • Max Drawdown: The largest drop of all the peak-to-trough movement in the portfolio’s history.
  • Volatility: Standard deviation of the portfolio’s returns.

Pat yourself on the back as you have successfully implemented your quantitative trading strategy!

Where to go From Here?

Now that your algorithm is ready, you’ll need to backtest the results and assess the metrics mapping the risk involved in the strategy and the stock. Again, you can use BlueShift and Quantopian to learn more about backtesting and trading strategies.

Further Resources

Quantra is a brainchild of QuantInsti. With a range of free and paid courses by experts in the field, Quantra offers a thorough guide on a bunch of basic and advanced trading strategies.

  • Data Science Course — They have rolled out an introductory course on Data Science that helps you build a strong foundation for projects in Data Science.
  • Trading Courses for Beginners — From momentum trading to machine and deep learning-based trading strategies, researchers in the trading world like Dr. Ernest P. Chan are the authors of these niche courses.

Free Resources

To learn more about trading algorithms, check out these blogs:

  • Quantstart — they cover a wide range of backtesting algorithms, beginner guides, and more.
  • Investopedia — everything you want to know about investment and finance.
  • Quantivity — detailed mathematical explanations of algorithms and their pros and cons.

Warren Buffet says he reads about 500 pages a day, which should tell you that reading is essential in order to succeed in the field of finance.

Embark upon this journey of trading and you can lead a life full of excitement, passion, and mathematics.

Data Science with Harshit

With this channel, I am planning to roll out a couple of series covering the entire data science space. Here is why you should be subscribing to the channel:

  • These series would cover all the required/demanded quality tutorials on each of the topics and subtopics like Python fundamentals for Data Science.
  • Explained Mathematics and derivations of why we do what we do in ML and Deep Learning.
  • Podcasts with Data Scientists and Engineers at Google, Microsoft, Amazon, etc, and CEOs of big data-driven companies.
  • Projects and instructions to implement the topics learned so far. Learn about new certifications, Bootcamp, and resources to crack those certifications like this TensorFlow Developer Certificate Exam by Google.

Further on, you can connect with me on Twitter or LinkedIn.