Tuesday 13 February 2018

استراتيجيات التداول الخوارزمية r


تجارة خوارزمية في R تعليمي.


في هذا المنصب، وسوف تظهر كيفية استخدام R لجمع الأسهم المدرجة على loyal3، والحصول على البيانات التاريخية من ياهو ومن ثم تنفيذ استراتيجية التداول خوارزمية بسيطة. على طول الطريق، سوف تتعلم بعض كشط على شبكة الإنترنت، وظيفة ضرب أبي المالية و هتملويدجيت لجعل الرسم البياني سلسلة زمنية تفاعلية.


بالنسبة إلى هذه الوظيفة، يتم تعريف الغرامة التجارية بأنها مجموعة من القواعد التي تؤدي إلى حدث شراء أو بيع بدلا من نموذج تنبؤي أو توقعات سلسلة زمنية. هذا هو أبسط أنواع التداول ألغو، ولكن إذا كنت ترغب في حفر أعمق في التمويل مع R، وأود أن أشجعكم على اتخاذ مسار DataCampЂЂ ™ في نمذجة استراتيجية التداول الكمي في R.


خلفية.


في عام 2018، بدأت الاستثمار قليلا في الولاء 3. خدمتهم غير عادية ومكان عظيم لبدء رحلة الاستثمار الخاص. بدلا من توجيه الاتهام للمستثمر في الصفقات، الموالين 3 يتهم الشركات على قائمة على منصة. الفرضية هي أن الناس الذين يحبون خدمة company'Ђ ™ سوف أيضا شراء الأسهم وفي القيام بذلك تصبح قوية المدافعين عن العلامة التجارية. جعل المنصة أكثر إقناعا هو أنه يمكنك شراء أسهم كسور. لذلك، يمكنك الحصول على أن 800 $ الأمازون الأسهم فقط 10 $ وشراء آخر 10 $ الكسور في كل مرة لديك قليلا من النقود الإضافية في نهاية الشهر. بالتأكيد هناك تكاليف الاحتكاك منذ لديك للتداول في ويندوز ومحفظتك بأكملها يقتصر على.


70 أسهم ولكن loyal3 يمثل وسيلة ممتعة ومنخفضة التكلفة لاستكشاف التدريب على الإنصاف. يمكنك وضع الجلد الحقيقي في اللعبة لمدة لا تقل عن 10 $!


أن تكون واضحة، لدي حسابات التقاعد والتقاعد نموذجية ولكن أنا أحب Lyn3†™ ق واجهة نظيفة على التطبيق وعدم وجود رسوم. أنا في نهاية المطاف فحص بلدي محفظة loyal3 متعة في كثير من الأحيان من صناديق الاستثمار بلدي ببساطة لأنه من السهل ومسلية لمعرفة أداء الأسهم اخترت مباشرة.


الأسهم المتاحة في الولاء 3.


إعداد مساحة العمل الخاصة بك.


للبدء، تحميل المكتبات في البيئة الخاصة بك. أنا دائما تقريبا استخدام رفيست لشبكة الإنترنت كشط هذه الأيام. هناك حزم أخرى التي تعمل بما في ذلك رسلينيوم، ولكن أنا أحب كيف يمكن تنفيذ رفيست سهلة.


الحزمة الثانية، بابابلي، اختيارية لأنها ببساطة إضافة شريط التقدم إلى وظائف تطبيق. منذ كنت يمكن أن يكون كشط مئات من صفحات الويب شريط التقدم يمكن أن تكون مفيدة لتقدير الوقت.


بعد ذلك، تر هي الحزمة التي بدأت للتو لاستكشاف. يتم استخدام المكتبة لبناء ЂњTechnical قواعد التداول Ђќ. على الرغم من أنك سوف تتعلم ألغو التداول بسيطة في هذا المنصب، حزمة تر يمكن أن تؤدي العمليات الحسابية أكثر تطورا ويستحق التعلم.


مكتبة ديغرافس عبارة عن مجمع لمكتبة جافا سكريبت مفتوحة المصدر للمخططات. وهي واحدة من هتملويدجيتس التي تجعل R رسم أكثر ديناميكية وجزء من ملف هتمل بدلا من صورة ثابتة. وأخيرا، يتم استخدام حزمة لوبريديت للتلاعب تاريخ سهل.


جمع البيانات.


يتم إدراج جميع الأسهم الموالية 3 في صفحة واحدة. قبل أن تتمكن من البحث عن أسعار الأسهم اليومية الفردية لبناء خوارزمية التداول الخاص بك، تحتاج إلى جمع كل ما تبذلونه من المخزون ستوكر المتاحة. أول شيء يجب القيام به هو إعلان stock. list كسلسلة ورل. استخدم التالي read_html () بحيث تقوم جلسة R بإنشاء جلسة إنترنت وجمع كل معلومات هتمل على الصفحة كمجموعة عقدة شمل. تحتوي صفحة كس على معرف يسمى “pany-nameЂќЂќ. استخدم هذا كمعلمة عند استدعاء html_nodes () لتحديد بيانات شمل المرتبطة بهذه العقدة فقط. وأخيرا، استخدم html_text () بحيث يتم جمع قيم النص الفعلية لأسماء الشركة.


لفحص الأسهم المتوفرة على loyal3، يمكنك طباعة الكائن stock. names إلى وحدة التحكم الخاصة بك. يؤدي هذا إلى إرجاع اسم الشركة كمتجه نصي.


من أجل البحث في أسعار الأسهم، تحتاج إلى الحصول على رمز شريط أولا. عندما كنت على موقع loyal3، يمكنك النقر على البلاط الشركة لتحميل صفحة مع رمز شريط ومعلومات الشركة الأخرى.


باستخدام html_nodes () على الأسهم، يمكنك سحب كافة العقد ملحوظ مع “a. ” في هتمل & لوت؛ a & غ؛ علامة الارتباط التشعبي الذي يستخدم لربط نموذج صفحة واحدة إلى أخرى. ضمن علامة الارتباط التشعبي، يشير “hrefв to إلى عنوان ورل الدقيق. لذا سوف يستخرج html_attr () عنوان ورل لكل الروابط الموجودة في الصفحة إذا كنت تمر في “href”.


بعد القيام ببعض التفتيش اليدوي، وجدت 54 إلى 123rd الروابط على الصفحة تمثل صفحات الشركة أحتاج من أجل كشط المعلومات شريط. يستخدم السطر الأخير paste0 () لتوصيل سلسلة عنوان ورل الأساسي †™ loyal3` إلى صفحات الشركة المحددة، مثل “ / WALMART”. على سبيل المثال، loyal3 / والمارت:


على كل صفحة من صفحات الشركة هناك وصف، وسعر الإغلاق الأخير و شريط. ويتم تنظيم جميع صفحات الشركة نفسها بحيث يمكن استخدام وظيفة مخصصة get. ticker () لاستخراج رمز شريط.


داخل صفحة ويب company' s s هناك جدول يسمى “ticker-price”. ستنتقل الدالة إلى صفحة شركة، وتحدد الجدول المناسب، وتستخرج النص باستخدام html_text (). وأخيرا، باستخدام سوب () جنبا إلى جنب مع التعبير العادي ^ ([[: ألفا:]] *). * و \\ 1 سوف تحتفظ بجميع الأحرف الأبجدية. والنتيجة هي أن أي أحرف خاصة، مثل $، وأية أحرف رقمية، مثل سعر الإغلاق، تتم إزالة. كما يقرأ وظيفة كل من 70 صفحة، فإنه سيتم جمع فقط شريط الأسهم.


صفحة الأسهم 3 ل علي بابا، حيث ترى الجدول الذي يحتوي على شريط الأسهم، ™ بابا، هو أقل من النص عريض.


المسلحة مع وظيفة مخصصة الخاص بك، استخدام بلابلي () لتطبيقه على كل من stock. links التي تحتوي على كل صفحة companyЂЂ ™ ق. الكائن الناتج، stock. tickers، هو قائمة من الأوراق المالية الفردية مع كل عنصر المقابلة لشركة فردية.


طريقة واحدة لتغيير قائمة العناصر في كائن مسطح مع do. call (). هنا، كنت تطبيق ربيند إلى صف ربط كل عنصر القائمة في متجه واحد. وأخيرا، يمكنك إنشاء إطار بيانات مع الرمز ومعلومات اسم الشركة.


لكي تكون متسقة في تحليلك، قد ترغب في تحديد مقدار المعلومات التاريخية التي تجمعها على كل سهم. ستقوم الدالة Sys. Data () بتخزين عنصر تاريخ كسنة وشهر ثم يوم. استخدام سنوات مع عدد صحيح هو طريقة واحدة لطرح كمية معينة من الوقت من كائن start. date.


للحصول على بيانات مالية ياهو، يجب تغيير كائن التاريخ إلى كائنات أحرف بسيطة بدون شرطة. استخدام الدالة الاستبدال العالمية غسوب () على حد سواء start. date و end. date سيغير الطبقة و في نفس الوقت إزالة الشرطات. داخل غسوب ()، تمر في نمط حرف للبحث عن، ثم أحرف استبدال. في هذه الحالة نمط الاستبدال هو حرف فارغ بين علامات الاقتباس. المعلمة الأخيرة هي الكائن الذي سيتم تطبيق غسوب () على.


الدالة تر () جيتياهوداتا () تقبل رمز الأسهم، وتاريخ البدء والانتهاء. ترجع الدالة إطار بيانات يحتوي على معلومات سلاسل زمنية. كل صف هو تاريخ والأعمدة تحتوي على معلومات مثل سعر “Open”، “High”، “Low” و “Closingв for للأسهم. منذ كنت تبحث عن شركات متعددة، يمكنك استخدام لابلي () أو بلابلي (). تمر في ناقلات رموز الشركة، ثم وظيفة، جيتياهوداتا ()، ومن ثم معلومات التاريخ. يتم إعادة تدوير الكائنات التاريخ المعلمات في كل مرة يتم تطبيق جيتياهوداتا () على رمز السهم.


لجعل اختيار قائمة عاد، stock. ts، وأسهل للتنقل يمكنك إضافة أسماء إلى عناصر القائمة. استخدام أسماء مع الكائن stock. ts تعلن أسماء كمتجه رمز الأصلي $.


عند العمل مع القوائم الكبيرة، أود أن فحص الكائن الناتج للتأكد من أن النتيجة هي ما كنت أتوقع. الآن بعد أن العناصر لها أسماء، يمكنك الرجوع إليها مباشرة. في هذا المثال، كنت تدرس الصفوف الأولى 6 ل أمك الترفيه القابضة (أمك). سيؤدي استخدام رأس () في القائمة أثناء الرجوع إلى أمك $ إلى إعادة جزء من السلاسل الزمنية لهذا المخزون:


فحص بيانات المخزون.


عندما أستمع إلى معلقين الأخبار المالية غالبا ما تشير إلى الرسوم البيانية. على الرغم من التداول عالية التردد وإدارة نشطة يؤديها آخرون، العديد من المستثمرين الصغار لا تزال تشير إلى الرسوم البيانية للحصول على البصيرة. يمكن عرض الكائن سلسلة الوقت بسرعة باستخدام مؤامرة. مرر في القائمة التي تشير إلى العنصر المسمى مثل أمك $ ثم العمود الذي تريد عرضه، وهنا إغلاق $.


المؤامرة السابقة هي ثابتة وغير مثيرة جدا للاهتمام.


استخدام مكتبة جافا سكريبت لجعل الرسم البياني يمكنك استكشاف. في مقتطف الشفرة هذا، قد تلاحظ عامل التشغيل Ђњ٪ & غ؛٪ ” أو الأنبوب. مشغل الأنابيب هو وسيلة جيدة لكتابة رمز موجزة. فإنه يحيل كائن إلى الدالة التالية دون إجبارك على إعادة كتابة اسم كائن كما فعلت في وقت سابق في هذا المنصب.


في هذا المثال، يمكنك إنشاء ديغراف يشير إلى الأسهم تويتر، $ توتر، ثم العمود الذي تريد مؤامرة، $ إغلاق. داخل ديغراف، يضيف الرئيسي عنوان الذي تم تحديده بين علامات الاقتباس. باستخدام “٪ & غ؛٪ ” يتم إعادة توجيه هذا الكائن بأكمله إلى الدالة التالية ديرانجيسليكتور (). يمكنك تحديد نطاق تاريخ افتراضي باستخدام c () مع سلسلة تاريخ البدء والنهاية. كائن هتمل الناتج هو سلسلة زمنية ديناميكية لمخزون Twitter†™ مع شريط تمرير التاريخ في الأسفل.


تذكر، لتغيير الأسهم المعروضة، تغيير رمز شريط في قائمة stock. ts ثم عنوان الرسم البياني.


هذا هو ديغراف الأساسية لمخزون Twitter†™ ل.


استراتيجية التداول بسيطة: الاتجاه التالي.


تجار عالية التردد وصناديق التحوط استخدام نماذج متطورة والقواعد القائمة على نهج لتنفيذ الصفقات. إذا كنت ترغب في معرفة المزيد أقترح زيارة كوانتوبيان للنهج المتقدمة. لتبدأ نهج أبسط مع هذه الصفحة في إنفستوبيديا.


في التعليمات البرمجية أدناه، سوف تصور استراتيجية التداول الزخم بسيطة. في الأساس، كنت ترغب في حساب المتوسطات المتحركة ل 200 يوم و 50 يوم لسعر السهم. في أي يوم من الأيام أن المتوسط ​​المتحرك لمدة 50 يوم فوق المتوسط ​​المتحرك ل 200 يوم، يمكنك شراء أو الاحتفاظ بموقفك. في الأيام التي يكون فيها المتوسط ​​200 يوم أكثر من المتوسط ​​المتحرك ل 50 يوم، ستبيع أسهمك. وتسمى هذه الاستراتيجية استراتيجية الاتجاه التالي. تمثل الطبيعة الإيجابية أو السلبية بين المتوسطين الزمنيين الزخم قوة الزخم.


وتوفر الحزمة تر سما () لحساب المتوسط ​​المتحرك البسيط. في مقتطف الشفرة هذا، فإنك تدرس القيم الستة الأولى لمتوسطات متحركة ل 200 و 50 يوم. سما () يعمل عن طريق تمرير في سلسلة البيانات الزمنية لمخزون وعمود معين مثل إغلاق. هذا هو متجه واحد لأسعار إغلاق الأسهم توتر. والمعلمة الثانية هي عدد صحيح يمثل عدد المشاهدات للمتوسط ​​المتحرك. بدون استخدام الرأس () ستقوم الدالة سما () بإرجاع كل القيم.


الآن بعد أن كنت قد فحصت المتوسط ​​المتحرك وظيفة بالتفصيل، تحتاج إلى تطبيق على كل من 70 أسهم. stock. ts هي قائمة من 70 إطار البيانات التي تحتوي على بيانات المخزون الفردية. يحتوي العمود الرابع من كل إطار بيانات على سعر الإغلاق الذي نريد استخدامه للمتوسطات المتحركة.


تقبل الدالة المخصصة mov. avgs () إطار بيانات مخزون واحد لحساب المتوسطات المتحركة. السطر الأول يختار أسعار الإغلاق لأنه فهرسة [، 4] لإنشاء stock. close. بعد ذلك، تستخدم الدالة إفيلز للتحقق من عدد الصفوف في إطار البيانات. على وجه التحديد إذا كان نرو في إطار البيانات أقل من (2 * 260)، ثم وظيفة إنشاء إطار بيانات للمتوسطات المتحركة مع “NA”.


لقد اخترت هذا الرقم لأن هناك حوالي 250 أيام التداول في السنة لذلك هذا سوف تحقق من أن سلسلة زمنية حوالي 2 سنوات أو أكثر في الطول. يمكن لويال 3 في بعض الأحيان الحصول على الاكتتابات العامة وإذا كان الأسهم العامة الجديدة لن تكون هناك بيانات كافية لمتوسط ​​المتحرك 200 يوم. ومع ذلك، إذا كانت قيمة نرو أكبر من 2 * 260 ثم وظيفة إنشاء إطار بيانات مع البيانات الأصلية جنبا إلى جنب مع 200 و 50 يوم المتوسطات المتحركة كأعمدة جديدة. باستخدام الأسماء، أعلن أسماء الأعمدة. يستخدم الجزء الأخير من الدالة كومبليت. يتم التحقق من القيم في العمود المتوسط ​​المتحرك ل 200 يوم. يتم إسقاط أية صفوف لا تحتوي على قيمة في النتيجة النهائية.


المسلحة مع هذه الوظيفة mov. avgs () يمكنك استخدام بلابلي () لإضافة حسابات المتوسط ​​المتحرك إلى كل من إطارات البيانات 70.


استخدم الرمز أدناه لتصور المتوسطات المتحركة StockЂ s ™ باستخدام ديغراف. مرة أخرى، يستخدم هذا الرمز عامل التشغيل “٪ & غ؛٪ в to لإعادة توجيه الكائنات. و ديغراف () وظيفة يقبل الأسهم. $ فوكس إطار البيانات. على وجه التحديد، يتم فهرسة إطار البيانات حسب اسم العمود مع c ('sma_200'، 'sma_50'). يتم تمرير هذا الكائن إلى ديسريز () في السطرين التاليين. يمكنك الرجوع إلى عمود بالاسم حتى ديسيريز () كل مؤامرة سطر للقيم “sma_50” و “sma_200в in في السطرين 2 و 3. يتم إعادة توجيه هذا الكائن مرة أخرى إلى ديرانجيسليكتور () لضبط ارتفاع المحدد. وأخيرا، أضفت بعض التظليل لتحديد فترات عندما كنت ترغب في شراء أو الاحتفاظ الأسهم وفترة عندما كنت قد باعت أسهمك أو بقي بعيدا اعتمادا على موقفكم.


هنا هي النتيجة النهائية في سلسلة زمنية تفاعلية.


المتوسطات المتحركة فوكس مع المناطق المظللة لشراء / عقد مقابل بيع.


استنتاج.


كما المتداول الخوارزمية الناشئة، لا تحتاج إلى مؤامرة جميع 70 سهم. بدلا من ذلك، كنت ترغب في تشغيل التعليمات البرمجية كل يوم وإضافة طريقة برنامجية لتحديد الأسهم التي تناسب الطريقة القائمة على القاعدة، “buy إذا كان المتوسط ​​المتحرك لمدة 50 يوم فوق المتوسط ​​المتحرك ل 200 يومЂќЂќ. كما كنت مراجعة الرسم البياني السابق، القسم الأخضر هو الوقت الذي كنت شراء الأسهم فوكس. يمثل القسم الأحمر الوقت لبيع أسهمك وعدم إعادة الدخول.


نظرا لأن الرسم البياني تفاعلي، يمكنك استخدام شريط التمرير لتغيير حجم العنصر المرئي. وبناء على هذا النهج التداول ألغو بسيط، والآن قد يكون وقتا طيبا لشراء فوكس! كان 30 ديسمبر 2018 يوم تداول حيث تحرك المتوسط ​​المتحرك ل 50 يوم 0.01 دولار أعلى من المتوسط ​​المتحرك ل 200 يوم!


قسم التكبير من فوكس الأسهم.


وبطبيعة الحال، تذكر جميع الاستثمارات يمكن أن تفقد القيمة. لمعرفة المزيد عن التمويل والتداول ألغو، В تحقق من الدورات DataCamp†™ ل هنا.


تجارة خوارزمية في R تعليمي.


في هذا المنصب، وسوف تظهر كيفية استخدام R لجمع الأسهم المدرجة على loyal3، والحصول على البيانات التاريخية من ياهو ومن ثم تنفيذ استراتيجية التداول خوارزمية بسيطة. على طول الطريق، سوف تتعلم بعض كشط على شبكة الإنترنت، وظيفة ضرب أبي المالية و هتملويدجيت لجعل الرسم البياني سلسلة زمنية تفاعلية.


بالنسبة إلى هذه الوظيفة، يتم تعريف الغرامة التجارية بأنها مجموعة من القواعد التي تؤدي إلى حدث شراء أو بيع بدلا من نموذج تنبؤي أو توقعات سلسلة زمنية. هذا هو أبسط أنواع التداول ألغو، ولكن إذا كنت ترغب في حفر أعمق في التمويل مع R، وأود أن أشجعكم على اتخاذ مسار DataCampЂЂ ™ في نمذجة استراتيجية التداول الكمي في R.


خلفية.


في عام 2018، بدأت الاستثمار قليلا في الولاء 3. خدمتهم غير عادية ومكان عظيم لبدء رحلة الاستثمار الخاص. بدلا من توجيه الاتهام للمستثمر في الصفقات، الموالين 3 يتهم الشركات على قائمة على منصة. الفرضية هي أن الناس الذين يحبون خدمة company'Ђ ™ سوف أيضا شراء الأسهم وفي القيام بذلك تصبح قوية المدافعين عن العلامة التجارية. جعل المنصة أكثر إقناعا هو أنه يمكنك شراء أسهم كسور. لذلك، يمكنك الحصول على أن 800 $ الأمازون الأسهم فقط 10 $ وشراء آخر 10 $ الكسور في كل مرة لديك قليلا من النقود الإضافية في نهاية الشهر. بالتأكيد هناك تكاليف الاحتكاك منذ لديك للتداول في ويندوز ومحفظتك بأكملها يقتصر على.


70 أسهم ولكن loyal3 يمثل وسيلة ممتعة ومنخفضة التكلفة لاستكشاف التدريب على الإنصاف. يمكنك وضع الجلد الحقيقي في اللعبة لمدة لا تقل عن 10 $!


أن تكون واضحة، لدي حسابات التقاعد والتقاعد نموذجية ولكن أنا أحب Lyn3†™ ق واجهة نظيفة على التطبيق وعدم وجود رسوم. أنا في نهاية المطاف فحص بلدي محفظة loyal3 متعة في كثير من الأحيان من صناديق الاستثمار بلدي ببساطة لأنه من السهل ومسلية لمعرفة أداء الأسهم اخترت مباشرة.


الأسهم المتاحة في الولاء 3.


إعداد مساحة العمل الخاصة بك.


للبدء، تحميل المكتبات في البيئة الخاصة بك. أنا دائما تقريبا استخدام رفيست لشبكة الإنترنت كشط هذه الأيام. هناك حزم أخرى التي تعمل بما في ذلك رسلينيوم، ولكن أنا أحب كيف يمكن تنفيذ رفيست سهلة.


الحزمة الثانية، بابابلي، اختيارية لأنها ببساطة إضافة شريط التقدم إلى وظائف تطبيق. منذ كنت يمكن أن يكون كشط مئات من صفحات الويب شريط التقدم يمكن أن تكون مفيدة لتقدير الوقت.


بعد ذلك، تر هي الحزمة التي بدأت للتو لاستكشاف. يتم استخدام المكتبة لبناء Ђњ قواعد التداول الفنية Ђќ. على الرغم من أنك سوف تتعلم ألغو التداول بسيطة في هذا المنصب، حزمة تر يمكن أن تؤدي العمليات الحسابية أكثر تطورا ويستحق التعلم.


مكتبة ديغرافس عبارة عن مجمع لمكتبة جافا سكريبت مفتوحة المصدر للمخططات. وهي واحدة من هتملويدجيتس التي تجعل R رسم أكثر ديناميكية وجزء من ملف هتمل بدلا من صورة ثابتة. وأخيرا، يتم استخدام حزمة لوبريديت للتلاعب تاريخ سهل.


جمع البيانات.


يتم إدراج جميع الأسهم الموالية 3 في صفحة واحدة. قبل أن تتمكن من البحث عن أسعار الأسهم اليومية الفردية لبناء خوارزمية التداول الخاص بك، تحتاج إلى جمع كل ما تبذلونه من المخزون ستوكر المتاحة. أول شيء يجب القيام به هو إعلان stock. list كسلسلة ورل. استخدم التالي read_html () بحيث تقوم جلسة R بإنشاء جلسة إنترنت وجمع كل معلومات هتمل على الصفحة كمجموعة عقدة شمل. تحتوي صفحة كس على معرف يسمى “pany-nameЂќЂќ. استخدم هذا كمعلمة عند استدعاء html_nodes () لتحديد بيانات شمل المرتبطة بهذه العقدة فقط. وأخيرا، استخدم html_text () بحيث يتم جمع قيم النص الفعلية لأسماء الشركة.


لفحص الأسهم المتوفرة على loyal3، يمكنك طباعة الكائن stock. names إلى وحدة التحكم الخاصة بك. يؤدي هذا إلى إرجاع اسم الشركة كمتجه نصي.


من أجل البحث في أسعار الأسهم، تحتاج إلى الحصول على رمز شريط أولا. عندما كنت على موقع loyal3، يمكنك النقر على البلاط الشركة لتحميل صفحة مع رمز شريط ومعلومات الشركة الأخرى.


باستخدام html_nodes () على الأسهم، يمكنك سحب كافة العقد ملحوظ مع “a. ” في هتمل & لوت؛ a & غ؛ علامة الارتباط التشعبي الذي يستخدم لربط نموذج صفحة واحدة إلى أخرى. ضمن علامة الارتباط التشعبي، يشير “hrefв to إلى عنوان ورل الدقيق. لذا سوف يستخرج html_attr () عنوان ورل لكل الروابط الموجودة في الصفحة إذا كنت تمر في “href”.


بعد القيام ببعض التفتيش اليدوي، وجدت 54 إلى 123rd الروابط على الصفحة تمثل صفحات الشركة أحتاج من أجل كشط المعلومات شريط. يستخدم السطر الأخير paste0 () لتوصيل سلسلة عنوان ورل الأساسي †™ loyal3` إلى صفحات الشركة المحددة، مثل “ / WALMART”. على سبيل المثال، loyal3 / والمارت:


على كل صفحة من صفحات الشركة هناك وصف، وسعر الإغلاق الأخير و شريط. ويتم تنظيم جميع صفحات الشركة نفسها بحيث يمكن استخدام وظيفة مخصصة get. ticker () لاستخراج رمز شريط.


داخل صفحة ويب company' s s هناك جدول يسمى “ticker-price”. ستنتقل الدالة إلى صفحة شركة، وتحدد الجدول المناسب، وتستخرج النص باستخدام html_text (). وأخيرا، باستخدام سوب () جنبا إلى جنب مع التعبير العادي ^ ([[: ألفا:]] *). * و \\ 1 سوف تحتفظ بجميع الأحرف الأبجدية. والنتيجة هي أن أي أحرف خاصة، مثل $، وأية أحرف رقمية، مثل سعر الإغلاق، تتم إزالة. كما يقرأ وظيفة كل من 70 صفحة، فإنه سيتم جمع فقط شريط الأسهم.


صفحة الأسهم 3 ل علي بابا، حيث ترى الجدول الذي يحتوي على شريط الأسهم، ™ بابا، هو أقل من النص عريض.


المسلحة مع وظيفة مخصصة الخاص بك، استخدام بلابلي () لتطبيقه على كل من stock. links التي تحتوي على كل صفحة companyЂЂ ™ ق. الكائن الناتج، stock. tickers، هو قائمة من الأوراق المالية الفردية مع كل عنصر المقابلة لشركة فردية.


طريقة واحدة لتغيير قائمة العناصر في كائن مسطح مع do. call (). هنا، كنت تطبيق ربيند إلى صف ربط كل عنصر القائمة في متجه واحد. وأخيرا، يمكنك إنشاء إطار بيانات مع الرمز ومعلومات اسم الشركة.


لكي تكون متسقة في تحليلك، قد ترغب في تحديد مقدار المعلومات التاريخية التي تجمعها على كل سهم. ستقوم الدالة Sys. Data () بتخزين عنصر تاريخ كسنة وشهر ثم يوم. استخدام سنوات مع عدد صحيح هو طريقة واحدة لطرح كمية معينة من الوقت من كائن start. date.


للحصول على بيانات مالية ياهو، يجب تغيير كائن التاريخ إلى كائنات أحرف بسيطة بدون شرطة. استخدام الدالة الاستبدال العالمية غسوب () على حد سواء start. date و end. date سيغير الطبقة و في نفس الوقت إزالة الشرطات. داخل غسوب ()، تمر في نمط حرف للبحث عن، ثم أحرف استبدال. في هذه الحالة نمط الاستبدال هو حرف فارغ بين علامات الاقتباس. المعلمة الأخيرة هي الكائن الذي سيتم تطبيق غسوب () على.


الدالة تر () جيتياهوداتا () تقبل رمز الأسهم، وتاريخ البدء والانتهاء. ترجع الدالة إطار بيانات يحتوي على معلومات سلسلة زمنية. كل صف هو تاريخ والأعمدة تحتوي على معلومات مثل سعر “Open”، “High”، “Low” و “Closingв for للأسهم. منذ كنت تبحث عن شركات متعددة، يمكنك استخدام لابلي () أو بلابلي (). تمر في ناقلات رموز الشركة، ثم وظيفة، جيتياهوداتا ()، ومن ثم معلومات التاريخ. يتم إعادة تدوير الكائنات التاريخ المعلمات في كل مرة يتم تطبيق جيتياهوداتا () على رمز السهم.


لجعل اختيار قائمة عاد، stock. ts، وأسهل للتنقل يمكنك إضافة أسماء إلى عناصر القائمة. استخدام أسماء مع الكائن stock. ts تعلن أسماء كمتجه رمز الأصلي $.


عند العمل مع القوائم الكبيرة، أود أن فحص الكائن الناتج للتأكد من أن النتيجة هي ما كنت أتوقع. الآن بعد أن العناصر لها أسماء، يمكنك الرجوع إليها مباشرة. في هذا المثال، كنت تدرس الصفوف الأولى 6 ل أمك الترفيه القابضة (أمك). سيؤدي استخدام رأس () في القائمة أثناء الرجوع إلى أمك $ إلى إعادة جزء من السلاسل الزمنية لهذا المخزون:


فحص بيانات المخزون.


عندما أستمع إلى معلقين الأخبار المالية غالبا ما تشير إلى الرسوم البيانية. على الرغم من التداول عالية التردد وإدارة نشطة يؤديها آخرون، العديد من المستثمرين الصغار لا تزال تشير إلى الرسوم البيانية للحصول على البصيرة. يمكن عرض الكائن سلسلة الوقت بسرعة باستخدام مؤامرة. مرر في القائمة التي تشير إلى العنصر المسمى مثل أمك $ ثم العمود الذي تريد عرضه، وهنا إغلاق $.


المؤامرة السابقة هي ثابتة وغير مثيرة جدا للاهتمام.


استخدام مكتبة جافا سكريبت لجعل الرسم البياني يمكنك استكشاف. في مقتطف الشفرة هذا، قد تلاحظ عامل التشغيل Ђњ٪ & غ؛٪ ” أو الأنبوب. مشغل الأنابيب هو وسيلة جيدة لكتابة رمز موجزة. فإنه يحيل كائن إلى الدالة التالية دون إجبارك على إعادة كتابة اسم كائن كما فعلت في وقت سابق في هذا المنصب.


في هذا المثال، يمكنك إنشاء ديغراف يشير إلى الأسهم تويتر، $ توتر، ثم العمود الذي تريد مؤامرة، $ إغلاق. داخل ديغراف، يضيف الرئيسي عنوان الذي تم تحديده بين علامات الاقتباس. باستخدام “٪ & غ؛٪ ” يتم إعادة توجيه هذا الكائن بأكمله إلى الدالة التالية ديرانجيسليكتور (). يمكنك تحديد نطاق تاريخ افتراضي باستخدام c () مع سلسلة تاريخ البدء والنهاية. كائن هتمل الناتج هو سلسلة زمنية ديناميكية لمخزون Twitter†™ مع شريط تمرير التاريخ في الأسفل.


تذكر، لتغيير الأسهم المعروضة، تغيير رمز شريط في قائمة stock. ts ثم عنوان الرسم البياني.


هذا هو ديغراف الأساسية لمخزون Twitter†™ ل.


استراتيجية التداول بسيطة: الاتجاه التالي.


تجار عالية التردد وصناديق التحوط استخدام نماذج متطورة والقواعد القائمة على نهج لتنفيذ الصفقات. إذا كنت ترغب في معرفة المزيد أقترح زيارة كوانتوبيان للنهج المتقدمة. لتبدأ نهج أبسط مع هذه الصفحة في إنفستوبيديا.


في التعليمات البرمجية أدناه، سوف تصور استراتيجية التداول الزخم بسيطة. في الأساس، كنت ترغب في حساب المتوسطات المتحركة ل 200 يوم و 50 يوم لسعر السهم. في أي يوم من الأيام أن المتوسط ​​المتحرك لمدة 50 يوم فوق المتوسط ​​المتحرك ل 200 يوم، يمكنك شراء أو الاحتفاظ بموقفك. في الأيام التي يكون فيها المتوسط ​​200 يوم أكثر من المتوسط ​​المتحرك ل 50 يوم، ستبيع أسهمك. وتسمى هذه الاستراتيجية استراتيجية الاتجاه التالي. وتمثل الطبيعة الإيجابية أو السلبية بين المتوسطين الزمنيين الزخم قوة الزخم.


وتوفر الحزمة تر سما () لحساب المتوسط ​​المتحرك البسيط. في مقتطف الشفرة هذا، فإنك تدرس القيم الستة الأولى لمتوسطات متحركة ل 200 و 50 يوم. سما () يعمل عن طريق تمرير في سلسلة البيانات الزمنية لمخزون وعمود معين مثل إغلاق. هذا هو متجه واحد لأسعار إغلاق الأسهم توتر. والمعلمة الثانية هي عدد صحيح يمثل عدد المشاهدات للمتوسط ​​المتحرك. بدون استخدام الرأس () ستقوم الدالة سما () بإرجاع كل القيم.


الآن بعد أن كنت قد فحصت المتوسط ​​المتحرك وظيفة بالتفصيل، تحتاج إلى تطبيق على كل من 70 أسهم. stock. ts هي قائمة من 70 إطار البيانات التي تحتوي على بيانات المخزون الفردية. يحتوي العمود الرابع من كل إطار بيانات على سعر الإغلاق الذي نريد استخدامه للمتوسطات المتحركة.


تقبل الدالة المخصصة mov. avgs () إطار بيانات مخزون واحد لحساب المتوسطات المتحركة. السطر الأول يختار أسعار الإغلاق لأنه فهرسة [، 4] لإنشاء stock. close. بعد ذلك، تستخدم الدالة إفيلز للتحقق من عدد الصفوف في إطار البيانات. على وجه التحديد إذا كان نرو في إطار البيانات أقل من (2 * 260)، ثم وظيفة إنشاء إطار بيانات للمتوسطات المتحركة مع “NA”.


لقد اخترت هذا الرقم لأن هناك حوالي 250 أيام التداول في السنة لذلك هذا سوف تحقق من أن سلسلة زمنية حوالي 2 سنوات أو أكثر في الطول. يمكن لويال 3 في بعض الأحيان الحصول على الاكتتابات العامة وإذا كان الأسهم العامة الجديدة لن تكون هناك بيانات كافية لمتوسط ​​المتحرك 200 يوم. ومع ذلك، إذا كانت قيمة نرو أكبر من 2 * 260 ثم وظيفة إنشاء إطار بيانات مع البيانات الأصلية جنبا إلى جنب مع 200 و 50 يوم المتوسطات المتحركة كأعمدة جديدة. باستخدام الأسماء، أعلن أسماء الأعمدة. يستخدم الجزء الأخير من الدالة كومبليت. يتم التحقق من القيم في العمود المتوسط ​​المتحرك ل 200 يوم. يتم إسقاط أية صفوف لا تحتوي على قيمة في النتيجة النهائية.


المسلحة مع هذه الوظيفة mov. avgs () يمكنك استخدام بلابلي () لإضافة حسابات المتوسط ​​المتحرك إلى كل من إطارات البيانات 70.


استخدم الرمز أدناه لتصور المتوسطات المتحركة StockЂ s ™ باستخدام ديغراف. مرة أخرى، يستخدم هذا الرمز عامل التشغيل “٪ & غ؛٪ в to لإعادة توجيه الكائنات. و ديغراف () وظيفة يقبل الأسهم. $ فوكس إطار البيانات. على وجه التحديد، يتم فهرسة إطار البيانات حسب اسم العمود مع c ('sma_200'، 'sma_50'). يتم تمرير هذا الكائن إلى ديسريز () في السطرين التاليين. يمكنك الرجوع إلى عمود بالاسم حتى ديسيريز () كل مؤامرة سطر للقيم “sma_50” و “sma_200в in في السطرين 2 و 3. يتم إعادة توجيه هذا الكائن مرة أخرى إلى ديرانجيسليكتور () لضبط ارتفاع المحدد. وأخيرا، أضفت بعض التظليل لتحديد فترات عندما كنت ترغب في شراء أو الاحتفاظ الأسهم وفترة عندما كنت قد باعت أسهمك أو بقي بعيدا اعتمادا على موقفكم.


هنا هي النتيجة النهائية في سلسلة زمنية تفاعلية.


المتوسطات المتحركة فوكس مع المناطق المظللة لشراء / عقد مقابل بيع.


استنتاج.


كما المتداول الخوارزمية الناشئة، لا تحتاج إلى مؤامرة جميع 70 سهم. بدلا من ذلك، كنت ترغب في تشغيل التعليمات البرمجية كل يوم وإضافة طريقة برنامجية لتحديد الأسهم التي تناسب الطريقة القائمة على القاعدة، “buy إذا كان المتوسط ​​المتحرك لمدة 50 يوم فوق المتوسط ​​المتحرك ل 200 يومЂќЂќ. كما كنت مراجعة الرسم البياني السابق، القسم الأخضر هو الوقت الذي كنت شراء الأسهم فوكس. يمثل القسم الأحمر الوقت لبيع أسهمك وعدم إعادة الدخول.


نظرا لأن الرسم البياني تفاعلي، يمكنك استخدام شريط التمرير لتغيير حجم العنصر المرئي. وبناء على هذا النهج التداول ألغو بسيط، والآن قد يكون وقتا طيبا لشراء فوكس! كان 30 ديسمبر 2018 يوم تداول حيث تحرك المتوسط ​​المتحرك ل 50 يوم 0.01 دولار أعلى من المتوسط ​​المتحرك ل 200 يوم!


قسم التكبير من فوكس الأسهم.


وبطبيعة الحال، تذكر جميع الاستثمارات يمكن أن تفقد القيمة. لمعرفة المزيد عن التمويل والتداول ألغو، В تحقق من الدورات DataCamp†™ ل هنا.


استراتيجية التداول الكمية باستخدام R: دليل خطوة بخطوة.


في هذا المنصب سوف نناقش حول بناء استراتيجية التداول باستخدام R. قبل السكن في المصطلحات التجارية باستخدام R دعونا نقضي بعض الوقت فهم ما هو R. R هو مصدر مفتوح. هناك أكثر من 4000 إضافة على الحزم، 18000 بالإضافة إلى أعضاء مجموعة لينكيدين وما يقرب من 80 R مجموعات ميتوب الموجودة حاليا. بل هو أداة مثالية للتحليل الإحصائي وخاصة لتحليل البيانات. الإعداد موجزة من شبكة الأرشيف R شاملة يعرف كما كران يوفر لك قائمة الحزم جنبا إلى جنب مع تركيب قاعدة المطلوبة. هناك الكثير من الحزم المتاحة اعتمادا على تحليل يجب القيام به. لتنفيذ استراتيجية التداول، وسوف نستخدم حزمة تسمى كوانسترات.


عملية أربع خطوات لأي إستراتيجية تداول أساسية.


تكوين الفرضية اختبار تكرير الإنتاج.


وقد صيغت فرضيتنا على أنها "السوق يعني العودة". متوسط ​​العائد هو نظرية تشير إلى أن الأسعار تتحرك في نهاية المطاف إلى القيمة المتوسطة. أما الخطوة الثانية فتتضمن اختبار الفرضية التي نقوم بصياغة إستراتيجية لها على فرضيتنا وحساب المؤشرات والإشارات ومقاييس الأداء. يمكن تقسيم مرحلة الاختبار إلى ثلاث خطوات، والحصول على البيانات، وكتابة الاستراتيجية وتحليل الإخراج. في هذا المثال نعتبر نيفتي النحل. وهو صندوق تداول تبادل تدار من قبل جولدمان ساكس. نس لديها حجم ضخم للأداة وبالتالي فإننا نعتبر هذا. تظهر الصورة أدناه السعر المفتوح-العالي-المنخفض-إغلاق نفسه.


وضعنا مستوى عتبة لمقارنة التقلبات في السعر. في حالة ارتفاع / نقص السعر نقوم بتحديث عمود العتبة. يتم مقارنة سعر الإغلاق مع الفرقة العليا ومع الفرقة السفلى. عندما يتم عبر الشريط العلوي، هو إشارة للبيع. وبالمثل عندما يتم عبور النطاق السفلي، بل هو إشارة للبيع.


ويمكن تلخيص قسم الترميز على النحو التالي،


ويرد في الرسم البياني أدناه عرض لطائرات الهليكوبتر باتجاه إنتاج الاستراتيجية.


وبالتالي فإن فرضيتنا أن السوق يعني العودة يتم دعم. وبما أن هذا هو الاختبار الخلفي لدينا مجال لتنقيح المعلمات التجارية التي من شأنها تحسين متوسط ​​عوائدنا والأرباح المحققة. ويمكن القيام بذلك عن طريق تحديد مستويات عتبة مختلفة، وقواعد دخول أكثر صرامة، ووقف الخسارة وما إلى ذلك يمكن للمرء أن يختار المزيد من البيانات للاختبار الخلفي، واستخدام نهج بايسيان لعتبة اقامة، تأخذ التقلب بعين الاعتبار.


مرة كنت واثقا من استراتيجية التداول المدعومة من نتائج الاختبار الخلفي هل يمكن أن خطوة إلى التداول المباشر. بيئة الإنتاج هو موضوع كبير في حد ذاته وانها خارج النطاق في سياق المقال. لشرح باختصار هذا ينطوي على كتابة الاستراتيجية على منصة التداول.


كما ذكرنا سابقا، سنقوم ببناء النموذج باستخدام حزمة كوانسترات. يوفر كوانتسترات بنية تحتية عامة لنموذج واستراتيجيات باكتست إشارة القائمة على إشارة. بل هو طبقة التجريد رفيعة المستوى (التي بنيت على شتس، فينانسيالينسترومنت، النازل، الخ) التي تسمح لك لبناء واختبار الاستراتيجيات في عدد قليل جدا من خطوط التعليمات البرمجية.


The key features of quantstrat are,


Supports strategies which include indicators, signals, and rules Allows strategies to be applied to multi-asset portfolios Supports market, limit, stoplimit, and stoptrailing order types Supports order sizing and parameter optimization.


In this post we build a strategy that includes indicators, signals, and rules.


For a generic signal based model following are the objects one should consider,


Instruments - Contain market data Indicators - Quantitative values derived from market data Signals - Result of interaction between market data and indicators Rules - Generate orders using market data, indicators and signals.


Without much ado let’s discuss the coding part. We prefer R studio for coding and insist you use the same. You need to have certain packages installed before programming the strategy.


The following set of commands installs the necessary packages.


Once you have installed the packages you import them for further usage.


Read the data from csv file and convert it into xts object.


We initialize the portfolio with the stock, currency, initial equity and the strategy type.


Add position limit if you wish to trade more than once on the same side.


Create the strategy object.


We build a function that computes the thresholds are which we want to trade. If price moves by thresh1 we update threshold to new price. New bands for trading are Threshold+/-Thresh2. Output is an xts object though we use reclass function to ensure.


Add the indicator, signal and the trading rule.


Run the strategy and have a look at the order book.


Update the portfolio and view the trade statistics.


Here is the complete code.


Once you are familiar with these basics you could take a look at how to start using quantimod package in R. Or in case you’re good at C++, take a look at an example strategy coded in C++.


If you’re a retail trader or a tech professional looking to start your own automated trading desk, start learning algo trading today! Begin with basic concepts like automated trading architecture, market microstructure, strategy backtesting system and order management system.


التعليقات مغلقة.


Recent popular posts.


Most visited articles of the week.


Jobs for R users.


Is powered by WordPress using a bavotasan design.


كوبيرايت & كوبي؛ 2017 R-bloggers . كل الحقوق محفوظة. Terms and Conditions for this website.


تجارة خوارزمية في R تعليمي.


In this post, I will show how to use R to collect the stocks listed on loyal3, get historical data from Yahoo and then perform a simple algorithmic trading strategy. Along the way, you will learn some web scraping, a function hitting a finance API and an htmlwidget to make an interactive time series chart.


For this post, a trading algo is defined as a set of rules that trigger a buy or sell event rather than a predictive model or time series forecast. This is the simplest type of trading algo, but if you are interested in digging deeper into finance with R, I would encourage you to take DataCamp’s course in modelling a quantitative trading strategy in R.


خلفية.


In 2018, I started investing a little at loyal3. Their service is unusual and a great place to start your investment journey. Rather than charge the investor for trades, loyal3 charges the companies to list on their platform. The premise is that people who like a company’s service would also buy the stock and in doing so become strong brand advocates. Making the platform more compelling is that you can buy fractional shares. So, you can get into that $800 amazon stock for only $10 and buy another $10 fraction each time you have a bit of extra cash at the end of the month. Sure there are friction costs since you have to trade in windows and your entire portfolio is limited to.


70 stocks but loyal3 represents a fun and low cost way to explore equity training. You can put real skin in the game for as little as $10 !


To be clear, I have the typical retirement and investment accounts but I like loyal3’s clean interface on the app and the lack of fees. I end up checking my fun loyal3 portfolio more often than my mutual funds simply because it is easy and amusing to see the performance of the stocks I directly picked.


The stocks that are available at loyal3.


Setting Up Your Workspace.


To start, load the libraries into your environment. I almost always use rvest for web scraping these days. There are other packages that work including RSelenium , but I like how easy rvest can be executed.


The second package, pbapply , is optional because it simply adds a progress bar to the apply functions. Since you could be scraping hundreds of web pages a progress bar can be helpful to estimate the time.


Next, TTR is a package that I just started to explore. The library is used to construct “Technical Trading Rules”. Although you will learn a simple trading algo in this post, the TTR package can perform more sophisticated calculations and is worth learning.


The dygraphs library is a wrapper for a fast, open source JavaScript charting library. It is one of the htmlwidgets that makes R charting more dynamic and part of an html file instead of a static image. Lastly, the lubridate package is used for easy date manipulation.


Data Collection.


All the loyal3 stocks are all listed on a single page. Before you can look up individual daily stock prices to build your trading algorithm, you need to collect all available stocker tickers. The first thing to do is declare stock. list as a URL string. Next use read_html() so your R session will create an Internet session and collect all the html information on the page as an XML node set. The page CSS has an ID called “pany-name”. Use this as a parameter when calling html_nodes() to select only the XML data associated to this node. Lastly, use html_text() so the actual text values for the company names is collected.


To examine the stocks that are available on loyal3, you can print the stocks. names object to your console. This returns the company name as a text vector.


In order to research the stock prices, you need to get the ticker symbol first. When you are on the loyal3 site, you can click on the company tile to load a page with a ticker symbol and other company information.


Using html_nodes() on stocks, you pull all nodes marked with an “a. ” In HTML the <a> tag defines a hyperlink which is used to link form one page to another. Within the hyperlink tag, the “href” refers to the exact URL address. So html_attr() will extract the URL for ALL links on the page if you pass in “href”.


After doing some manual inspection, I found the 54th to 123rd links on the page represent the company pages I need in order to scrape the ticker information. The last line uses paste0() to concatenate the base URL string ’loyal3` to the specific company pages, like “/WALMART”. For example, loyal3/WALMART:


On each of the company pages there is a description, a recent closing price and the ticker. All company pages are organized the same so the custom function get. ticker() can be used to extract the ticker symbol.


Within a company’s web page there is a table called “ticker-price”. The function will navigate to a company page, identify the appropriate table, extract the text with html_text() . Lastly, using sub() along with the regular expression ^([[:alpha:]]*).* and \\1 will retain all alphabetical characters. The result is that the any special characters, like $, and any numeric characters, like the closing price, are removed. As the function reads each of the 70 pages, it will only collect the stock ticker.


the loyal3 stock page for Alibaba, where you see the table containing the stock’s ticker, BABA, is below the bolded text.


Armed with your custom function, use pblapply() to apply it to each of the stock. links which contain each company’s page. The resulting object, stock. tickers , is a list of individual stock tickers with each element corresponding to an individual company.


One way to change a list of elements into a flat object is with do. call() . Here, you are applying rbind to row bind each list element into a single vector. Lastly, you create a data frame with the symbol and company name information.


To be consistent in your analysis, you may want to limit the amount of historical information you gather on each stock. The Sys. Data() function will store a date object as year, month and then day. Using years with an integer is one way to subtract a specific amount of time from the start. date object.


To get the Yahoo finance data, the date object has to be changed to simple character objects without a dash. Using the global substitution function gsub() on both start. date and end. date will change the class and simultaneously remove dashes. Within gsub() , pass in the character pattern to search for, then the replacement characters. In this case the replacing pattern is an empty character in between quotes. The last parameter is the object that gsub() will be applied to.


The TTR() function getYahooData() accepts a stock symbol, and a starting and ending date. The function returns a data frame that has time series information. Each row is a date and the columns contain information such as the “Open”, “High”, “Low” and “Closing” price for an equity. Since you are looking up multiple companies, you can use lapply() or pblapply() . Pass in the vector of company symbols, then the function, getYahooData() , and then the date information. The date objects are recycled parameters each time getYahooData() is applied to a stock symbol.


To make selecting the returned list, stocks. ts , easier to navigate you can add names to the list elements. Using names with the stocks. ts object declare the names as the original $symbol vector.


When working with large lists, I like to examine the resulting object to make sure the outcome is what I expected. Now that the elements have names, you can reference them directly. In this example, you are examining the first 6 rows for AMC Entertainment Holdings (AMC). Using head() on the list while referencing $AMC will return a portion of the time series for this stock:


Examining the Stock Data.


When I listen to financial news commentators often refer to charts. Despite high frequency trading and active management performed by others, many small investors still refer to charts to gain insight. The time series object can be quickly displayed using plot. Pass in the list referring to the named element such as $AMC and then the column you want to display, here $Close .


The preceding plot is static and not very interesting.


Let’s use a JavaScript library to make a chart you can explore. In this code snippet, you may observe the “%>%” or pipe operator. The pipe operator is a good way to write concise code. It forwards an object to the next function without forcing you to rewrite an object name like you did earlier in this post.


In this example, you create a dygraph referring to the Twitter stock, $TWTR , and then the column you want to plot, $Close . Within dygraph, main adds a title that is specified in between the quotes. Using the “%>%” this entire object is forwarded to the next function dyRangeSelector() . You can specify a default date range using c() with a start and end date string. The resulting HTML object is a dynamic time series for Twitter’s stock with a date slider at the bottom.


Remember, to change the equity displayed, change the ticker symbol in the stocks. ts list and then the graph title.


This is a basic dygraph for Twitter’s stock.


A Simple Trading Strategy: Trend Following.


High frequency traders and hedge funds use sophisticated models and rules based approaches to execute trades. If you want to learn more I suggest visiting quantopian for advanced approaches. For simpler approaches start with this page at Investopedia.


In the code below, you will visualize a simple momentum trading strategy. Basically, you would want to calculate the 200 day and 50 day moving averages for a stock price. On any given day that the 50 day moving average is above the 200 day moving average, you would buy or hold your position. On days where the 200 day average is more than the 50 day moving average, you would sell your shares. This strategy is called a trend following strategy. The positive or negative nature between the two temporal based averages represents the stock’s momentum.


The TTR package provides SMA() for calculating simple moving average. In this code snippet, you are examining the first 6 values for Twitter’s 200 and 50 day moving averages. SMA() works by passing in the time series data for a stock and a specific column like Close . This is a single vector of closing prices for the TWTR stock. The second parameter is an integer representing the number of observations for the moving average. Without using head() the SMA() function will return all values.


Now that you have examined the moving average function in detail, you need to apply to each of the 70 stocks. stocks. ts is a list of 70 data frames containing individual stock data. The fourth column of each data frame contains the closing price that we want to use for the moving averages.


The custom function mov. avgs() accepts a single stock data frame to calculate the moving averages. The first line selects the closing prices because it indexes [,4] to create stock. close . Next, the function uses ifelse to check the number of rows in the data frame. Specifically if the nrow in the data frame is less than (2*260) , then the function will create a data frame of moving averages with “NA”.


I chose this number because there is about 250 trading days a year so this will check that the time series is about 2 years or more in length. Loyal3 sometimes can get access to IPOs and if the stock is newly public there will not be enough data for a 200 day moving average. However, if the nrow value is greater than 2*260 then the function will create a data frame with the original data along with 200 and 50 day moving averages as new columns. Using colnames , I declare the column names. The last part of the function uses complete. cases to check for values in the 200 day moving average column. Any rows that do not have a value are dropped in the final result.


Armed with this mov. avgs() function you can use pblapply() to add the moving average calculations to each of the 70 data frames.


Use the code below to visualize a stock’s moving averages using a dygraph. Once again, this code is using the “%>%” operator to forward objects. The dygraph() function accepts the stocks. ts$FOX data frame. Specifically, the data frame is indexed by column name with c('sma_200','sma_50') . This object is passed to dySeries() in the next 2 lines. You can refer to a column by name so dySeries() each plot a line for the “sma_50” and “sma_200” values in lines 2 and 3. This object is forwarded again to the dyRangeSelector() to adjust the selector’s height. Lastly, I added some shading to define periods when you would have wanted to buy or hold the equity and a period when you should have sold your shares or stayed away depending on your position.


Here is the final result in an interactive time series.


The FOX moving averages with shaded regions for buying/holding versus selling.


استنتاج.


As a budding algorithmic trader, you do not need to plot all 70 shares. Instead, you would want to run the code every day and add a programmatic way to identify stocks that fit the rule based method, “buy if the 50 day moving average is above the 200 day moving average”. As you review the preceding chart, the green section is a time in which you would buy the FOX equity. The red section represents the time to sell your shares and not reenter.


Since the graph is interactive, you can use the slider to resize the visual. Based on this simple algo trading approach, now may be a good time to buy FOX! December 30, 2018 was a trading day where the 50 day moving average moved $0.01 higher than the 200 day moving average!


The zoomed section of the FOX equity.


Of course, remember all investments can lose value. To learn more about finance and algo trading,  check out DataCamp’s courses here.


تجارة خوارزمية في R تعليمي.


In this post, I will show how to use R to collect the stocks listed on loyal3, get historical data from Yahoo and then perform a simple algorithmic trading strategy. Along the way, you will learn some web scraping, a function hitting a finance API and an htmlwidget to make an interactive time series chart.


For this post, a trading algo is defined as a set of rules that trigger a buy or sell event rather than a predictive model or time series forecast. This is the simplest type of trading algo, but if you are interested in digging deeper into finance with R, I would encourage you to take DataCamp’s course in modelling a quantitative trading strategy in R.


خلفية.


In 2018, I started investing a little at loyal3. Their service is unusual and a great place to start your investment journey. Rather than charge the investor for trades, loyal3 charges the companies to list on their platform. The premise is that people who like a company’s service would also buy the stock and in doing so become strong brand advocates. Making the platform more compelling is that you can buy fractional shares. So, you can get into that $800 amazon stock for only $10 and buy another $10 fraction each time you have a bit of extra cash at the end of the month. Sure there are friction costs since you have to trade in windows and your entire portfolio is limited to.


70 stocks but loyal3 represents a fun and low cost way to explore equity training. You can put real skin in the game for as little as $10 !


To be clear, I have the typical retirement and investment accounts but I like loyal3’s clean interface on the app and the lack of fees. I end up checking my fun loyal3 portfolio more often than my mutual funds simply because it is easy and amusing to see the performance of the stocks I directly picked.


The stocks that are available at loyal3.


Setting Up Your Workspace.


To start, load the libraries into your environment. I almost always use rvest for web scraping these days. There are other packages that work including RSelenium , but I like how easy rvest can be executed.


The second package, pbapply , is optional because it simply adds a progress bar to the apply functions. Since you could be scraping hundreds of web pages a progress bar can be helpful to estimate the time.


Next, TTR is a package that I just started to explore. The library is used to construct “Technical Trading Rules”. Although you will learn a simple trading algo in this post, the TTR package can perform more sophisticated calculations and is worth learning.


The dygraphs library is a wrapper for a fast, open source JavaScript charting library. It is one of the htmlwidgets that makes R charting more dynamic and part of an html file instead of a static image. Lastly, the lubridate package is used for easy date manipulation.


Data Collection.


All the loyal3 stocks are all listed on a single page. Before you can look up individual daily stock prices to build your trading algorithm, you need to collect all available stocker tickers. The first thing to do is declare stock. list as a URL string. Next use read_html() so your R session will create an Internet session and collect all the html information on the page as an XML node set. The page CSS has an ID called “pany-name”. Use this as a parameter when calling html_nodes() to select only the XML data associated to this node. Lastly, use html_text() so the actual text values for the company names is collected.


To examine the stocks that are available on loyal3, you can print the stocks. names object to your console. This returns the company name as a text vector.


In order to research the stock prices, you need to get the ticker symbol first. When you are on the loyal3 site, you can click on the company tile to load a page with a ticker symbol and other company information.


Using html_nodes() on stocks, you pull all nodes marked with an “a. ” In HTML the <a> tag defines a hyperlink which is used to link form one page to another. Within the hyperlink tag, the “href” refers to the exact URL address. So html_attr() will extract the URL for ALL links on the page if you pass in “href”.


After doing some manual inspection, I found the 54th to 123rd links on the page represent the company pages I need in order to scrape the ticker information. The last line uses paste0() to concatenate the base URL string ’loyal3` to the specific company pages, like “/WALMART”. For example, loyal3/WALMART:


On each of the company pages there is a description, a recent closing price and the ticker. All company pages are organized the same so the custom function get. ticker() can be used to extract the ticker symbol.


Within a company’s web page there is a table called “ticker-price”. The function will navigate to a company page, identify the appropriate table, extract the text with html_text() . Lastly, using sub() along with the regular expression ^([[:alpha:]]*).* and \\1 will retain all alphabetical characters. The result is that the any special characters, like $, and any numeric characters, like the closing price, are removed. As the function reads each of the 70 pages, it will only collect the stock ticker.


the loyal3 stock page for Alibaba, where you see the table containing the stock’s ticker, BABA, is below the bolded text.


Armed with your custom function, use pblapply() to apply it to each of the stock. links which contain each company’s page. The resulting object, stock. tickers , is a list of individual stock tickers with each element corresponding to an individual company.


One way to change a list of elements into a flat object is with do. call() . Here, you are applying rbind to row bind each list element into a single vector. Lastly, you create a data frame with the symbol and company name information.


To be consistent in your analysis, you may want to limit the amount of historical information you gather on each stock. The Sys. Data() function will store a date object as year, month and then day. Using years with an integer is one way to subtract a specific amount of time from the start. date object.


To get the Yahoo finance data, the date object has to be changed to simple character objects without a dash. Using the global substitution function gsub() on both start. date and end. date will change the class and simultaneously remove dashes. Within gsub() , pass in the character pattern to search for, then the replacement characters. In this case the replacing pattern is an empty character in between quotes. The last parameter is the object that gsub() will be applied to.


The TTR() function getYahooData() accepts a stock symbol, and a starting and ending date. The function returns a data frame that has time series information. Each row is a date and the columns contain information such as the “Open”, “High”, “Low” and “Closing” price for an equity. Since you are looking up multiple companies, you can use lapply() or pblapply() . Pass in the vector of company symbols, then the function, getYahooData() , and then the date information. The date objects are recycled parameters each time getYahooData() is applied to a stock symbol.


To make selecting the returned list, stocks. ts , easier to navigate you can add names to the list elements. Using names with the stocks. ts object declare the names as the original $symbol vector.


When working with large lists, I like to examine the resulting object to make sure the outcome is what I expected. Now that the elements have names, you can reference them directly. In this example, you are examining the first 6 rows for AMC Entertainment Holdings (AMC). Using head() on the list while referencing $AMC will return a portion of the time series for this stock:


Examining the Stock Data.


When I listen to financial news commentators often refer to charts. Despite high frequency trading and active management performed by others, many small investors still refer to charts to gain insight. The time series object can be quickly displayed using plot. Pass in the list referring to the named element such as $AMC and then the column you want to display, here $Close .


The preceding plot is static and not very interesting.


Let’s use a JavaScript library to make a chart you can explore. In this code snippet, you may observe the “%>%” or pipe operator. The pipe operator is a good way to write concise code. It forwards an object to the next function without forcing you to rewrite an object name like you did earlier in this post.


In this example, you create a dygraph referring to the Twitter stock, $TWTR , and then the column you want to plot, $Close . Within dygraph, main adds a title that is specified in between the quotes. Using the “%>%” this entire object is forwarded to the next function dyRangeSelector() . You can specify a default date range using c() with a start and end date string. The resulting HTML object is a dynamic time series for Twitter’s stock with a date slider at the bottom.


Remember, to change the equity displayed, change the ticker symbol in the stocks. ts list and then the graph title.


This is a basic dygraph for Twitter’s stock.


A Simple Trading Strategy: Trend Following.


High frequency traders and hedge funds use sophisticated models and rules based approaches to execute trades. If you want to learn more I suggest visiting quantopian for advanced approaches. For simpler approaches start with this page at Investopedia.


In the code below, you will visualize a simple momentum trading strategy. Basically, you would want to calculate the 200 day and 50 day moving averages for a stock price. On any given day that the 50 day moving average is above the 200 day moving average, you would buy or hold your position. On days where the 200 day average is more than the 50 day moving average, you would sell your shares. This strategy is called a trend following strategy. The positive or negative nature between the two temporal based averages represents the stock’s momentum.


The TTR package provides SMA() for calculating simple moving average. In this code snippet, you are examining the first 6 values for Twitter’s 200 and 50 day moving averages. SMA() works by passing in the time series data for a stock and a specific column like Close . This is a single vector of closing prices for the TWTR stock. The second parameter is an integer representing the number of observations for the moving average. Without using head() the SMA() function will return all values.


Now that you have examined the moving average function in detail, you need to apply to each of the 70 stocks. stocks. ts is a list of 70 data frames containing individual stock data. The fourth column of each data frame contains the closing price that we want to use for the moving averages.


The custom function mov. avgs() accepts a single stock data frame to calculate the moving averages. The first line selects the closing prices because it indexes [,4] to create stock. close . Next, the function uses ifelse to check the number of rows in the data frame. Specifically if the nrow in the data frame is less than (2*260) , then the function will create a data frame of moving averages with “NA”.


I chose this number because there is about 250 trading days a year so this will check that the time series is about 2 years or more in length. Loyal3 sometimes can get access to IPOs and if the stock is newly public there will not be enough data for a 200 day moving average. However, if the nrow value is greater than 2*260 then the function will create a data frame with the original data along with 200 and 50 day moving averages as new columns. Using colnames , I declare the column names. The last part of the function uses complete. cases to check for values in the 200 day moving average column. Any rows that do not have a value are dropped in the final result.


Armed with this mov. avgs() function you can use pblapply() to add the moving average calculations to each of the 70 data frames.


Use the code below to visualize a stock’s moving averages using a dygraph. Once again, this code is using the “%>%” operator to forward objects. The dygraph() function accepts the stocks. ts$FOX data frame. Specifically, the data frame is indexed by column name with c('sma_200','sma_50') . This object is passed to dySeries() in the next 2 lines. You can refer to a column by name so dySeries() each plot a line for the “sma_50” and “sma_200” values in lines 2 and 3. This object is forwarded again to the dyRangeSelector() to adjust the selector’s height. Lastly, I added some shading to define periods when you would have wanted to buy or hold the equity and a period when you should have sold your shares or stayed away depending on your position.


Here is the final result in an interactive time series.


The FOX moving averages with shaded regions for buying/holding versus selling.


استنتاج.


As a budding algorithmic trader, you do not need to plot all 70 shares. Instead, you would want to run the code every day and add a programmatic way to identify stocks that fit the rule based method, “buy if the 50 day moving average is above the 200 day moving average”. As you review the preceding chart, the green section is a time in which you would buy the FOX equity. The red section represents the time to sell your shares and not reenter.


Since the graph is interactive, you can use the slider to resize the visual. Based on this simple algo trading approach, now may be a good time to buy FOX! December 30, 2018 was a trading day where the 50 day moving average moved $0.01 higher than the 200 day moving average!


The zoomed section of the FOX equity.


Of course, remember all investments can lose value. To learn more about finance and algo trading,  check out DataCamp’s courses here.

No comments:

Post a Comment